From 5ba29b72996e31ccd4d1cbed865d506bd5490113 Mon Sep 17 00:00:00 2001 From: julian Date: Fri, 3 Nov 2023 13:46:55 -0600 Subject: [PATCH] mostly (roughly) refactored with new wallet providers as well as using a TxData object in place of dynamic Maps --- lib/db/isar/main_db.dart | 2 +- .../edit_wallet_tokens_view.dart | 14 +- .../name_your_wallet_view.dart | 103 ++-- .../new_wallet_recovery_phrase_view.dart | 23 +- ...w_wallet_recovery_phrase_warning_view.dart | 82 +-- .../restore_wallet_view.dart | 83 ++- .../sub_widgets/restore_failed_dialog.dart | 6 +- .../select_wallet_for_token_view.dart | 44 +- .../verify_recovery_phrase_view.dart | 34 +- .../address_book_views/address_book_view.dart | 10 +- .../subviews/contact_details_view.dart | 41 +- .../subviews/contact_popup.dart | 21 +- lib/pages/buy_view/buy_form.dart | 6 +- lib/pages/cashfusion/cashfusion_view.dart | 4 +- .../cashfusion/fusion_progress_view.dart | 6 +- lib/pages/coin_control/coin_control_view.dart | 34 +- lib/pages/coin_control/utxo_card.dart | 12 +- lib/pages/coin_control/utxo_details_view.dart | 16 +- .../exchange_view/choose_from_stack_view.dart | 14 +- .../confirm_change_now_send.dart | 114 ++-- .../exchange_step_views/step_2_view.dart | 35 +- .../exchange_step_views/step_4_view.dart | 77 +-- lib/pages/exchange_view/exchange_view.dart | 6 +- lib/pages/exchange_view/send_from_view.dart | 130 +++-- .../manage_favorites_view.dart | 123 ++++- lib/pages/monkey/monkey_loaded_view.dart | 6 +- lib/pages/monkey/monkey_view.dart | 76 +-- lib/pages/ordinals/ordinal_details_view.dart | 6 +- lib/pages/ordinals/ordinals_view.dart | 2 +- .../paynym/dialogs/paynym_details_popup.dart | 49 +- lib/pages/paynym/paynym_claim_view.dart | 13 +- .../subwidgets/desktop_paynym_details.dart | 44 +- .../subwidgets/paynym_followers_list.dart | 6 +- .../subwidgets/paynym_following_list.dart | 6 +- lib/pages/pinpad_views/lock_screen_view.dart | 14 +- .../addresses/address_details_view.dart | 11 +- .../addresses/wallet_addresses_view.dart | 6 +- lib/pages/receive_view/receive_view.dart | 80 ++- .../send_view/confirm_transaction_view.dart | 182 +++---- lib/pages/send_view/send_view.dart | 505 +++++++----------- .../firo_balance_selection_sheet.dart | 16 +- .../transaction_fee_selection_sheet.dart | 74 +-- lib/pages/send_view/token_send_view.dart | 58 +- .../helpers/restore_create_backup.dart | 4 +- .../sub_widgets/restoring_wallet_card.dart | 6 +- .../startup_preferences_view.dart | 48 +- .../startup_wallet_selection_view.dart | 26 +- .../syncing_options_view.dart | 9 +- .../wallet_syncing_options_view.dart | 45 +- .../wallet_backup_view.dart | 7 +- .../wallet_network_settings_view.dart | 88 ++- .../wallet_settings_view.dart | 77 +-- .../change_representative_view.dart | 20 +- .../delete_wallet_recovery_phrase_view.dart | 64 +-- .../delete_wallet_warning_view.dart | 23 +- .../rename_wallet_view.dart | 64 ++- .../wallet_settings_wallet_settings_view.dart | 4 +- .../xpub_view.dart | 11 +- .../firo_rescan_recovery_error_dialog.dart | 57 +- lib/pages/token_view/my_tokens_view.dart | 9 +- .../sub_widgets/my_token_select_item.dart | 12 +- .../token_view/sub_widgets/token_summary.dart | 14 +- .../token_transaction_list_widget.dart | 29 +- .../sub_widgets/transactions_list.dart | 70 ++- .../wallet_balance_toggle_sheet.dart | 21 +- .../sub_widgets/wallet_refresh_button.dart | 10 +- .../sub_widgets/wallet_summary_info.dart | 77 +-- .../all_transactions_view.dart | 51 +- .../transaction_details_view.dart | 14 +- .../tx_v2/all_transactions_v2_view.dart | 41 +- .../tx_v2/fusion_tx_group_card.dart | 8 +- .../tx_v2/transaction_v2_card.dart | 7 +- .../tx_v2/transaction_v2_details_view.dart | 4 +- .../tx_v2/transaction_v2_list.dart | 17 +- .../tx_v2/transaction_v2_list_item.dart | 18 +- lib/pages/wallet_view/wallet_view.dart | 112 ++-- .../wallets_view/sub_widgets/all_wallets.dart | 9 +- .../sub_widgets/favorite_card.dart | 39 +- .../sub_widgets/favorite_wallets.dart | 12 +- .../sub_widgets/wallet_list_item.dart | 20 +- lib/pages/wallets_view/wallets_overview.dart | 36 +- .../desktop_address_book.dart | 10 +- .../subwidgets/desktop_contact_details.dart | 39 +- .../sub_widgets/desktop_address_list.dart | 5 +- .../cashfusion/desktop_cashfusion_view.dart | 4 +- .../cashfusion/sub_widgets/fusion_dialog.dart | 10 +- .../desktop_coin_control_use_dialog.dart | 4 +- .../desktop_coin_control_view.dart | 4 +- .../coin_control/utxo_row.dart | 11 +- .../desktop_all_trades_view.dart | 33 +- .../subwidgets/desktop_step_2.dart | 29 +- .../subwidgets/desktop_step_4.dart | 4 +- .../subwidgets/desktop_choose_from_stack.dart | 45 +- .../subwidgets/desktop_trade_history.dart | 9 +- .../desktop_home_view.dart | 18 +- .../my_stack_view/coin_wallets_table.dart | 19 +- .../desktop_favorite_wallets.dart | 213 ++++---- .../desktop_expanding_wallet_card.dart | 12 +- .../paynym/desktop_paynym_send_dialog.dart | 43 +- .../my_stack_view/wallet_summary_table.dart | 15 +- .../wallet_view/desktop_token_view.dart | 14 +- .../wallet_view/desktop_wallet_view.dart | 104 ++-- .../sub_widgets/delete_wallet_keys_popup.dart | 56 +- .../desktop_attention_delete_wallet.dart | 27 +- .../sub_widgets/desktop_fee_dropdown.dart | 61 ++- .../sub_widgets/desktop_receive.dart | 76 ++- .../wallet_view/sub_widgets/desktop_send.dart | 243 +++++---- .../sub_widgets/desktop_token_send.dart | 51 +- .../sub_widgets/desktop_wallet_features.dart | 39 +- .../sub_widgets/desktop_wallet_summary.dart | 24 +- .../more_features/more_features_dialog.dart | 36 +- .../wallet_view/sub_widgets/my_wallet.dart | 11 +- .../sub_widgets/network_info_button.dart | 6 +- .../unlock_wallet_keys_desktop.dart | 27 +- .../sub_widgets/wallet_options_button.dart | 13 +- .../desktop_ordinal_details_view.dart | 31 +- .../ordinals/desktop_ordinals_view.dart | 3 +- .../global/active_wallet_provider.dart | 3 + .../global/wallets_service_provider.dart | 54 +- lib/providers/providers.dart | 2 - lib/route_generator.dart | 27 +- .../ethereum/ethereum_token_service.dart | 34 +- .../mixins/paynym_wallet_interface.dart | 99 ++-- lib/services/wallets.dart | 46 +- .../crypto_currency/crypto_currency.dart | 4 + lib/wallets/isar/models/wallet_info.dart | 95 ++++ .../providers/all_wallets_info_provider.dart | 45 ++ .../providers/favourite_wallets_provider.dart | 57 ++ .../isar/providers/wallet_info_provider.dart | 7 + lib/wallets/migration/migrate_wallets.dart | 2 +- lib/wallets/models/tx_data.dart | 39 +- lib/wallets/wallet/bip39_hd_wallet.dart | 22 +- lib/wallets/wallet/bip39_wallet.dart | 9 +- lib/wallets/wallet/cryptonote_wallet.dart | 2 +- lib/wallets/wallet/impl/bitcoin_wallet.dart | 16 +- .../wallet/impl/bitcoincash_wallet.dart | 14 +- lib/wallets/wallet/impl/epiccash_wallet.dart | 12 + .../wallet/mixins/electrumx_mixin.dart | 137 +++++ .../wallet/private_key_based_wallet.dart | 2 +- .../epiccash_wallet_info_extension.dart | 2 +- lib/wallets/wallet/wallet.dart | 43 +- lib/widgets/coin_card.dart | 2 +- .../paynym_follow_toggle_button.dart | 12 +- .../favourite_wallets_watcher.dart | 40 ++ lib/widgets/desktop/desktop_fee_dialog.dart | 40 +- lib/widgets/eth_wallet_radio.dart | 8 +- lib/widgets/hover_text_field.dart | 35 +- lib/widgets/managed_favorite.dart | 72 +-- lib/widgets/master_wallet_card.dart | 2 +- lib/widgets/node_card.dart | 25 +- lib/widgets/node_options_sheet.dart | 24 +- lib/widgets/transaction_card.dart | 6 +- lib/widgets/wallet_card.dart | 24 +- .../sub_widgets/wallet_info_row_balance.dart | 14 +- .../wallet_info_row/wallet_info_row.dart | 11 +- pubspec.lock | 2 +- pubspec.yaml | 1 + test/pages/send_view/send_view_test.dart | 8 +- .../add_address_book_view_screen_test.dart | 42 +- ...s_book_entry_details_view_screen_test.dart | 22 +- ...t_address_book_entry_view_screen_test.dart | 24 +- .../lockscreen_view_screen_test.dart | 10 +- .../main_view_screen_testA_test.dart | 2 +- .../main_view_screen_testB_test.dart | 2 +- .../main_view_screen_testC_test.dart | 2 +- .../backup_key_view_screen_test.dart | 12 +- .../backup_key_warning_view_screen_test.dart | 4 +- .../create_pin_view_screen_test.dart | 4 +- .../restore_wallet_view_screen_test.dart | 8 +- .../verify_backup_key_view_screen_test.dart | 6 +- .../currency_view_screen_test.dart | 8 +- .../add_custom_node_view_screen_test.dart | 14 +- .../node_details_view_screen_test.dart | 4 +- .../wallet_backup_view_screen_test.dart | 10 +- .../rescan_warning_view_screen_test.dart | 14 +- ...llet_delete_mnemonic_view_screen_test.dart | 14 +- .../wallet_settings_view_screen_test.dart | 34 +- .../settings_view_screen_test.dart | 6 +- ...ction_search_results_view_screen_test.dart | 10 +- .../confirm_send_view_screen_test.dart | 8 +- .../wallet_view/receive_view_screen_test.dart | 12 +- .../wallet_view/send_view_screen_test.dart | 44 +- .../wallet_view/wallet_view_screen_test.dart | 12 +- test/services/coins/manager_test.dart | 44 +- test/widget_tests/managed_favorite_test.dart | 12 +- .../table_view/table_view_row_test.dart | 2 +- test/widget_tests/transaction_card_test.dart | 8 +- test/widget_tests/wallet_card_test.dart | 2 +- .../wallet_info_row_balance_future_test.dart | 2 +- .../wallet_info_row/wallet_info_row_test.dart | 2 +- 190 files changed, 3262 insertions(+), 2963 deletions(-) create mode 100644 lib/providers/global/active_wallet_provider.dart create mode 100644 lib/wallets/isar/providers/all_wallets_info_provider.dart create mode 100644 lib/wallets/isar/providers/favourite_wallets_provider.dart create mode 100644 lib/widgets/db_watchers/favourite_wallets_watcher.dart diff --git a/lib/db/isar/main_db.dart b/lib/db/isar/main_db.dart index 09512def9..dd3fa0202 100644 --- a/lib/db/isar/main_db.dart +++ b/lib/db/isar/main_db.dart @@ -21,7 +21,7 @@ import 'package:stackwallet/models/isar/stack_theme.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/stack_file_system.dart'; -import 'package:stackwallet/wallets/isar_models/wallet_info.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:tuple/tuple.dart'; part '../queries/queries.dart'; diff --git a/lib/pages/add_wallet_views/add_token_view/edit_wallet_tokens_view.dart b/lib/pages/add_wallet_views/add_token_view/edit_wallet_tokens_view.dart index 98f88949c..6c111c501 100644 --- a/lib/pages/add_wallet_views/add_token_view/edit_wallet_tokens_view.dart +++ b/lib/pages/add_wallet_views/add_token_view/edit_wallet_tokens_view.dart @@ -31,6 +31,7 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/default_eth_tokens.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -99,7 +100,7 @@ class _EditWalletTokensViewState extends ConsumerState { .toList(); final ethWallet = - ref.read(pWallets).getManager(widget.walletId).wallet as EthereumWallet; + ref.read(pWallets).getWallet(widget.walletId) as EthereumWallet; await ethWallet.updateTokenContracts(selectedTokens); if (mounted) { @@ -179,11 +180,9 @@ class _EditWalletTokensViewState extends ConsumerState { tokenEntities.addAll(contracts.map((e) => AddTokenListElementData(e))); - final walletContracts = (ref - .read(pWallets) - .getManager(widget.walletId) - .wallet as EthereumWallet) - .getWalletTokenContractAddresses(); + final walletContracts = + (ref.read(pWallets).getWallet(widget.walletId) as EthereumWallet) + .getWalletTokenContractAddresses(); final shouldMarkAsSelectedContracts = [ ...walletContracts, @@ -207,8 +206,7 @@ class _EditWalletTokensViewState extends ConsumerState { @override Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final walletName = ref.watch(pWallets - .select((value) => value.getManager(widget.walletId).walletName)); + final walletName = ref.watch(pWalletName(widget.walletId)); if (isDesktop) { return ConditionalParent( diff --git a/lib/pages/add_wallet_views/name_your_wallet_view/name_your_wallet_view.dart b/lib/pages/add_wallet_views/name_your_wallet_view/name_your_wallet_view.dart index f07941e36..350c839f8 100644 --- a/lib/pages/add_wallet_views/name_your_wallet_view/name_your_wallet_view.dart +++ b/lib/pages/add_wallet_views/name_your_wallet_view/name_your_wallet_view.dart @@ -12,22 +12,22 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:stackwallet/notifications/show_flush_bar.dart'; +import 'package:isar/isar.dart'; import 'package:stackwallet/pages/add_wallet_views/create_or_restore_wallet_view/sub_widgets/coin_image.dart'; import 'package:stackwallet/pages/add_wallet_views/new_wallet_options/new_wallet_options_view.dart'; import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart'; import 'package:stackwallet/pages/add_wallet_views/restore_wallet_view/restore_options_view/restore_options_view.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/exit_to_my_stack_button.dart'; -import 'package:stackwallet/providers/global/wallets_service_provider.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/ui/verify_recovery_phrase/mnemonic_word_count_state_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; -import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/add_wallet_type_enum.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/name_generator.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; @@ -81,10 +81,15 @@ class _NameYourWalletViewState extends ConsumerState { void initState() { isDesktop = Util.isDesktop; - ref.read(walletsServiceChangeNotifierProvider).walletNames.then( - (value) => namesToExclude.addAll( - value.values.map((e) => e.name), - ), + ref + .read(mainDBProvider) + .isar + .walletInfo + .where() + .nameProperty() + .findAll() + .then( + (values) => namesToExclude.addAll(values), ); generator = NameGenerator(); addWalletType = widget.addWalletType; @@ -333,64 +338,48 @@ class _NameYourWalletViewState extends ConsumerState { child: TextButton( onPressed: _nextEnabled ? () async { - final walletsService = - ref.read(walletsServiceChangeNotifierProvider); final name = textEditingController.text; - final hasDuplicateName = - await walletsService.checkForDuplicate(name); - if (mounted) { - if (hasDuplicateName) { - unawaited(showFloatingFlushBar( - type: FlushBarType.warning, - message: "Wallet name already in use.", - iconAsset: Assets.svg.circleAlert, - context: context, - )); - } else { - // hide keyboard if has focus - if (FocusScope.of(context).hasFocus) { - FocusScope.of(context).unfocus(); - await Future.delayed( - const Duration(milliseconds: 50)); - } + // hide keyboard if has focus + if (FocusScope.of(context).hasFocus) { + FocusScope.of(context).unfocus(); + await Future.delayed( + const Duration(milliseconds: 50)); + } - if (mounted) { - ref - .read(mnemonicWordCountStateProvider.state) - .state = - Constants.possibleLengthsForCoin(coin).last; - ref.read(pNewWalletOptions.notifier).state = null; + if (mounted) { + ref.read(mnemonicWordCountStateProvider.state).state = + Constants.possibleLengthsForCoin(coin).last; + ref.read(pNewWalletOptions.notifier).state = null; - switch (widget.addWalletType) { - case AddWalletType.New: - unawaited( - Navigator.of(context).pushNamed( - coin.hasMnemonicPassphraseSupport - ? NewWalletOptionsView.routeName - : NewWalletRecoveryPhraseWarningView - .routeName, - arguments: Tuple2( - name, - coin, - ), + switch (widget.addWalletType) { + case AddWalletType.New: + unawaited( + Navigator.of(context).pushNamed( + coin.hasMnemonicPassphraseSupport + ? NewWalletOptionsView.routeName + : NewWalletRecoveryPhraseWarningView + .routeName, + arguments: Tuple2( + name, + coin, ), - ); - break; + ), + ); + break; - case AddWalletType.Restore: - unawaited( - Navigator.of(context).pushNamed( - RestoreOptionsView.routeName, - arguments: Tuple2( - name, - coin, - ), + case AddWalletType.Restore: + unawaited( + Navigator.of(context).pushNamed( + RestoreOptionsView.routeName, + arguments: Tuple2( + name, + coin, ), - ); - break; - } + ), + ); + break; } } } diff --git a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_view/new_wallet_recovery_phrase_view.dart b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_view/new_wallet_recovery_phrase_view.dart index 2a1619364..9d8ffba80 100644 --- a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_view/new_wallet_recovery_phrase_view.dart +++ b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_view/new_wallet_recovery_phrase_view.dart @@ -22,13 +22,14 @@ import 'package:stackwallet/pages/add_wallet_views/verify_recovery_phrase_view/v import 'package:stackwallet/pages_desktop_specific/desktop_home_view.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/exit_to_my_stack_button.dart'; import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/clipboard_interface.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; import 'package:stackwallet/widgets/desktop/desktop_scaffold.dart'; @@ -37,14 +38,14 @@ import 'package:tuple/tuple.dart'; class NewWalletRecoveryPhraseView extends ConsumerStatefulWidget { const NewWalletRecoveryPhraseView({ Key? key, - required this.manager, + required this.wallet, required this.mnemonic, this.clipboardInterface = const ClipboardWrapper(), }) : super(key: key); static const routeName = "/newWalletRecoveryPhrase"; - final Manager manager; + final Wallet wallet; final List mnemonic; final ClipboardInterface clipboardInterface; @@ -58,14 +59,14 @@ class _NewWalletRecoveryPhraseViewState extends ConsumerState // with WidgetsBindingObserver { - late Manager _manager; + late Wallet _wallet; late List _mnemonic; late ClipboardInterface _clipboardInterface; late final bool isDesktop; @override void initState() { - _manager = widget.manager; + _wallet = widget.wallet; _mnemonic = widget.mnemonic; _clipboardInterface = widget.clipboardInterface; isDesktop = Util.isDesktop; @@ -78,14 +79,12 @@ class _NewWalletRecoveryPhraseViewState } Future delete() async { - await ref - .read(walletsServiceChangeNotifierProvider) - .deleteWallet(_manager.walletName, false); - await _manager.exitCurrentWallet(); + await _wallet.exit(); + await ref.read(pWallets).deleteWallet(_wallet.walletId); } Future _copy() async { - final words = await _manager.mnemonic; + final words = _mnemonic; await _clipboardInterface.setData(ClipboardData(text: words.join(" "))); unawaited(showFloatingFlushBar( type: FlushBarType.info, @@ -191,7 +190,7 @@ class _NewWalletRecoveryPhraseViewState ), if (!isDesktop) Text( - _manager.walletName, + ref.watch(pWalletName(_wallet.walletId)), textAlign: TextAlign.center, style: STextStyles.label(context).copyWith( fontSize: 12, @@ -305,7 +304,7 @@ class _NewWalletRecoveryPhraseViewState unawaited(Navigator.of(context).pushNamed( VerifyRecoveryPhraseView.routeName, - arguments: Tuple2(_manager, _mnemonic), + arguments: Tuple2(_wallet, _mnemonic), )); }, style: Theme.of(context) diff --git a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart index d843f6ec8..7ecfab46e 100644 --- a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart +++ b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart @@ -17,10 +17,9 @@ import 'package:stackwallet/pages/add_wallet_views/new_wallet_options/new_wallet import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_view/new_wallet_recovery_phrase_view.dart'; import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/recovery_phrase_explanation_dialog.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/exit_to_my_stack_button.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/secure_store_provider.dart'; import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/coin_service.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/services/transaction_notification_tracker.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; @@ -30,6 +29,9 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/bip39_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; @@ -453,14 +455,9 @@ class _NewWalletRecoveryPhraseWarningViewState }, )); - final walletsService = ref.read( - walletsServiceChangeNotifierProvider); - - final walletId = - await walletsService.addNewWallet( - name: walletName, - coin: coin, - shouldNotifyListeners: false, + final info = WalletInfo.createNew( + coin: widget.coin, + name: widget.walletName, ); var node = ref @@ -480,43 +477,45 @@ class _NewWalletRecoveryPhraseWarningViewState final txTracker = TransactionNotificationTracker( - walletId: walletId!); + walletId: info.walletId, + ); final failovers = ref .read(nodeServiceChangeNotifierProvider) .failoverNodesFor(coin: widget.coin); - final wallet = CoinServiceAPI.from( - coin, - walletId, - walletName, - ref.read(secureStoreProvider), - node, - txTracker, - ref.read(prefsChangeNotifierProvider), - failovers, + final wallet = await Wallet.create( + walletInfo: info, + mainDB: ref.read(mainDBProvider), + secureStorageInterface: + ref.read(secureStoreProvider), + nodeService: ref.read( + nodeServiceChangeNotifierProvider), + prefs: + ref.read(prefsChangeNotifierProvider), ); - final manager = Manager(wallet); + await wallet.init(); - if (coin.hasMnemonicPassphraseSupport && - ref - .read(pNewWalletOptions.state) - .state != - null) { - await manager.initializeNew(( - mnemonicPassphrase: ref - .read(pNewWalletOptions.state) - .state! - .mnemonicPassphrase, - wordCount: ref - .read(pNewWalletOptions.state) - .state! - .mnemonicWordsCount, - )); - } else { - await manager.initializeNew(null); - } + // TODO: [prio=high] finish fleshing this out + // if (coin.hasMnemonicPassphraseSupport && + // ref + // .read(pNewWalletOptions.state) + // .state != + // null) { + // await manager.initializeNew(( + // mnemonicPassphrase: ref + // .read(pNewWalletOptions.state) + // .state! + // .mnemonicPassphrase, + // wordCount: ref + // .read(pNewWalletOptions.state) + // .state! + // .mnemonicWordsCount, + // )); + // } else { + // await manager.initializeNew(null); + // } // pop progress dialog if (mounted) { @@ -531,8 +530,9 @@ class _NewWalletRecoveryPhraseWarningViewState unawaited(Navigator.of(context).pushNamed( NewWalletRecoveryPhraseView.routeName, arguments: Tuple2( - manager, - await manager.mnemonic, + wallet.walletId, + await (wallet as Bip39Wallet) + .getMnemonicAsWords(), ), )); } diff --git a/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart b/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart index 0cf8ee703..e43af72ce 100644 --- a/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart +++ b/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart @@ -32,10 +32,9 @@ import 'package:stackwallet/pages/add_wallet_views/verify_recovery_phrase_view/v import 'package:stackwallet/pages/home_view/home_view.dart'; import 'package:stackwallet/pages_desktop_specific/desktop_home_view.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/exit_to_my_stack_button.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/secure_store_provider.dart'; import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/coin_service.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/services/transaction_notification_tracker.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/address_utils.dart'; @@ -50,6 +49,8 @@ import 'package:stackwallet/utilities/enums/form_input_status_enum.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; import 'package:stackwallet/widgets/desktop/desktop_scaffold.dart'; @@ -239,13 +240,13 @@ class _RestoreWalletViewState extends ConsumerState { )); } else { if (!Platform.isLinux) await Wakelock.enable(); - final walletsService = ref.read(walletsServiceChangeNotifierProvider); - final walletId = await walletsService.addNewWallet( - name: widget.walletName, - coin: widget.coin, - shouldNotifyListeners: false, - ); + final info = WalletInfo.createNew( + coin: widget.coin, + name: widget.walletName, + ); + + bool isRestoring = true; // show restoring in progress unawaited(showDialog( @@ -256,12 +257,10 @@ class _RestoreWalletViewState extends ConsumerState { return RestoringDialog( onCancel: () async { isRestoring = false; - ref.read(pWallets.notifier).removeWallet(walletId: walletId!); - await walletsService.deleteWallet( - widget.walletName, - false, - ); + await ref.read(pWallets).deleteWallet( + info.walletId, + ); }, ); }, @@ -279,49 +278,29 @@ class _RestoreWalletViewState extends ConsumerState { ); } - final txTracker = TransactionNotificationTracker(walletId: walletId!); - - final failovers = ref - .read(nodeServiceChangeNotifierProvider) - .failoverNodesFor(coin: widget.coin); - - final wallet = CoinServiceAPI.from( - widget.coin, - walletId, - widget.walletName, - ref.read(secureStoreProvider), - node, - txTracker, - ref.read(prefsChangeNotifierProvider), - failovers, - ); - - final manager = Manager(wallet); + final txTracker = + TransactionNotificationTracker(walletId: info.walletId); try { - // TODO GUI option to set maxUnusedAddressGap? - // default is 20 but it may miss some transactions if - // the previous wallet software generated many addresses - // without using them - await manager.recoverFromMnemonic( - mnemonic: mnemonic, + final wallet = await Wallet.create( + walletInfo: info, + mainDB: ref.read(mainDBProvider), + secureStorageInterface: ref.read(secureStoreProvider), + nodeService: ref.read(nodeServiceChangeNotifierProvider), + prefs: ref.read(prefsChangeNotifierProvider), mnemonicPassphrase: widget.mnemonicPassphrase, - maxUnusedAddressGap: widget.coin == Coin.firo ? 50 : 20, - maxNumberOfIndexesToCheck: 1000, - height: height, + mnemonic: mnemonic, ); + await wallet.recover(isRescan: false); + // check if state is still active before continuing if (mounted) { - await ref - .read(walletsServiceChangeNotifierProvider) - .setMnemonicVerified( - walletId: manager.walletId, - ); + await wallet.info.setMnemonicVerified( + isar: ref.read(mainDBProvider).isar, + ); - ref - .read(pWallets.notifier) - .addWallet(walletId: manager.walletId, manager: manager); + ref.read(pWallets).addWallet(wallet); final isCreateSpecialEthWallet = ref.read(createSpecialEthWalletRoutingFlag); @@ -358,11 +337,11 @@ class _RestoreWalletViewState extends ConsumerState { (route) => false, ), ); - if (manager.coin == Coin.ethereum) { + if (info.coin == Coin.ethereum) { unawaited( Navigator.of(context).pushNamed( EditWalletTokensView.routeName, - arguments: manager.walletId, + arguments: wallet.walletId, ), ); } @@ -408,8 +387,8 @@ class _RestoreWalletViewState extends ConsumerState { builder: (context) { return RestoreFailedDialog( errorMessage: e.toString(), - walletId: wallet.walletId, - walletName: wallet.walletName, + walletId: info.walletId, + walletName: info.name, ); }, ); diff --git a/lib/pages/add_wallet_views/restore_wallet_view/sub_widgets/restore_failed_dialog.dart b/lib/pages/add_wallet_views/restore_wallet_view/sub_widgets/restore_failed_dialog.dart index 414b53dae..91d855341 100644 --- a/lib/pages/add_wallet_views/restore_wallet_view/sub_widgets/restore_failed_dialog.dart +++ b/lib/pages/add_wallet_views/restore_wallet_view/sub_widgets/restore_failed_dialog.dart @@ -63,12 +63,8 @@ class _RestoreFailedDialogState extends ConsumerState { style: STextStyles.itemSubtitle12(context), ), onPressed: () async { - ref.read(pWallets.notifier).removeWallet(walletId: walletId); + await ref.read(pWallets).deleteWallet(walletId); - await ref.read(walletsServiceChangeNotifierProvider).deleteWallet( - walletName, - false, - ); if (mounted) { Navigator.of(context).pop(); } diff --git a/lib/pages/add_wallet_views/select_wallet_for_token_view.dart b/lib/pages/add_wallet_views/select_wallet_for_token_view.dart index 05b84f1f8..c395bbf7d 100644 --- a/lib/pages/add_wallet_views/select_wallet_for_token_view.dart +++ b/lib/pages/add_wallet_views/select_wallet_for_token_view.dart @@ -16,11 +16,10 @@ import 'package:stackwallet/models/add_wallet_list_entity/sub_classes/eth_token_ import 'package:stackwallet/pages/add_wallet_views/add_token_view/edit_wallet_tokens_view.dart'; import 'package:stackwallet/pages/add_wallet_views/create_or_restore_wallet_view/create_or_restore_wallet_view.dart'; import 'package:stackwallet/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart'; -import 'package:stackwallet/providers/global/wallets_service_provider.dart'; -import 'package:stackwallet/services/wallets_service.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/all_wallets_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -54,8 +53,6 @@ class SelectWalletForTokenView extends ConsumerStatefulWidget { class _SelectWalletForTokenViewState extends ConsumerState { final isDesktop = Util.isDesktop; - late final List ethWalletIds; - bool _hasEthWallets = false; String? _selectedWalletId; @@ -77,18 +74,19 @@ class _SelectWalletForTokenViewState ); } - late int _cachedWalletCount; + @override + Widget build(BuildContext context) { + final ethWalletInfos = ref + .watch(pAllWalletsInfo) + .where((e) => e.coin == widget.entity.coin) + .toList(); - void _updateWalletsList(Map walletsData) { - _cachedWalletCount = walletsData.length; + final _hasEthWallets = ethWalletInfos.isNotEmpty; - walletsData.removeWhere((key, value) => value.coin != widget.entity.coin); - ethWalletIds.clear(); - - _hasEthWallets = walletsData.isNotEmpty; + final List ethWalletIds = []; // TODO: proper wallet data class instead of this Hive silliness - for (final walletId in walletsData.values.map((e) => e.walletId).toList()) { + for (final walletId in ethWalletInfos.map((e) => e.walletId).toList()) { final walletContracts = DB.instance.get( boxName: walletId, key: DBKeys.ethTokenContracts, @@ -98,28 +96,6 @@ class _SelectWalletForTokenViewState ethWalletIds.add(walletId); } } - } - - @override - void initState() { - ethWalletIds = []; - - final walletsData = - ref.read(walletsServiceChangeNotifierProvider).fetchWalletsData(); - _updateWalletsList(walletsData); - - super.initState(); - } - - @override - Widget build(BuildContext context) { - // dumb hack - ref.watch(newEthWalletTriggerTempUntilHiveCompletelyDeleted); - final walletsData = - ref.read(walletsServiceChangeNotifierProvider).fetchWalletsData(); - if (walletsData.length != _cachedWalletCount) { - _updateWalletsList(walletsData); - } return WillPopScope( onWillPop: () async { diff --git a/lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart b/lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart index 2e001f3ee..424f83e53 100644 --- a/lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart +++ b/lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart @@ -24,14 +24,16 @@ import 'package:stackwallet/pages/add_wallet_views/verify_recovery_phrase_view/v import 'package:stackwallet/pages/home_view/home_view.dart'; import 'package:stackwallet/pages_desktop_specific/desktop_home_view.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/exit_to_my_stack_button.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; import 'package:stackwallet/widgets/desktop/desktop_scaffold.dart'; @@ -42,13 +44,13 @@ final createSpecialEthWalletRoutingFlag = StateProvider((ref) => false); class VerifyRecoveryPhraseView extends ConsumerStatefulWidget { const VerifyRecoveryPhraseView({ Key? key, - required this.manager, + required this.wallet, required this.mnemonic, }) : super(key: key); static const routeName = "/verifyRecoveryPhrase"; - final Manager manager; + final Wallet wallet; final List mnemonic; @override @@ -60,13 +62,13 @@ class _VerifyRecoveryPhraseViewState extends ConsumerState // with WidgetsBindingObserver { - late Manager _manager; + late Wallet _wallet; late List _mnemonic; late final bool isDesktop; @override void initState() { - _manager = widget.manager; + _wallet = widget.wallet; _mnemonic = widget.mnemonic; isDesktop = Util.isDesktop; // WidgetsBinding.instance?.addObserver(this); @@ -119,13 +121,11 @@ class _VerifyRecoveryPhraseViewState } } - await ref.read(walletsServiceChangeNotifierProvider).setMnemonicVerified( - walletId: _manager.walletId, + await ref.read(pWalletInfo(_wallet.walletId)).setMnemonicVerified( + isar: ref.read(mainDBProvider).isar, ); - ref - .read(pWallets.notifier) - .addWallet(walletId: _manager.walletId, manager: _manager); + ref.read(pWallets).addWallet(_wallet); final isCreateSpecialEthWallet = ref.read(createSpecialEthWalletRoutingFlag); @@ -153,11 +153,11 @@ class _VerifyRecoveryPhraseViewState DesktopHomeView.routeName, ), ); - if (widget.manager.coin == Coin.ethereum) { + if (widget.wallet.info.coin == Coin.ethereum) { unawaited( Navigator.of(context).pushNamed( EditWalletTokensView.routeName, - arguments: widget.manager.walletId, + arguments: widget.wallet.walletId, ), ); } @@ -176,11 +176,11 @@ class _VerifyRecoveryPhraseViewState (route) => false, ), ); - if (widget.manager.coin == Coin.ethereum) { + if (widget.wallet.info.coin == Coin.ethereum) { unawaited( Navigator.of(context).pushNamed( EditWalletTokensView.routeName, - arguments: widget.manager.walletId, + arguments: widget.wallet.walletId, ), ); } @@ -260,10 +260,8 @@ class _VerifyRecoveryPhraseViewState } Future delete() async { - await ref - .read(walletsServiceChangeNotifierProvider) - .deleteWallet(_manager.walletName, false); - await _manager.exitCurrentWallet(); + await _wallet.exit(); + await ref.read(pWallets).deleteWallet(_wallet.walletId); } @override diff --git a/lib/pages/address_book_views/address_book_view.dart b/lib/pages/address_book_views/address_book_view.dart index 1b88f3bc1..009077f71 100644 --- a/lib/pages/address_book_views/address_book_view.dart +++ b/lib/pages/address_book_views/address_book_view.dart @@ -79,14 +79,14 @@ class _AddressBookViewState extends ConsumerState { WidgetsBinding.instance.addPostFrameCallback((_) async { List addresses = []; - final managers = ref.read(pWallets).managers; - for (final manager in managers) { + final wallets = ref.read(pWallets).wallets; + for (final wallet in wallets) { addresses.add( ContactAddressEntry() - ..coinName = manager.coin.name - ..address = await manager.currentReceivingAddress + ..coinName = wallet.info.coin.name + ..address = (await wallet.getCurrentReceivingAddress())!.value ..label = "Current Receiving" - ..other = manager.walletName, + ..other = wallet.info.name, ); } final self = ContactEntry( diff --git a/lib/pages/address_book_views/subviews/contact_details_view.dart b/lib/pages/address_book_views/subviews/contact_details_view.dart index 29e9d77bb..419081f2b 100644 --- a/lib/pages/address_book_views/subviews/contact_details_view.dart +++ b/lib/pages/address_book_views/subviews/contact_details_view.dart @@ -15,16 +15,14 @@ import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; import 'package:isar/isar.dart'; -import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/isar_models.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/pages/address_book_views/subviews/add_new_contact_address_view.dart'; import 'package:stackwallet/pages/address_book_views/subviews/edit_contact_address_view.dart'; import 'package:stackwallet/pages/address_book_views/subviews/edit_contact_name_emoji_view.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/address_book_service_provider.dart'; -import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/ui/address_book_providers/address_entry_data_provider.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; @@ -63,29 +61,33 @@ class _ContactDetailsViewState extends ConsumerState { List> _cachedTransactions = []; - Future>> _filteredTransactionsByContact( - List managers, - ) async { + Future>> + _filteredTransactionsByContact() async { final contact = ref.read(addressBookServiceProvider).getContactById(_contactId); // TODO: optimise - List> result = []; - for (final manager in managers) { - final transactions = await MainDB.instance - .getTransactions(manager.walletId) - .filter() - .anyOf(contact.addresses.map((e) => e.address), - (q, String e) => q.address((q) => q.valueEqualTo(e))) - .sortByTimestampDesc() - .findAll(); + final transactions = await ref + .read(mainDBProvider) + .isar + .transactions + .where() + .filter() + .anyOf(contact.addresses.map((e) => e.address), + (q, String e) => q.address((q) => q.valueEqualTo(e))) + .sortByTimestampDesc() + .findAll(); - for (final tx in transactions) { - result.add(Tuple2(manager.walletId, tx)); - } + List> result = []; + + for (final tx in transactions) { + result.add(Tuple2(tx.walletId, tx)); } + // sort by date + result.sort((a, b) => b.item2.timestamp - a.item2.timestamp); + return result; } @@ -461,8 +463,7 @@ class _ContactDetailsViewState extends ConsumerState { height: 12, ), FutureBuilder( - future: _filteredTransactionsByContact( - ref.watch(pWallets).managers), + future: _filteredTransactionsByContact(), builder: (_, AsyncSnapshot>> snapshot) { diff --git a/lib/pages/address_book_views/subviews/contact_popup.dart b/lib/pages/address_book_views/subviews/contact_popup.dart index 46a3e947e..ca91001c4 100644 --- a/lib/pages/address_book_views/subviews/contact_popup.dart +++ b/lib/pages/address_book_views/subviews/contact_popup.dart @@ -19,6 +19,7 @@ import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/pages/address_book_views/subviews/contact_details_view.dart'; import 'package:stackwallet/pages/exchange_view/exchange_step_views/step_2_view.dart'; import 'package:stackwallet/pages/send_view/send_view.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/global/address_book_service_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; @@ -28,6 +29,7 @@ import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/clipboard_interface.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/rounded_container.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; import 'package:tuple/tuple.dart'; @@ -51,21 +53,15 @@ class ContactPopUp extends ConsumerWidget { final contact = ref.watch(addressBookServiceProvider .select((value) => value.getContactById(contactId))); - final active = ref - .read(pWallets) - .managers - .where((e) => e.isActiveWallet) - .toList(growable: false); + final active = ref.read(currentWalletIdProvider); - assert(active.isEmpty || active.length == 1); - - bool hasActiveWallet = active.length == 1; + bool hasActiveWallet = active != null; bool isExchangeFlow = ref.watch(exchangeFlowIsActiveStateProvider.state).state; final addresses = contact.addressesSorted.where((e) { if (hasActiveWallet && !isExchangeFlow) { - return e.coin == active[0].coin; + return e.coin == ref.watch(pWalletCoin(active)); } else { return true; } @@ -201,7 +197,7 @@ class ContactPopUp extends ConsumerWidget { child: RoundedWhiteContainer( child: Center( child: Text( - "No ${active[0].coin.prettyName} addresses found", + "No ${ref.watch(pWalletCoin(active!)).prettyName} addresses found", style: STextStyles.itemSubtitle(context), ), @@ -372,8 +368,9 @@ class ContactPopUp extends ConsumerWidget { .pushNamed( SendView.routeName, arguments: Tuple3( - active[0].walletId, - active[0].coin, + active, + ref.read( + pWalletCoin(active)), SendViewAutoFillData( address: address, contactLabel: diff --git a/lib/pages/buy_view/buy_form.dart b/lib/pages/buy_view/buy_form.dart index 5ff4d85a3..d986a1e3c 100644 --- a/lib/pages/buy_view/buy_form.dart +++ b/lib/pages/buy_view/buy_form.dart @@ -1160,14 +1160,14 @@ class _BuyFormState extends ConsumerState { ) .then((value) async { if (value is String) { - final manager = - ref.read(pWallets).getManager(value); + final wallet = ref.read(pWallets).getWallet(value); // _toController.text = manager.walletName; // model.recipientAddress = // await manager.currentReceivingAddress; _receiveAddressController.text = - await manager.currentReceivingAddress; + (await wallet.getCurrentReceivingAddress())! + .value; setState(() { _addressToggleFlag = diff --git a/lib/pages/cashfusion/cashfusion_view.dart b/lib/pages/cashfusion/cashfusion_view.dart index 218ddb25f..0ae226600 100644 --- a/lib/pages/cashfusion/cashfusion_view.dart +++ b/lib/pages/cashfusion/cashfusion_view.dart @@ -61,8 +61,8 @@ class _CashFusionViewState extends ConsumerState { FusionOption _option = FusionOption.continuous; Future _startFusion() async { - final fusionWallet = ref.read(pWallets).getManager(widget.walletId).wallet - as FusionWalletInterface; + final fusionWallet = + ref.read(pWallets).getWallet(widget.walletId) as FusionWalletInterface; try { fusionWallet.uiState = ref.read( diff --git a/lib/pages/cashfusion/fusion_progress_view.dart b/lib/pages/cashfusion/fusion_progress_view.dart index e490b9d2f..1823b2bd5 100644 --- a/lib/pages/cashfusion/fusion_progress_view.dart +++ b/lib/pages/cashfusion/fusion_progress_view.dart @@ -67,7 +67,7 @@ class _FusionProgressViewState extends ConsumerState { ); if (shouldCancel == true && mounted) { - final fusionWallet = ref.read(pWallets).getManager(widget.walletId).wallet + final fusionWallet = ref.read(pWallets).getWallet(widget.walletId) as FusionWalletInterface; await showLoading( @@ -223,8 +223,8 @@ class _FusionProgressViewState extends ConsumerState { /// Fuse again. void _fuseAgain() async { - final fusionWallet = ref.read(pWallets).getManager(widget.walletId).wallet - as FusionWalletInterface; + final fusionWallet = + ref.read(pWallets).getWallet(widget.walletId) as FusionWalletInterface; final fusionInfo = ref.read(prefsChangeNotifierProvider).fusionServerInfo; diff --git a/lib/pages/coin_control/coin_control_view.dart b/lib/pages/coin_control/coin_control_view.dart index 9b8476fdd..930e2f1ff 100644 --- a/lib/pages/coin_control/coin_control_view.dart +++ b/lib/pages/coin_control/coin_control_view.dart @@ -27,6 +27,7 @@ import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/animated_widgets/rotate_icon.dart'; import 'package:stackwallet/widgets/app_bar_field.dart'; import 'package:stackwallet/widgets/background.dart'; @@ -82,10 +83,8 @@ class _CoinControlViewState extends ConsumerState { final Set _selectedBlocked = {}; Future _refreshBalance() async { - final coinControlInterface = ref - .read(pWallets) - .getManager(widget.walletId) - .wallet as CoinControlInterface; + final coinControlInterface = + ref.read(pWallets).getWallet(widget.walletId) as CoinControlInterface; await coinControlInterface.refreshBalance(notify: true); } @@ -113,25 +112,8 @@ class _CoinControlViewState extends ConsumerState { Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final coin = ref.watch( - pWallets.select( - (value) => value - .getManager( - widget.walletId, - ) - .coin, - ), - ); - - final currentChainHeight = ref.watch( - pWallets.select( - (value) => value - .getManager( - widget.walletId, - ) - .currentHeight, - ), - ); + final coin = ref.watch(pWalletCoin(widget.walletId)); + final currentHeight = ref.watch(pWalletChainHeight(widget.walletId)); if (_sort == CCSortDescriptor.address && !_isSearching) { _list = null; @@ -357,7 +339,7 @@ class _CoinControlViewState extends ConsumerState { (widget.type == CoinControlViewType.use && !utxo.isBlocked && utxo.isConfirmed( - currentChainHeight, + currentHeight, coin.requiredConfirmations, )), initialSelectedState: isSelected, @@ -420,7 +402,7 @@ class _CoinControlViewState extends ConsumerState { CoinControlViewType.use && !_showBlocked && utxo.isConfirmed( - currentChainHeight, + currentHeight, coin.requiredConfirmations, )), initialSelectedState: isSelected, @@ -562,7 +544,7 @@ class _CoinControlViewState extends ConsumerState { .use && !utxo.isBlocked && utxo.isConfirmed( - currentChainHeight, + currentHeight, coin.requiredConfirmations, )), initialSelectedState: isSelected, diff --git a/lib/pages/coin_control/utxo_card.dart b/lib/pages/coin_control/utxo_card.dart index cedf56590..1529263c7 100644 --- a/lib/pages/coin_control/utxo_card.dart +++ b/lib/pages/coin_control/utxo_card.dart @@ -12,12 +12,13 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/isar_models.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; import 'package:stackwallet/utilities/constants.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/icon_widgets/utxo_status_icon.dart'; import 'package:stackwallet/widgets/rounded_container.dart'; @@ -63,11 +64,8 @@ class _UtxoCardState extends ConsumerState { Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final coin = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId).coin)); - - final currentChainHeight = ref.watch(pWallets - .select((value) => value.getManager(widget.walletId).currentHeight)); + final coin = ref.watch(pWalletCoin(widget.walletId)); + final currentHeight = ref.watch(pWalletChainHeight(widget.walletId)); return ConditionalParent( condition: widget.onPressed != null, @@ -112,7 +110,7 @@ class _UtxoCardState extends ConsumerState { child: UTXOStatusIcon( blocked: utxo.isBlocked, status: utxo.isConfirmed( - currentChainHeight, + currentHeight, coin.requiredConfirmations, ) ? UTXOStatusIconStatus.confirmed diff --git a/lib/pages/coin_control/utxo_details_view.dart b/lib/pages/coin_control/utxo_details_view.dart index 9048abeaa..5158071b7 100644 --- a/lib/pages/coin_control/utxo_details_view.dart +++ b/lib/pages/coin_control/utxo_details_view.dart @@ -16,12 +16,13 @@ import 'package:isar/isar.dart'; import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/isar_models.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/transaction_details_view.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -90,17 +91,8 @@ class _UtxoDetailsViewState extends ConsumerState { @override Widget build(BuildContext context) { - final coin = ref.watch( - pWallets.select( - (value) => value.getManager(widget.walletId).coin, - ), - ); - - final currentHeight = ref.watch( - pWallets.select( - (value) => value.getManager(widget.walletId).currentHeight, - ), - ); + final coin = ref.watch(pWalletCoin(widget.walletId)); + final currentHeight = ref.watch(pWalletChainHeight(widget.walletId)); final confirmed = utxo!.isConfirmed( currentHeight, diff --git a/lib/pages/exchange_view/choose_from_stack_view.dart b/lib/pages/exchange_view/choose_from_stack_view.dart index 524ee5499..553c11628 100644 --- a/lib/pages/exchange_view/choose_from_stack_view.dart +++ b/lib/pages/exchange_view/choose_from_stack_view.dart @@ -15,6 +15,7 @@ import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; @@ -48,7 +49,11 @@ class _ChooseFromStackViewState extends ConsumerState { @override Widget build(BuildContext context) { final walletIds = ref - .watch(pWallets.select((value) => value.getWalletIdsFor(coin: coin))); + .watch(pWallets) + .wallets + .where((e) => e.info.coin == coin) + .map((e) => e.walletId) + .toList(); return Background( child: Scaffold( @@ -78,8 +83,7 @@ class _ChooseFromStackViewState extends ConsumerState { : ListView.builder( itemCount: walletIds.length, itemBuilder: (context, index) { - final manager = ref.watch(pWallets - .select((value) => value.getManager(walletIds[index]))); + final walletId = walletIds[index]; return Padding( padding: const EdgeInsets.symmetric(vertical: 5.0), @@ -98,7 +102,7 @@ class _ChooseFromStackViewState extends ConsumerState { elevation: 0, onPressed: () async { if (mounted) { - Navigator.of(context).pop(manager.walletId); + Navigator.of(context).pop(walletId); } }, child: RoundedWhiteContainer( @@ -115,7 +119,7 @@ class _ChooseFromStackViewState extends ConsumerState { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - manager.walletName, + ref.watch(pWalletName(walletId)), style: STextStyles.titleBold12(context), overflow: TextOverflow.ellipsis, ), diff --git a/lib/pages/exchange_view/confirm_change_now_send.dart b/lib/pages/exchange_view/confirm_change_now_send.dart index 3aeba301a..545f8b73a 100644 --- a/lib/pages/exchange_view/confirm_change_now_send.dart +++ b/lib/pages/exchange_view/confirm_change_now_send.dart @@ -20,14 +20,16 @@ import 'package:stackwallet/pages/wallet_view/wallet_view.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/route_generator.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; import 'package:stackwallet/utilities/constants.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -43,7 +45,7 @@ import 'package:uuid/uuid.dart'; class ConfirmChangeNowSendView extends ConsumerStatefulWidget { const ConfirmChangeNowSendView({ Key? key, - required this.transactionInfo, + required this.txData, required this.walletId, this.routeOnSuccessName = WalletView.routeName, required this.trade, @@ -53,7 +55,7 @@ class ConfirmChangeNowSendView extends ConsumerStatefulWidget { static const String routeName = "/confirmChangeNowSend"; - final Map transactionInfo; + final TxData txData; final String walletId; final String routeOnSuccessName; final Trade trade; @@ -67,7 +69,6 @@ class ConfirmChangeNowSendView extends ConsumerStatefulWidget { class _ConfirmChangeNowSendViewState extends ConsumerState { - late final Map transactionInfo; late final String walletId; late final String routeOnSuccessName; late final Trade trade; @@ -75,7 +76,8 @@ class _ConfirmChangeNowSendViewState final isDesktop = Util.isDesktop; Future _attemptSend(BuildContext context) async { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); + final coin = wallet.info.coin; final sendProgressController = ProgressAndSuccessController(); @@ -86,7 +88,7 @@ class _ConfirmChangeNowSendViewState barrierDismissible: false, builder: (context) { return SendingTransactionDialog( - coin: manager.coin, + coin: coin, controller: sendProgressController, ); }, @@ -100,19 +102,21 @@ class _ConfirmChangeNowSendViewState ); late String txid; - Future txidFuture; + Future txidFuture; - final String note = transactionInfo["note"] as String? ?? ""; + final String note = widget.txData.note ?? ""; try { if (widget.shouldSendPublicFiroFunds == true) { - txidFuture = (manager.wallet as FiroWallet) - .confirmSendPublic(txData: transactionInfo); + // TODO: [prio=high] fixme + throw UnimplementedError("fixme"); + // txidFuture = (wallet as FiroWallet) + // .confirmSendPublic(txData: widget.txData); } else { - txidFuture = manager.confirmSend(txData: transactionInfo); + txidFuture = wallet.confirmSend(txData: widget.txData); } - unawaited(manager.refresh()); + unawaited(wallet.refresh()); final results = await Future.wait([ txidFuture, @@ -122,7 +126,7 @@ class _ConfirmChangeNowSendViewState sendProgressController.triggerSuccess?.call(); await Future.delayed(const Duration(seconds: 5)); - txid = results.first as String; + txid = (results.first as TxData).txid!; // save note await ref @@ -197,7 +201,7 @@ class _ConfirmChangeNowSendViewState Future _confirmSend() async { final dynamic unlocked; - final coin = ref.read(pWallets).getManager(walletId).coin; + final coin = ref.read(pWalletCoin(walletId)); if (Util.isDesktop) { unlocked = await showDialog( @@ -254,7 +258,6 @@ class _ConfirmChangeNowSendViewState @override void initState() { - transactionInfo = widget.transactionInfo; walletId = widget.walletId; routeOnSuccessName = widget.routeOnSuccessName; trade = widget.trade; @@ -263,9 +266,6 @@ class _ConfirmChangeNowSendViewState @override Widget build(BuildContext context) { - final managerProvider = ref - .watch(pWallets.select((value) => value.getManagerProvider(walletId))); - return ConditionalParent( condition: !isDesktop, builder: (child) { @@ -337,7 +337,7 @@ class _ConfirmChangeNowSendViewState width: 12, ), Text( - "Confirm ${ref.watch(managerProvider.select((value) => value.coin)).ticker} transaction", + "Confirm ${ref.watch(pWalletCoin(walletId)).ticker} transaction", style: STextStyles.desktopH3(context), ) ], @@ -381,18 +381,9 @@ class _ConfirmChangeNowSendViewState children: [ Text( ref - .watch(pAmountFormatter(ref.watch( - managerProvider.select((value) => value.coin), - ))) - .format(transactionInfo["fee"] is Amount - ? transactionInfo["fee"] as Amount - : (transactionInfo["fee"] as int) - .toAmountAsRaw( - fractionDigits: ref.watch( - managerProvider.select( - (value) => value.coin.decimals), - ), - )), + .watch(pAmountFormatter( + ref.watch(pWalletCoin(walletId)))) + .format(widget.txData.fee!), style: STextStyles.desktopTextExtraExtraSmall(context) .copyWith( @@ -424,17 +415,9 @@ class _ConfirmChangeNowSendViewState ), Builder( builder: (context) { - final coin = ref.watch( - managerProvider.select((value) => value.coin), - ); - final fee = transactionInfo["fee"] is Amount - ? transactionInfo["fee"] as Amount - : (transactionInfo["fee"] as int) - .toAmountAsRaw( - fractionDigits: coin.decimals, - ); - final amount = - transactionInfo["recipientAmt"] as Amount; + final coin = ref.read(pWalletCoin(walletId)); + final fee = widget.txData.fee!; + final amount = widget.txData.amount!; final total = amount + fee; return Text( @@ -506,7 +489,7 @@ class _ConfirmChangeNowSendViewState ), ), child: Text( - "Send ${ref.watch(managerProvider.select((value) => value.coin)).ticker}", + "Send ${ref.watch(pWalletCoin(walletId)).ticker}", style: isDesktop ? STextStyles.desktopTextMedium(context) : STextStyles.pageTitleH1(context), @@ -533,7 +516,7 @@ class _ConfirmChangeNowSendViewState height: 4, ), Text( - ref.watch(pWallets).getManager(walletId).walletName, + ref.watch(pWalletName(walletId)), style: STextStyles.itemSubtitle12(context), ), ], @@ -560,7 +543,7 @@ class _ConfirmChangeNowSendViewState height: 4, ), Text( - "${transactionInfo["address"] ?? "ERROR"}", + widget.txData.recipients!.first.address, style: STextStyles.itemSubtitle12(context), ), ], @@ -589,13 +572,11 @@ class _ConfirmChangeNowSendViewState children: [ child, Builder(builder: (context) { - final coin = ref.watch(pWallets.select( - (value) => value.getManager(walletId).coin)); + final coin = ref.watch(pWalletCoin(walletId)); final price = ref.watch( priceAnd24hChangeNotifierProvider .select((value) => value.getPrice(coin))); - final amount = - transactionInfo["recipientAmt"] as Amount; + final amount = widget.txData.amount!; final value = (price.item1 * amount.decimal) .toAmount(fractionDigits: 2); final currency = ref.watch(prefsChangeNotifierProvider @@ -621,9 +602,9 @@ class _ConfirmChangeNowSendViewState ), child: Text( ref - .watch(pAmountFormatter(ref.watch(pWallets.select( - (value) => value.getManager(walletId).coin)))) - .format((transactionInfo["recipientAmt"] as Amount)), + .watch(pAmountFormatter( + ref.watch(pWalletCoin(walletId)))) + .format((widget.txData.amount!)), style: STextStyles.itemSubtitle12(context), textAlign: TextAlign.right, ), @@ -650,18 +631,10 @@ class _ConfirmChangeNowSendViewState ), Text( ref - .watch(pAmountFormatter(ref.watch( - managerProvider.select((value) => value.coin), - ))) + .watch( + pAmountFormatter(ref.read(pWalletCoin(walletId)))) .format( - (transactionInfo["fee"] is Amount - ? transactionInfo["fee"] as Amount - : (transactionInfo["fee"] as int).toAmountAsRaw( - fractionDigits: ref.watch( - managerProvider.select( - (value) => value.coin.decimals, - ), - ))), + widget.txData.fee!, ), style: STextStyles.itemSubtitle12(context), textAlign: TextAlign.right, @@ -690,7 +663,7 @@ class _ConfirmChangeNowSendViewState height: 4, ), Text( - transactionInfo["note"] as String? ?? "", + widget.txData.note ?? "", style: STextStyles.itemSubtitle12(context), ), ], @@ -743,16 +716,9 @@ class _ConfirmChangeNowSendViewState ), Builder( builder: (context) { - final coin = ref.watch( - managerProvider.select((value) => value.coin), - ); - final fee = transactionInfo["fee"] is Amount - ? transactionInfo["fee"] as Amount - : (transactionInfo["fee"] as int).toAmountAsRaw( - fractionDigits: coin.decimals, - ); - final amount = - transactionInfo["recipientAmt"] as Amount; + final coin = ref.watch(pWalletCoin(walletId)); + final fee = widget.txData.fee!; + final amount = widget.txData.amount!; final total = amount + fee; return Text( diff --git a/lib/pages/exchange_view/exchange_step_views/step_2_view.dart b/lib/pages/exchange_view/exchange_step_views/step_2_view.dart index e30f1b527..7a7058648 100644 --- a/lib/pages/exchange_view/exchange_step_views/step_2_view.dart +++ b/lib/pages/exchange_view/exchange_step_views/step_2_view.dart @@ -97,10 +97,10 @@ class _Step2ViewState extends ConsumerState { tuple.item2.ticker.toLowerCase()) { ref .read(pWallets) - .getManager(tuple.item1) - .currentReceivingAddress + .getWallet(tuple.item1) + .getCurrentReceivingAddress() .then((value) { - _toController.text = value; + _toController.text = value!.value; model.recipientAddress = _toController.text; }); } else { @@ -108,10 +108,10 @@ class _Step2ViewState extends ConsumerState { tuple.item2.ticker.toUpperCase()) { ref .read(pWallets) - .getManager(tuple.item1) - .currentReceivingAddress + .getWallet(tuple.item1) + .getCurrentReceivingAddress() .then((value) { - _refundController.text = value; + _refundController.text = value!.value; model.refundAddress = _refundController.text; }); } @@ -218,14 +218,14 @@ class _Step2ViewState extends ConsumerState { ) .then((value) async { if (value is String) { - final manager = ref + final wallet = ref .read(pWallets) - .getManager(value); + .getWallet(value); - _toController.text = - manager.walletName; - model.recipientAddress = await manager - .currentReceivingAddress; + _toController.text = wallet.info.name; + model.recipientAddress = (await wallet + .getCurrentReceivingAddress())! + .value; setState(() { enableNext = @@ -489,14 +489,15 @@ class _Step2ViewState extends ConsumerState { ) .then((value) async { if (value is String) { - final manager = ref + final wallet = ref .read(pWallets) - .getManager(value); + .getWallet(value); _refundController.text = - manager.walletName; - model.refundAddress = await manager - .currentReceivingAddress; + wallet.info.name; + model.refundAddress = (await wallet + .getCurrentReceivingAddress())! + .value; } setState(() { enableNext = diff --git a/lib/pages/exchange_view/exchange_step_views/step_4_view.dart b/lib/pages/exchange_view/exchange_step_views/step_4_view.dart index 4ba819b5e..38959ba3b 100644 --- a/lib/pages/exchange_view/exchange_step_views/step_4_view.dart +++ b/lib/pages/exchange_view/exchange_step_views/step_4_view.dart @@ -35,6 +35,7 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/secondary_button.dart'; @@ -72,8 +73,8 @@ class _Step4ViewState extends ConsumerState { final coin = coinFromTickerCaseInsensitive(ticker); return ref .read(pWallets) - .managers - .where((element) => element.coin == coin) + .wallets + .where((e) => e.info.coin == coin) .isNotEmpty; } catch (_) { return false; @@ -134,8 +135,7 @@ class _Step4ViewState extends ConsumerState { } Future _showSendFromFiroBalanceSelectSheet(String walletId) async { - final firoWallet = - ref.read(pWallets).getManager(walletId).wallet as FiroWallet; + final firoWallet = ref.read(pWallets).getWallet(walletId) as FiroWallet; final locale = ref.read(localeServiceChangeNotifierProvider).locale; return await showModalBottomSheet( @@ -204,10 +204,10 @@ class _Step4ViewState extends ConsumerState { firoPublicSend = false; } - final manager = ref.read(pWallets).getManager(tuple.item1); + final wallet = ref.read(pWallets).getWallet(tuple.item1); final Amount amount = model.sendAmount.toAmount( - fractionDigits: manager.coin.decimals, + fractionDigits: wallet.info.coin.decimals, ); final address = model.trade!.payInAddress; @@ -222,7 +222,7 @@ class _Step4ViewState extends ConsumerState { barrierDismissible: false, builder: (context) { return BuildingTransactionDialog( - coin: manager.coin, + coin: wallet.info.coin, onCancel: () { wasCancelled = true; }, @@ -237,32 +237,36 @@ class _Step4ViewState extends ConsumerState { ), ); - Future> txDataFuture; + Future txDataFuture; if (firoPublicSend) { - txDataFuture = (manager.wallet as FiroWallet).prepareSendPublic( - address: address, - amount: amount, - args: { - "feeRate": FeeRateType.average, - // ref.read(feeRateTypeStateProvider) - }, - ); + // TODO: [prio=high] + throw UnimplementedError(); + // txDataFuture = (wallet as FiroWallet).prepareSendPublic( + // address: address, + // amount: amount, + // args: { + // "feeRate": FeeRateType.average, + // // ref.read(feeRateTypeStateProvider) + // }, + // ); } else { - final memo = - manager.coin == Coin.stellar || manager.coin == Coin.stellarTestnet - ? model.trade!.payInExtraId.isNotEmpty - ? model.trade!.payInExtraId - : null - : null; - txDataFuture = manager.prepareSend( - address: address, - amount: amount, - args: { - "memo": memo, - "feeRate": FeeRateType.average, - // ref.read(feeRateTypeStateProvider) - }, + final memo = wallet.info.coin == Coin.stellar || + wallet.info.coin == Coin.stellarTestnet + ? model.trade!.payInExtraId.isNotEmpty + ? model.trade!.payInExtraId + : null + : null; + txDataFuture = wallet.prepareSend( + txData: TxData( + recipients: [ + (address: address, amount: amount), + ], + memo: memo, + feeRateType: FeeRateType.average, + note: "${model.trade!.payInCurrency.toUpperCase()}/" + "${model.trade!.payOutCurrency.toUpperCase()} exchange", + ), ); } @@ -271,7 +275,7 @@ class _Step4ViewState extends ConsumerState { time, ]); - final txData = results.first as Map; + final txData = results.first as TxData; if (!wasCancelled) { // pop building dialog @@ -280,17 +284,13 @@ class _Step4ViewState extends ConsumerState { Navigator.of(context).pop(); } - txData["note"] = - "${model.trade!.payInCurrency.toUpperCase()}/${model.trade!.payOutCurrency.toUpperCase()} exchange"; - txData["address"] = address; - if (mounted) { unawaited( Navigator.of(context).push( RouteGenerator.getRoute( shouldUseMaterialRoute: RouteGenerator.useMaterialPageRoute, builder: (_) => ConfirmChangeNowSendView( - transactionInfo: txData, + txData: txData, walletId: tuple.item1, routeOnSuccessName: HomeView.routeName, trade: model.trade!, @@ -813,8 +813,9 @@ class _Step4ViewState extends ConsumerState { tuple.item2.ticker.toLowerCase()) { final walletName = ref .read(pWallets) - .getManager(tuple.item1) - .walletName; + .getWallet(tuple.item1) + .info + .name; buttonTitle = "Send from $walletName"; } diff --git a/lib/pages/exchange_view/exchange_view.dart b/lib/pages/exchange_view/exchange_view.dart index de815ac07..e13f97a8e 100644 --- a/lib/pages/exchange_view/exchange_view.dart +++ b/lib/pages/exchange_view/exchange_view.dart @@ -195,9 +195,9 @@ class _ExchangeViewState extends ConsumerState { if (txid != null && walletIds != null && walletIds.isNotEmpty) { - final manager = ref + final wallet = ref .read(pWallets) - .getManager(walletIds.first); + .getWallet(walletIds.first); //todo: check if print needed // debugPrint("name: ${manager.walletName}"); @@ -212,7 +212,7 @@ class _ExchangeViewState extends ConsumerState { unawaited(Navigator.of(context).pushNamed( TradeDetailsView.routeName, arguments: Tuple4(tradeId, tx, - walletIds.first, manager.walletName), + walletIds.first, wallet.info.name), )); } } else { diff --git a/lib/pages/exchange_view/send_from_view.dart b/lib/pages/exchange_view/send_from_view.dart index 0653f19c5..79410657f 100644 --- a/lib/pages/exchange_view/send_from_view.dart +++ b/lib/pages/exchange_view/send_from_view.dart @@ -22,7 +22,6 @@ import 'package:stackwallet/pages_desktop_specific/desktop_exchange/desktop_exch import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/route_generator.dart'; import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -33,6 +32,8 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -86,7 +87,11 @@ class _SendFromViewState extends ConsumerState { debugPrint("BUILD: $runtimeType"); final walletIds = ref - .watch(pWallets.select((value) => value.getWalletIdsFor(coin: coin))); + .watch(pWallets) + .wallets + .where((e) => e.info.coin == coin) + .map((e) => e.walletId) + .toList(); final isDesktop = Util.isDesktop; @@ -224,7 +229,9 @@ class _SendFromCardState extends ConsumerState { late final String address; late final Trade trade; - Future _send(Manager manager, {bool? shouldSendPublicFiroFunds}) async { + Future _send({bool? shouldSendPublicFiroFunds}) async { + final coin = ref.read(pWalletCoin(walletId)); + try { bool wasCancelled = false; @@ -245,7 +252,7 @@ class _SendFromCardState extends ConsumerState { ), ), child: BuildingTransactionDialog( - coin: manager.coin, + coin: coin, onCancel: () { wasCancelled = true; @@ -263,46 +270,54 @@ class _SendFromCardState extends ConsumerState { ), ); - Map txData; - Future> txDataFuture; + TxData txData; + Future txDataFuture; + + final wallet = ref.read(pWallets).getWallet(walletId); // if not firo then do normal send if (shouldSendPublicFiroFunds == null) { - final memo = - manager.coin == Coin.stellar || manager.coin == Coin.stellarTestnet - ? trade.payInExtraId.isNotEmpty - ? trade.payInExtraId - : null - : null; - txDataFuture = manager.prepareSend( - address: address, - amount: amount, - args: { - "memo": memo, - "feeRate": FeeRateType.average, - // ref.read(feeRateTypeStateProvider) - }, + final memo = coin == Coin.stellar || coin == Coin.stellarTestnet + ? trade.payInExtraId.isNotEmpty + ? trade.payInExtraId + : null + : null; + txDataFuture = wallet.prepareSend( + txData: TxData( + recipients: [ + ( + address: address, + amount: amount, + ), + ], + memo: memo, + feeRateType: FeeRateType.average, + ), ); } else { - final firoWallet = manager.wallet as FiroWallet; + final firoWallet = wallet as FiroWallet; // otherwise do firo send based on balance selected if (shouldSendPublicFiroFunds) { - txDataFuture = firoWallet.prepareSendPublic( - address: address, - amount: amount, - args: { - "feeRate": FeeRateType.average, - // ref.read(feeRateTypeStateProvider) - }, - ); + throw UnimplementedError(); + // txDataFuture = firoWallet.prepareSendPublic( + // address: address, + // amount: amount, + // args: { + // "feeRate": FeeRateType.average, + // // ref.read(feeRateTypeStateProvider) + // }, + // ); } else { - txDataFuture = firoWallet.prepareSend( - address: address, - amount: amount, - args: { - "feeRate": FeeRateType.average, - // ref.read(feeRateTypeStateProvider) - }, + txDataFuture = wallet.prepareSend( + txData: TxData( + recipients: [ + ( + address: address, + amount: amount, + ), + ], + feeRateType: FeeRateType.average, + ), ); } } @@ -312,7 +327,7 @@ class _SendFromCardState extends ConsumerState { time, ]); - txData = results.first as Map; + txData = results.first as TxData; if (!wasCancelled) { // pop building dialog @@ -324,16 +339,17 @@ class _SendFromCardState extends ConsumerState { ).pop(); } - txData["note"] = - "${trade.payInCurrency.toUpperCase()}/${trade.payOutCurrency.toUpperCase()} exchange"; - txData["address"] = address; + txData = txData.copyWith( + note: "${trade.payInCurrency.toUpperCase()}/" + "${trade.payOutCurrency.toUpperCase()} exchange", + ); if (mounted) { await Navigator.of(context).push( RouteGenerator.getRoute( shouldUseMaterialRoute: RouteGenerator.useMaterialPageRoute, builder: (_) => ConfirmChangeNowSendView( - transactionInfo: txData, + txData: txData, walletId: walletId, routeOnSuccessName: Util.isDesktop ? DesktopExchangeView.routeName @@ -396,13 +412,12 @@ class _SendFromCardState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = - ref.watch(ref.watch(pWallets.notifier).getManagerProvider(walletId)); + final wallet = ref.watch(pWallets).getWallet(walletId); final locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); - final coin = manager.coin; + final coin = ref.watch(pWalletCoin(walletId)); final isFiro = coin == Coin.firoTestNet || coin == Coin.firo; @@ -437,7 +452,6 @@ class _SendFromCardState extends ConsumerState { if (mounted) { unawaited( _send( - manager, shouldSendPublicFiroFunds: false, ), ); @@ -464,10 +478,9 @@ class _SendFromCardState extends ConsumerState { style: STextStyles.itemSubtitle(context), ), Text( - ref.watch(pAmountFormatter(coin)).format( - (manager.wallet as FiroWallet) - .availablePrivateBalance(), - ), + ref.watch(pAmountFormatter(coin)).format(ref + .watch(pWalletBalance(walletId)) + .spendable), style: STextStyles.itemSubtitle(context), ), ], @@ -500,7 +513,6 @@ class _SendFromCardState extends ConsumerState { if (mounted) { unawaited( _send( - manager, shouldSendPublicFiroFunds: true, ), ); @@ -528,8 +540,11 @@ class _SendFromCardState extends ConsumerState { ), Text( ref.watch(pAmountFormatter(coin)).format( - (manager.wallet as FiroWallet) - .availablePublicBalance()), + ref + .watch( + pWalletBalanceSecondary(walletId)) + .spendable, + ), style: STextStyles.itemSubtitle(context), ), ], @@ -568,7 +583,7 @@ class _SendFromCardState extends ConsumerState { onPressed: () async { if (mounted) { unawaited( - _send(manager), + _send(), ); } }, @@ -580,7 +595,7 @@ class _SendFromCardState extends ConsumerState { decoration: BoxDecoration( color: Theme.of(context) .extension()! - .colorForCoin(manager.coin) + .colorForCoin(coin) .withOpacity(0.5), borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, @@ -608,7 +623,7 @@ class _SendFromCardState extends ConsumerState { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - manager.walletName, + ref.watch(pWalletName(walletId)), style: STextStyles.titleBold12(context), ), if (!isFiro) @@ -617,9 +632,8 @@ class _SendFromCardState extends ConsumerState { ), if (!isFiro) Text( - ref - .watch(pAmountFormatter(coin)) - .format(manager.balance.spendable), + ref.watch(pAmountFormatter(coin)).format( + ref.watch(pWalletBalance(walletId)).spendable), style: STextStyles.itemSubtitle(context), ), ], diff --git a/lib/pages/manage_favorites_view/manage_favorites_view.dart b/lib/pages/manage_favorites_view/manage_favorites_view.dart index 737d83c2e..8cde4a583 100644 --- a/lib/pages/manage_favorites_view/manage_favorites_view.dart +++ b/lib/pages/manage_favorites_view/manage_favorites_view.dart @@ -10,11 +10,13 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/favourite_wallets_provider.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; import 'package:stackwallet/widgets/desktop/desktop_scaffold.dart'; @@ -61,8 +63,17 @@ class ManageFavoritesView extends StatelessWidget { body: isDesktop ? Consumer( builder: (_, ref, __) { - final favorites = ref.watch(favoritesProvider); - final nonFavorites = ref.watch(nonFavoritesProvider); + final favorites = ref.watch(pFavouriteWalletInfos); + print( + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); + + // todo [prio=??] do this differently + final nonFavorites = ref + .watch(pWallets) + .wallets + .map((e) => e.info) + .where((e) => !e.isFavourite) + .toList(); return Column( children: [ @@ -108,8 +119,7 @@ class ManageFavoritesView extends StatelessWidget { key: key, itemCount: favorites.length, itemBuilder: (builderContext, index) { - final walletId = - ref.read(favorites[index]).walletId; + final walletId = favorites[index].walletId; return Padding( key: Key( "manageFavoriteWalletsItem_$walletId", @@ -127,14 +137,43 @@ class ManageFavoritesView extends StatelessWidget { ); }, onReorder: (oldIndex, newIndex) { - ref - .read(walletsServiceChangeNotifierProvider) - .moveFavorite( - fromIndex: oldIndex, toIndex: newIndex); + final isar = ref.read(mainDBProvider).isar; - ref - .read(favoritesProvider) - .reorder(oldIndex, newIndex, true); + final actualIndex = + favorites[oldIndex].favouriteOrderIndex; + if (oldIndex > newIndex) { + for (int i = oldIndex - 1; i >= newIndex; i--) { + final next = favorites[i]; + next.updateIsFavourite( + true, + isar: isar, + customIndexOverride: + next.favouriteOrderIndex + 1, + ); + } + favorites[oldIndex].updateIsFavourite( + true, + isar: isar, + customIndexOverride: + actualIndex - (oldIndex - newIndex), + ); + } else { + for (int i = oldIndex + 1; i <= newIndex; i++) { + final next = favorites[i]; + next.updateIsFavourite( + true, + isar: isar, + customIndexOverride: + next.favouriteOrderIndex - 1, + ); + } + favorites[oldIndex].updateIsFavourite( + true, + isar: isar, + customIndexOverride: + actualIndex + (newIndex - oldIndex), + ); + } }, proxyDecorator: (child, index, animation) { return Material( @@ -176,8 +215,7 @@ class ManageFavoritesView extends StatelessWidget { itemBuilder: (buildContext, index) { // final walletId = ref.watch( // nonFavorites[index].select((value) => value.walletId)); - final walletId = - ref.read(nonFavorites[index]).walletId; + final walletId = nonFavorites[index].walletId; return Padding( key: Key( "manageNonFavoriteWalletsItem_$walletId", @@ -236,13 +274,12 @@ class ManageFavoritesView extends StatelessWidget { Expanded( child: Consumer( builder: (_, ref, __) { - final favorites = ref.watch(favoritesProvider); + final favorites = ref.watch(pFavouriteWalletInfos); return ReorderableListView.builder( key: key, itemCount: favorites.length, itemBuilder: (builderContext, index) { - final walletId = - ref.read(favorites[index]).walletId; + final walletId = favorites[index].walletId; return Padding( key: Key( "manageFavoriteWalletsItem_$walletId", @@ -254,14 +291,43 @@ class ManageFavoritesView extends StatelessWidget { ); }, onReorder: (oldIndex, newIndex) { - ref - .read(walletsServiceChangeNotifierProvider) - .moveFavorite( - fromIndex: oldIndex, toIndex: newIndex); + final isar = ref.read(mainDBProvider).isar; - ref - .read(favoritesProvider) - .reorder(oldIndex, newIndex, true); + final actualIndex = + favorites[oldIndex].favouriteOrderIndex; + if (oldIndex > newIndex) { + for (int i = oldIndex - 1; i >= newIndex; i--) { + final next = favorites[i]; + next.updateIsFavourite( + true, + isar: isar, + customIndexOverride: + next.favouriteOrderIndex + 1, + ); + } + favorites[oldIndex].updateIsFavourite( + true, + isar: isar, + customIndexOverride: + actualIndex - (oldIndex - newIndex), + ); + } else { + for (int i = oldIndex + 1; i <= newIndex; i++) { + final next = favorites[i]; + next.updateIsFavourite( + true, + isar: isar, + customIndexOverride: + next.favouriteOrderIndex - 1, + ); + } + favorites[oldIndex].updateIsFavourite( + true, + isar: isar, + customIndexOverride: + actualIndex + (newIndex - oldIndex), + ); + } }, proxyDecorator: (child, index, animation) { return Material( @@ -301,15 +367,20 @@ class ManageFavoritesView extends StatelessWidget { Expanded( child: Consumer( builder: (_, ref, __) { - final nonFavorites = ref.watch(nonFavoritesProvider); + // todo [prio=??] do this differently + final nonFavorites = ref + .watch(pWallets) + .wallets + .map((e) => e.info) + .where((e) => !e.isFavourite) + .toList(); return ListView.builder( itemCount: nonFavorites.length, itemBuilder: (buildContext, index) { // final walletId = ref.watch( // nonFavorites[index].select((value) => value.walletId)); - final walletId = - ref.read(nonFavorites[index]).walletId; + final walletId = nonFavorites[index].walletId; return Padding( key: Key( "manageNonFavoriteWalletsItem_$walletId", diff --git a/lib/pages/monkey/monkey_loaded_view.dart b/lib/pages/monkey/monkey_loaded_view.dart index 93c28b39a..5e222257e 100644 --- a/lib/pages/monkey/monkey_loaded_view.dart +++ b/lib/pages/monkey/monkey_loaded_view.dart @@ -146,7 +146,7 @@ // WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { // final address = await ref // .read(walletsChangeNotifierProvider) -// .getManager(walletId) +// .getWallet(walletId) // .currentReceivingAddress; // setState(() { // receivingAddress = address; @@ -164,8 +164,8 @@ // @override // Widget build(BuildContext context) { // final Coin coin = ref.watch(managerProvider.select((value) => value.coin)); -// final manager = ref.watch(walletsChangeNotifierProvider -// .select((value) => value.getManager(widget.walletId))); +// final wallet = ref.watch(walletsChangeNotifierProvider +// .select((value) => value.getWallet(widget.walletId))); // // List? imageBytes; // imageBytes = (manager.wallet as BananoWallet).getMonkeyImageBytes(); diff --git a/lib/pages/monkey/monkey_view.dart b/lib/pages/monkey/monkey_view.dart index d0f041937..093fab50c 100644 --- a/lib/pages/monkey/monkey_view.dart +++ b/lib/pages/monkey/monkey_view.dart @@ -13,10 +13,10 @@ import 'package:stackwallet/services/monkey_service.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; -import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/show_loading.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -48,8 +48,7 @@ class _MonkeyViewState extends ConsumerState { List? imageBytes; Future _updateWalletMonKey(Uint8List monKeyBytes) async { - final manager = ref.read(pWallets).getManager(walletId); - await (manager.wallet as BananoWallet) + await (ref.read(pWallets).getWallet(walletId) as BananoWallet) .updateMonkeyImageBytes(monKeyBytes.toList()); } @@ -81,8 +80,10 @@ class _MonkeyViewState extends ConsumerState { throw Exception("Failed to get documents directory to save monKey image"); } - final address = - await ref.read(pWallets).getManager(walletId).currentReceivingAddress; + final address = await ref + .read(pWallets) + .getWallet(walletId) + .getCurrentReceivingAddress(); final docPath = dir.path; String filePath = "$docPath/monkey_$address"; @@ -107,13 +108,12 @@ class _MonkeyViewState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); - final Coin coin = manager.coin; + final wallet = ref.watch(pWallets).getWallet(widget.walletId); + final coin = ref.watch(pWalletCoin(widget.walletId)); final bool isDesktop = Util.isDesktop; - imageBytes ??= (manager.wallet as BananoWallet).getMonkeyImageBytes(); + imageBytes ??= (wallet as BananoWallet).getMonkeyImageBytes(); return Background( child: ConditionalParent( @@ -341,7 +341,7 @@ class _MonkeyViewState extends ConsumerState { whileFuture: Future.wait([ _saveMonKeyToFile( bytes: Uint8List.fromList( - (manager.wallet as BananoWallet) + (wallet as BananoWallet) .getMonkeyImageBytes()!), ), Future.delayed( @@ -383,21 +383,21 @@ class _MonkeyViewState extends ConsumerState { bool didError = false; await showLoading( whileFuture: Future.wait([ - manager.currentReceivingAddress.then( - (address) async => await ref - .read(pMonKeyService) - .fetchMonKey( - address: address, - png: true, - ) - .then( - (monKeyBytes) async => - await _saveMonKeyToFile( - bytes: monKeyBytes, - isPNG: true, - ), - ), - ), + wallet.getCurrentReceivingAddress().then( + (address) async => await ref + .read(pMonKeyService) + .fetchMonKey( + address: address!.value, + png: true, + ) + .then( + (monKeyBytes) async => + await _saveMonKeyToFile( + bytes: monKeyBytes, + isPNG: true, + ), + ), + ), Future.delayed( const Duration(seconds: 2)), ]), @@ -486,17 +486,17 @@ class _MonkeyViewState extends ConsumerState { onPressed: () async { await showLoading( whileFuture: Future.wait([ - manager.currentReceivingAddress.then( - (address) async => await ref - .read(pMonKeyService) - .fetchMonKey(address: address) - .then( - (monKeyBytes) async => - await _updateWalletMonKey( - monKeyBytes, - ), - ), - ), + wallet.getCurrentReceivingAddress().then( + (address) async => await ref + .read(pMonKeyService) + .fetchMonKey(address: address!.value) + .then( + (monKeyBytes) async => + await _updateWalletMonKey( + monKeyBytes, + ), + ), + ), Future.delayed(const Duration(seconds: 2)), ]), context: context, @@ -517,8 +517,8 @@ class _MonkeyViewState extends ConsumerState { }, ); - imageBytes = (manager.wallet as BananoWallet) - .getMonkeyImageBytes(); + imageBytes = + (wallet as BananoWallet).getMonkeyImageBytes(); if (imageBytes != null) { setState(() {}); diff --git a/lib/pages/ordinals/ordinal_details_view.dart b/lib/pages/ordinals/ordinal_details_view.dart index 714fc7c1f..d15523e10 100644 --- a/lib/pages/ordinals/ordinal_details_view.dart +++ b/lib/pages/ordinals/ordinal_details_view.dart @@ -13,15 +13,16 @@ import 'package:stackwallet/networking/http.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/prefs_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/services/tor_service.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/show_loading.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/secondary_button.dart'; @@ -56,8 +57,7 @@ class _OrdinalDetailsViewState extends ConsumerState { @override Widget build(BuildContext context) { - final coin = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId).coin)); + final coin = ref.watch(pWalletCoin(widget.walletId)); return Background( child: SafeArea( diff --git a/lib/pages/ordinals/ordinals_view.dart b/lib/pages/ordinals/ordinals_view.dart index d38b9a17a..2b6099c50 100644 --- a/lib/pages/ordinals/ordinals_view.dart +++ b/lib/pages/ordinals/ordinals_view.dart @@ -89,7 +89,7 @@ class _OrdinalsViewState extends ConsumerState { await showLoading( whileFuture: Future.wait([ Future.delayed(const Duration(seconds: 2)), - (ref.read(pWallets).getManager(widget.walletId).wallet + (ref.read(pWallets).getWallet(widget.walletId) as OrdinalsInterface) .refreshInscriptions() ]), diff --git a/lib/pages/paynym/dialogs/paynym_details_popup.dart b/lib/pages/paynym/dialogs/paynym_details_popup.dart index 1cc0c07c3..12a70d9c1 100644 --- a/lib/pages/paynym/dialogs/paynym_details_popup.dart +++ b/lib/pages/paynym/dialogs/paynym_details_popup.dart @@ -28,9 +28,11 @@ import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/route_generator.dart'; import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/themes/stack_colors.dart'; -import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/assets.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/custom_buttons/paynym_follow_toggle_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/primary_button.dart'; @@ -58,12 +60,12 @@ class _PaynymDetailsPopupState extends ConsumerState { bool _showInsufficientFundsInfo = false; Future _onSend() async { - final manager = ref.read(pWallets).getManager(widget.walletId); + final wallet = ref.read(pWallets).getWallet(widget.walletId); await Navigator.of(context).pushNamed( SendView.routeName, arguments: Tuple3( - manager.walletId, - manager.coin, + wallet.walletId, + wallet.info.coin, widget.accountLite, ), ); @@ -83,9 +85,9 @@ class _PaynymDetailsPopupState extends ConsumerState { ), ); - final manager = ref.read(pWallets).getManager(widget.walletId); - - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = + ref.read(pWallets).getWallet(widget.walletId) as PaynymWalletInterface; + final coin = ref.read(pWalletCoin(widget.walletId)); if (await wallet.hasConnected(widget.accountLite.code)) { canPop = true; @@ -94,9 +96,9 @@ class _PaynymDetailsPopupState extends ConsumerState { return; } - final rates = await manager.fees; + final rates = await ref.read(pWallets).getWallet(widget.walletId).fees; - Map preparedTx; + TxData preparedTx; try { preparedTx = await wallet.prepareNotificationTx( @@ -145,32 +147,19 @@ class _PaynymDetailsPopupState extends ConsumerState { nymName: widget.accountLite.nymName, locale: ref.read(localeServiceChangeNotifierProvider).locale, onConfirmPressed: () { - // - print("CONFIRM NOTIF TX: $preparedTx"); - Navigator.of(context).push( RouteGenerator.getRoute( builder: (_) => ConfirmTransactionView( - walletId: manager.walletId, + walletId: widget.walletId, routeOnSuccessName: PaynymHomeView.routeName, isPaynymNotificationTransaction: true, - transactionInfo: { - "hex": preparedTx["hex"], - "address": preparedTx["recipientPaynym"], - "recipientAmt": preparedTx["amount"], - "fee": preparedTx["fee"], - "vSize": preparedTx["vSize"], - "note": "PayNym connect" - }, + txData: preparedTx, ), ), ); }, - amount: (preparedTx["amount"] as Amount) + - (preparedTx["fee"] as int).toAmountAsRaw( - fractionDigits: manager.coin.decimals, - ), - coin: manager.coin, + amount: preparedTx.amount! + preparedTx.fee!, + coin: coin, ), ); } @@ -178,10 +167,8 @@ class _PaynymDetailsPopupState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); - - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = + ref.watch(pWallets).getWallet(widget.walletId) as PaynymWalletInterface; return DesktopDialog( maxWidth: MediaQuery.of(context).size.width - 32, @@ -313,7 +300,7 @@ class _PaynymDetailsPopupState extends ConsumerState { "Adding a PayNym to your contacts requires a one-time " "transaction fee for creating the record on the " "blockchain. Please deposit more " - "${ref.read(pWallets).getManager(widget.walletId).wallet.coin.ticker} " + "${ref.watch(pWalletCoin(widget.walletId)).ticker} " "into your wallet and try again.", style: STextStyles.infoSmall(context).copyWith( color: Theme.of(context) diff --git a/lib/pages/paynym/paynym_claim_view.dart b/lib/pages/paynym/paynym_claim_view.dart index 035dfa273..12e12eaeb 100644 --- a/lib/pages/paynym/paynym_claim_view.dart +++ b/lib/pages/paynym/paynym_claim_view.dart @@ -47,10 +47,8 @@ class PaynymClaimView extends ConsumerStatefulWidget { class _PaynymClaimViewState extends ConsumerState { Future _addSegwitCode(PaynymAccount myAccount) async { - final manager = ref.read(pWallets).getManager(widget.walletId); - - // get wallet to access paynym calls - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = + ref.read(pWallets).getWallet(widget.walletId) as PaynymWalletInterface; final token = await ref .read(paynymAPIProvider) @@ -189,11 +187,8 @@ class _PaynymClaimViewState extends ConsumerState { ).then((value) => shouldCancel = value == true), ); - final manager = - ref.read(pWallets).getManager(widget.walletId); - - // get wallet to access paynym calls - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = ref.read(pWallets).getWallet(widget.walletId) + as PaynymWalletInterface; if (shouldCancel) return; diff --git a/lib/pages/paynym/subwidgets/desktop_paynym_details.dart b/lib/pages/paynym/subwidgets/desktop_paynym_details.dart index 5d2cdeb56..297d00264 100644 --- a/lib/pages/paynym/subwidgets/desktop_paynym_details.dart +++ b/lib/pages/paynym/subwidgets/desktop_paynym_details.dart @@ -26,9 +26,11 @@ import 'package:stackwallet/providers/global/locale_provider.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/themes/stack_colors.dart'; -import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/assets.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; import 'package:stackwallet/widgets/custom_buttons/paynym_follow_toggle_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; @@ -69,9 +71,8 @@ class _PaynymDetailsPopupState extends ConsumerState { ), ); - final manager = ref.read(pWallets).getManager(widget.walletId); - - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = + ref.read(pWallets).getWallet(widget.walletId) as PaynymWalletInterface; if (await wallet.hasConnected(widget.accountLite.code)) { canPop = true; @@ -80,9 +81,9 @@ class _PaynymDetailsPopupState extends ConsumerState { return; } - final rates = await manager.fees; + final rates = await ref.read(pWallets).getWallet(widget.walletId).fees; - Map preparedTx; + TxData preparedTx; try { preparedTx = await wallet.prepareNotificationTx( @@ -122,16 +123,9 @@ class _PaynymDetailsPopupState extends ConsumerState { maxHeight: double.infinity, maxWidth: 580, child: ConfirmTransactionView( - walletId: manager.walletId, + walletId: widget.walletId, isPaynymNotificationTransaction: true, - transactionInfo: { - "hex": preparedTx["hex"], - "address": preparedTx["recipientPaynym"], - "recipientAmt": preparedTx["amount"], - "fee": preparedTx["fee"], - "vSize": preparedTx["vSize"], - "note": "PayNym connect" - }, + txData: preparedTx, onSuccessInsteadOfRouteOnSuccess: () { Navigator.of(context, rootNavigator: true).pop(); Navigator.of(context, rootNavigator: true).pop(); @@ -150,11 +144,8 @@ class _PaynymDetailsPopupState extends ConsumerState { ), ); }, - amount: (preparedTx["amount"] as Amount) + - (preparedTx["fee"] as int).toAmountAsRaw( - fractionDigits: manager.coin.decimals, - ), - coin: manager.coin, + amount: preparedTx.amount! + preparedTx.fee!, + coin: ref.read(pWalletCoin(widget.walletId)), ), ); } @@ -172,10 +163,9 @@ class _PaynymDetailsPopupState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); + final wallet = ref.watch(pWallets).getWallet(widget.walletId); - final wallet = manager.wallet as PaynymWalletInterface; + final paynymWallet = wallet as PaynymWalletInterface; return RoundedWhiteContainer( padding: const EdgeInsets.all(0), @@ -203,7 +193,8 @@ class _PaynymDetailsPopupState extends ConsumerState { style: STextStyles.desktopTextSmall(context), ), FutureBuilder( - future: wallet.hasConnected(widget.accountLite.code), + future: paynymWallet + .hasConnected(widget.accountLite.code), builder: (context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done && @@ -241,7 +232,8 @@ class _PaynymDetailsPopupState extends ConsumerState { children: [ Expanded( child: FutureBuilder( - future: wallet.hasConnected(widget.accountLite.code), + future: + paynymWallet.hasConnected(widget.accountLite.code), builder: (context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done && @@ -313,7 +305,7 @@ class _PaynymDetailsPopupState extends ConsumerState { "Adding a PayNym to your contacts requires a one-time " "transaction fee for creating the record on the " "blockchain. Please deposit more " - "${ref.read(pWallets).getManager(widget.walletId).wallet.coin.ticker} " + "${ref.watch(pWalletCoin(widget.walletId)).ticker} " "into your wallet and try again.", style: STextStyles.desktopTextExtraExtraSmall(context) .copyWith( diff --git a/lib/pages/paynym/subwidgets/paynym_followers_list.dart b/lib/pages/paynym/subwidgets/paynym_followers_list.dart index 399b1ce9f..2d493f3f8 100644 --- a/lib/pages/paynym/subwidgets/paynym_followers_list.dart +++ b/lib/pages/paynym/subwidgets/paynym_followers_list.dart @@ -75,10 +75,8 @@ class _PaynymFollowersListState extends ConsumerState { child: child, onRefresh: () async { try { - final manager = ref.read(pWallets).getManager(widget.walletId); - - // get wallet to access paynym calls - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = ref.read(pWallets).getWallet(widget.walletId) + as PaynymWalletInterface; // get payment code final pCode = await wallet.getPaymentCode( diff --git a/lib/pages/paynym/subwidgets/paynym_following_list.dart b/lib/pages/paynym/subwidgets/paynym_following_list.dart index e18eec534..980d0ac3d 100644 --- a/lib/pages/paynym/subwidgets/paynym_following_list.dart +++ b/lib/pages/paynym/subwidgets/paynym_following_list.dart @@ -75,10 +75,8 @@ class _PaynymFollowingListState extends ConsumerState { child: child, onRefresh: () async { try { - final manager = ref.read(pWallets).getManager(widget.walletId); - - // get wallet to access paynym calls - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = ref.read(pWallets).getWallet(widget.walletId) + as PaynymWalletInterface; // get payment code final pCode = await wallet.getPaymentCode( diff --git a/lib/pages/pinpad_views/lock_screen_view.dart b/lib/pages/pinpad_views/lock_screen_view.dart index 66ae5b62c..f8b473d5c 100644 --- a/lib/pages/pinpad_views/lock_screen_view.dart +++ b/lib/pages/pinpad_views/lock_screen_view.dart @@ -32,7 +32,6 @@ import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; import 'package:stackwallet/widgets/custom_pin_put/custom_pin_put.dart'; import 'package:stackwallet/widgets/shake/shake.dart'; -import 'package:tuple/tuple.dart'; class LockscreenView extends ConsumerStatefulWidget { const LockscreenView({ @@ -98,13 +97,13 @@ class _LockscreenViewState extends ConsumerState { if (loadIntoWallet) { final walletId = widget.routeOnSuccessArguments as String; - final manager = ref.read(pWallets).getManager(walletId); - if (manager.coin == Coin.monero) { + final wallet = ref.read(pWallets).getWallet(walletId); + if (wallet.info.coin == Coin.monero) { await showLoading( opaqueBG: true, - whileFuture: manager.initializeExisting(), + whileFuture: wallet.init(), context: context, - message: "Loading ${manager.coin.prettyName} wallet...", + message: "Loading ${wallet.info.coin.prettyName} wallet...", ); } } @@ -123,10 +122,7 @@ class _LockscreenViewState extends ConsumerState { unawaited( Navigator.of(context).pushNamed( WalletView.routeName, - arguments: Tuple2( - walletId, - ref.read(pWallets).getManagerProvider(walletId), - ), + arguments: walletId, ), ); } diff --git a/lib/pages/receive_view/addresses/address_details_view.dart b/lib/pages/receive_view/addresses/address_details_view.dart index 73d51a808..64cfe41cd 100644 --- a/lib/pages/receive_view/addresses/address_details_view.dart +++ b/lib/pages/receive_view/addresses/address_details_view.dart @@ -22,12 +22,12 @@ import 'package:stackwallet/pages/wallet_view/sub_widgets/no_transactions_found. import 'package:stackwallet/pages/wallet_view/transaction_views/transaction_details_view.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/transaction_v2_card.dart'; import 'package:stackwallet/providers/db/main_db_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/address_utils.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -95,8 +95,7 @@ class _AddressDetailsViewState extends ConsumerState { key: _qrKey, child: QrImageView( data: AddressUtils.buildUriString( - ref.watch(pWallets.select((value) => - value.getManager(widget.walletId).coin)), + ref.watch(pWalletCoin(widget.walletId)), address.value, {}, ), @@ -150,8 +149,7 @@ class _AddressDetailsViewState extends ConsumerState { @override Widget build(BuildContext context) { - final coin = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId).coin)); + final coin = ref.watch(pWalletCoin(widget.walletId)); return ConditionalParent( condition: !isDesktop, builder: (child) => Background( @@ -291,8 +289,7 @@ class _AddressDetailsViewState extends ConsumerState { key: _qrKey, child: QrImageView( data: AddressUtils.buildUriString( - ref.watch(pWallets.select((value) => - value.getManager(widget.walletId).coin)), + coin, address.value, {}, ), diff --git a/lib/pages/receive_view/addresses/wallet_addresses_view.dart b/lib/pages/receive_view/addresses/wallet_addresses_view.dart index 6cfdd3a17..597ca44fe 100644 --- a/lib/pages/receive_view/addresses/wallet_addresses_view.dart +++ b/lib/pages/receive_view/addresses/wallet_addresses_view.dart @@ -16,11 +16,11 @@ import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/isar_models.dart'; import 'package:stackwallet/pages/receive_view/addresses/address_card.dart'; import 'package:stackwallet/pages/receive_view/addresses/address_details_view.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -135,8 +135,8 @@ class _WalletAddressesViewState extends ConsumerState { @override Widget build(BuildContext context) { - final coin = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId).coin)); + final coin = ref.watch(pWalletCoin(widget.walletId)); + return ConditionalParent( condition: !isDesktop, builder: (child) => Background( diff --git a/lib/pages/receive_view/receive_view.dart b/lib/pages/receive_view/receive_view.dart index 84b8823e9..d0f7a3e79 100644 --- a/lib/pages/receive_view/receive_view.dart +++ b/lib/pages/receive_view/receive_view.dart @@ -28,6 +28,8 @@ import 'package:stackwallet/utilities/clipboard_interface.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/bip39_hd_wallet.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; @@ -58,54 +60,49 @@ class _ReceiveViewState extends ConsumerState { late final ClipboardInterface clipboard; Future generateNewAddress() async { - bool shouldPop = false; - unawaited( - showDialog( - context: context, - builder: (_) { - return WillPopScope( - onWillPop: () async => shouldPop, - child: Container( - color: Theme.of(context) - .extension()! - .overlay - .withOpacity(0.5), - child: const CustomLoadingOverlay( - message: "Generating address", - eventBus: null, + // TODO: [prio=med] handle other wallet cases + final wallet = ref.read(pWallets).getWallet(walletId); + + if (wallet is Bip39HDWallet) { + bool shouldPop = false; + unawaited( + showDialog( + context: context, + builder: (_) { + return WillPopScope( + onWillPop: () async => shouldPop, + child: Container( + color: Theme.of(context) + .extension()! + .overlay + .withOpacity(0.5), + child: const CustomLoadingOverlay( + message: "Generating address", + eventBus: null, + ), ), - ), - ); - }, - ), - ); + ); + }, + ), + ); - await ref.read(pWallets).getManager(walletId).generateNewAddress(); + await wallet.generateNewReceivingAddress(); - shouldPop = true; + shouldPop = true; - if (mounted) { - Navigator.of(context) - .popUntil(ModalRoute.withName(ReceiveView.routeName)); + if (mounted) { + Navigator.of(context) + .popUntil(ModalRoute.withName(ReceiveView.routeName)); + } } } - String receivingAddress = ""; - @override void initState() { walletId = widget.walletId; - coin = ref.read(pWallets).getManager(walletId).coin; + coin = ref.read(pWalletCoin(walletId)); clipboard = widget.clipboard; - WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { - final address = - await ref.read(pWallets).getManager(walletId).currentReceivingAddress; - setState(() { - receivingAddress = address; - }); - }); - super.initState(); } @@ -113,16 +110,7 @@ class _ReceiveViewState extends ConsumerState { Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - ref.listen( - ref - .read(pWallets) - .getManagerProvider(walletId) - .select((value) => value.currentReceivingAddress), - (previous, next) { - if (next is Future) { - next.then((value) => setState(() => receivingAddress = value)); - } - }); + final receivingAddress = ref.watch(pWalletReceivingAddress(walletId)); final ticker = widget.tokenContract?.symbol ?? coin.ticker; diff --git a/lib/pages/send_view/confirm_transaction_view.dart b/lib/pages/send_view/confirm_transaction_view.dart index f1a4f06d9..ed3f5466e 100644 --- a/lib/pages/send_view/confirm_transaction_view.dart +++ b/lib/pages/send_view/confirm_transaction_view.dart @@ -16,7 +16,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_libepiccash/lib.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; -import 'package:stackwallet/models/paynym/paynym_account_lite.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/pages/pinpad_views/lock_screen_view.dart'; import 'package:stackwallet/pages/send_view/sub_widgets/sending_transaction_dialog.dart'; @@ -27,8 +26,6 @@ import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/wallet/public_private_balance_state_provider.dart'; import 'package:stackwallet/route_generator.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; -import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/themes/theme_providers.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -37,6 +34,8 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; // import 'package:stackwallet/wallets/example/libepiccash.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; @@ -54,7 +53,7 @@ import 'package:stackwallet/widgets/textfield_icon_button.dart'; class ConfirmTransactionView extends ConsumerStatefulWidget { const ConfirmTransactionView({ Key? key, - required this.transactionInfo, + required this.txData, required this.walletId, this.routeOnSuccessName = WalletView.routeName, this.isTradeTransaction = false, @@ -66,7 +65,7 @@ class ConfirmTransactionView extends ConsumerStatefulWidget { static const String routeName = "/confirmTransactionView"; - final Map transactionInfo; + final TxData txData; final String walletId; final String routeOnSuccessName; final bool isTradeTransaction; @@ -82,7 +81,6 @@ class ConfirmTransactionView extends ConsumerStatefulWidget { class _ConfirmTransactionViewState extends ConsumerState { - late final Map transactionInfo; late final String walletId; late final String routeOnSuccessName; late final bool isDesktop; @@ -94,7 +92,8 @@ class _ConfirmTransactionViewState late final TextEditingController onChainNoteController; Future _attemptSend(BuildContext context) async { - pWalletsf.read(walletsChangeNotifierProvider).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); + final coin = wallet.info.coin; final sendProgressController = ProgressAndSuccessController(); @@ -105,7 +104,7 @@ class _ConfirmTransactionViewState barrierDismissible: false, builder: (context) { return SendingTransactionDialog( - coin: manager.coin, + coin: coin, controller: sendProgressController, ); }, @@ -119,32 +118,42 @@ class _ConfirmTransactionViewState ); late String txid; - Future txidFuture; + Future txidFuture; final note = noteController.text; try { if (widget.isTokenTx) { - txidFuture = ref - .read(tokenServiceProvider)! - .confirmSend(txData: transactionInfo); + // TODO: [prio=high] fixme + throw UnimplementedError("fixme"); + // txidFuture = ref + // .read(tokenServiceProvider)! + // .confirmSend(txData: transactionInfo); } else if (widget.isPaynymNotificationTransaction) { - txidFuture = (manager.wallet as PaynymWalletInterface) - .broadcastNotificationTx(preparedTx: transactionInfo); + // TODO: [prio=high] fixme + throw UnimplementedError("fixme"); + // txidFuture = (wallet as PaynymWalletInterface) + // .broadcastNotificationTx(preparedTx: transactionInfo); } else if (widget.isPaynymTransaction) { - txidFuture = manager.confirmSend(txData: transactionInfo); + txidFuture = wallet.confirmSend(txData: widget.txData); } else { - final coin = manager.coin; if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { - txidFuture = (manager.wallet as FiroWallet) - .confirmSendPublic(txData: transactionInfo); + // TODO: [prio=high] fixme + throw UnimplementedError("fixme"); + // txidFuture = (wallet as FiroWallet) + // .confirmSendPublic(txData: transactionInfo); } else { if (coin == Coin.epicCash) { - transactionInfo["onChainNote"] = onChainNoteController.text; + txidFuture = wallet.confirmSend( + txData: widget.txData.copyWith( + noteOnChain: onChainNoteController.text, + ), + ); + } else { + txidFuture = wallet.confirmSend(txData: widget.txData); } - txidFuture = manager.confirmSend(txData: transactionInfo); } } @@ -167,7 +176,7 @@ class _ConfirmTransactionViewState if (widget.isTokenTx) { unawaited(ref.read(tokenServiceProvider)!.refresh()); } else { - unawaited(manager.refresh()); + unawaited(wallet.refresh()); } // pop back to wallet @@ -272,17 +281,15 @@ class _ConfirmTransactionViewState @override void initState() { isDesktop = Util.isDesktop; - transactionInfo = widget.transactionInfo; walletId = widget.walletId; routeOnSuccessName = widget.routeOnSuccessName; _noteFocusNode = FocusNode(); noteController = TextEditingController(); - noteController.text = transactionInfo["note"] as String? ?? ""; + noteController.text = widget.txData.note ?? ""; _onChainNoteFocusNode = FocusNode(); onChainNoteController = TextEditingController(); - onChainNoteController.text = - transactionInfo["onChainNote"] as String? ?? ""; + onChainNoteController.text = widget.txData.noteOnChain ?? ""; super.initState(); } @@ -298,9 +305,8 @@ class _ConfirmTransactionViewState } @override - Widget build(BuildContext contepWalletser = ref.watch(walletsChangeNotifierProvider - .select((value) => value.getManagerProvidpWalletsin = ref.watch(walletsChangeNotifierProvider - .select((value) => value.getManager(walletId).coin)); + Widget build(BuildContext context) { + final coin = ref.watch(pWalletCoin(walletId)); final String unit; if (widget.isTokenTx) { @@ -309,7 +315,6 @@ class _ConfirmTransactionViewState } else { unit = coin.ticker; } - return ConditionalParent( condition: !isDesktop, builder: (child) => Background( @@ -414,10 +419,8 @@ class _ConfirmTransactionViewState ), Text( widget.isPaynymTransaction - ? (transactionInfo["paynymAccountLite"] - as PaynymAccountLite) - .nymName - : "${transactionInfo["address"] ?? "ERROR"}", + ? widget.txData.paynymAccountLite!.nymName + : widget.txData.recipients!.first.address, style: STextStyles.itemSubtitle12(context), ), ], @@ -436,7 +439,7 @@ class _ConfirmTransactionViewState ), Text( ref.watch(pAmountFormatter(coin)).format( - transactionInfo["recipientAmt"] as Amount, + widget.txData.amount!, ethContract: ref .watch(tokenServiceProvider) ?.tokenContract, @@ -461,31 +464,20 @@ class _ConfirmTransactionViewState style: STextStyles.smallMed12(context), ), Text( - ref.watch(pAmountFormatter(coin)).format( - (transactionInfo["fee"] is Amount - ? transactionInfo["fee"] as Amount - : (transactionInfo["fee"] as int) - .toAmountAsRaw( - fractionDigits: ref.watch( - managerProvider.select( - (value) => value.coin.decimals, - ), - ), - )), - ), + ref + .watch(pAmountFormatter(coin)) + .format(widget.txData.fee!), style: STextStyles.itemSubtitle12(context), textAlign: TextAlign.right, ), ], ), ), - if (transactionInfo["fee"] is int && - transactionInfo["vSize"] is int) + if (widget.txData.fee != null && widget.txData.vSize != null) const SizedBox( height: 12, ), - if (transactionInfo["fee"] is int && - transactionInfo["vSize"] is int) + if (widget.txData.fee != null && widget.txData.vSize != null) RoundedWhiteContainer( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -498,19 +490,19 @@ class _ConfirmTransactionViewState height: 4, ), Text( - "~${(transactionInfo["fee"] / transactionInfo["vSize"]).toInt()}", + "~${widget.txData.fee!.raw.toInt() ~/ widget.txData.vSize!}", style: STextStyles.itemSubtitle12(context), ), ], ), ), if (coin == Coin.epicCash && - (transactionInfo["onChainNote"] as String).isNotEmpty) + widget.txData.noteOnChain!.isNotEmpty) const SizedBox( height: 12, ), if (coin == Coin.epicCash && - (transactionInfo["onChainNote"] as String).isNotEmpty) + widget.txData.noteOnChain!.isNotEmpty) RoundedWhiteContainer( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -523,17 +515,17 @@ class _ConfirmTransactionViewState height: 4, ), Text( - transactionInfo["onChainNote"] as String, + widget.txData.noteOnChain!, style: STextStyles.itemSubtitle12(context), ), ], ), ), - if ((transactionInfo["note"] as String).isNotEmpty) + if (widget.txData.note!.isNotEmpty) const SizedBox( height: 12, ), - if ((transactionInfo["note"] as String).isNotEmpty) + if (widget.txData.note!.isNotEmpty) RoundedWhiteContainer( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -546,7 +538,7 @@ class _ConfirmTransactionViewState height: 4, ), Text( - transactionInfo["note"] as String, + widget.txData.note!, style: STextStyles.itemSubtitle12(context), ), ], @@ -629,13 +621,7 @@ class _ConfirmTransactionViewState ), Builder( builder: (context) { - final coin = ref.watch( - managerProvider.select( - (value) => value.coin, - ), - ); - final amount = - transactionInfo["recipientAmt"] as Amount; + final amount = widget.txData.amount!; final externalCalls = ref.watch( prefsChangeNotifierProvider.select( (value) => value.externalCalls)); @@ -734,10 +720,8 @@ class _ConfirmTransactionViewState ), Text( widget.isPaynymTransaction - ? (transactionInfo["paynymAccountLite"] - as PaynymAccountLite) - .nymName - : "${transactionInfo["address"] ?? "ERROR"}", + ? widget.txData.paynymAccountLite!.nymName + : widget.txData.recipients!.first.address, style: STextStyles.desktopTextExtraExtraSmall( context) .copyWith( @@ -773,18 +757,7 @@ class _ConfirmTransactionViewState ), Builder( builder: (context) { - final coin = ref - pWallets .watch(walletsChangeNotifierProvider - .select((value) => - value.getManager(walletId))) - .coin; - - final fee = transactionInfo["fee"] is Amount - ? transactionInfo["fee"] as Amount - : (transactionInfo["fee"] as int) - .toAmountAsRaw( - fractionDigits: coin.decimals, - ); + final fee = widget.txData.fee!; return Text( ref @@ -1004,17 +977,9 @@ class _ConfirmTransactionViewState color: Theme.of(context) .extension()! .textFieldDefaultBG, - pWallets builder: (context) { - final coin = ref - .watch(walletsChangeNotifierProvider - .select((value) => value.getManager(walletId))) - .coin; - - final fee = transactionInfo["fee"] is Amount - ? transactionInfo["fee"] as Amount - : (transactionInfo["fee"] as int).toAmountAsRaw( - fractionDigits: coin.decimals, - ); + child: Builder( + builder: (context) { + final fee = widget.txData.fee!; return Text( ref.watch(pAmountFormatter(coin)).format(fee), @@ -1026,8 +991,8 @@ class _ConfirmTransactionViewState ), if (isDesktop && !widget.isPaynymTransaction && - transactionInfo["fee"] is int && - transactionInfo["vSize"] is int) + widget.txData.fee != null && + widget.txData.vSize != null) Padding( padding: const EdgeInsets.only( left: 32, @@ -1039,8 +1004,8 @@ class _ConfirmTransactionViewState ), if (isDesktop && !widget.isPaynymTransaction && - transactionInfo["fee"] is int && - transactionInfo["vSize"] is int) + widget.txData.fee != null && + widget.txData.vSize != null) Padding( padding: const EdgeInsets.only( top: 10, @@ -1056,7 +1021,7 @@ class _ConfirmTransactionViewState .extension()! .textFieldDefaultBG, child: Text( - "~${(transactionInfo["fee"] / transactionInfo["vSize"]).toInt()}", + "~${widget.txData.fee!.raw.toInt() ~/ widget.txData.vSize!}", style: STextStyles.itemSubtitle(context), ), ), @@ -1099,17 +1064,11 @@ class _ConfirmTransactionViewState .extension()! .textConfirmTotalAmount, ), - pWallets Builder(builder: (context) { - final coin = ref.watch( - walletsChangeNotifierProvider.select( - (value) => value.getManager(walletId).coin)); - final fee = transactionInfo["fee"] is Amount - ? transactionInfo["fee"] as Amount - : (transactionInfo["fee"] as int) - .toAmountAsRaw(fractionDigits: coin.decimals); + ), + Builder(builder: (context) { + final fee = widget.txData.fee!; - final amount = - transactionInfo["recipientAmt"] as Amount; + final amount = widget.txData.amount!; return Text( ref .watch(pAmountFormatter(coin)) @@ -1145,14 +1104,9 @@ class _ConfirmTransactionViewState child: PrimaryButton( label: "Send", buttonHeight: isDesktop ? ButtonHeight.l : null, - pWallets + onPressed: () async { final dynamic unlocked; - final coin = ref - .read(walletsChangeNotifierProvider) - .getManager(walletId) - .coin; - if (isDesktop) { unlocked = await showDialog( context: context, @@ -1162,9 +1116,9 @@ class _ConfirmTransactionViewState child: Column( mainAxisSize: MainAxisSize.min, children: [ - Row( + const Row( mainAxisAlignment: MainAxisAlignment.end, - children: const [ + children: [ DesktopDialogCloseButton(), ], ), diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index 0b803d2f5..9237136c4 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -32,8 +32,7 @@ import 'package:stackwallet/providers/ui/fee_rate_type_state_provider.dart'; import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart'; import 'package:stackwallet/providers/wallet/public_private_balance_state_provider.dart'; import 'package:stackwallet/route_generator.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; -import 'package:stackwallet/services/coins/manager.dart'; +import 'package:stackwallet/services/mixins/coin_control_interface.dart'; import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; @@ -52,6 +51,8 @@ import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/animated_text.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -120,16 +121,11 @@ class _SendViewState extends ConsumerState { Amount? _cachedAmountToSend; String? _address; - String? _privateBalanceString; - String? _publicBalanceString; - bool _addressToggleFlag = false; bool _cryptoAmountChangeLock = false; late VoidCallback onCryptoAmountChanged; - Amount? _cachedBalance; - Set selectedUTXOs = {}; void _cryptoAmountChanged() async { @@ -225,11 +221,16 @@ class _SendViewState extends ConsumerState { } } - String? _updateInvalidAddressText(String address, Manager manager) { + String? _updateInvalidAddressText(String address) { if (_data != null && _data!.contactLabel == address) { return null; } - if (address.isNotEmpty && !manager.validateAddress(address)) { + if (address.isNotEmpty && + !ref + .read(pWallets) + .getWallet(walletId) + .cryptoCurrency + .validateAddress(address)) { return "Invalid address"; } return null; @@ -242,7 +243,8 @@ class _SendViewState extends ConsumerState { } else { final isValidAddress = ref .read(pWallets) - .getManager(walletId) + .getWallet(walletId) + .cryptoCurrency .validateAddress(address ?? ""); ref.read(previewTxButtonStateProvider.state).state = (isValidAddress && amount != null && amount > Amount.zero); @@ -275,9 +277,8 @@ class _SendViewState extends ConsumerState { return cachedFees[amount]!; } - final manager = - ref.read(pWallets).getManager(walletId); - final feeObject = await manager.fees; + final wallet = ref.read(pWallets).getWallet(walletId); + final feeObject = await wallet.fees; late final int feeRate; @@ -312,7 +313,7 @@ class _SendViewState extends ConsumerState { throw ArgumentError("custom fee not available for monero"); } - fee = await manager.estimateFeeFor(amount, specialMoneroId.raw!); + fee = await wallet.estimateFeeFor(amount, specialMoneroId.raw!); cachedFees[amount] = ref.read(pAmountFormatter(coin)).format( fee, withUnitName: true, @@ -323,7 +324,7 @@ class _SendViewState extends ConsumerState { } else if (coin == Coin.firo || coin == Coin.firoTestNet) { if (ref.read(publicPrivateBalanceStateProvider.state).state == "Private") { - fee = await manager.estimateFeeFor(amount, feeRate); + fee = await wallet.estimateFeeFor(amount, feeRate); cachedFiroPrivateFees[amount] = ref.read(pAmountFormatter(coin)).format( fee, @@ -333,19 +334,21 @@ class _SendViewState extends ConsumerState { return cachedFiroPrivateFees[amount]!; } else { - fee = await (manager.wallet as FiroWallet) - .estimateFeeForPublic(amount, feeRate); - - cachedFiroPublicFees[amount] = ref.read(pAmountFormatter(coin)).format( - fee, - withUnitName: true, - indicatePrecisionLoss: false, - ); - - return cachedFiroPublicFees[amount]!; + // TODO: [prio=high] firo public send fees refactor or something... + throw UnimplementedError("Firo pub fees todo"); + // fee = await (manager.wallet as FiroWallet) + // .estimateFeeForPublic(amount, feeRate); + // + // cachedFiroPublicFees[amount] = ref.read(pAmountFormatter(coin)).format( + // fee, + // withUnitName: true, + // indicatePrecisionLoss: false, + // ); + // + // return cachedFiroPublicFees[amount]!; } } else { - fee = await manager.estimateFeeFor(amount, feeRate); + fee = await wallet.estimateFeeFor(amount, feeRate); cachedFees[amount] = ref.read(pAmountFormatter(coin)).format( fee, withUnitName: true, @@ -356,57 +359,34 @@ class _SendViewState extends ConsumerState { } } - Future _firoBalanceFuture( - ChangeNotifierProvider provider, String locale) async { - final wallet = ref.read(provider).wallet as FiroWallet?; - - if (wallet != null) { - Amount? balance; - if (ref.read(publicPrivateBalanceStateProvider.state).state == - "Private") { - balance = wallet.availablePrivateBalance(); - } else { - balance = wallet.availablePublicBalance(); - } - - return ref.read(pAmountFormatter(coin)).format( - balance, - ); - } - - return null; - } - Future _previewTransaction() async { // wait for keyboard to disappear FocusScope.of(context).unfocus(); await Future.delayed( const Duration(milliseconds: 100), ); - final manager = - ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); final Amount amount = _amountToSend!; final Amount availableBalance; if ((coin == Coin.firo || coin == Coin.firoTestNet)) { if (ref.read(publicPrivateBalanceStateProvider.state).state == "Private") { - availableBalance = - (manager.wallet as FiroWallet).availablePrivateBalance(); + availableBalance = ref.read(pWalletBalance(walletId)).spendable; } else { availableBalance = - (manager.wallet as FiroWallet).availablePublicBalance(); + ref.read(pWalletBalanceSecondary(walletId)).spendable; } } else { - availableBalance = manager.balance.spendable; + availableBalance = ref.read(pWalletBalance(walletId)).spendable; } final coinControlEnabled = ref.read(prefsChangeNotifierProvider).enableCoinControl; if (coin != Coin.ethereum && - !(manager.hasCoinControlSupport && coinControlEnabled) || - (manager.hasCoinControlSupport && + !(wallet is CoinControlInterface && coinControlEnabled) || + (wallet is CoinControlInterface && coinControlEnabled && selectedUTXOs.isEmpty)) { // confirm send all @@ -472,7 +452,7 @@ class _SendViewState extends ConsumerState { barrierDismissible: false, builder: (context) { return BuildingTransactionDialog( - coin: manager.coin, + coin: wallet.info.coin, onCancel: () { wasCancelled = true; @@ -490,59 +470,59 @@ class _SendViewState extends ConsumerState { ), ); - Map txData; - Future> txDataFuture; + Future txDataFuture; if (isPaynymSend) { - final wallet = manager.wallet as PaynymWalletInterface; final paymentCode = PaymentCode.fromPaymentCode( widget.accountLite!.code, - networkType: wallet.networkType, - ); - final feeRate = ref.read(feeRateTypeStateProvider); - txDataFuture = wallet.preparePaymentCodeSend( - paymentCode: paymentCode, - isSegwit: widget.accountLite!.segwit, - amount: amount, - args: { - "satsPerVByte": isCustomFee ? customFeeRate : null, - "feeRate": feeRate, - "UTXOs": (manager.hasCoinControlSupport && - coinControlEnabled && - selectedUTXOs.isNotEmpty) - ? selectedUTXOs - : null, - }, + networkType: (wallet as PaynymWalletInterface).networkType, ); + throw UnimplementedError("FIXME"); + // TODO: [prio=high] paynym prepare send using TxData + // final feeRate = ref.read(feeRateTypeStateProvider); + // txDataFuture = (wallet as PaynymWalletInterface).preparePaymentCodeSend( + // paymentCode: paymentCode, + // isSegwit: widget.accountLite!.segwit, + // amount: amount, + // args: { + // "satsPerVByte": isCustomFee ? customFeeRate : null, + // "feeRate": feeRate, + // "UTXOs": (wallet is CoinControlInterface && + // coinControlEnabled && + // selectedUTXOs.isNotEmpty) + // ? selectedUTXOs + // : null, + // }, + // ); } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { - txDataFuture = (manager.wallet as FiroWallet).prepareSendPublic( - address: _address!, - amount: amount, - args: { - "feeRate": ref.read(feeRateTypeStateProvider), - "satsPerVByte": isCustomFee ? customFeeRate : null, - }, - ); + throw UnimplementedError("FIXME"); + // TODO: [prio=high] firo prepare send using TxData + // txDataFuture = (manager.wallet as FiroWallet).prepareSendPublic( + // address: _address!, + // amount: amount, + // args: { + // "feeRate": ref.read(feeRateTypeStateProvider), + // "satsPerVByte": isCustomFee ? customFeeRate : null, + // }, + // ); } else { - final memo = - manager.coin == Coin.stellar || manager.coin == Coin.stellarTestnet - ? memoController.text - : null; - txDataFuture = manager.prepareSend( - address: _address!, - amount: amount, - args: { - "memo": memo, - "feeRate": ref.read(feeRateTypeStateProvider), - "satsPerVByte": isCustomFee ? customFeeRate : null, - "UTXOs": (manager.hasCoinControlSupport && + final memo = coin == Coin.stellar || coin == Coin.stellarTestnet + ? memoController.text + : null; + txDataFuture = wallet.prepareSend( + txData: TxData( + recipients: [(address: _address!, amount: amount)], + memo: memo, + feeRateType: ref.read(feeRateTypeStateProvider), + satsPerVByte: isCustomFee ? customFeeRate : null, + utxos: (wallet is CoinControlInterface && coinControlEnabled && selectedUTXOs.isNotEmpty) ? selectedUTXOs : null, - }, + ), ); } @@ -551,24 +531,22 @@ class _SendViewState extends ConsumerState { time, ]); - txData = results.first as Map; + TxData txData = results.first as TxData; if (!wasCancelled && mounted) { // pop building dialog Navigator.of(context).pop(); - txData["note"] = noteController.text; - txData["onChainNote"] = onChainNoteController.text; + txData = txData.copyWith(note: noteController.text); + txData = txData.copyWith(noteOnChain: onChainNoteController.text); if (isPaynymSend) { - txData["paynymAccountLite"] = widget.accountLite!; - } else { - txData["address"] = _address; + txData = txData.copyWith(paynymAccountLite: widget.accountLite!); } unawaited(Navigator.of(context).push( RouteGenerator.getRoute( shouldUseMaterialRoute: RouteGenerator.useMaterialPageRoute, builder: (_) => ConfirmTransactionView( - transactionInfo: txData, + txData: txData, walletId: walletId, isPaynymTransaction: isPaynymSend, ), @@ -729,16 +707,11 @@ class _SendViewState extends ConsumerState { @override Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final provider = ref.watch(pWallets - .select((value) => value.getManagerProvider(walletId))); + final wallet = ref.watch(pWallets).getWallet(walletId); final String locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); - final showCoinControl = ref.watch( - pWallets.select( - (value) => value.getManager(walletId).hasCoinControlSupport, - ), - ) && + final showCoinControl = wallet is CoinControlInterface && ref.watch( prefsChangeNotifierProvider.select( (value) => value.enableCoinControl, @@ -848,8 +821,7 @@ class _SendViewState extends ConsumerState { CrossAxisAlignment.start, children: [ Text( - ref.watch(provider.select( - (value) => value.walletName)), + ref.watch(pWalletName(walletId)), style: STextStyles.titleBold12(context) .copyWith(fontSize: 14), overflow: TextOverflow.ellipsis, @@ -875,116 +847,75 @@ class _SendViewState extends ConsumerState { ], ), const Spacer(), - FutureBuilder( - // TODO redo this widget now that its not actually a future - future: (coin != Coin.firo && - coin != Coin.firoTestNet) - ? Future(() => ref.watch( - provider.select((value) => - value.balance.spendable))) - : ref.watch(publicPrivateBalanceStateProvider.state).state == - "Private" - ? Future(() => (ref - .watch(provider) - .wallet as FiroWallet) - .availablePrivateBalance()) - : Future(() => (ref - .watch(provider) - .wallet as FiroWallet) - .availablePublicBalance()), - builder: - (_, AsyncSnapshot snapshot) { - if (snapshot.connectionState == - ConnectionState.done && - snapshot.hasData) { - _cachedBalance = snapshot.data!; - } - - if (_cachedBalance != null) { - return GestureDetector( - onTap: () { - cryptoAmountController.text = ref - .read(pAmountFormatter(coin)) - .format( - _cachedBalance!, - withUnitName: false, - ); - }, - child: Container( - color: Colors.transparent, - child: Column( - crossAxisAlignment: - CrossAxisAlignment.end, - children: [ - Text( - ref - .watch(pAmountFormatter( - coin)) - .format(_cachedBalance!), - style: - STextStyles.titleBold12( - context) - .copyWith( - fontSize: 10, - ), - textAlign: TextAlign.right, - ), - Text( - "${(_cachedBalance!.decimal * ref.watch(priceAnd24hChangeNotifierProvider.select((value) => value.getPrice(coin).item1))).toAmount( - fractionDigits: 2, - ).fiatString( - locale: locale, - )} ${ref.watch(prefsChangeNotifierProvider.select((value) => value.currency))}", - style: STextStyles.subtitle( - context) - .copyWith( - fontSize: 8, - ), - textAlign: TextAlign.right, - ) - ], - ), - ), - ); + Builder(builder: (context) { + final Amount amount; + if (coin != Coin.firo && + coin != Coin.firoTestNet) { + if (ref + .watch( + publicPrivateBalanceStateProvider + .state) + .state == + "Private") { + amount = ref + .read(pWalletBalance(walletId)) + .spendable; } else { - return Column( + amount = ref + .read(pWalletBalanceSecondary( + walletId)) + .spendable; + } + } else { + amount = ref + .read(pWalletBalance(walletId)) + .spendable; + } + + return GestureDetector( + onTap: () { + cryptoAmountController.text = ref + .read(pAmountFormatter(coin)) + .format( + amount, + withUnitName: false, + ); + }, + child: Container( + color: Colors.transparent, + child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ - AnimatedText( - stringsToLoopThrough: const [ - "Loading balance ", - "Loading balance. ", - "Loading balance.. ", - "Loading balance...", - ], - style: STextStyles.itemSubtitle( + Text( + ref + .watch(pAmountFormatter(coin)) + .format(amount), + style: STextStyles.titleBold12( context) .copyWith( fontSize: 10, ), + textAlign: TextAlign.right, ), - const SizedBox( - height: 2, - ), - AnimatedText( - stringsToLoopThrough: const [ - "Loading balance ", - "Loading balance. ", - "Loading balance.. ", - "Loading balance...", - ], - style: STextStyles.itemSubtitle( - context) - .copyWith( + Text( + "${(amount.decimal * ref.watch(priceAnd24hChangeNotifierProvider.select((value) => value.getPrice(coin).item1))).toAmount( + fractionDigits: 2, + ).fiatString( + locale: locale, + )} ${ref.watch(prefsChangeNotifierProvider.select((value) => value.currency))}", + style: + STextStyles.subtitle(context) + .copyWith( fontSize: 8, ), + textAlign: TextAlign.right, ) ], - ); - } - }, - ), + ), + ), + ); + }), ], ), ), @@ -1269,9 +1200,9 @@ class _SendViewState extends ConsumerState { // now check for non standard encoded basic address } else if (ref - .read( - pWallets) - .getManager(walletId) + .read(pWallets) + .getWallet(walletId) + .cryptoCurrency .validateAddress(qrResult .rawContent)) { _address = qrResult @@ -1397,9 +1328,6 @@ class _SendViewState extends ConsumerState { builder: (_) { final error = _updateInvalidAddressText( _address ?? "", - ref - .read(pWallets) - .getManager(walletId), ); if (error == null || error.isEmpty) { @@ -1493,68 +1421,40 @@ class _SendViewState extends ConsumerState { const SizedBox( width: 10, ), - FutureBuilder( - future: _firoBalanceFuture( - provider, locale), - builder: (context, - AsyncSnapshot - snapshot) { - if (snapshot.connectionState == - ConnectionState.done && - snapshot.hasData) { - if (ref - .read( - publicPrivateBalanceStateProvider - .state) - .state == - "Private") { - _privateBalanceString = - snapshot.data!; - } else { - _publicBalanceString = - snapshot.data!; - } - } - if (ref - .read( - publicPrivateBalanceStateProvider - .state) - .state == - "Private" && - _privateBalanceString != - null) { - return Text( - "$_privateBalanceString", - style: STextStyles - .itemSubtitle(context), - ); - } else if (ref - .read( - publicPrivateBalanceStateProvider - .state) - .state == - "Public" && - _publicBalanceString != - null) { - return Text( - "$_publicBalanceString", - style: STextStyles - .itemSubtitle(context), - ); - } else { - return AnimatedText( - stringsToLoopThrough: const [ - "Loading balance", - "Loading balance.", - "Loading balance..", - "Loading balance...", - ], - style: STextStyles - .itemSubtitle(context), - ); - } - }, - ), + if (ref + .read( + publicPrivateBalanceStateProvider + .state) + .state == + "Private") + Text( + ref + .watch( + pAmountFormatter(coin)) + .format( + ref + .watch(pWalletBalance( + walletId)) + .spendable, + ), + style: STextStyles.itemSubtitle( + context), + ) + else + Text( + ref + .watch( + pAmountFormatter(coin)) + .format( + ref + .watch( + pWalletBalanceSecondary( + walletId)) + .spendable, + ), + style: STextStyles.itemSubtitle( + context), + ), ], ), SvgPicture.asset( @@ -1586,40 +1486,29 @@ class _SendViewState extends ConsumerState { CustomTextButton( text: "Send all ${coin.ticker}", onTap: () async { - if (coin == Coin.firo || - coin == Coin.firoTestNet) { - final firoWallet = ref - .read(provider) - .wallet as FiroWallet; - if (ref - .read( - publicPrivateBalanceStateProvider - .state) - .state == - "Private") { - cryptoAmountController.text = ref - .read(pAmountFormatter(coin)) - .format( - firoWallet - .availablePrivateBalance(), - withUnitName: false, - ); - } else { - cryptoAmountController.text = ref - .read(pAmountFormatter(coin)) - .format( - firoWallet - .availablePublicBalance(), - withUnitName: false, - ); - } + if ((coin == Coin.firo || + coin == Coin.firoTestNet) && + ref + .read( + publicPrivateBalanceStateProvider + .state) + .state == + "Public") { + cryptoAmountController.text = ref + .read(pAmountFormatter(coin)) + .format( + ref + .read(pWalletBalanceSecondary( + walletId)) + .spendable, + withUnitName: false, + ); } else { cryptoAmountController.text = ref .read(pAmountFormatter(coin)) .format( ref - .read(provider) - .balance + .read(pWalletBalance(walletId)) .spendable, withUnitName: false, ); @@ -1853,9 +1742,7 @@ class _SendViewState extends ConsumerState { if (mounted) { final spendable = ref - .read(pWallets) - .getManager(widget.walletId) - .balance + .read(pWalletBalance(walletId)) .spendable; Amount? amount; diff --git a/lib/pages/send_view/sub_widgets/firo_balance_selection_sheet.dart b/lib/pages/send_view/sub_widgets/firo_balance_selection_sheet.dart index d0c61e4b0..a5f9c121c 100644 --- a/lib/pages/send_view/sub_widgets/firo_balance_selection_sheet.dart +++ b/lib/pages/send_view/sub_widgets/firo_balance_selection_sheet.dart @@ -52,9 +52,11 @@ class _FiroBalanceSelectionSheetState Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final manager = - ref.watch(pWallets.select((value) => value.getManager(walletId))); - final firoWallet = manager.wallet as FiroWallet; + final wallet = + ref.watch(pWallets.select((value) => value.getWallet(walletId))); + final firoWallet = wallet as FiroWallet; + + final coin = wallet.info.coin; return Container( decoration: BoxDecoration( @@ -162,9 +164,7 @@ class _FiroBalanceSelectionSheetState width: 2, ), Text( - ref - .watch(pAmountFormatter(manager.coin)) - .format( + ref.watch(pAmountFormatter(coin)).format( firoWallet.availablePrivateBalance(), ), style: STextStyles.itemSubtitle(context), @@ -240,9 +240,7 @@ class _FiroBalanceSelectionSheetState width: 2, ), Text( - ref - .watch(pAmountFormatter(manager.coin)) - .format( + ref.watch(pAmountFormatter(coin)).format( firoWallet.availablePublicBalance(), ), style: STextStyles.itemSubtitle(context), diff --git a/lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart b/lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart index 1e6cce281..e9a9a8c0d 100644 --- a/lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart +++ b/lib/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart @@ -25,6 +25,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/animated_text.dart'; final feeSheetSessionCacheProvider = @@ -83,21 +84,21 @@ class _TransactionFeeSelectionSheetState case FeeRateType.fast: if (ref.read(feeSheetSessionCacheProvider).fast[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.fast.raw!); ref.read(feeSheetSessionCacheProvider).fast[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { ref.read(feeSheetSessionCacheProvider).fast[amount] = - await (manager.wallet as FiroWallet) + await (wallet as FiroWallet) .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).fast[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -110,20 +111,20 @@ class _TransactionFeeSelectionSheetState case FeeRateType.average: if (ref.read(feeSheetSessionCacheProvider).average[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.regular.raw!); ref.read(feeSheetSessionCacheProvider).average[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { ref.read(feeSheetSessionCacheProvider).average[amount] = - await (manager.wallet as FiroWallet) + await (wallet as FiroWallet) .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).average[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -136,20 +137,20 @@ class _TransactionFeeSelectionSheetState case FeeRateType.slow: if (ref.read(feeSheetSessionCacheProvider).slow[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.slow.raw!); ref.read(feeSheetSessionCacheProvider).slow[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { ref.read(feeSheetSessionCacheProvider).slow[amount] = - await (manager.wallet as FiroWallet) + await (wallet as FiroWallet) .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).slow[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -200,8 +201,9 @@ class _TransactionFeeSelectionSheetState Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final manager = - ref.watch(pWallets.select((value) => value.getManager(walletId))); + final wallet = ref.watch(pWallets).getWallet(walletId); + + final coin = ref.watch(pWalletCoin(walletId)); return Container( decoration: BoxDecoration( @@ -241,7 +243,7 @@ class _TransactionFeeSelectionSheetState FutureBuilder( future: widget.isToken ? ref.read(tokenServiceProvider)!.fees - : manager.fees, + : wallet.fees, builder: (context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) { @@ -267,7 +269,8 @@ class _TransactionFeeSelectionSheetState ref.read(feeRateTypeStateProvider.state).state = FeeRateType.fast; } - String? fee = getAmount(FeeRateType.fast, manager.coin); + String? fee = + getAmount(FeeRateType.fast, wallet.info.coin); if (fee != null) { widget.updateChosen(fee); } @@ -330,7 +333,7 @@ class _TransactionFeeSelectionSheetState if (feeObject != null) FutureBuilder( future: feeFor( - coin: manager.coin, + coin: coin, feeRateType: FeeRateType.fast, feeRate: feeObject!.fast, amount: amount, @@ -343,7 +346,7 @@ class _TransactionFeeSelectionSheetState return Text( "(~${ref.watch( pAmountFormatter( - manager.coin, + coin, ), ).format( snapshot.data!, @@ -370,18 +373,18 @@ class _TransactionFeeSelectionSheetState height: 2, ), if (feeObject == null && - manager.coin != Coin.ethereum) + coin != Coin.ethereum) AnimatedText( stringsToLoopThrough: stringsToLoopThrough, style: STextStyles.itemSubtitle(context), ), if (feeObject != null && - manager.coin != Coin.ethereum) + coin != Coin.ethereum) Text( estimatedTimeToBeIncludedInNextBlock( Constants.targetBlockTimeInSeconds( - manager.coin), + coin), feeObject!.numberOfBlocksFast, ), style: STextStyles.itemSubtitle(context), @@ -405,8 +408,7 @@ class _TransactionFeeSelectionSheetState ref.read(feeRateTypeStateProvider.state).state = FeeRateType.average; } - String? fee = - getAmount(FeeRateType.average, manager.coin); + String? fee = getAmount(FeeRateType.average, coin); if (fee != null) { widget.updateChosen(fee); } @@ -467,7 +469,7 @@ class _TransactionFeeSelectionSheetState if (feeObject != null) FutureBuilder( future: feeFor( - coin: manager.coin, + coin: coin, feeRateType: FeeRateType.average, feeRate: feeObject!.medium, amount: amount, @@ -480,7 +482,7 @@ class _TransactionFeeSelectionSheetState return Text( "(~${ref.watch( pAmountFormatter( - manager.coin, + coin, ), ).format( snapshot.data!, @@ -507,18 +509,18 @@ class _TransactionFeeSelectionSheetState height: 2, ), if (feeObject == null && - manager.coin != Coin.ethereum) + coin != Coin.ethereum) AnimatedText( stringsToLoopThrough: stringsToLoopThrough, style: STextStyles.itemSubtitle(context), ), if (feeObject != null && - manager.coin != Coin.ethereum) + coin != Coin.ethereum) Text( estimatedTimeToBeIncludedInNextBlock( Constants.targetBlockTimeInSeconds( - manager.coin), + coin), feeObject!.numberOfBlocksAverage, ), style: STextStyles.itemSubtitle(context), @@ -542,7 +544,7 @@ class _TransactionFeeSelectionSheetState ref.read(feeRateTypeStateProvider.state).state = FeeRateType.slow; } - String? fee = getAmount(FeeRateType.slow, manager.coin); + String? fee = getAmount(FeeRateType.slow, coin); if (fee != null) { widget.updateChosen(fee); } @@ -603,7 +605,7 @@ class _TransactionFeeSelectionSheetState if (feeObject != null) FutureBuilder( future: feeFor( - coin: manager.coin, + coin: coin, feeRateType: FeeRateType.slow, feeRate: feeObject!.slow, amount: amount, @@ -616,7 +618,7 @@ class _TransactionFeeSelectionSheetState return Text( "(~${ref.watch( pAmountFormatter( - manager.coin, + coin, ), ).format( snapshot.data!, @@ -643,18 +645,18 @@ class _TransactionFeeSelectionSheetState height: 2, ), if (feeObject == null && - manager.coin != Coin.ethereum) + coin != Coin.ethereum) AnimatedText( stringsToLoopThrough: stringsToLoopThrough, style: STextStyles.itemSubtitle(context), ), if (feeObject != null && - manager.coin != Coin.ethereum) + coin != Coin.ethereum) Text( estimatedTimeToBeIncludedInNextBlock( Constants.targetBlockTimeInSeconds( - manager.coin), + coin), feeObject!.numberOfBlocksSlow, ), style: STextStyles.itemSubtitle(context), @@ -670,7 +672,7 @@ class _TransactionFeeSelectionSheetState const SizedBox( height: 24, ), - if (manager.coin.isElectrumXCoin) + if (coin.isElectrumXCoin) GestureDetector( onTap: () { final state = @@ -739,7 +741,7 @@ class _TransactionFeeSelectionSheetState ), ), ), - if (manager.coin.isElectrumXCoin) + if (coin.isElectrumXCoin) const SizedBox( height: 24, ), diff --git a/lib/pages/send_view/token_send_view.dart b/lib/pages/send_view/token_send_view.dart index f5d4ce082..b05beeb25 100644 --- a/lib/pages/send_view/token_send_view.dart +++ b/lib/pages/send_view/token_send_view.dart @@ -26,7 +26,6 @@ import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/ui/fee_rate_type_state_provider.dart'; import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart'; import 'package:stackwallet/route_generator.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/address_utils.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -42,6 +41,8 @@ import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/animated_text.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -194,7 +195,8 @@ class _TokenSendViewState extends ConsumerState { // now check for non standard encoded basic address } else if (ref .read(pWallets) - .getManager(walletId) + .getWallet(walletId) + .cryptoCurrency .validateAddress(qrResult.rawContent)) { _address = qrResult.rawContent.trim(); sendToController.text = _address ?? ""; @@ -325,19 +327,27 @@ class _TokenSendViewState extends ConsumerState { }); } - String? _updateInvalidAddressText(String address, Manager manager) { + String? _updateInvalidAddressText(String address) { if (_data != null && _data!.contactLabel == address) { return null; } - if (address.isNotEmpty && !manager.validateAddress(address)) { + if (address.isNotEmpty && + !ref + .read(pWallets) + .getWallet(walletId) + .cryptoCurrency + .validateAddress(address)) { return "Invalid address"; } return null; } void _updatePreviewButtonState(String? address, Amount? amount) { - final isValidAddress = - ref.read(pWallets).getManager(walletId).validateAddress(address ?? ""); + final isValidAddress = ref + .read(pWallets) + .getWallet(walletId) + .cryptoCurrency + .validateAddress(address ?? ""); ref.read(previewTxButtonStateProvider.state).state = (isValidAddress && amount != null && amount > Amount.zero); } @@ -378,7 +388,7 @@ class _TokenSendViewState extends ConsumerState { await Future.delayed( const Duration(milliseconds: 100), ); - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); final tokenWallet = ref.read(tokenServiceProvider)!; final Amount amount = _amountToSend!; @@ -445,7 +455,7 @@ class _TokenSendViewState extends ConsumerState { barrierDismissible: false, builder: (context) { return BuildingTransactionDialog( - coin: manager.coin, + coin: wallet.info.coin, onCancel: () { wasCancelled = true; @@ -463,15 +473,20 @@ class _TokenSendViewState extends ConsumerState { ), ); - Map txData; - Future> txDataFuture; + TxData txData; + Future txDataFuture; txDataFuture = tokenWallet.prepareSend( - address: _address!, - amount: amount, - args: { - "feeRate": ref.read(feeRateTypeStateProvider), - }, + txData: TxData( + recipients: [ + ( + address: _address!, + amount: amount, + ) + ], + feeRateType: ref.read(feeRateTypeStateProvider), + note: noteController.text, + ), ); final results = await Future.wait([ @@ -479,20 +494,17 @@ class _TokenSendViewState extends ConsumerState { time, ]); - txData = results.first as Map; + txData = results.first as TxData; if (!wasCancelled && mounted) { // pop building dialog Navigator.of(context).pop(); - txData["note"] = noteController.text; - - txData["address"] = _address; unawaited(Navigator.of(context).push( RouteGenerator.getRoute( shouldUseMaterialRoute: RouteGenerator.useMaterialPageRoute, builder: (_) => ConfirmTransactionView( - transactionInfo: txData, + txData: txData, walletId: walletId, isTokenTx: true, ), @@ -595,8 +607,6 @@ class _TokenSendViewState extends ConsumerState { @override Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final provider = ref - .watch(pWallets.select((value) => value.getManagerProvider(walletId))); final String locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); @@ -664,8 +674,7 @@ class _TokenSendViewState extends ConsumerState { CrossAxisAlignment.start, children: [ Text( - ref.watch(provider.select( - (value) => value.walletName)), + ref.watch(pWalletName(walletId)), style: STextStyles.titleBold12(context) .copyWith(fontSize: 14), overflow: TextOverflow.ellipsis, @@ -857,7 +866,6 @@ class _TokenSendViewState extends ConsumerState { builder: (_) { final error = _updateInvalidAddressText( _address ?? "", - ref.read(pWallets).getManager(walletId), ); if (error == null || error.isEmpty) { diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart index 32c21566a..cc6bf7086 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart @@ -359,7 +359,7 @@ abstract class SWB { StackRestoringUIState? uiState, WalletsService walletsService, ) async { - final manager = tuple.item2; + final wallet = tuple.item2; final walletbackup = tuple.item1; List mnemonicList = (walletbackup['mnemonic'] as List) @@ -705,7 +705,7 @@ abstract class SWB { failovers, ); - final manager = Manager(wallet); + final wallet = Manager(wallet); managers.add(Tuple2(walletbackup, manager)); // check if cancel was requested and restore previous state diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_widgets/restoring_wallet_card.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_widgets/restoring_wallet_card.dart index 3e762e177..5b6b7d8d1 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_widgets/restoring_wallet_card.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/sub_widgets/restoring_wallet_card.dart @@ -105,10 +105,10 @@ class _RestoringWalletCardState extends ConsumerState { ), onRightTapped: restoringStatus == StackRestoringStatus.failed ? () async { - final manager = ref.read(provider).manager!; + final wallet = ref.read(provider).manager!; ref.read(stackRestoringUIStateProvider).update( - walletId: manager.walletId, + walletId: wallet.walletId, restoringStatus: StackRestoringStatus.restoring); try { @@ -250,7 +250,7 @@ class _RestoringWalletCardState extends ConsumerState { ), onRightTapped: restoringStatus == StackRestoringStatus.failed ? () async { - final manager = ref.read(provider).manager!; + final wallet = ref.read(provider).manager!; ref.read(stackRestoringUIStateProvider).update( walletId: manager.walletId, diff --git a/lib/pages/settings_views/global_settings_view/startup_preferences/startup_preferences_view.dart b/lib/pages/settings_views/global_settings_view/startup_preferences/startup_preferences_view.dart index b5939f1fe..835d156df 100644 --- a/lib/pages/settings_views/global_settings_view/startup_preferences/startup_preferences_view.dart +++ b/lib/pages/settings_views/global_settings_view/startup_preferences/startup_preferences_view.dart @@ -19,6 +19,7 @@ import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; @@ -45,7 +46,7 @@ class _StartupPreferencesViewState // check if wallet exists (hasn't been deleted or otherwise missing) if (possibleWalletId != null) { try { - ref.read(pWallets).getManager(possibleWalletId); + ref.read(pWallets).getWallet(possibleWalletId); } catch (_) { safe = false; WidgetsBinding.instance.addPostFrameCallback((timeStamp) { @@ -252,19 +253,14 @@ class _StartupPreferencesViewState File( ref.watch( coinIconProvider( - ref - .watch( - pWallets - .select( - (value) => - value.getManager( - ref.watch( - prefsChangeNotifierProvider.select((value) => value.startupWalletId!), - ), - ), - ), - ) - .coin, + ref.watch( + pWalletCoin( + ref.watch( + prefsChangeNotifierProvider.select((value) => + value.startupWalletId!), + ), + ), + ), ), ), ), @@ -273,21 +269,15 @@ class _StartupPreferencesViewState width: 10, ), Text( - ref - .watch( - pWallets - .select( - (value) => - value - .getManager( - ref.watch( - prefsChangeNotifierProvider.select((value) => - value.startupWalletId!), - ), - ), - ), - ) - .walletName, + ref.watch( + pWalletName( + ref.watch( + prefsChangeNotifierProvider.select( + (value) => + value.startupWalletId!), + ), + ), + ), style: STextStyles .itemSubtitle( context), diff --git a/lib/pages/settings_views/global_settings_view/startup_preferences/startup_wallet_selection_view.dart b/lib/pages/settings_views/global_settings_view/startup_preferences/startup_wallet_selection_view.dart index 31d439b2f..6e057eaf4 100644 --- a/lib/pages/settings_views/global_settings_view/startup_preferences/startup_wallet_selection_view.dart +++ b/lib/pages/settings_views/global_settings_view/startup_preferences/startup_wallet_selection_view.dart @@ -18,6 +18,7 @@ import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/custom_buttons/draggable_switch_button.dart'; @@ -38,10 +39,10 @@ class _StartupWalletSelectionViewState @override Widget build(BuildContext context) { - final managers = ref.watch(pWallets.select((value) => value.managers)); + final wallets = ref.watch(pWallets).wallets; _controllers.clear(); - for (final manager in managers) { + for (final manager in wallets) { _controllers[manager.walletId] = DSBController(); } @@ -94,18 +95,21 @@ class _StartupWalletSelectionViewState padding: const EdgeInsets.all(0), child: Column( children: [ - ...managers.map( - (manager) => Padding( + ...wallets.map( + (wallet) => Padding( padding: const EdgeInsets.all(12), child: Row( key: Key( - "startupWalletSelectionGroupKey_${manager.walletId}"), + "startupWalletSelectionGroupKey_${wallet.walletId}"), children: [ Container( decoration: BoxDecoration( color: Theme.of(context) .extension()! - .colorForCoin(manager.coin) + .colorForCoin( + ref.watch(pWalletCoin( + wallet.walletId)), + ) .withOpacity(0.5), borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, @@ -116,7 +120,10 @@ class _StartupWalletSelectionViewState child: SvgPicture.file( File( ref.watch( - coinIconProvider(manager.coin), + coinIconProvider( + ref.watch(pWalletCoin( + wallet.walletId)), + ), ), ), width: 20, @@ -135,7 +142,8 @@ class _StartupWalletSelectionViewState CrossAxisAlignment.start, children: [ Text( - manager.walletName, + ref.watch( + pWalletName(wallet.walletId)), style: STextStyles.titleBold12( context), ), @@ -183,7 +191,7 @@ class _StartupWalletSelectionViewState activeColor: Theme.of(context) .extension()! .radioButtonIconEnabled, - value: manager.walletId, + value: wallet.walletId, groupValue: ref.watch( prefsChangeNotifierProvider.select( (value) => diff --git a/lib/pages/settings_views/global_settings_view/syncing_preferences_views/syncing_options_view.dart b/lib/pages/settings_views/global_settings_view/syncing_preferences_views/syncing_options_view.dart index 6c964529a..4ff5da679 100644 --- a/lib/pages/settings_views/global_settings_view/syncing_preferences_views/syncing_options_view.dart +++ b/lib/pages/settings_views/global_settings_view/syncing_preferences_views/syncing_options_view.dart @@ -11,6 +11,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:stackwallet/pages/settings_views/global_settings_view/syncing_preferences_views/wallet_syncing_options_view.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; @@ -95,8 +96,8 @@ class SyncingOptionsView extends ConsumerWidget { SyncingType.currentWalletOnly; // disable auto sync on all wallets that aren't active/current - ref.read(pWallets).managers.forEach((e) { - if (!e.isActiveWallet) { + ref.read(pWallets).wallets.forEach((e) { + if (e.walletId != ref.read(currentWalletIdProvider)) { e.shouldAutoSync = false; } }); @@ -176,7 +177,7 @@ class SyncingOptionsView extends ConsumerWidget { // enable auto sync on all wallets ref .read(pWallets) - .managers + .wallets .forEach((e) => e.shouldAutoSync = true); } }, @@ -256,7 +257,7 @@ class SyncingOptionsView extends ConsumerWidget { .walletIdsSyncOnStartup; // enable auto sync on selected wallets only - ref.read(pWallets).managers.forEach( + ref.read(pWallets).wallets.forEach( (e) => e.shouldAutoSync = ids.contains(e.walletId)); } }, diff --git a/lib/pages/settings_views/global_settings_view/syncing_preferences_views/wallet_syncing_options_view.dart b/lib/pages/settings_views/global_settings_view/syncing_preferences_views/wallet_syncing_options_view.dart index 32f2dbc17..824656496 100644 --- a/lib/pages/settings_views/global_settings_view/syncing_preferences_views/wallet_syncing_options_view.dart +++ b/lib/pages/settings_views/global_settings_view/syncing_preferences_views/wallet_syncing_options_view.dart @@ -13,6 +13,7 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; @@ -21,6 +22,7 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/sync_type_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -34,7 +36,7 @@ class WalletSyncingOptionsView extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final managers = ref.watch(pWallets.select((value) => value.managers)); + final walletInfos = ref.watch(pWallets).wallets.map((e) => e.info); final isDesktop = Util.isDesktop; return ConditionalParent( @@ -73,7 +75,7 @@ class WalletSyncingOptionsView extends ConsumerWidget { condition: isDesktop, builder: (child) { return Padding( - padding: EdgeInsets.symmetric(horizontal: 32), + padding: const EdgeInsets.symmetric(horizontal: 32), child: child, ); }, @@ -108,18 +110,18 @@ class WalletSyncingOptionsView extends ConsumerWidget { .background, child: Column( children: [ - ...managers.map( - (manager) => Padding( + ...walletInfos.map( + (info) => Padding( padding: const EdgeInsets.all(12), child: Row( key: Key( - "syncingPrefsSelectedWalletIdGroupKey_${manager.walletId}"), + "syncingPrefsSelectedWalletIdGroupKey_${info.walletId}"), children: [ Container( decoration: BoxDecoration( color: Theme.of(context) .extension()! - .colorForCoin(manager.coin) + .colorForCoin(info.coin) .withOpacity(0.5), borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, @@ -130,7 +132,7 @@ class WalletSyncingOptionsView extends ConsumerWidget { child: SvgPicture.file( File( ref.watch( - coinIconProvider(manager.coin), + coinIconProvider(info.coin), ), ), width: 20, @@ -148,7 +150,7 @@ class WalletSyncingOptionsView extends ConsumerWidget { CrossAxisAlignment.start, children: [ Text( - manager.walletName, + info.name, style: STextStyles.titleBold12(context), ), @@ -157,9 +159,12 @@ class WalletSyncingOptionsView extends ConsumerWidget { ), Text( ref - .watch(pAmountFormatter( - manager.coin)) - .format(manager.balance.total), + .watch( + pAmountFormatter(info.coin)) + .format(ref + .watch(pWalletBalance( + info.walletId)) + .total), style: STextStyles.itemSubtitle(context), ) @@ -174,7 +179,7 @@ class WalletSyncingOptionsView extends ConsumerWidget { .watch(prefsChangeNotifierProvider .select((value) => value .walletIdsSyncOnStartup)) - .contains(manager.walletId), + .contains(info.walletId), onValueChanged: (value) { final syncType = ref .read(prefsChangeNotifierProvider) @@ -184,22 +189,28 @@ class WalletSyncingOptionsView extends ConsumerWidget { .walletIdsSyncOnStartup .toList(); if (value) { - ids.add(manager.walletId); + ids.add(info.walletId); } else { - ids.remove(manager.walletId); + ids.remove(info.walletId); } + final wallet = ref + .read(pWallets) + .getWallet(info.walletId); + switch (syncType) { case SyncingType.currentWalletOnly: - if (manager.isActiveWallet) { - manager.shouldAutoSync = value; + if (info.walletId == + ref.read( + currentWalletIdProvider)) { + wallet.shouldAutoSync = value; } break; case SyncingType .selectedWalletsAtStartup: case SyncingType .allWalletsOnStartup: - manager.shouldAutoSync = value; + wallet.shouldAutoSync = value; break; } diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_backup_views/wallet_backup_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_backup_views/wallet_backup_view.dart index 53980b9d8..8c2873d0d 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_backup_views/wallet_backup_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_backup_views/wallet_backup_view.dart @@ -17,13 +17,13 @@ import 'package:flutter_svg/svg.dart'; import 'package:qr_flutter/qr_flutter.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_view/sub_widgets/mnemonic_table.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/address_utils.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/clipboard_interface.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/stack_dialog.dart'; @@ -98,10 +98,7 @@ class WalletBackupView extends ConsumerWidget { height: 4, ), Text( - ref - .watch( - pWallets.select((value) => value.getManager(walletId))) - .walletName, + ref.watch(pWalletName(walletId)), textAlign: TextAlign.center, style: STextStyles.label(context).copyWith( fontSize: 12, diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart index 606553ae2..b15a33390 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_network_settings_view/wallet_network_settings_view.dart @@ -38,6 +38,7 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/animated_text.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; @@ -136,12 +137,10 @@ class _WalletNetworkSettingsViewState ); try { - if (ref.read(pWallets).getManager(widget.walletId).coin == Coin.firo) { - maxUnusedAddressGap = 50; - } - await ref.read(pWallets).getManager(widget.walletId).fullRescan( - maxUnusedAddressGap, - maxNumberOfIndexesToCheck, + final wallet = ref.read(pWallets).getWallet(widget.walletId); + + await wallet.recover(isRescan: true + , ); if (mounted) { @@ -250,7 +249,7 @@ class _WalletNetworkSettingsViewState }, ); - final coin = ref.read(pWallets).getManager(widget.walletId).coin; + final coin = ref.read(pWalletCoin(widget.walletId)); if (coin == Coin.monero || coin == Coin.wownero || coin == Coin.epicCash) { _blocksRemainingSubscription = eventBus.on().listen( @@ -309,36 +308,36 @@ class _WalletNetworkSettingsViewState ? 430.0 : screenWidth - (_padding * 2) - (_boxPadding * 3) - _iconSize; - final coin = ref.read(pWallets).getManager(widget.walletId).coin; + final coin = ref.watch(pWalletCoin(widget.walletId)); - if (coin == Coin.monero) { - double highestPercent = (ref - .read(pWallets) - .getManager(widget.walletId) - .wallet as MoneroWallet) - .highestPercentCached; - if (_percent < highestPercent) { - _percent = highestPercent.clamp(0.0, 1.0); - } - } else if (coin == Coin.wownero) { - double highestPercent = (ref - .read(pWallets) - .getManager(widget.walletId) - .wallet as WowneroWallet) - .highestPercentCached; - if (_percent < highestPercent) { - _percent = highestPercent.clamp(0.0, 1.0); - } - } else if (coin == Coin.epicCash) { - double highestPercent = (ref - .read(pWallets) - .getManager(widget.walletId) - .wallet as EpicCashWallet) - .highestPercent; - if (_percent < highestPercent) { - _percent = highestPercent.clamp(0.0, 1.0); - } - } + + // TODO: [prio=high] sync percent for certain wallets + // if (coin == Coin.monero) { + // double highestPercent = + // (ref.read(pWallets).getWallet(widget.walletId).wallet as MoneroWallet) + // .highestPercentCached; + // if (_percent < highestPercent) { + // _percent = highestPercent.clamp(0.0, 1.0); + // } + // } else if (coin == Coin.wownero) { + // double highestPercent = (ref + // .watch(pWallets) + // .getWallet(widget.walletId) + // .wallet as WowneroWallet) + // .highestPercentCached; + // if (_percent < highestPercent) { + // _percent = highestPercent.clamp(0.0, 1.0); + // } + // } else if (coin == Coin.epicCash) { + // double highestPercent = (ref + // .watch(pWallets) + // .getWallet(widget.walletId) + // .wallet as EpicCashWallet) + // .highestPercent; + // if (_percent < highestPercent) { + // _percent = highestPercent.clamp(0.0, 1.0); + // } + // } return ConditionalParent( condition: !isDesktop, @@ -358,7 +357,7 @@ class _WalletNetworkSettingsViewState style: STextStyles.navBarTitle(context), ), actions: [ - if (ref.read(pWallets).getManager(widget.walletId).coin != + if (ref.watch(pWalletCoin(widget.walletId)) != Coin.epicCash) Padding( padding: const EdgeInsets.only( @@ -483,7 +482,7 @@ class _WalletNetworkSettingsViewState CustomTextButton( text: "Resync", onTap: () { - ref.read(pWallets).getManager(widget.walletId).refresh(); + ref.read(pWallets).getWallet(widget.walletId).refresh(); }, ), ], @@ -886,7 +885,7 @@ class _WalletNetworkSettingsViewState mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - "${ref.watch(pWallets.select((value) => value.getManager(widget.walletId).coin)).prettyName} nodes", + "${ref.watch(pWalletCoin(widget.walletId)).prettyName} nodes", textAlign: TextAlign.left, style: isDesktop ? STextStyles.desktopTextExtraExtraSmall(context) @@ -899,7 +898,7 @@ class _WalletNetworkSettingsViewState AddEditNodeView.routeName, arguments: Tuple4( AddEditNodeViewType.add, - ref.read(pWallets).getManager(widget.walletId).coin, + ref.read(pWalletCoin(widget.walletId)), null, WalletNetworkSettingsView.routeName, ), @@ -912,18 +911,17 @@ class _WalletNetworkSettingsViewState height: isDesktop ? 12 : 8, ), NodesList( - coin: ref.watch(pWallets - .select((value) => value.getManager(widget.walletId).coin)), + coin: ref.watch(pWalletCoin(widget.walletId)), popBackToRoute: WalletNetworkSettingsView.routeName, ), if (isDesktop && - ref.read(pWallets).getManager(widget.walletId).coin != + ref.watch(pWalletCoin(widget.walletId)) != Coin.epicCash) const SizedBox( height: 32, ), if (isDesktop && - ref.read(pWallets).getManager(widget.walletId).coin != + ref.watch(pWalletCoin(widget.walletId)) != Coin.epicCash) Padding( padding: const EdgeInsets.only( @@ -941,7 +939,7 @@ class _WalletNetworkSettingsViewState ), ), if (isDesktop && - ref.read(pWallets).getManager(widget.walletId).coin != + ref.watch(pWalletCoin(widget.walletId)) != Coin.epicCash) RoundedWhiteContainer( borderColor: isDesktop diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_view.dart index 6bae275e1..c331e900e 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_view.dart @@ -40,6 +40,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/show_loading.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/wallet/bip39_wallet.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/secondary_button.dart'; @@ -88,7 +89,9 @@ class _WalletSettingsViewState extends ConsumerState { void initState() { walletId = widget.walletId; coin = widget.coin; - xPubEnabled = ref.read(pWallets).getManager(walletId).hasXPub; + // TODO: [prio=low] xpubs + // xPubEnabled = ref.read(pWallets).getWallet(walletId).hasXPub; + xPubEnabled = false; xpub = ""; _currentSyncStatus = widget.initialSyncStatus; @@ -229,36 +232,42 @@ class _WalletSettingsViewState extends ConsumerState { iconSize: 16, title: "Wallet backup", onPressed: () async { - final mnemonic = await ref + final wallet = ref .read(pWallets) - .getManager(walletId) - .mnemonic; + .getWallet(widget.walletId); + // TODO: [prio=high] take wallets that don't have amnemonic into account + if (wallet is Bip39Wallet) { + final mnemonic = + await wallet.getMnemonicAsWords(); - if (mounted) { - await Navigator.push( - context, - RouteGenerator.getRoute( - shouldUseMaterialRoute: - RouteGenerator - .useMaterialPageRoute, - builder: (_) => LockscreenView( - routeOnSuccessArguments: - Tuple2(walletId, mnemonic), - showBackButton: true, - routeOnSuccess: - WalletBackupView.routeName, - biometricsCancelButtonString: - "CANCEL", - biometricsLocalizedReason: - "Authenticate to view recovery phrase", - biometricsAuthenticationTitle: - "View recovery phrase", + if (mounted) { + await Navigator.push( + context, + RouteGenerator.getRoute( + shouldUseMaterialRoute: + RouteGenerator + .useMaterialPageRoute, + builder: (_) => LockscreenView( + routeOnSuccessArguments: + Tuple2( + walletId, mnemonic), + showBackButton: true, + routeOnSuccess: + WalletBackupView + .routeName, + biometricsCancelButtonString: + "CANCEL", + biometricsLocalizedReason: + "Authenticate to view recovery phrase", + biometricsAuthenticationTitle: + "View recovery phrase", + ), + settings: const RouteSettings( + name: + "/viewRecoverPhraseLockscreen"), ), - settings: const RouteSettings( - name: - "/viewRecoverPhraseLockscreen"), - ), - ); + ); + } } }, ); @@ -405,10 +414,11 @@ class _WalletSettingsViewState extends ConsumerState { builder: (_, ref, __) { return TextButton( onPressed: () { - ref - .read(pWallets) - .getManager(walletId) - .isActiveWallet = false; + // TODO: [prio=med] needs more thought if this is still required + // ref + // .read(pWallets) + // .getWallet(walletId) + // .isActiveWallet = false; ref .read(transactionFilterProvider.state) .state = null; @@ -464,8 +474,7 @@ class _EpiBoxInfoFormState extends ConsumerState { @override void initState() { - wallet = - ref.read(pWallets).getManager(widget.walletId).wallet as EpicCashWallet; + wallet = ref.read(pWallets).getWallet(widget.walletId) as EpicCashWallet; wallet.getEpicBoxConfig().then((EpicBoxConfigModel epicBoxConfig) { hostController.text = epicBoxConfig.host; diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/change_representative_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/change_representative_view.dart index b7e22797f..7e471d6e7 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/change_representative_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/change_representative_view.dart @@ -64,22 +64,24 @@ class _XPubViewState extends ConsumerState { String? representative; Future loadRepresentative() async { - final manager = ref.read(pWallets).getManager(widget.walletId); + final wallet = ref.read(pWallets).getWallet(widget.walletId); + final coin = wallet.info.coin; - if (manager.coin == Coin.nano) { - return (manager.wallet as NanoWallet).getCurrentRepresentative(); - } else if (manager.coin == Coin.banano) { - return (manager.wallet as BananoWallet).getCurrentRepresentative(); + if (coin == Coin.nano) { + return (wallet as NanoWallet).getCurrentRepresentative(); + } else if (coin == Coin.banano) { + return (wallet as BananoWallet).getCurrentRepresentative(); } throw Exception("Unsupported wallet attempted to show representative!"); } Future _save() async { - final manager = ref.read(pWallets).getManager(widget.walletId); + final wallet = ref.read(pWallets).getWallet(widget.walletId); + final coin = wallet.info.coin; - final changeFuture = manager.coin == Coin.nano - ? (manager.wallet as NanoWallet).changeRepresentative - : (manager.wallet as BananoWallet).changeRepresentative; + final changeFuture = coin == Coin.nano + ? (wallet as NanoWallet).changeRepresentative + : (wallet as BananoWallet).changeRepresentative; final result = await showLoading( whileFuture: changeFuture(_textController.text), diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_recovery_phrase_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_recovery_phrase_view.dart index e08f2db39..2baff002f 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_recovery_phrase_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_recovery_phrase_view.dart @@ -8,20 +8,20 @@ * */ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_view/sub_widgets/mnemonic_table.dart'; -import 'package:stackwallet/pages/home_view/home_view.dart'; -import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/clipboard_interface.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/stack_dialog.dart'; @@ -29,14 +29,14 @@ import 'package:stackwallet/widgets/stack_dialog.dart'; class DeleteWalletRecoveryPhraseView extends ConsumerStatefulWidget { const DeleteWalletRecoveryPhraseView({ Key? key, - required this.manager, + required this.walletId, required this.mnemonic, this.clipboardInterface = const ClipboardWrapper(), }) : super(key: key); static const routeName = "/deleteWalletRecoveryPhrase"; - final Manager manager; + final String walletId; final List mnemonic; final ClipboardInterface clipboardInterface; @@ -48,13 +48,11 @@ class DeleteWalletRecoveryPhraseView extends ConsumerStatefulWidget { class _DeleteWalletRecoveryPhraseViewState extends ConsumerState { - late Manager _manager; late List _mnemonic; late ClipboardInterface _clipboardInterface; @override void initState() { - _manager = widget.manager; _mnemonic = widget.mnemonic; _clipboardInterface = widget.clipboardInterface; super.initState(); @@ -90,15 +88,18 @@ class _DeleteWalletRecoveryPhraseViewState .topNavIconPrimary, ), onPressed: () async { - final words = await _manager.mnemonic; await _clipboardInterface - .setData(ClipboardData(text: words.join(" "))); - showFloatingFlushBar( - type: FlushBarType.info, - message: "Copied to clipboard", - iconAsset: Assets.svg.copy, - context: context, - ); + .setData(ClipboardData(text: _mnemonic.join(" "))); + if (mounted) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.info, + message: "Copied to clipboard", + iconAsset: Assets.svg.copy, + context: context, + ), + ); + } }, ), ), @@ -114,7 +115,7 @@ class _DeleteWalletRecoveryPhraseViewState height: 4, ), Text( - _manager.walletName, + ref.watch(pWalletName(widget.walletId)), textAlign: TextAlign.center, style: STextStyles.label(context).copyWith( fontSize: 12, @@ -192,22 +193,23 @@ class _DeleteWalletRecoveryPhraseViewState .extension()! .getPrimaryEnabledButtonStyle(context), onPressed: () async { - final walletId = _manager.walletId; - final walletsInstance = - ref.read(pWallets); - await ref - .read(walletsServiceChangeNotifierProvider) - .deleteWallet(_manager.walletName, true); + // TODO: [prio=high] wallet deletion - if (mounted) { - Navigator.of(context).popUntil( - ModalRoute.withName(HomeView.routeName)); - } - - // wait for widget tree to dispose of any widgets watching the manager - await Future.delayed( - const Duration(seconds: 1)); - walletsInstance.removeWallet(walletId: walletId); + // final walletId = _manager.walletId; + // final walletsInstance = ref.read(pWallets); + // await ref + // .read(walletsServiceChangeNotifierProvider) + // .deleteWallet(_manager.walletName, true); + // + // if (mounted) { + // Navigator.of(context).popUntil( + // ModalRoute.withName(HomeView.routeName)); + // } + // + // // wait for widget tree to dispose of any widgets watching the manager + // await Future.delayed( + // const Duration(seconds: 1)); + // walletsInstance.removeWallet(walletId: walletId); }, child: Text( "Ok", diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_warning_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_warning_view.dart index 6fcc3cf5b..a41ded80d 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_warning_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_warning_view.dart @@ -14,10 +14,10 @@ import 'package:stackwallet/pages/settings_views/wallet_settings_view/wallet_set import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/wallet/bip39_wallet.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/rounded_container.dart'; -import 'package:tuple/tuple.dart'; class DeleteWalletWarningView extends ConsumerWidget { const DeleteWalletWarningView({ @@ -99,15 +99,18 @@ class DeleteWalletWarningView extends ConsumerWidget { .extension()! .getPrimaryEnabledButtonStyle(context), onPressed: () async { - final manager = ref.read(pWallets).getManager(walletId); - final mnemonic = await manager.mnemonic; - Navigator.of(context).pushNamed( - DeleteWalletRecoveryPhraseView.routeName, - arguments: Tuple2( - manager, - mnemonic, - ), - ); + final wallet = ref.read(pWallets).getWallet(walletId); + final mnemonic = + await (wallet as Bip39Wallet).getMnemonicAsWords(); + if (context.mounted) { + await Navigator.of(context).pushNamed( + DeleteWalletRecoveryPhraseView.routeName, + arguments: ( + walletId: walletId, + mnemonicWords: mnemonic, + ), + ); + } }, child: Text( "View Backup Key", diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/rename_wallet_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/rename_wallet_view.dart index 43bec92c5..b4b457c39 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/rename_wallet_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/rename_wallet_view.dart @@ -8,14 +8,17 @@ * */ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; -import 'package:stackwallet/providers/providers.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/icon_widgets/x_icon.dart'; @@ -47,7 +50,7 @@ class _RenameWalletViewState extends ConsumerState { void initState() { _controller = TextEditingController(); walletId = widget.walletId; - originalName = ref.read(pWallets).getManager(walletId).walletName; + originalName = ref.read(pWalletName(walletId)); _controller.text = originalName; super.initState(); } @@ -125,29 +128,42 @@ class _RenameWalletViewState extends ConsumerState { .getPrimaryEnabledButtonStyle(context), onPressed: () async { final newName = _controller.text; - final success = await ref - .read(walletsServiceChangeNotifierProvider) - .renameWallet( - from: originalName, - to: newName, - shouldNotifyListeners: true, - ); - if (success) { - ref.read(pWallets).getManager(walletId).walletName = - newName; - Navigator.of(context).pop(); - showFloatingFlushBar( - type: FlushBarType.success, - message: "Wallet renamed", - context: context, - ); - } else { - showFloatingFlushBar( - type: FlushBarType.warning, - message: "Wallet named \"$newName\" already exists", - context: context, - ); + String? errMessage; + try { + await ref.read(pWalletInfo(walletId)).updateName( + newName: newName, + isar: ref.read(mainDBProvider).isar, + ); + } catch (e) { + if (e + .toString() + .contains("Empty wallet name not allowed!")) { + errMessage = "Empty wallet name not allowed."; + } else { + errMessage = e.toString(); + } + } + + if (mounted) { + if (errMessage == null) { + Navigator.of(context).pop(); + unawaited( + showFloatingFlushBar( + type: FlushBarType.success, + message: "Wallet renamed", + context: context, + ), + ); + } else { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: "Wallet named \"$newName\" already exists", + context: context, + ), + ); + } } }, child: Text( diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart index 9db16be31..8ead8cd35 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/wallet_settings_wallet_settings_view.dart @@ -13,11 +13,11 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:stackwallet/pages/pinpad_views/lock_screen_view.dart'; import 'package:stackwallet/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/delete_wallet_warning_view.dart'; import 'package:stackwallet/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/rename_wallet_view.dart'; -import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/route_generator.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; @@ -111,7 +111,7 @@ class WalletSettingsWalletSettingsView extends ConsumerWidget { context: context, builder: (_) => StackDialog( title: - "Do you want to delete ${ref.read(pWallets).getManager(walletId).walletName}?", + "Do you want to delete ${ref.read(pWalletName(walletId))}?", leftButton: TextButton( style: Theme.of(context) .extension()! diff --git a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/xpub_view.dart b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/xpub_view.dart index 7ca563a02..230e0798e 100644 --- a/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/xpub_view.dart +++ b/lib/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/xpub_view.dart @@ -17,12 +17,12 @@ import 'package:flutter_svg/svg.dart'; import 'package:qr_flutter/qr_flutter.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/clipboard_interface.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -53,14 +53,14 @@ class _XPubViewState extends ConsumerState { final bool isDesktop = Util.isDesktop; late ClipboardInterface _clipboardInterface; - late final Manager manager; + late final Wallet wallet; String? xpub; @override void initState() { _clipboardInterface = widget.clipboardInterface; - manager = ref.read(pWallets).getManager(widget.walletId); + wallet = ref.read(pWallets).getWallet(widget.walletId); super.initState(); } @@ -152,7 +152,7 @@ class _XPubViewState extends ConsumerState { left: 32, ), child: Text( - "${manager.walletName} xPub", + "${wallet.info.name} xPub", style: STextStyles.desktopH2(context), ), ), @@ -185,7 +185,8 @@ class _XPubViewState extends ConsumerState { child: child, ), child: FutureBuilder( - future: manager.xpub, + future: Future(() => "fixme"), + // future: wallet.xpub, builder: (context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) { diff --git a/lib/pages/special/firo_rescan_recovery_error_dialog.dart b/lib/pages/special/firo_rescan_recovery_error_dialog.dart index 0aea6328e..ad6c7ec65 100644 --- a/lib/pages/special/firo_rescan_recovery_error_dialog.dart +++ b/lib/pages/special/firo_rescan_recovery_error_dialog.dart @@ -12,6 +12,8 @@ import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/bip39_wallet.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -131,12 +133,13 @@ class _FiroRescanRecoveryErrorViewState .topNavIconPrimary, ), onPressed: () async { + final walletName = + ref.read(pWalletName(widget.walletId)); await showDialog( barrierDismissible: true, context: context, builder: (_) => StackDialog( - title: - "Do you want to delete ${ref.read(pWallets).getManager(widget.walletId).walletName}?", + title: "Do you want to delete $walletName?", leftButton: TextButton( style: Theme.of(context) .extension()! @@ -253,32 +256,34 @@ class _FiroRescanRecoveryErrorViewState ), ); } else { - final mnemonic = await ref - .read(pWallets) - .getManager(widget.walletId) - .mnemonic; + final wallet = + ref.read(pWallets).getWallet(widget.walletId); + // TODO: [prio=high] take wallets that don't have amnemonic into account + if (wallet is Bip39Wallet) { + final mnemonic = await wallet.getMnemonicAsWords(); - if (mounted) { - await Navigator.push( - context, - RouteGenerator.getRoute( - shouldUseMaterialRoute: - RouteGenerator.useMaterialPageRoute, - builder: (_) => LockscreenView( - routeOnSuccessArguments: - Tuple2(widget.walletId, mnemonic), - showBackButton: true, - routeOnSuccess: WalletBackupView.routeName, - biometricsCancelButtonString: "CANCEL", - biometricsLocalizedReason: - "Authenticate to view recovery phrase", - biometricsAuthenticationTitle: - "View recovery phrase", + if (mounted) { + await Navigator.push( + context, + RouteGenerator.getRoute( + shouldUseMaterialRoute: + RouteGenerator.useMaterialPageRoute, + builder: (_) => LockscreenView( + routeOnSuccessArguments: + Tuple2(widget.walletId, mnemonic), + showBackButton: true, + routeOnSuccess: WalletBackupView.routeName, + biometricsCancelButtonString: "CANCEL", + biometricsLocalizedReason: + "Authenticate to view recovery phrase", + biometricsAuthenticationTitle: + "View recovery phrase", + ), + settings: const RouteSettings( + name: "/viewRecoverPhraseLockscreen"), ), - settings: const RouteSettings( - name: "/viewRecoverPhraseLockscreen"), - ), - ); + ); + } } } }, diff --git a/lib/pages/token_view/my_tokens_view.dart b/lib/pages/token_view/my_tokens_view.dart index 92ea720c6..7a8b3d1d3 100644 --- a/lib/pages/token_view/my_tokens_view.dart +++ b/lib/pages/token_view/my_tokens_view.dart @@ -22,6 +22,7 @@ import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -89,8 +90,7 @@ class _MyTokensViewState extends ConsumerState { ), title: Text( "${ref.watch( - pWallets.select( - (value) => value.getManager(widget.walletId).walletName), + pWalletName(widget.walletId), )} Tokens", style: STextStyles.navBarTitle(context), ), @@ -234,9 +234,8 @@ class _MyTokensViewState extends ConsumerState { walletId: widget.walletId, searchTerm: _searchString, tokenContracts: ref - .watch(pWallets.select((value) => value - .getManager(widget.walletId) - .wallet as EthereumWallet)) + .watch(pWallets.select((value) => + value.getWallet(widget.walletId) as EthereumWallet)) .getWalletTokenContractAddresses(), ), ), diff --git a/lib/pages/token_view/sub_widgets/my_token_select_item.dart b/lib/pages/token_view/sub_widgets/my_token_select_item.dart index 35edaa5cf..e678dfa19 100644 --- a/lib/pages/token_view/sub_widgets/my_token_select_item.dart +++ b/lib/pages/token_view/sub_widgets/my_token_select_item.dart @@ -26,6 +26,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/show_loading.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/desktop/primary_button.dart'; import 'package:stackwallet/widgets/dialogs/basic_dialog.dart'; import 'package:stackwallet/widgets/icon_widgets/eth_token_icon.dart'; @@ -84,10 +85,8 @@ class _MyTokenSelectItemState extends ConsumerState { ref.read(tokenServiceStateProvider.state).state = EthTokenWallet( token: widget.token, secureStore: ref.read(secureStoreProvider), - ethWallet: ref - .read(pWallets) - .getManager(widget.walletId) - .wallet as EthereumWallet, + ethWallet: + ref.read(pWallets).getWallet(widget.walletId) as EthereumWallet, tracker: TransactionNotificationTracker( walletId: widget.walletId, ), @@ -117,10 +116,7 @@ class _MyTokenSelectItemState extends ConsumerState { cachedBalance = CachedEthTokenBalance(widget.walletId, widget.token); WidgetsBinding.instance.addPostFrameCallback((_) async { - final address = await ref - .read(pWallets) - .getManager(widget.walletId) - .currentReceivingAddress; + final address = ref.read(pWalletReceivingAddress(widget.walletId)); await cachedBalance.fetchAndUpdateCachedBalance(address); if (mounted) { setState(() {}); diff --git a/lib/pages/token_view/sub_widgets/token_summary.dart b/lib/pages/token_view/sub_widgets/token_summary.dart index f8548aa3e..83f6f8c5f 100644 --- a/lib/pages/token_view/sub_widgets/token_summary.dart +++ b/lib/pages/token_view/sub_widgets/token_summary.dart @@ -24,7 +24,6 @@ import 'package:stackwallet/pages/wallet_view/sub_widgets/wallet_refresh_button. import 'package:stackwallet/providers/global/locale_provider.dart'; import 'package:stackwallet/providers/global/prefs_provider.dart'; import 'package:stackwallet/providers/global/price_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/themes/theme_providers.dart'; @@ -34,6 +33,7 @@ import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/rounded_container.dart'; import 'package:tuple/tuple.dart'; @@ -78,9 +78,7 @@ class TokenSummary extends ConsumerWidget { ), Text( ref.watch( - pWallets.select( - (value) => value.getManager(walletId).walletName, - ), + pWalletName(walletId), ), style: STextStyles.w500_12(context).copyWith( color: Theme.of(context) @@ -366,9 +364,11 @@ class CoinTickerTag extends ConsumerWidget { radiusMultiplier: 0.25, color: Theme.of(context).extension()!.ethTagBG, child: Text( - ref.watch( - pWallets.select((value) => value.getManager(walletId).coin.ticker), - ), + ref + .watch( + pWalletCoin(walletId), + ) + .ticker, style: STextStyles.w600_12(context).copyWith( color: Theme.of(context).extension()!.ethTagText, ), diff --git a/lib/pages/token_view/sub_widgets/token_transaction_list_widget.dart b/lib/pages/token_view/sub_widgets/token_transaction_list_widget.dart index b2a57faf8..85778cf1b 100644 --- a/lib/pages/token_view/sub_widgets/token_transaction_list_widget.dart +++ b/lib/pages/token_view/sub_widgets/token_transaction_list_widget.dart @@ -24,6 +24,7 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog_close_button.dart'; import 'package:stackwallet/widgets/loading_indicator.dart'; @@ -95,8 +96,7 @@ class _TransactionsListState extends ConsumerState { TransactionCard( // this may mess with combined firo transactions key: tx.isConfirmed( - ref.watch(pWallets.select((value) => - value.getManager(widget.walletId).currentHeight)), + ref.watch(pWalletChainHeight(widget.walletId)), coin.requiredConfirmations) ? Key(tx.txid + tx.type.name + tx.address.value.toString()) : UniqueKey(), // @@ -111,8 +111,7 @@ class _TransactionsListState extends ConsumerState { trade.uuid), // trade: trade, onTap: () async { - final walletName = - ref.read(pWallets).getManager(widget.walletId).walletName; + final walletName = ref.read(pWalletName(widget.walletId)); if (Util.isDesktop) { await showDialog( context: context, @@ -195,9 +194,7 @@ class _TransactionsListState extends ConsumerState { ), child: TransactionCard( // this may mess with combined firo transactions - key: tx.isConfirmed( - ref.watch(pWallets.select((value) => - value.getManager(widget.walletId).currentHeight)), + key: tx.isConfirmed(ref.watch(pWalletChainHeight(widget.walletId)), coin.requiredConfirmations) ? Key(tx.txid + tx.type.name + tx.address.value.toString()) : UniqueKey(), @@ -210,8 +207,8 @@ class _TransactionsListState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); + final wallet = + ref.watch(pWallets.select((value) => value.getWallet(widget.walletId))); return FutureBuilder( future: ref @@ -262,7 +259,12 @@ class _TransactionsListState extends ConsumerState { radius = _borderRadiusFirst; } final tx = _transactions2[index]; - return itemBuilder(context, tx, radius, manager.coin); + return itemBuilder( + context, + tx, + radius, + wallet.info.coin, + ); }, separatorBuilder: (context, index) { return Container( @@ -289,7 +291,12 @@ class _TransactionsListState extends ConsumerState { radius = _borderRadiusFirst; } final tx = _transactions2[index]; - return itemBuilder(context, tx, radius, manager.coin); + return itemBuilder( + context, + tx, + radius, + wallet.info.coin, + ); }, ), ); diff --git a/lib/pages/wallet_view/sub_widgets/transactions_list.dart b/lib/pages/wallet_view/sub_widgets/transactions_list.dart index 2007017ab..1bbc803fb 100644 --- a/lib/pages/wallet_view/sub_widgets/transactions_list.dart +++ b/lib/pages/wallet_view/sub_widgets/transactions_list.dart @@ -12,19 +12,21 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:isar/isar.dart'; import 'package:stackwallet/models/isar/models/isar_models.dart'; import 'package:stackwallet/pages/exchange_view/trade_details_view.dart'; import 'package:stackwallet/pages/wallet_view/sub_widgets/no_transactions_found.dart'; import 'package:stackwallet/pages/wallet_view/wallet_view.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/trades_service_provider.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/route_generator.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog_close_button.dart'; import 'package:stackwallet/widgets/loading_indicator.dart'; @@ -36,11 +38,9 @@ class TransactionsList extends ConsumerStatefulWidget { const TransactionsList({ Key? key, required this.walletId, - required this.managerProvider, }) : super(key: key); final String walletId; - final ChangeNotifierProvider managerProvider; @override ConsumerState createState() => _TransactionsListState(); @@ -51,7 +51,8 @@ class _TransactionsListState extends ConsumerState { bool _hasLoaded = false; List _transactions2 = []; - late final ChangeNotifierProvider managerProvider; + late final StreamSubscription> _subscription; + late final QueryBuilder _query; BorderRadius get _borderRadiusFirst { return BorderRadius.only( @@ -80,17 +81,13 @@ class _TransactionsListState extends ConsumerState { Transaction tx, BorderRadius? radius, Coin coin, + int chainHeight, ) { final matchingTrades = ref .read(tradesServiceProvider) .trades .where((e) => e.payInTxid == tx.txid || e.payOutTxid == tx.txid); - final isConfirmed = tx.isConfirmed( - ref.watch( - widget.managerProvider.select((value) => value.currentHeight)), - coin.requiredConfirmations); - if (tx.type == TransactionType.outgoing && matchingTrades.isNotEmpty) { final trade = matchingTrades.first; return Container( @@ -115,6 +112,8 @@ class _TransactionsListState extends ConsumerState { trade.uuid), // trade: trade, onTap: () async { + final walletName = ref.read(pWalletName(widget.walletId)); + if (Util.isDesktop) { await showDialog( context: context, @@ -156,8 +155,7 @@ class _TransactionsListState extends ConsumerState { child: TradeDetailsView( tradeId: trade.tradeId, transactionIfSentFromStack: tx, - walletName: - ref.read(managerProvider).walletName, + walletName: walletName, walletId: widget.walletId, ), ), @@ -180,7 +178,7 @@ class _TransactionsListState extends ConsumerState { trade.tradeId, tx, widget.walletId, - ref.read(managerProvider).walletName, + walletName, ), ), ); @@ -208,17 +206,39 @@ class _TransactionsListState extends ConsumerState { @override void initState() { - managerProvider = widget.managerProvider; + _query = ref + .read(mainDBProvider) + .isar + .transactions + .where() + .walletIdEqualTo(widget.walletId) + .sortByTimestampDesc(); + + _subscription = _query.watch().listen((event) { + WidgetsBinding.instance.addPostFrameCallback((_) { + setState(() { + _transactions2 = event; + }); + }); + }); + super.initState(); } + @override + void dispose() { + _subscription.cancel(); + super.dispose(); + } + @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); + final walletInfo = ref.watch(pWallets).getWallet(widget.walletId).info; + final height = walletInfo.cachedChainHeight; + final coin = walletInfo.coin; return FutureBuilder( - future: manager.transactions, + future: _query.findAll(), builder: (fbContext, AsyncSnapshot> snapshot) { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) { @@ -226,8 +246,8 @@ class _TransactionsListState extends ConsumerState { _hasLoaded = true; } if (!_hasLoaded) { - return Column( - children: const [ + return const Column( + children: [ Spacer(), Center( child: LoadingIndicator( @@ -247,13 +267,7 @@ class _TransactionsListState extends ConsumerState { _transactions2.sort((a, b) => b.timestamp - a.timestamp); return RefreshIndicator( onRefresh: () async { - //todo: check if print needed - // debugPrint("pulled down to refresh on transaction list"); - final managerProvider = - ref.read(pWallets).getManagerProvider(widget.walletId); - if (!ref.read(managerProvider).isRefreshing) { - unawaited(ref.read(managerProvider).refresh()); - } + await ref.read(pWallets).getWallet(widget.walletId).refresh(); }, child: Util.isDesktop ? ListView.separated( @@ -270,7 +284,7 @@ class _TransactionsListState extends ConsumerState { radius = _borderRadiusFirst; } final tx = _transactions2[index]; - return itemBuilder(context, tx, radius, manager.coin); + return itemBuilder(context, tx, radius, coin, height); }, separatorBuilder: (context, index) { return Container( @@ -302,14 +316,14 @@ class _TransactionsListState extends ConsumerState { if (shouldWrap) { return Column( children: [ - itemBuilder(context, tx, radius, manager.coin), + itemBuilder(context, tx, radius, coin, height), const SizedBox( height: WalletView.navBarHeight + 14, ), ], ); } else { - return itemBuilder(context, tx, radius, manager.coin); + return itemBuilder(context, tx, radius, coin, height); } }, ), diff --git a/lib/pages/wallet_view/sub_widgets/wallet_balance_toggle_sheet.dart b/lib/pages/wallet_view/sub_widgets/wallet_balance_toggle_sheet.dart index 90e4c62bd..a0e5a29ee 100644 --- a/lib/pages/wallet_view/sub_widgets/wallet_balance_toggle_sheet.dart +++ b/lib/pages/wallet_view/sub_widgets/wallet_balance_toggle_sheet.dart @@ -11,10 +11,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:stackwallet/models/balance.dart'; -import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/wallet/public_private_balance_state_provider.dart'; import 'package:stackwallet/providers/wallet/wallet_balance_toggle_state_provider.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; @@ -22,6 +20,7 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/wallet_balance_toggle_state.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; enum _BalanceType { available, @@ -42,11 +41,9 @@ class WalletBalanceToggleSheet extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final maxHeight = MediaQuery.of(context).size.height * 0.60; - final coin = - ref.watch(pWallets.select((value) => value.getManager(walletId).coin)); + final coin = ref.watch(pWalletCoin(walletId)); - final balance = ref - .watch(pWallets.select((value) => value.getManager(walletId).balance)); + Balance balance = ref.watch(pWalletBalance(walletId)); _BalanceType _bal = ref.watch(walletBalanceToggleStateProvider.state).state == @@ -56,13 +53,11 @@ class WalletBalanceToggleSheet extends ConsumerWidget { Balance? balanceSecondary; if (coin == Coin.firo || coin == Coin.firoTestNet) { - balanceSecondary = ref - .watch( - pWallets.select( - (value) => value.getManager(walletId).wallet as FiroWallet?, - ), - ) - ?.balancePrivate; + balanceSecondary = ref.watch(pWalletBalanceSecondary(walletId)); + + final temp = balance; + balance = balanceSecondary!; + balanceSecondary = temp; if (ref.watch(publicPrivateBalanceStateProvider.state).state == "Private") { diff --git a/lib/pages/wallet_view/sub_widgets/wallet_refresh_button.dart b/lib/pages/wallet_view/sub_widgets/wallet_refresh_button.dart index d64ad8bff..7700f3f02 100644 --- a/lib/pages/wallet_view/sub_widgets/wallet_refresh_button.dart +++ b/lib/pages/wallet_view/sub_widgets/wallet_refresh_button.dart @@ -133,15 +133,11 @@ class _RefreshButtonState extends ConsumerState { splashColor: Theme.of(context).extension()!.highlight, onPressed: () { if (widget.tokenContractAddress == null) { - final managerProvider = - ref.read(pWallets).getManagerProvider(widget.walletId); - final isRefreshing = ref.read(managerProvider).isRefreshing; + final wallet = ref.read(pWallets).getWallet(widget.walletId); + final isRefreshing = wallet.refreshMutex.isLocked; if (!isRefreshing) { _spinController.repeat?.call(); - ref - .read(managerProvider) - .refresh() - .then((_) => _spinController.stop?.call()); + wallet.refresh().then((_) => _spinController.stop?.call()); } } else { if (!ref.read(tokenServiceProvider)!.isRefreshing) { diff --git a/lib/pages/wallet_view/sub_widgets/wallet_summary_info.dart b/lib/pages/wallet_view/sub_widgets/wallet_summary_info.dart index 3b34625f1..b7eb4d390 100644 --- a/lib/pages/wallet_view/sub_widgets/wallet_summary_info.dart +++ b/lib/pages/wallet_view/sub_widgets/wallet_summary_info.dart @@ -8,7 +8,6 @@ * */ -import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; @@ -20,11 +19,7 @@ import 'package:stackwallet/pages/wallet_view/sub_widgets/wallet_refresh_button. import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/wallet/public_private_balance_state_provider.dart'; import 'package:stackwallet/providers/wallet/wallet_balance_toggle_state_provider.dart'; -import 'package:stackwallet/services/coins/banano/banano_wallet.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; -import 'package:stackwallet/services/event_bus/events/global/balance_refreshed_event.dart'; import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; -import 'package:stackwallet/services/event_bus/global_event_bus.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -33,9 +28,10 @@ import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/wallet_balance_toggle_state.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; -class WalletSummaryInfo extends ConsumerStatefulWidget { +class WalletSummaryInfo extends ConsumerWidget { const WalletSummaryInfo({ Key? key, required this.walletId, @@ -45,16 +41,7 @@ class WalletSummaryInfo extends ConsumerStatefulWidget { final String walletId; final WalletSyncStatus initialSyncStatus; - @override - ConsumerState createState() => _WalletSummaryInfoState(); -} - -class _WalletSummaryInfoState extends ConsumerState { - late StreamSubscription _balanceUpdated; - - String receivingAddress = ""; - - void showSheet() { + void showSheet(BuildContext context) { showModalBottomSheet( backgroundColor: Colors.transparent, context: context, @@ -63,54 +50,22 @@ class _WalletSummaryInfoState extends ConsumerState { top: Radius.circular(20), ), ), - builder: (_) => WalletBalanceToggleSheet(walletId: widget.walletId), + builder: (_) => WalletBalanceToggleSheet(walletId: walletId), ); } @override - void initState() { - _balanceUpdated = - GlobalEventBus.instance.on().listen( - (event) async { - if (event.walletId == widget.walletId) { - setState(() {}); - } - }, - ); - - // managerProvider = widget.managerProvider; - WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { - final address = await ref - .read(pWallets) - .getManager(widget.walletId) - .currentReceivingAddress; - setState(() { - receivingAddress = address; - }); - }); - super.initState(); - } - - @override - void dispose() { - _balanceUpdated.cancel(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { debugPrint("BUILD: $runtimeType"); bool isMonkey = true; - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); + final receivingAddress = ref.watch(pWalletReceivingAddress(walletId)); final externalCalls = ref.watch( prefsChangeNotifierProvider.select((value) => value.externalCalls)); - final coin = manager.coin; - final balance = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId).balance)); + final coin = ref.watch(pWalletCoin(walletId)); + final balance = ref.watch(pWalletBalance(walletId)); final locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); @@ -132,10 +87,9 @@ class _WalletSummaryInfoState extends ConsumerState { final _showPrivate = ref.watch(publicPrivateBalanceStateProvider.state).state == "Private"; - final firoWallet = ref.watch(pWallets.select( - (value) => value.getManager(widget.walletId).wallet)) as FiroWallet; + final secondaryBal = ref.watch(pWalletBalanceSecondary(walletId)); - final bal = _showPrivate ? firoWallet.balancePrivate : firoWallet.balance; + final bal = _showPrivate ? balance : secondaryBal; balanceToShow = _showAvailable ? bal.spendable : bal.total; title = _showAvailable ? "Available" : "Full"; @@ -148,7 +102,8 @@ class _WalletSummaryInfoState extends ConsumerState { List? imageBytes; if (coin == Coin.banano) { - imageBytes = (manager.wallet as BananoWallet).getMonkeyImageBytes(); + // TODO: [prio=high] fix this and uncomment: + // imageBytes = (manager.wallet as BananoWallet).getMonkeyImageBytes(); } return ConditionalParent( @@ -171,7 +126,9 @@ class _WalletSummaryInfoState extends ConsumerState { crossAxisAlignment: CrossAxisAlignment.start, children: [ GestureDetector( - onTap: showSheet, + onTap: () { + showSheet(context); + }, child: Row( children: [ Text( @@ -236,8 +193,8 @@ class _WalletSummaryInfoState extends ConsumerState { ), const Spacer(), WalletRefreshButton( - walletId: widget.walletId, - initialSyncStatus: widget.initialSyncStatus, + walletId: walletId, + initialSyncStatus: initialSyncStatus, ), ], ) diff --git a/lib/pages/wallet_view/transaction_views/all_transactions_view.dart b/lib/pages/wallet_view/transaction_views/all_transactions_view.dart index c44ef20e3..8e208ff19 100644 --- a/lib/pages/wallet_view/transaction_views/all_transactions_view.dart +++ b/lib/pages/wallet_view/transaction_views/all_transactions_view.dart @@ -13,6 +13,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; +import 'package:isar/isar.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; import 'package:stackwallet/models/isar/models/contact_entry.dart'; import 'package:stackwallet/models/transaction_filter.dart'; @@ -21,6 +22,7 @@ import 'package:stackwallet/pages/token_view/token_view.dart'; import 'package:stackwallet/pages/wallet_view/sub_widgets/tx_icon.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/transaction_details_view.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/transaction_search_filter_view.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/address_book_service_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/ui/transaction_filter_provider.dart'; @@ -33,6 +35,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/format.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; @@ -307,7 +310,7 @@ class _TransactionDetailsViewState extends ConsumerState { Navigator.of(context).pushNamed( TransactionSearchFilterView.routeName, arguments: - ref.read(pWallets).getManager(walletId).coin, + ref.read(pWallets).getWallet(walletId).info.coin, ); }, ), @@ -422,7 +425,7 @@ class _TransactionDetailsViewState extends ConsumerState { ), onPressed: () { final coin = - ref.read(pWallets).getManager(walletId).coin; + ref.read(pWallets).getWallet(walletId).info.coin; if (isDesktop) { showDialog( context: context, @@ -465,21 +468,44 @@ class _TransactionDetailsViewState extends ConsumerState { Expanded( child: Consumer( builder: (_, ref, __) { - final managerProvider = ref.watch(pWallets - .select((value) => value.getManagerProvider(walletId))); - final criteria = ref.watch(transactionFilterProvider.state).state; //todo: check if print needed // debugPrint("Consumer build called"); + final WhereClause ww; + return FutureBuilder( future: widget.isTokens - ? ref.watch(tokenServiceProvider - .select((value) => value!.transactions)) - : ref.watch(managerProvider - .select((value) => value.transactions)), + ? ref + .watch(mainDBProvider) + .getTransactions(walletId) + .filter() + .otherDataEqualTo(ref + .watch(tokenServiceProvider)! + .tokenContract + .address) + .sortByTimestampDesc() + .findAll() + : ref.watch(mainDBProvider).isar.transactions.buildQuery< + Transaction>( + whereClauses: [ + IndexWhereClause.equalTo( + indexName: 'walletId', + value: [widget.walletId], + ) + ], + // TODO: [prio=high] add filters to wallet or cryptocurrency class + // filter: [ + // // todo + // ], + sortBy: [ + const SortProperty( + property: "timestamp", + sort: Sort.desc, + ), + ]).findAll(), builder: (_, AsyncSnapshot> snapshot) { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) { @@ -851,13 +877,11 @@ class _DesktopTransactionCardRowState Widget build(BuildContext context) { final locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); - final manager = - ref.watch(pWallets.select((value) => value.getManager(walletId))); final baseCurrency = ref .watch(prefsChangeNotifierProvider.select((value) => value.currency)); - final coin = manager.coin; + final coin = ref.watch(pWalletCoin(walletId)); final price = ref .watch(priceAnd24hChangeNotifierProvider @@ -877,8 +901,7 @@ class _DesktopTransactionCardRowState prefix = ""; } - final currentHeight = ref.watch( - pWallets.select((value) => value.getManager(walletId).currentHeight)); + final currentHeight = ref.watch(pWalletChainHeight(walletId)); return Material( color: Theme.of(context).extension()!.popupBG, diff --git a/lib/pages/wallet_view/transaction_views/transaction_details_view.dart b/lib/pages/wallet_view/transaction_views/transaction_details_view.dart index d4b56fd5c..8562e0585 100644 --- a/lib/pages/wallet_view/transaction_views/transaction_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/transaction_details_view.dart @@ -39,6 +39,7 @@ import 'package:stackwallet/utilities/format.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -355,8 +356,7 @@ class _TransactionDetailsViewState @override Widget build(BuildContext context) { - final currentHeight = ref.watch( - pWallets.select((value) => value.getManager(walletId).currentHeight)); + final currentHeight = ref.watch(pWalletChainHeight(walletId)); return ConditionalParent( condition: !isDesktop, @@ -1597,10 +1597,10 @@ class _TransactionDetailsViewState ), ), onPressed: () async { - final Manager manager = - ref.read(pWallets).getManager(walletId); + final wallet = + ref.read(pWallets).getWallet(walletId); - if (manager.wallet is EpicCashWallet) { + if (wallet is EpicCashWallet) { final String? id = _transaction.slateId; if (id == null) { unawaited(showFloatingFlushBar( @@ -1618,7 +1618,7 @@ class _TransactionDetailsViewState const CancellingTransactionProgressDialog(), )); - final result = await (manager.wallet as EpicCashWallet) + final result = await (wallet as EpicCashWallet) .cancelPendingTransactionAndPost(id); if (mounted) { // pop progress dialog @@ -1630,7 +1630,7 @@ class _TransactionDetailsViewState builder: (_) => StackOkDialog( title: "Transaction cancelled", onOkPressed: (_) { - manager.refresh(); + wallet.refresh(); Navigator.of(context).popUntil( ModalRoute.withName( WalletView.routeName)); diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/all_transactions_v2_view.dart b/lib/pages/wallet_view/transaction_views/tx_v2/all_transactions_v2_view.dart index e018785a8..6553cc1df 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/all_transactions_v2_view.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/all_transactions_v2_view.dart @@ -35,6 +35,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/format.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; @@ -308,8 +309,7 @@ class _AllTransactionsV2ViewState extends ConsumerState { onPressed: () { Navigator.of(context).pushNamed( TransactionSearchFilterView.routeName, - arguments: - ref.read(pWallets).getManager(walletId).coin, + arguments: ref.read(pWalletCoin(walletId)), ); }, ), @@ -423,21 +423,19 @@ class _AllTransactionsV2ViewState extends ConsumerState { height: 20, ), onPressed: () { - final coin = - ref.read(pWallets).getManager(walletId).coin; if (isDesktop) { showDialog( context: context, builder: (context) { return TransactionSearchFilterView( - coin: coin, + coin: ref.read(pWalletCoin(walletId)), ); }, ); } else { Navigator.of(context).pushNamed( TransactionSearchFilterView.routeName, - arguments: coin, + arguments: ref.read(pWalletCoin(walletId)), ); } }, @@ -467,9 +465,6 @@ class _AllTransactionsV2ViewState extends ConsumerState { Expanded( child: Consumer( builder: (_, ref, __) { - final managerProvider = ref.watch(pWallets - .select((value) => value.getManagerProvider(walletId))); - final criteria = ref.watch(transactionFilterProvider.state).state; @@ -481,10 +476,23 @@ class _AllTransactionsV2ViewState extends ConsumerState { .watch(mainDBProvider) .isar .transactionV2s - .where() - .walletIdEqualTo(walletId) - .sortByTimestampDesc() - .findAll(), + .buildQuery( + whereClauses: [ + IndexWhereClause.equalTo( + indexName: 'walletId', + value: [widget.walletId], + ) + ], + // TODO: [prio=high] add filters to wallet or cryptocurrency class + // filter: [ + // // todo + // ], + sortBy: [ + const SortProperty( + property: "timestamp", + sort: Sort.desc, + ), + ]).findAll(), builder: (_, AsyncSnapshot> snapshot) { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) { @@ -852,13 +860,11 @@ class _DesktopTransactionCardRowState Widget build(BuildContext context) { final locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); - final manager = - ref.watch(pWallets.select((value) => value.getManager(walletId))); final baseCurrency = ref .watch(prefsChangeNotifierProvider.select((value) => value.currency)); - final coin = manager.coin; + final coin = ref.watch(pWalletCoin(walletId)); final price = ref .watch(priceAnd24hChangeNotifierProvider @@ -878,8 +884,7 @@ class _DesktopTransactionCardRowState prefix = ""; } - final currentHeight = ref.watch( - pWallets.select((value) => value.getManager(walletId).currentHeight)); + final currentHeight = ref.watch(pWalletChainHeight(walletId)); final Amount amount; diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/fusion_tx_group_card.dart b/lib/pages/wallet_view/transaction_views/tx_v2/fusion_tx_group_card.dart index ffe5d7145..e26017b6c 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/fusion_tx_group_card.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/fusion_tx_group_card.dart @@ -5,12 +5,12 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; import 'package:stackwallet/pages/wallet_view/sub_widgets/tx_icon.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/fusion_group_details_view.dart'; -import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/format.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; class FusionTxGroup { @@ -27,11 +27,9 @@ class FusionTxGroupCard extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final walletId = group.transactions.first.walletId; - final coin = - ref.watch(pWallets.select((value) => value.getManager(walletId).coin)); + final coin = ref.watch(pWalletCoin(walletId)); - final currentHeight = ref.watch( - pWallets.select((value) => value.getManager(walletId).currentHeight)); + final currentHeight = ref.watch(pWalletChainHeight(walletId)); return Material( color: Theme.of(context).extension()!.popupBG, diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_card.dart b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_card.dart index 83d1f87b6..acbefbe84 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_card.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_card.dart @@ -9,7 +9,6 @@ import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/transactio import 'package:stackwallet/providers/global/locale_provider.dart'; import 'package:stackwallet/providers/global/prefs_provider.dart'; import 'package:stackwallet/providers/global/price_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; @@ -18,6 +17,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/format.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; class TransactionCardV2 extends ConsumerStatefulWidget { @@ -96,7 +96,7 @@ class _TransactionCardStateV2 extends ConsumerState { } else { prefix = ""; } - coin = ref.read(pWallets).getManager(walletId).coin; + coin = ref.read(pWalletCoin(walletId)); unit = coin.ticker; super.initState(); @@ -115,8 +115,7 @@ class _TransactionCardStateV2 extends ConsumerState { .select((value) => value.getPrice(coin))) .item1; - final currentHeight = ref.watch( - pWallets.select((value) => value.getManager(walletId).currentHeight)); + final currentHeight = ref.watch(pWalletChainHeight(walletId)); final Amount amount; diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart index 9df84725e..b722f3850 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.dart @@ -33,6 +33,7 @@ import 'package:stackwallet/utilities/format.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -397,8 +398,7 @@ class _TransactionV2DetailsViewState @override Widget build(BuildContext context) { - final currentHeight = ref.watch( - pWallets.select((value) => value.getManager(walletId).currentHeight)); + final currentHeight = ref.watch(pWalletChainHeight(walletId)); final String outputLabel; diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list.dart b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list.dart index 34f163758..db818a60d 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list.dart @@ -8,8 +8,6 @@ * */ -import 'dart:async'; - import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:isar/isar.dart'; @@ -66,8 +64,7 @@ class _TransactionsV2ListState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); + final coin = ref.watch(pWallets).getWallet(widget.walletId).info.coin; return FutureBuilder( future: ref @@ -145,11 +142,7 @@ class _TransactionsV2ListState extends ConsumerState { return RefreshIndicator( onRefresh: () async { - final managerProvider = - ref.read(pWallets).getManagerProvider(widget.walletId); - if (!ref.read(managerProvider).isRefreshing) { - unawaited(ref.read(managerProvider).refresh()); - } + await ref.read(pWallets).getWallet(widget.walletId).refresh(); }, child: Util.isDesktop ? ListView.separated( @@ -168,7 +161,7 @@ class _TransactionsV2ListState extends ConsumerState { final tx = _txns[index]; return TxListItem( tx: tx, - coin: manager.coin, + coin: coin, radius: radius, ); }, @@ -204,7 +197,7 @@ class _TransactionsV2ListState extends ConsumerState { children: [ TxListItem( tx: tx, - coin: manager.coin, + coin: coin, radius: radius, ), const SizedBox( @@ -215,7 +208,7 @@ class _TransactionsV2ListState extends ConsumerState { } else { return TxListItem( tx: tx, - coin: manager.coin, + coin: coin, radius: radius, ); } diff --git a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list_item.dart b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list_item.dart index c5df69248..ec5c50183 100644 --- a/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list_item.dart +++ b/lib/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list_item.dart @@ -8,12 +8,12 @@ import 'package:stackwallet/pages/exchange_view/trade_details_view.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/fusion_tx_group_card.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/transaction_v2_card.dart'; import 'package:stackwallet/providers/global/trades_service_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/route_generator.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog_close_button.dart'; import 'package:stackwallet/widgets/trade_card.dart'; @@ -103,16 +103,11 @@ class TxListItem extends ConsumerWidget { Flexible( child: TradeDetailsView( tradeId: trade.tradeId, - // TODO + // TODO: [prio:med] // transactionIfSentFromStack: tx, transactionIfSentFromStack: null, - walletName: ref.watch( - pWallets.select( - (value) => value - .getManager(_tx.walletId) - .walletName, - ), - ), + walletName: ref + .watch(pWalletName(_tx.walletId)), walletId: _tx.walletId, ), ), @@ -135,10 +130,7 @@ class TxListItem extends ConsumerWidget { trade.tradeId, _tx, _tx.walletId, - ref - .read(pWallets) - .getManager(_tx.walletId) - .walletName, + ref.read(pWalletName(_tx.walletId)), ), ), ); diff --git a/lib/pages/wallet_view/wallet_view.dart b/lib/pages/wallet_view/wallet_view.dart index 8b6e95f11..5fc371ff2 100644 --- a/lib/pages/wallet_view/wallet_view.dart +++ b/lib/pages/wallet_view/wallet_view.dart @@ -39,6 +39,7 @@ import 'package:stackwallet/pages/wallet_view/sub_widgets/wallet_summary.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/all_transactions_view.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/all_transactions_v2_view.dart'; import 'package:stackwallet/pages/wallet_view/transaction_views/tx_v2/transaction_v2_list.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/global/auto_swb_service_provider.dart'; import 'package:stackwallet/providers/global/paynym_api_provider.dart'; import 'package:stackwallet/providers/providers.dart'; @@ -48,11 +49,13 @@ import 'package:stackwallet/providers/wallet/my_paynym_account_state_provider.da import 'package:stackwallet/providers/wallet/public_private_balance_state_provider.dart'; import 'package:stackwallet/providers/wallet/wallet_balance_toggle_state_provider.dart'; import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/services/event_bus/events/global/node_connection_status_changed_event.dart'; import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; import 'package:stackwallet/services/event_bus/global_event_bus.dart'; import 'package:stackwallet/services/exchange/exchange_data_loading_service.dart'; +import 'package:stackwallet/services/mixins/coin_control_interface.dart'; +import 'package:stackwallet/services/mixins/fusion_wallet_interface.dart'; +import 'package:stackwallet/services/mixins/ordinals_interface.dart'; import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; @@ -67,6 +70,7 @@ import 'package:stackwallet/utilities/enums/wallet_balance_toggle_state.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/show_loading.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -94,7 +98,6 @@ class WalletView extends ConsumerStatefulWidget { const WalletView({ Key? key, required this.walletId, - required this.managerProvider, this.eventBus, this.clipboardInterface = const ClipboardWrapper(), }) : super(key: key); @@ -103,7 +106,6 @@ class WalletView extends ConsumerStatefulWidget { static const double navBarHeight = 65.0; final String walletId; - final ChangeNotifierProvider managerProvider; final EventBus? eventBus; final ClipboardInterface clipboardInterface; @@ -115,7 +117,7 @@ class WalletView extends ConsumerStatefulWidget { class _WalletViewState extends ConsumerState { late final EventBus eventBus; late final String walletId; - late final ChangeNotifierProvider managerProvider; + late final Coin coin; late final bool _shouldDisableAutoSyncOnLogOut; @@ -129,7 +131,7 @@ class _WalletViewState extends ConsumerState { bool _lelantusRescanRecovery = false; Future _firoRescanRecovery() async { - final success = await (ref.read(managerProvider).wallet as FiroWallet) + final success = await (ref.read(pWallets).getWallet(walletId) as FiroWallet) .firoRescanRecovery(); if (success) { @@ -160,43 +162,45 @@ class _WalletViewState extends ConsumerState { @override void initState() { walletId = widget.walletId; - managerProvider = widget.managerProvider; + final wallet = ref.read(pWallets).getWallet(walletId); + coin = wallet.info.coin; - ref.read(managerProvider).isActiveWallet = true; - if (!ref.read(managerProvider).shouldAutoSync) { + ref.read(currentWalletIdProvider.notifier).state = wallet.walletId; + + if (!wallet.shouldAutoSync) { // enable auto sync if it wasn't enabled when loading wallet - ref.read(managerProvider).shouldAutoSync = true; + wallet.shouldAutoSync = true; _shouldDisableAutoSyncOnLogOut = true; } else { _shouldDisableAutoSyncOnLogOut = false; } - if (ref.read(managerProvider).coin == Coin.firo && - (ref.read(managerProvider).wallet as FiroWallet) - .lelantusCoinIsarRescanRequired) { + if (coin == Coin.firo && + (wallet as FiroWallet).lelantusCoinIsarRescanRequired) { _rescanningOnOpen = true; _lelantusRescanRecovery = true; _firoRescanRecovery(); - } else if (ref.read(managerProvider).rescanOnOpenVersion == - Constants.rescanV1) { - _rescanningOnOpen = true; - ref.read(managerProvider).fullRescan(20, 1000).then( - (_) => ref.read(managerProvider).resetRescanOnOpen().then( - (_) => WidgetsBinding.instance.addPostFrameCallback( - (_) => setState(() => _rescanningOnOpen = false), - ), - ), - ); + // } else if (ref.read(managerProvider).rescanOnOpenVersion == + // TODO: [prio=high] + // Constants.rescanV1) { + // _rescanningOnOpen = true; + // ref.read(managerProvider).fullRescan(20, 1000).then( + // (_) => ref.read(managerProvider).resetRescanOnOpen().then( + // (_) => WidgetsBinding.instance.addPostFrameCallback( + // (_) => setState(() => _rescanningOnOpen = false), + // ), + // ), + // ); } else { - ref.read(managerProvider).refresh(); + wallet.refresh(); } - if (ref.read(managerProvider).isRefreshing) { + if (wallet.refreshMutex.isLocked) { _currentSyncStatus = WalletSyncStatus.syncing; _currentNodeStatus = NodeConnectionStatus.connected; } else { _currentSyncStatus = WalletSyncStatus.synced; - if (ref.read(managerProvider).isConnected) { + if (wallet.isConnected) { _currentNodeStatus = NodeConnectionStatus.connected; } else { _currentNodeStatus = NodeConnectionStatus.disconnected; @@ -290,9 +294,10 @@ class _WalletViewState extends ConsumerState { void _logout() async { if (_shouldDisableAutoSyncOnLogOut) { // disable auto sync if it was enabled only when loading wallet - ref.read(managerProvider).shouldAutoSync = false; + ref.read(pWallets).getWallet(walletId).shouldAutoSync = false; } - ref.read(managerProvider.notifier).isActiveWallet = false; + + ref.read(currentWalletIdProvider.notifier).state = null; ref.read(transactionFilterProvider.state).state = null; if (ref.read(prefsChangeNotifierProvider).isAutoBackupEnabled && ref.read(prefsChangeNotifierProvider).backupFrequencyType == @@ -328,7 +333,7 @@ class _WalletViewState extends ConsumerState { } void _onExchangePressed(BuildContext context) async { - final Coin coin = ref.read(managerProvider).coin; + final Coin coin = ref.read(pWalletCoin(walletId)); if (coin.isTestNet) { await showDialog( @@ -373,7 +378,7 @@ class _WalletViewState extends ConsumerState { } void _onBuyPressed(BuildContext context) async { - final coin = ref.read(managerProvider).coin; + final Coin coin = ref.read(pWalletCoin(walletId)); if (coin.isTestNet) { await showDialog( @@ -408,7 +413,7 @@ class _WalletViewState extends ConsumerState { ), ), ); - final firoWallet = ref.read(managerProvider).wallet as FiroWallet; + final firoWallet = ref.read(pWallets).getWallet(walletId) as FiroWallet; final Amount publicBalance = firoWallet.availablePublicBalance(); if (publicBalance <= Amount.zero) { @@ -464,7 +469,7 @@ class _WalletViewState extends ConsumerState { Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final Coin coin = ref.watch(managerProvider.select((value) => value.coin)); + final coin = ref.watch(pWalletCoin(walletId)); return ConditionalParent( condition: _rescanningOnOpen, @@ -549,8 +554,7 @@ class _WalletViewState extends ConsumerState { ), Expanded( child: Text( - ref.watch(managerProvider - .select((value) => value.walletName)), + ref.watch(pWalletName(walletId)), style: STextStyles.navBarTitle(context), overflow: TextOverflow.ellipsis, ), @@ -721,7 +725,7 @@ class _WalletViewState extends ConsumerState { WalletSettingsView.routeName, arguments: Tuple4( walletId, - ref.read(managerProvider).coin, + coin, _currentSyncStatus, _currentNodeStatus, ), @@ -747,8 +751,11 @@ class _WalletViewState extends ConsumerState { child: WalletSummary( walletId: walletId, aspectRatio: 1.75, - initialSyncStatus: ref.watch(managerProvider - .select((value) => value.isRefreshing)) + initialSyncStatus: ref + .watch(pWallets) + .getWallet(walletId) + .refreshMutex + .isLocked ? WalletSyncStatus.syncing : WalletSyncStatus.synced, ), @@ -907,8 +914,6 @@ class _WalletViewState extends ConsumerState { walletId: widget.walletId, ) : TransactionsList( - managerProvider: - managerProvider, walletId: walletId, ), ), @@ -944,8 +949,6 @@ class _WalletViewState extends ConsumerState { label: "Send", icon: const SendNavIcon(), onTap: () { - final walletId = ref.read(managerProvider).walletId; - final coin = ref.read(managerProvider).coin; switch (ref .read(walletBalanceToggleStateProvider.state) .state) { @@ -985,8 +988,10 @@ class _WalletViewState extends ConsumerState { moreItems: [ if (ref.watch( pWallets.select( - (value) => - value.getManager(widget.walletId).hasTokenSupport, + (value) => value + .getWallet(widget.walletId) + .cryptoCurrency + .hasTokenSupport, ), )) WalletNavigationBarItemData( @@ -1018,9 +1023,8 @@ class _WalletViewState extends ConsumerState { }), if (ref.watch( pWallets.select( - (value) => value - .getManager(widget.walletId) - .hasCoinControlSupport, + (value) => value.getWallet(widget.walletId) + is CoinControlInterface, ), ) && ref.watch( @@ -1041,8 +1045,8 @@ class _WalletViewState extends ConsumerState { ); }, ), - if (ref.watch(pWallets.select((value) => - value.getManager(widget.walletId).hasPaynymSupport))) + if (ref.watch(pWallets.select((value) => value + .getWallet(widget.walletId) is PaynymWalletInterface))) WalletNavigationBarItemData( label: "PayNym", icon: const PaynymNavIcon(), @@ -1056,12 +1060,10 @@ class _WalletViewState extends ConsumerState { ), ); - final manager = ref - .read(pWallets) - .getManager(widget.walletId); + final wallet = + ref.read(pWallets).getWallet(widget.walletId); - final paynymInterface = - manager.wallet as PaynymWalletInterface; + final paynymInterface = wallet as PaynymWalletInterface; final code = await paynymInterface.getPaymentCode( isSegwit: false, @@ -1102,7 +1104,7 @@ class _WalletViewState extends ConsumerState { if (ref.watch( pWallets.select( (value) => - value.getManager(widget.walletId).hasOrdinalsSupport, + value.getWallet(widget.walletId) is OrdinalsInterface, ), )) WalletNavigationBarItemData( @@ -1117,8 +1119,8 @@ class _WalletViewState extends ConsumerState { ), if (ref.watch( pWallets.select( - (value) => - value.getManager(widget.walletId).hasFusionSupport, + (value) => value.getWallet(widget.walletId) + is FusionWalletInterface, ), )) WalletNavigationBarItemData( diff --git a/lib/pages/wallets_view/sub_widgets/all_wallets.dart b/lib/pages/wallets_view/sub_widgets/all_wallets.dart index a62832532..5f77354c4 100644 --- a/lib/pages/wallets_view/sub_widgets/all_wallets.dart +++ b/lib/pages/wallets_view/sub_widgets/all_wallets.dart @@ -48,14 +48,13 @@ class AllWallets extends StatelessWidget { Expanded( child: Consumer( builder: (_, ref, __) { - final providersByCoin = ref.watch(pWallets - .select((value) => value.getManagerProvidersByCoin())); + final walletsByCoin = ref.watch(pWallets).walletsByCoin; return ListView.builder( - itemCount: providersByCoin.length, + itemCount: walletsByCoin.length, itemBuilder: (builderContext, index) { - final coin = providersByCoin[index].item1; - final int walletCount = providersByCoin[index].item2.length; + final coin = walletsByCoin[index].coin; + final int walletCount = walletsByCoin[index].wallets.length; return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: WalletListItem( diff --git a/lib/pages/wallets_view/sub_widgets/favorite_card.dart b/lib/pages/wallets_view/sub_widgets/favorite_card.dart index acf63bee3..a6e219ff1 100644 --- a/lib/pages/wallets_view/sub_widgets/favorite_card.dart +++ b/lib/pages/wallets_view/sub_widgets/favorite_card.dart @@ -16,7 +16,6 @@ import 'package:flutter_svg/flutter_svg.dart'; import 'package:stackwallet/pages/wallet_view/wallet_view.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart'; import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -25,9 +24,9 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/coin_card.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; -import 'package:tuple/tuple.dart'; class FavoriteCard extends ConsumerStatefulWidget { const FavoriteCard({ @@ -59,9 +58,7 @@ class _FavoriteCardState extends ConsumerState { @override Widget build(BuildContext context) { - final coin = ref.watch( - pWallets.select((value) => value.getManager(walletId).coin), - ); + final coin = ref.watch(pWalletCoin(walletId)); final externalCalls = ref.watch( prefsChangeNotifierProvider.select((value) => value.externalCalls), ); @@ -116,7 +113,7 @@ class _FavoriteCardState extends ConsumerState { child: GestureDetector( onTap: () async { if (coin == Coin.monero || coin == Coin.wownero) { - await ref.read(pWallets).getManager(walletId).initializeExisting(); + await ref.read(pWallets).getWallet(walletId).init(); } if (mounted) { if (Util.isDesktop) { @@ -127,10 +124,7 @@ class _FavoriteCardState extends ConsumerState { } else { await Navigator.of(context).pushNamed( WalletView.routeName, - arguments: Tuple2( - walletId, - ref.read(pWallets).getManagerProvider(walletId), - ), + arguments: walletId, ); } } @@ -157,12 +151,7 @@ class _FavoriteCardState extends ConsumerState { children: [ Expanded( child: Text( - ref.watch( - pWallets.select( - (value) => - value.getManager(walletId).walletName, - ), - ), + ref.watch(pWalletName(walletId)), style: STextStyles.itemSubtitle12(context).copyWith( color: Theme.of(context) .extension()! @@ -184,22 +173,16 @@ class _FavoriteCardState extends ConsumerState { Builder( builder: (context) { final balance = ref.watch( - pWallets.select( - (value) => value.getManager(walletId).balance, - ), + pWalletBalance(walletId), ); Amount total = balance.total; if (coin == Coin.firo || coin == Coin.firoTestNet) { - final balancePrivate = ref.watch( - pWallets.select( - (value) => (value.getManager(walletId).wallet - as FiroWallet) - .balancePrivate, - ), - ); - - total += balancePrivate.total; + total += ref + .watch( + pWalletBalanceSecondary(walletId), + ) + .total; } Amount fiatTotal = Amount.zero; diff --git a/lib/pages/wallets_view/sub_widgets/favorite_wallets.dart b/lib/pages/wallets_view/sub_widgets/favorite_wallets.dart index a55c8bef7..01bb5513f 100644 --- a/lib/pages/wallets_view/sub_widgets/favorite_wallets.dart +++ b/lib/pages/wallets_view/sub_widgets/favorite_wallets.dart @@ -15,12 +15,11 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; import 'package:stackwallet/pages/manage_favorites_view/manage_favorites_view.dart'; import 'package:stackwallet/pages/wallets_view/sub_widgets/favorite_card.dart'; -import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/favourite_wallets_provider.dart'; import 'package:stackwallet/widgets/custom_page_view/custom_page_view.dart' as cpv; @@ -74,10 +73,10 @@ class _FavoriteWalletsState extends ConsumerState { Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final favorites = ref.watch(favoritesProvider); + final favorites = ref.watch(pFavouriteWalletInfos); _favLength = favorites.length; - bool hasFavorites = favorites.length > 0; + bool hasFavorites = favorites.isNotEmpty; final remaining = ((screenWidth - cardWidth) / cardWidth).ceil(); @@ -192,12 +191,9 @@ class _FavoriteWalletsState extends ConsumerState { }), itemBuilder: (_, index) { String? walletId; - ChangeNotifierProvider? managerProvider; if (index < favorites.length) { - walletId = ref.read(favorites[index]).walletId; - managerProvider = - ref.read(pWallets).getManagerProvider(walletId); + walletId = favorites[index].walletId; } const double scaleDown = 0.95; diff --git a/lib/pages/wallets_view/sub_widgets/wallet_list_item.dart b/lib/pages/wallets_view/sub_widgets/wallet_list_item.dart index 62f7d9025..449e62d26 100644 --- a/lib/pages/wallets_view/sub_widgets/wallet_list_item.dart +++ b/lib/pages/wallets_view/sub_widgets/wallet_list_item.dart @@ -24,7 +24,6 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; -import 'package:tuple/tuple.dart'; class WalletListItem extends ConsumerWidget { const WalletListItem({ @@ -57,25 +56,18 @@ class WalletListItem extends ConsumerWidget { ), onPressed: () async { if (walletCount == 1 && coin != Coin.ethereum) { - final providersByCoin = ref - .watch(pWallets - .select((value) => value.getManagerProvidersByCoin())) - .where((e) => e.item1 == coin) - .map((e) => e.item2) - .expand((e) => e) - .toList(); - final manager = ref.read(providersByCoin.first); + final wallet = ref + .read(pWallets) + .wallets + .firstWhere((e) => e.info.coin == coin); if (coin == Coin.monero || coin == Coin.wownero) { - await manager.initializeExisting(); + await wallet.init(); } if (context.mounted) { unawaited( Navigator.of(context).pushNamed( WalletView.routeName, - arguments: Tuple2( - manager.walletId, - providersByCoin.first, - ), + arguments: wallet.walletId, ), ); } diff --git a/lib/pages/wallets_view/wallets_overview.dart b/lib/pages/wallets_view/wallets_overview.dart index 208a1a0b6..3fd2d6c9a 100644 --- a/lib/pages/wallets_view/wallets_overview.dart +++ b/lib/pages/wallets_view/wallets_overview.dart @@ -11,6 +11,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; +import 'package:isar/isar.dart'; import 'package:stackwallet/models/add_wallet_list_entity/sub_classes/coin_entity.dart'; import 'package:stackwallet/models/isar/models/ethereum/eth_contract.dart'; import 'package:stackwallet/pages/add_wallet_views/create_or_restore_wallet_view/create_or_restore_wallet_view.dart'; @@ -18,13 +19,14 @@ import 'package:stackwallet/pages_desktop_specific/my_stack_view/dialogs/desktop import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/services/coins/ethereum/ethereum_wallet.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -60,22 +62,22 @@ class _EthWalletsOverviewState extends ConsumerState { String _searchString = ""; - final List>> wallets = []; + final List>> wallets = []; - List>> _filter(String searchTerm) { + List>> _filter(String searchTerm) { if (searchTerm.isEmpty) { return wallets; } - final List>> results = []; + final List>> results = []; final term = searchTerm.toLowerCase(); for (final tuple in wallets) { bool includeManager = false; // search wallet name and total balance - includeManager |= _elementContains(tuple.item1.walletName, term); + includeManager |= _elementContains(tuple.item1.info.name, term); includeManager |= _elementContains( - tuple.item1.balance.total.decimal.toString(), + tuple.item1.info.cachedBalance.total.decimal.toString(), term, ); @@ -111,15 +113,15 @@ class _EthWalletsOverviewState extends ConsumerState { searchFieldFocusNode = FocusNode(); final walletsData = - ref.read(walletsServiceChangeNotifierProvider).fetchWalletsData(); - walletsData.removeWhere((key, value) => value.coin != widget.coin); + ref.read(mainDBProvider).isar.walletInfo.where().findAllSync(); + walletsData.removeWhere((e) => e.coin != widget.coin); if (widget.coin == Coin.ethereum) { - for (final data in walletsData.values) { + for (final data in walletsData) { final List contracts = []; - final manager = ref.read(pWallets).getManager(data.walletId); - final contractAddresses = (manager.wallet as EthereumWallet) - .getWalletTokenContractAddresses(); + final wallet = ref.read(pWallets).getWallet(data.walletId); + final contractAddresses = + (wallet as EthereumWallet).getWalletTokenContractAddresses(); // fetch each contract for (final contractAddress in contractAddresses) { @@ -140,7 +142,7 @@ class _EthWalletsOverviewState extends ConsumerState { // add tuple to list wallets.add( Tuple2( - ref.read(pWallets).getManager( + ref.read(pWallets).getWallet( data.walletId, ), contracts, @@ -149,10 +151,10 @@ class _EthWalletsOverviewState extends ConsumerState { } } else { // add non token wallet tuple to list - for (final data in walletsData.values) { + for (final data in walletsData) { wallets.add( Tuple2( - ref.read(pWallets).getManager( + ref.read(pWallets).getWallet( data.walletId, ), [], @@ -290,11 +292,11 @@ class _EthWalletsOverviewState extends ConsumerState { itemBuilder: (_, index) { final element = data[index]; - if (element.item1.hasTokenSupport) { + if (element.item1.cryptoCurrency.hasTokenSupport) { if (isDesktop) { return DesktopExpandingWalletCard( key: Key( - "${element.item1.walletName}_${element.item2.map((e) => e.address).join()}"), + "${element.item1.info.name}_${element.item2.map((e) => e.address).join()}"), data: element, navigatorState: widget.navigatorState!, ); diff --git a/lib/pages_desktop_specific/address_book_view/desktop_address_book.dart b/lib/pages_desktop_specific/address_book_view/desktop_address_book.dart index 77f1081ed..3da119839 100644 --- a/lib/pages_desktop_specific/address_book_view/desktop_address_book.dart +++ b/lib/pages_desktop_specific/address_book_view/desktop_address_book.dart @@ -111,14 +111,14 @@ class _DesktopAddressBook extends ConsumerState { WidgetsBinding.instance.addPostFrameCallback((_) async { List addresses = []; - final managers = ref.read(pWallets).managers; - for (final manager in managers) { + final wallets = ref.read(pWallets).wallets; + for (final wallet in wallets) { addresses.add( ContactAddressEntry() - ..coinName = manager.coin.name - ..address = await manager.currentReceivingAddress + ..coinName = wallet.info.coin.name + ..address = wallet.info.cachedReceivingAddress ..label = "Current Receiving" - ..other = manager.walletName, + ..other = wallet.info.name, ); } final self = ContactEntry( diff --git a/lib/pages_desktop_specific/address_book_view/subwidgets/desktop_contact_details.dart b/lib/pages_desktop_specific/address_book_view/subwidgets/desktop_contact_details.dart index 1de586043..4ce624db2 100644 --- a/lib/pages_desktop_specific/address_book_view/subwidgets/desktop_contact_details.dart +++ b/lib/pages_desktop_specific/address_book_view/subwidgets/desktop_contact_details.dart @@ -14,16 +14,14 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:isar/isar.dart'; -import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/contact_entry.dart'; import 'package:stackwallet/models/isar/models/isar_models.dart'; import 'package:stackwallet/pages/address_book_views/subviews/add_new_contact_address_view.dart'; import 'package:stackwallet/pages_desktop_specific/address_book_view/subwidgets/desktop_address_card.dart'; import 'package:stackwallet/pages_desktop_specific/address_book_view/subwidgets/desktop_contact_options_menu_popup.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/address_book_service_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/providers/ui/address_book_providers/address_entry_data_provider.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/themes/theme_providers.dart'; import 'package:stackwallet/utilities/assets.dart'; @@ -53,28 +51,30 @@ class DesktopContactDetails extends ConsumerStatefulWidget { class _DesktopContactDetailsState extends ConsumerState { List> _cachedTransactions = []; - Future>> _filteredTransactionsByContact( - List managers, - ) async { + Future>> + _filteredTransactionsByContact() async { final contact = ref.read(addressBookServiceProvider).getContactById(widget.contactId); // TODO: optimise - List> result = []; - for (final manager in managers) { - final transactions = await MainDB.instance - .getTransactions(manager.walletId) - .filter() - .anyOf(contact.addresses.map((e) => e.address), - (q, String e) => q.address((q) => q.valueEqualTo(e))) - .sortByTimestampDesc() - .findAll(); + final transactions = await ref + .read(mainDBProvider) + .isar + .transactions + .where() + .filter() + .anyOf(contact.addresses.map((e) => e.address), + (q, String e) => q.address((q) => q.valueEqualTo(e))) + .sortByTimestampDesc() + .findAll(); - for (final tx in transactions) { - result.add(Tuple2(manager.walletId, tx)); - } + List> result = []; + + for (final tx in transactions) { + result.add(Tuple2(tx.walletId, tx)); } + // sort by date result.sort((a, b) => b.item2.timestamp - a.item2.timestamp); @@ -287,8 +287,7 @@ class _DesktopContactDetailsState extends ConsumerState { ), ), FutureBuilder( - future: _filteredTransactionsByContact( - ref.watch(pWallets).managers), + future: _filteredTransactionsByContact(), builder: (_, AsyncSnapshot>> snapshot) { diff --git a/lib/pages_desktop_specific/addresses/sub_widgets/desktop_address_list.dart b/lib/pages_desktop_specific/addresses/sub_widgets/desktop_address_list.dart index 12511b114..9a9591e6c 100644 --- a/lib/pages_desktop_specific/addresses/sub_widgets/desktop_address_list.dart +++ b/lib/pages_desktop_specific/addresses/sub_widgets/desktop_address_list.dart @@ -16,12 +16,12 @@ import 'package:stackwallet/models/isar/models/isar_models.dart'; import 'package:stackwallet/pages/receive_view/addresses/address_card.dart'; import 'package:stackwallet/pages_desktop_specific/addresses/desktop_wallet_addresses_view.dart'; import 'package:stackwallet/providers/db/main_db_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/icon_widgets/x_icon.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; import 'package:stackwallet/widgets/stack_text_field.dart'; @@ -132,8 +132,7 @@ class _DesktopAddressListState extends ConsumerState { @override Widget build(BuildContext context) { - final coin = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId).coin)); + final coin = ref.watch(pWalletCoin(widget.walletId)); final ids = _search(_searchString); diff --git a/lib/pages_desktop_specific/cashfusion/desktop_cashfusion_view.dart b/lib/pages_desktop_specific/cashfusion/desktop_cashfusion_view.dart index 38a5d9072..c7985b50a 100644 --- a/lib/pages_desktop_specific/cashfusion/desktop_cashfusion_view.dart +++ b/lib/pages_desktop_specific/cashfusion/desktop_cashfusion_view.dart @@ -65,8 +65,8 @@ class _DesktopCashFusion extends ConsumerState { FusionOption _roundType = FusionOption.continuous; Future _startFusion() async { - final fusionWallet = ref.read(pWallets).getManager(widget.walletId).wallet - as FusionWalletInterface; + final fusionWallet = + ref.read(pWallets).getWallet(widget.walletId) as FusionWalletInterface; try { fusionWallet.uiState = ref.read( diff --git a/lib/pages_desktop_specific/cashfusion/sub_widgets/fusion_dialog.dart b/lib/pages_desktop_specific/cashfusion/sub_widgets/fusion_dialog.dart index a30b356d6..6e699ee96 100644 --- a/lib/pages_desktop_specific/cashfusion/sub_widgets/fusion_dialog.dart +++ b/lib/pages_desktop_specific/cashfusion/sub_widgets/fusion_dialog.dart @@ -119,10 +119,8 @@ class _FusionDialogViewState extends ConsumerState { ); if (shouldCancel == true && mounted) { - final fusionWallet = ref - .read(pWallets) - .getManager(widget.walletId) - .wallet as FusionWalletInterface; + final fusionWallet = ref.read(pWallets).getWallet(widget.walletId) + as FusionWalletInterface; await showLoading( whileFuture: Future.wait([ @@ -283,8 +281,8 @@ class _FusionDialogViewState extends ConsumerState { /// Fuse again. void _fuseAgain() async { - final fusionWallet = ref.read(pWallets).getManager(widget.walletId).wallet - as FusionWalletInterface; + final fusionWallet = + ref.read(pWallets).getWallet(widget.walletId) as FusionWalletInterface; final fusionInfo = ref.read(prefsChangeNotifierProvider).fusionServerInfo; diff --git a/lib/pages_desktop_specific/coin_control/desktop_coin_control_use_dialog.dart b/lib/pages_desktop_specific/coin_control/desktop_coin_control_use_dialog.dart index 1f593cb2b..3ef549e83 100644 --- a/lib/pages_desktop_specific/coin_control/desktop_coin_control_use_dialog.dart +++ b/lib/pages_desktop_specific/coin_control/desktop_coin_control_use_dialog.dart @@ -17,7 +17,6 @@ import 'package:isar/isar.dart'; import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/utxo.dart'; import 'package:stackwallet/pages_desktop_specific/coin_control/utxo_row.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -25,6 +24,7 @@ import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/animated_widgets/rotate_icon.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; @@ -81,7 +81,7 @@ class _DesktopCoinControlUseDialogState @override void initState() { _searchController = TextEditingController(); - coin = ref.read(pWallets).getManager(widget.walletId).coin; + coin = ref.read(pWalletCoin(widget.walletId)); for (final utxo in ref.read(desktopUseUTXOs)) { final data = UtxoRowData(utxo.id, true); diff --git a/lib/pages_desktop_specific/coin_control/desktop_coin_control_view.dart b/lib/pages_desktop_specific/coin_control/desktop_coin_control_view.dart index c3fbb6441..2b58652a7 100644 --- a/lib/pages_desktop_specific/coin_control/desktop_coin_control_view.dart +++ b/lib/pages_desktop_specific/coin_control/desktop_coin_control_view.dart @@ -18,13 +18,13 @@ import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/utxo.dart'; import 'package:stackwallet/pages_desktop_specific/coin_control/freeze_button.dart'; import 'package:stackwallet/pages_desktop_specific/coin_control/utxo_row.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/animated_widgets/rotate_icon.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/custom_buttons/dropdown_button.dart'; @@ -71,7 +71,7 @@ class _DesktopCoinControlViewState @override void initState() { _searchController = TextEditingController(); - coin = ref.read(pWallets).getManager(widget.walletId).coin; + coin = ref.read(pWalletCoin(widget.walletId)); super.initState(); } diff --git a/lib/pages_desktop_specific/coin_control/utxo_row.dart b/lib/pages_desktop_specific/coin_control/utxo_row.dart index 3675a079a..9da246014 100644 --- a/lib/pages_desktop_specific/coin_control/utxo_row.dart +++ b/lib/pages_desktop_specific/coin_control/utxo_row.dart @@ -14,11 +14,12 @@ import 'package:isar/isar.dart'; import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/isar_models.dart'; import 'package:stackwallet/pages/coin_control/utxo_details_view.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; import 'package:stackwallet/widgets/desktop/secondary_button.dart'; @@ -96,11 +97,7 @@ class _UtxoRowState extends ConsumerState { Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final coin = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId).coin)); - - final currentChainHeight = ref.watch(pWallets - .select((value) => value.getManager(widget.walletId).currentHeight)); + final coin = ref.watch(pWalletCoin(widget.walletId)); return StreamBuilder( stream: stream, @@ -138,7 +135,7 @@ class _UtxoRowState extends ConsumerState { UTXOStatusIcon( blocked: utxo.isBlocked, status: utxo.isConfirmed( - currentChainHeight, + ref.watch(pWalletChainHeight(widget.walletId)), coin.requiredConfirmations, ) ? UTXOStatusIconStatus.confirmed diff --git a/lib/pages_desktop_specific/desktop_exchange/desktop_all_trades_view.dart b/lib/pages_desktop_specific/desktop_exchange/desktop_all_trades_view.dart index 8cba6dcd7..112cd97eb 100644 --- a/lib/pages_desktop_specific/desktop_exchange/desktop_all_trades_view.dart +++ b/lib/pages_desktop_specific/desktop_exchange/desktop_all_trades_view.dart @@ -24,7 +24,6 @@ import 'package:stackwallet/models/isar/stack_theme.dart'; import 'package:stackwallet/pages/exchange_view/trade_details_view.dart'; import 'package:stackwallet/providers/exchange/trade_sent_from_stack_lookup_provider.dart'; import 'package:stackwallet/providers/global/trades_service_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/route_generator.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/themes/theme_providers.dart'; @@ -32,6 +31,7 @@ import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/format.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; @@ -367,8 +367,6 @@ class _DesktopTradeRowCardState extends ConsumerState { ), onPressed: () async { if (txid != null && walletIds != null && walletIds.isNotEmpty) { - final manager = ref.read(pWallets).getManager(walletIds.first); - //todo: check if print needed // debugPrint("name: ${manager.walletName}"); @@ -378,19 +376,21 @@ class _DesktopTradeRowCardState extends ConsumerState { .txidEqualTo(txid) .findFirst(); - await showDialog( - context: context, - builder: (context) => DesktopDialog( - maxHeight: MediaQuery.of(context).size.height - 64, - maxWidth: 580, - child: TradeDetailsView( - tradeId: tradeId, - transactionIfSentFromStack: tx, - walletName: manager.walletName, - walletId: walletIds.first, + if (mounted) { + await showDialog( + context: context, + builder: (context) => DesktopDialog( + maxHeight: MediaQuery.of(context).size.height - 64, + maxWidth: 580, + child: TradeDetailsView( + tradeId: tradeId, + transactionIfSentFromStack: tx, + walletName: ref.read(pWalletName(walletIds.first)), + walletId: walletIds.first, + ), ), - ), - ); + ); + } if (mounted) { unawaited( @@ -436,7 +436,8 @@ class _DesktopTradeRowCardState extends ConsumerState { child: TradeDetailsView( tradeId: tradeId, transactionIfSentFromStack: tx, - walletName: manager.walletName, + walletName: ref + .read(pWalletName(walletIds.first)), walletId: walletIds.first, ), ), diff --git a/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_2.dart b/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_2.dart index 410223a20..c3178b809 100644 --- a/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_2.dart +++ b/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_2.dart @@ -238,27 +238,24 @@ class _DesktopStep2State extends ConsumerState { if (tuple != null) { if (ref.read(desktopExchangeModelProvider)!.receiveTicker.toLowerCase() == tuple.item2.ticker.toLowerCase()) { - ref + _toController.text = ref .read(pWallets) - .getManager(tuple.item1) - .currentReceivingAddress - .then((value) { - _toController.text = value; - ref.read(desktopExchangeModelProvider)!.recipientAddress = - _toController.text; - }); + .getWallet(tuple.item1) + .info + .cachedReceivingAddress; + + ref.read(desktopExchangeModelProvider)!.recipientAddress = + _toController.text; } else { if (ref.read(desktopExchangeModelProvider)!.sendTicker.toUpperCase() == tuple.item2.ticker.toUpperCase()) { - ref + _refundController.text = ref .read(pWallets) - .getManager(tuple.item1) - .currentReceivingAddress - .then((value) { - _refundController.text = value; - ref.read(desktopExchangeModelProvider)!.refundAddress = - _refundController.text; - }); + .getWallet(tuple.item1) + .info + .cachedReceivingAddress; + ref.read(desktopExchangeModelProvider)!.refundAddress = + _refundController.text; } } } diff --git a/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_4.dart b/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_4.dart index 731e942fb..1787f1add 100644 --- a/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_4.dart +++ b/lib/pages_desktop_specific/desktop_exchange/exchange_steps/subwidgets/desktop_step_4.dart @@ -40,8 +40,8 @@ class _DesktopStep4State extends ConsumerState { final coin = coinFromTickerCaseInsensitive(ticker); return ref .read(pWallets) - .managers - .where((element) => element.coin == coin) + .wallets + .where((e) => e.info.coin == coin) .isNotEmpty; } catch (_) { return false; diff --git a/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_choose_from_stack.dart b/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_choose_from_stack.dart index de8231d33..c0dee0553 100644 --- a/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_choose_from_stack.dart +++ b/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_choose_from_stack.dart @@ -12,7 +12,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; @@ -20,6 +19,7 @@ import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; import 'package:stackwallet/widgets/desktop/secondary_button.dart'; import 'package:stackwallet/widgets/icon_widgets/x_icon.dart'; @@ -56,9 +56,9 @@ class _DesktopChooseFromStackState final List result = []; for (final walletId in walletIds) { - final manager = ref.read(pWallets).getManager(walletId); + final name = ref.read(pWalletName(walletId)); - if (manager.walletName.toLowerCase().contains(searchTerm.toLowerCase())) { + if (name.toLowerCase().contains(searchTerm.toLowerCase())) { result.add(walletId); } } @@ -158,13 +158,13 @@ class _DesktopChooseFromStackState Flexible( child: Builder( builder: (context) { - List walletIds = ref.watch( - pWallets.select( - (value) => value.getWalletIdsFor(coin: widget.coin), - ), - ); + final wallets = ref + .watch(pWallets) + .walletsByCoin + .where((e) => e.coin == widget.coin) + .map((e) => e.wallets); - if (walletIds.isEmpty) { + if (wallets.isEmpty) { return Column( children: [ RoundedWhiteContainer( @@ -183,6 +183,9 @@ class _DesktopChooseFromStackState ); } + List walletIds = + wallets.first.map((e) => e.walletId).toList(); + walletIds = filter(walletIds, _searchTerm); return ListView.separated( @@ -192,8 +195,8 @@ class _DesktopChooseFromStackState height: 5, ), itemBuilder: (context, index) { - final manager = ref.watch(pWallets - .select((value) => value.getManager(walletIds[index]))); + final wallet = ref.watch(pWallets + .select((value) => value.getWallet(walletIds[index]))); return RoundedWhiteContainer( borderColor: @@ -212,7 +215,7 @@ class _DesktopChooseFromStackState width: 12, ), Text( - manager.walletName, + wallet.info.name, style: STextStyles.desktopTextExtraExtraSmall( context) .copyWith( @@ -233,13 +236,12 @@ class _DesktopChooseFromStackState CustomTextButton( text: "Select wallet", onTap: () async { - final address = - await manager.currentReceivingAddress; + final address = wallet.info.cachedReceivingAddress; if (mounted) { Navigator.of(context).pop( Tuple2( - manager.walletName, + wallet.info.name, address, ), ); @@ -287,17 +289,14 @@ class _BalanceDisplay extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final manager = - ref.watch(pWallets.select((value) => value.getManager(walletId))); - - Amount total = manager.balance.total; - if (manager.coin == Coin.firo || manager.coin == Coin.firoTestNet) { - final firoWallet = manager.wallet as FiroWallet; - total += firoWallet.balancePrivate.total; + final coin = ref.watch(pWalletCoin(walletId)); + Amount total = ref.watch(pWalletBalance(walletId)).total; + if (coin == Coin.firo || coin == Coin.firoTestNet) { + total += ref.watch(pWalletBalanceSecondary(walletId)).total; } return Text( - ref.watch(pAmountFormatter(manager.coin)).format(total), + ref.watch(pAmountFormatter(coin)).format(total), style: STextStyles.desktopTextExtraSmall(context).copyWith( color: Theme.of(context).extension()!.textSubtitle1, ), diff --git a/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_trade_history.dart b/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_trade_history.dart index 9d2d836d1..9584533ac 100644 --- a/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_trade_history.dart +++ b/lib/pages_desktop_specific/desktop_exchange/subwidgets/desktop_trade_history.dart @@ -17,11 +17,11 @@ import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart' import 'package:stackwallet/pages/exchange_view/trade_details_view.dart'; import 'package:stackwallet/providers/exchange/trade_sent_from_stack_lookup_provider.dart'; import 'package:stackwallet/providers/global/trades_service_provider.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/route_generator.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog_close_button.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; @@ -117,9 +117,6 @@ class _DesktopTradeHistoryState extends ConsumerState { if (txid != null && walletIds != null && walletIds.isNotEmpty) { - final manager = - ref.read(pWallets).getManager(walletIds.first); - //todo: check if print needed // debugPrint("name: ${manager.walletName}"); @@ -175,7 +172,9 @@ class _DesktopTradeHistoryState extends ConsumerState { child: TradeDetailsView( tradeId: tradeId, transactionIfSentFromStack: tx, - walletName: manager.walletName, + walletName: ref.read( + pWalletName( + walletIds.first)), walletId: walletIds.first, ), ), diff --git a/lib/pages_desktop_specific/desktop_home_view.dart b/lib/pages_desktop_specific/desktop_home_view.dart index 365b0d115..4eba04ce8 100644 --- a/lib/pages_desktop_specific/desktop_home_view.dart +++ b/lib/pages_desktop_specific/desktop_home_view.dart @@ -20,6 +20,7 @@ import 'package:stackwallet/pages_desktop_specific/settings/desktop_settings_vie import 'package:stackwallet/pages_desktop_specific/settings/settings_menu/desktop_about_view.dart'; import 'package:stackwallet/pages_desktop_specific/settings/settings_menu/desktop_support_view.dart'; import 'package:stackwallet/providers/desktop/current_desktop_menu_item.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/global/auto_swb_service_provider.dart'; import 'package:stackwallet/providers/global/notifications_provider.dart'; import 'package:stackwallet/providers/global/prefs_provider.dart'; @@ -32,8 +33,6 @@ import 'package:stackwallet/utilities/enums/backup_frequency_type.dart'; import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/onetime_popups/tor_has_been_add_dialog.dart'; -final currentWalletIdProvider = StateProvider((_) => null); - class DesktopHomeView extends ConsumerStatefulWidget { const DesktopHomeView({Key? key}) : super(key: key); @@ -113,11 +112,11 @@ class _DesktopHomeViewState extends ConsumerState { Navigator.of(myStackViewNavKey.currentContext!) .popUntil(ModalRoute.withName(MyStackView.routeName)); if (ref.read(currentWalletIdProvider.state).state != null) { - final managerProvider = ref - .read(pWallets) - .getManagerProvider(ref.read(currentWalletIdProvider.state).state!); - if (ref.read(managerProvider).shouldAutoSync) { - ref.read(managerProvider).shouldAutoSync = false; + final wallet = + ref.read(pWallets).getWallet(ref.read(currentWalletIdProvider)!); + + if (wallet.shouldAutoSync) { + wallet.shouldAutoSync = false; } ref.read(transactionFilterProvider.state).state = null; if (ref.read(prefsChangeNotifierProvider).isAutoBackupEnabled && @@ -125,7 +124,10 @@ class _DesktopHomeViewState extends ConsumerState { BackupFrequencyType.afterClosingAWallet) { ref.read(autoSWBServiceProvider).doBackup(); } - ref.read(managerProvider.notifier).isActiveWallet = false; + + // ref.read(managerProvider.notifier).isActiveWallet = false; + // TODO: call exit here? + // wallet.exit(); ?? } } ref.read(prevDesktopMenuItemProvider.state).state = newKey; diff --git a/lib/pages_desktop_specific/my_stack_view/coin_wallets_table.dart b/lib/pages_desktop_specific/my_stack_view/coin_wallets_table.dart index 0b46ed83c..859e2dbd6 100644 --- a/lib/pages_desktop_specific/my_stack_view/coin_wallets_table.dart +++ b/lib/pages_desktop_specific/my_stack_view/coin_wallets_table.dart @@ -10,8 +10,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:stackwallet/pages_desktop_specific/desktop_home_view.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; @@ -30,7 +30,11 @@ class CoinWalletsTable extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final walletIds = ref - .watch(pWallets.select((value) => value.getWalletIdsFor(coin: coin))); + .watch(pWallets) + .wallets + .where((e) => e.info.coin == coin) + .map((e) => e.walletId) + .toList(); return Container( decoration: BoxDecoration( @@ -71,11 +75,12 @@ class CoinWalletsTable extends ConsumerWidget { ref.read(currentWalletIdProvider.state).state = walletIds[i]; - final manager = - ref.read(pWallets).getManager(walletIds[i]); - if (manager.coin == Coin.monero || - manager.coin == Coin.wownero) { - await manager.initializeExisting(); + final wallet = + ref.read(pWallets).getWallet(walletIds[i]); + if (wallet.info.coin == Coin.monero || + wallet.info.coin == Coin.wownero) { + // TODO: this can cause ui lag + await wallet.init(); } await Navigator.of(context).pushNamed( diff --git a/lib/pages_desktop_specific/my_stack_view/desktop_favorite_wallets.dart b/lib/pages_desktop_specific/my_stack_view/desktop_favorite_wallets.dart index 67fd870ba..82472625e 100644 --- a/lib/pages_desktop_specific/my_stack_view/desktop_favorite_wallets.dart +++ b/lib/pages_desktop_specific/my_stack_view/desktop_favorite_wallets.dart @@ -13,12 +13,12 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; import 'package:stackwallet/pages/manage_favorites_view/manage_favorites_view.dart'; import 'package:stackwallet/pages/wallets_view/sub_widgets/favorite_card.dart'; -import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; +import 'package:stackwallet/widgets/db_watchers/favourite_wallets_watcher.dart'; class DesktopFavoriteWallets extends ConsumerWidget { const DesktopFavoriteWallets({Key? key}) : super(key: key); @@ -31,117 +31,116 @@ class DesktopFavoriteWallets extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { debugPrint("BUILD: $runtimeType"); - final favorites = ref.watch(favoritesProvider); - bool hasFavorites = favorites.length > 0; - - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + return FavouriteWalletsWatcher( + builder: (context, favourites) { + bool hasFavorites = favourites.isNotEmpty; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - "Favorite wallets", - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of(context) - .extension()! - .textFieldActiveSearchIconRight, - ), - ), - CustomTextButton( - text: "Edit", - onTap: () { - Navigator.of(context).pushNamed(ManageFavoritesView.routeName); - }, - ), - ], - ), - const SizedBox( - height: 20, - ), - ConstrainedBox( - constraints: const BoxConstraints( - maxHeight: (cardHeight * 2) + standardPadding, - minHeight: cardHeight, - ), - child: hasFavorites - ? SingleChildScrollView( - primary: false, - child: Wrap( - spacing: 16, - runSpacing: 16, - children: [ - ...favorites.map((p0) { - final walletId = ref.read(p0).walletId; - final walletName = ref.read(p0).walletName; - final managerProvider = - ref.read(pWallets).getManagerProvider(walletId); - - return FavoriteCard( - walletId: walletId, - key: Key(walletName), - width: cardWidth, - height: cardHeight, - ); - }) - ], - ), - ) - : Container( - height: cardHeight, - width: cardWidth, - decoration: BoxDecoration( + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Favorite wallets", + style: STextStyles.desktopTextExtraSmall(context).copyWith( color: Theme.of(context) .extension()! - .textFieldDefaultBG, - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - ), - child: MaterialButton( - splashColor: - Theme.of(context).extension()!.highlight, - key: const Key("favoriteWalletsAddFavoriteButtonKey"), - padding: const EdgeInsets.all(12), - materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius), - ), - onPressed: () { - Navigator.of(context) - .pushNamed(ManageFavoritesView.routeName); - }, - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - SvgPicture.asset( - Assets.svg.plus, - width: 14, - height: 14, - color: Theme.of(context) - .extension()! - .textSubtitle1, - ), - const SizedBox( - width: 4, - ), - Text( - "Add a favorite", - style: STextStyles.itemSubtitle(context).copyWith( - fontSize: 18, - ), - ), - ], - ), + .textFieldActiveSearchIconRight, ), ), - ), - const SizedBox( - height: 40, - ), - ], + CustomTextButton( + text: "Edit", + onTap: () { + Navigator.of(context) + .pushNamed(ManageFavoritesView.routeName); + }, + ), + ], + ), + const SizedBox( + height: 20, + ), + ConstrainedBox( + constraints: const BoxConstraints( + maxHeight: (cardHeight * 2) + standardPadding, + minHeight: cardHeight, + ), + child: hasFavorites + ? SingleChildScrollView( + primary: false, + child: Wrap( + spacing: 16, + runSpacing: 16, + children: [ + ...favourites.map((e) { + return FavoriteCard( + walletId: e.walletId, + key: Key(e.name), + width: cardWidth, + height: cardHeight, + ); + }) + ], + ), + ) + : Container( + height: cardHeight, + width: cardWidth, + decoration: BoxDecoration( + color: Theme.of(context) + .extension()! + .textFieldDefaultBG, + borderRadius: BorderRadius.circular( + Constants.size.circularBorderRadius, + ), + ), + child: MaterialButton( + splashColor: Theme.of(context) + .extension()! + .highlight, + key: const Key("favoriteWalletsAddFavoriteButtonKey"), + padding: const EdgeInsets.all(12), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + Constants.size.circularBorderRadius), + ), + onPressed: () { + Navigator.of(context) + .pushNamed(ManageFavoritesView.routeName); + }, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SvgPicture.asset( + Assets.svg.plus, + width: 14, + height: 14, + color: Theme.of(context) + .extension()! + .textSubtitle1, + ), + const SizedBox( + width: 4, + ), + Text( + "Add a favorite", + style: STextStyles.itemSubtitle(context).copyWith( + fontSize: 18, + ), + ), + ], + ), + ), + ), + ), + const SizedBox( + height: 40, + ), + ], + ); + }, ); } } diff --git a/lib/pages_desktop_specific/my_stack_view/dialogs/desktop_expanding_wallet_card.dart b/lib/pages_desktop_specific/my_stack_view/dialogs/desktop_expanding_wallet_card.dart index 38171f763..9cee94e50 100644 --- a/lib/pages_desktop_specific/my_stack_view/dialogs/desktop_expanding_wallet_card.dart +++ b/lib/pages_desktop_specific/my_stack_view/dialogs/desktop_expanding_wallet_card.dart @@ -12,11 +12,11 @@ import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/svg.dart'; import 'package:stackwallet/models/isar/models/ethereum/eth_contract.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/animated_widgets/rotate_icon.dart'; import 'package:stackwallet/widgets/expandable.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; @@ -32,7 +32,7 @@ class DesktopExpandingWalletCard extends StatefulWidget { required this.navigatorState, }) : super(key: key); - final Tuple2> data; + final Tuple2> data; final NavigatorState navigatorState; @override @@ -48,7 +48,7 @@ class _DesktopExpandingWalletCardState @override void initState() { - if (widget.data.item1.hasTokenSupport) { + if (widget.data.item1.cryptoCurrency.hasTokenSupport) { tokenContractAddresses.addAll( widget.data.item2.map((e) => e.address), ); @@ -63,7 +63,7 @@ class _DesktopExpandingWalletCardState padding: EdgeInsets.zero, borderColor: Theme.of(context).extension()!.backgroundAppBar, child: Expandable( - initialState: widget.data.item1.hasTokenSupport + initialState: widget.data.item1.cryptoCurrency.hasTokenSupport ? ExpandableState.expanded : ExpandableState.collapsed, controller: expandableController, @@ -89,13 +89,13 @@ class _DesktopExpandingWalletCardState child: Row( children: [ WalletInfoCoinIcon( - coin: widget.data.item1.coin, + coin: widget.data.item1.info.coin, ), const SizedBox( width: 12, ), Text( - widget.data.item1.walletName, + widget.data.item1.info.name, style: STextStyles.desktopTextExtraSmall(context) .copyWith( color: Theme.of(context) diff --git a/lib/pages_desktop_specific/my_stack_view/paynym/desktop_paynym_send_dialog.dart b/lib/pages_desktop_specific/my_stack_view/paynym/desktop_paynym_send_dialog.dart index 55bca3dfa..456f3d89d 100644 --- a/lib/pages_desktop_specific/my_stack_view/paynym/desktop_paynym_send_dialog.dart +++ b/lib/pages_desktop_specific/my_stack_view/paynym/desktop_paynym_send_dialog.dart @@ -21,14 +21,15 @@ import 'package:stackwallet/providers/global/prefs_provider.dart'; import 'package:stackwallet/providers/global/price_provider.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/providers/wallet/public_private_balance_state_provider.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; import 'package:stackwallet/utilities/barcode_scanner_interface.dart'; import 'package:stackwallet/utilities/clipboard_interface.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog_close_button.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; @@ -58,12 +59,12 @@ class _DesktopPaynymSendDialogState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); + final wallet = + ref.watch(pWallets.select((value) => value.getWallet(widget.walletId))); final String locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); - final coin = manager.coin; + final coin = ref.watch(pWalletCoin(widget.walletId)); final isFiro = coin == Coin.firo || coin == Coin.firoTestNet; @@ -78,7 +79,7 @@ class _DesktopPaynymSendDialogState Padding( padding: const EdgeInsets.only(left: 32), child: Text( - "Send ${manager.coin.ticker.toUpperCase()}", + "Send ${coin.ticker.toUpperCase()}", style: STextStyles.desktopH3(context), ), ), @@ -107,7 +108,7 @@ class _DesktopPaynymSendDialogState crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - manager.walletName, + ref.watch(pWalletName(widget.walletId)), style: STextStyles.titleBold12(context), overflow: TextOverflow.ellipsis, maxLines: 1, @@ -135,9 +136,9 @@ class _DesktopPaynymSendDialogState children: [ Text( !isFiro - ? ref - .watch(pAmountFormatter(coin)) - .format(manager.balance.spendable) + ? ref.watch(pAmountFormatter(coin)).format(ref + .watch(pWalletBalance(widget.walletId)) + .spendable) : ref .watch( publicPrivateBalanceStateProvider @@ -146,12 +147,24 @@ class _DesktopPaynymSendDialogState .state == "Private" ? ref.watch(pAmountFormatter(coin)).format( - (manager.wallet as FiroWallet) - .availablePrivateBalance()) + ref + .watch( + pWalletBalance(widget.walletId)) + .spendable, + ) : ref.watch(pAmountFormatter(coin)).format( - (manager.wallet as FiroWallet) - .availablePublicBalance(), + ref + .watch(pWalletBalanceSecondary( + widget.walletId)) + .spendable, ), + // ? ref.watch(pAmountFormatter(coin)).format( + // (manager.wallet as FiroWallet) + // .availablePrivateBalance()) + // : ref.watch(pAmountFormatter(coin)).format( + // (manager.wallet as FiroWallet) + // .availablePublicBalance(), + // ), style: STextStyles.titleBold12(context), textAlign: TextAlign.right, ), @@ -159,7 +172,7 @@ class _DesktopPaynymSendDialogState height: 2, ), Text( - "${((!isFiro ? manager.balance.spendable.decimal : ref.watch(publicPrivateBalanceStateProvider.state).state == "Private" ? (manager.wallet as FiroWallet).availablePrivateBalance().decimal : (manager.wallet as FiroWallet).availablePublicBalance().decimal) * ref.watch( + "${((!isFiro ? ref.watch(pWalletBalance(widget.walletId)).spendable.decimal : ref.watch(publicPrivateBalanceStateProvider.state).state == "Private" ? ref.watch(pWalletBalance(widget.walletId)).spendable.decimal : ref.watch(pWalletBalanceSecondary(widget.walletId)).spendable.decimal) * ref.watch( priceAnd24hChangeNotifierProvider.select( (value) => value.getPrice(coin).item1, ), @@ -192,7 +205,7 @@ class _DesktopPaynymSendDialogState bottom: 32, ), child: DesktopSend( - walletId: manager.walletId, + walletId: widget.walletId, accountLite: widget.accountLite, ), ), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart b/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart index cac3838cb..c1e26475c 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_summary_table.dart @@ -36,19 +36,14 @@ class _WalletTableState extends ConsumerState { @override Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final providersByCoin = ref.watch( - pWallets.select( - (value) => value.getManagerProvidersByCoin(), - ), - ); + final walletsByCoin = ref.watch(pWallets).walletsByCoin; return ListView.separated( itemBuilder: (_, index) { - final providers = providersByCoin[index].item2; - final coin = providersByCoin[index].item1; + final coin = walletsByCoin[index].coin; return ConditionalParent( - condition: index + 1 == providersByCoin.length, + condition: index + 1 == walletsByCoin.length, builder: (child) => Padding( padding: const EdgeInsets.only( bottom: 16, @@ -58,14 +53,14 @@ class _WalletTableState extends ConsumerState { child: DesktopWalletSummaryRow( key: Key("DesktopWalletSummaryRow_key_${coin.name}"), coin: coin, - walletCount: providers.length, + walletCount: walletsByCoin[index].wallets.length, ), ); }, separatorBuilder: (_, __) => const SizedBox( height: 10, ), - itemCount: providersByCoin.length, + itemCount: walletsByCoin.length, ); } } diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_token_view.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_token_view.dart index 85b781f85..d2ade5b80 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_token_view.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_token_view.dart @@ -25,6 +25,7 @@ import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_ import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_app_bar.dart'; import 'package:stackwallet/widgets/desktop/desktop_scaffold.dart'; @@ -87,11 +88,7 @@ class _DesktopTokenViewState extends ConsumerState { right: 18, ), buttonHeight: ButtonHeight.s, - label: ref.watch( - pWallets.select( - (value) => value.getManager(widget.walletId).walletName, - ), - ), + label: ref.watch(pWalletName(widget.walletId)), icon: SvgPicture.asset( Assets.svg.arrowLeft, width: 18, @@ -168,8 +165,11 @@ class _DesktopTokenViewState extends ConsumerState { DesktopWalletSummary( walletId: widget.walletId, isToken: true, - initialSyncStatus: ref.watch(pWallets.select((value) => - value.getManager(widget.walletId).isRefreshing)) + initialSyncStatus: ref + .watch(pWallets) + .getWallet(widget.walletId) + .refreshMutex + .isLocked ? WalletSyncStatus.syncing : WalletSyncStatus.synced, ), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart index b2cbcecd6..75afa80e2 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart @@ -29,6 +29,7 @@ import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/network_info_button.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_keys_button.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/global/auto_swb_service_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/ui/transaction_filter_provider.dart'; @@ -39,7 +40,6 @@ import 'package:stackwallet/services/event_bus/global_event_bus.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; -import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/backup_frequency_type.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; @@ -92,11 +92,10 @@ class _DesktopWalletViewState extends ConsumerState { } Future _logout() async { - final managerProvider = - ref.read(pWallets).getManagerProvider(widget.walletId); + final wallet = ref.read(pWallets).getWallet(widget.walletId); if (_shouldDisableAutoSyncOnLogOut) { // disable auto sync if it was enabled only when loading wallet - ref.read(managerProvider).shouldAutoSync = false; + wallet.shouldAutoSync = false; } ref.read(transactionFilterProvider.state).state = null; if (ref.read(prefsChangeNotifierProvider).isAutoBackupEnabled && @@ -104,13 +103,15 @@ class _DesktopWalletViewState extends ConsumerState { BackupFrequencyType.afterClosingAWallet) { unawaited(ref.read(autoSWBServiceProvider).doBackup()); } - ref.read(managerProvider.notifier).isActiveWallet = false; + + ref.read(currentWalletIdProvider.notifier).state = null; } Future _firoRescanRecovery() async { - final success = await (ref.read(pWallets).getManager(widget.walletId).wallet - as FiroWallet) - .firoRescanRecovery(); + // TODO: [prio=high] FIX TYPE CAST as + final success = + await (ref.read(pWallets).getWallet(widget.walletId) as FiroWallet) + .firoRescanRecovery(); if (success) { // go into wallet @@ -140,41 +141,42 @@ class _DesktopWalletViewState extends ConsumerState { @override void initState() { controller = TextEditingController(); - final managerProvider = - ref.read(pWallets).getManagerProvider(widget.walletId); + final wallet = ref.read(pWallets).getWallet(widget.walletId); - controller.text = ref.read(managerProvider).walletName; + controller.text = wallet.info.name; eventBus = widget.eventBus != null ? widget.eventBus! : GlobalEventBus.instance; - ref.read(managerProvider).isActiveWallet = true; - if (!ref.read(managerProvider).shouldAutoSync) { + ref.read(currentWalletIdProvider.notifier).state = wallet.walletId; + + if (!wallet.shouldAutoSync) { // enable auto sync if it wasn't enabled when loading wallet - ref.read(managerProvider).shouldAutoSync = true; + wallet.shouldAutoSync = true; _shouldDisableAutoSyncOnLogOut = true; } else { _shouldDisableAutoSyncOnLogOut = false; } - if (ref.read(managerProvider).coin == Coin.firo && - (ref.read(managerProvider).wallet as FiroWallet) - .lelantusCoinIsarRescanRequired) { + if (wallet.info.coin == Coin.firo && + (wallet as FiroWallet).lelantusCoinIsarRescanRequired) { _rescanningOnOpen = true; _lelantusRescanRecovery = true; _firoRescanRecovery(); - } else if (ref.read(managerProvider).coin != Coin.ethereum && - ref.read(managerProvider).rescanOnOpenVersion == Constants.rescanV1) { - _rescanningOnOpen = true; - ref.read(managerProvider).fullRescan(20, 1000).then( - (_) => ref.read(managerProvider).resetRescanOnOpen().then( - (_) => WidgetsBinding.instance.addPostFrameCallback( - (_) => setState(() => _rescanningOnOpen = false), - ), - ), - ); + + // TODO: [prio=high] fix this!!!!!!!!!!!!!!! + // } else if (wallet.walletInfo.coin != Coin.ethereum && + // ref.read(managerProvider).rescanOnOpenVersion == Constants.rescanV1) { + // _rescanningOnOpen = true; + // wallet.fullRescan(20, 1000).then( + // (_) => ref.read(managerProvider).resetRescanOnOpen().then( + // (_) => WidgetsBinding.instance.addPostFrameCallback( + // (_) => setState(() => _rescanningOnOpen = false), + // ), + // ), + // ); } else { - ref.read(managerProvider).refresh(); + wallet.refresh(); } super.initState(); @@ -188,14 +190,11 @@ class _DesktopWalletViewState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); - final coin = manager.coin; - final managerProvider = ref.watch( - pWallets.select((value) => value.getManagerProvider(widget.walletId))); + final wallet = ref.watch(pWallets).getWallet(widget.walletId); + final walletInfo = wallet.info; - final monke = coin == Coin.banano - ? (manager.wallet as BananoWallet).getMonkeyImageBytes() + final monke = wallet.info.coin == Coin.banano + ? (wallet as BananoWallet).getMonkeyImageBytes() : null; return ConditionalParent( @@ -326,7 +325,7 @@ class _DesktopWalletViewState extends ConsumerState { ), SvgPicture.file( File( - ref.watch(coinIconProvider(coin)), + ref.watch(coinIconProvider(wallet.info.coin)), ), width: 32, height: 32, @@ -391,7 +390,7 @@ class _DesktopWalletViewState extends ConsumerState { if (monke == null) SvgPicture.file( File( - ref.watch(coinIconProvider(coin)), + ref.watch(coinIconProvider(wallet.info.coin)), ), width: 40, height: 40, @@ -401,8 +400,7 @@ class _DesktopWalletViewState extends ConsumerState { ), DesktopWalletSummary( walletId: widget.walletId, - initialSyncStatus: ref.watch(managerProvider - .select((value) => value.isRefreshing)) + initialSyncStatus: wallet.refreshMutex.isLocked ? WalletSyncStatus.syncing : WalletSyncStatus.synced, ), @@ -438,9 +436,7 @@ class _DesktopWalletViewState extends ConsumerState { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - ref.watch(pWallets.select((value) => value - .getManager(widget.walletId) - .hasTokenSupport)) + wallet.cryptoCurrency.hasTokenSupport ? "Tokens" : "Recent activity", style: STextStyles.desktopTextExtraSmall(context) @@ -451,16 +447,11 @@ class _DesktopWalletViewState extends ConsumerState { ), ), CustomTextButton( - text: ref.watch(pWallets.select((value) => value - .getManager(widget.walletId) - .hasTokenSupport)) + text: wallet.cryptoCurrency.hasTokenSupport ? "Edit" : "See all", onTap: () async { - if (ref - .read(pWallets) - .getManager(widget.walletId) - .hasTokenSupport) { + if (wallet.cryptoCurrency.hasTokenSupport) { final result = await showDialog( context: context, builder: (context) => EditWalletTokensView( @@ -475,8 +466,9 @@ class _DesktopWalletViewState extends ConsumerState { } } else { await Navigator.of(context).pushNamed( - coin == Coin.bitcoincash || - coin == Coin.bitcoincashTestnet + walletInfo.coin == Coin.bitcoincash || + walletInfo.coin == + Coin.bitcoincashTestnet ? AllTransactionsV2View.routeName : AllTransactionsView.routeName, arguments: widget.walletId, @@ -506,21 +498,15 @@ class _DesktopWalletViewState extends ConsumerState { width: 16, ), Expanded( - child: ref.watch(pWallets.select((value) => value - .getManager(widget.walletId) - .hasTokenSupport)) + child: wallet.cryptoCurrency.hasTokenSupport ? MyTokensView( walletId: widget.walletId, ) - : coin == Coin.bitcoincash || - coin == Coin.bitcoincashTestnet + : wallet.isarTransactionVersion == 2 ? TransactionsV2List( walletId: widget.walletId, ) : TransactionsList( - managerProvider: ref.watch(pWallets.select( - (value) => value.getManagerProvider( - widget.walletId))), walletId: widget.walletId, ), ), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/delete_wallet_keys_popup.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/delete_wallet_keys_popup.dart index ac20ccf1a..028d0c714 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/delete_wallet_keys_popup.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/delete_wallet_keys_popup.dart @@ -15,8 +15,6 @@ import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_view/sub_widgets/mnemonic_table.dart'; -import 'package:stackwallet/providers/global/wallets_provider.dart'; -import 'package:stackwallet/providers/global/wallets_service_provider.dart'; import 'package:stackwallet/route_generator.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; @@ -125,14 +123,16 @@ class _DeleteWalletKeysPopup extends ConsumerState { await _clipboardInterface.setData( ClipboardData(text: _words.join(" ")), ); - unawaited( - showFloatingFlushBar( - type: FlushBarType.info, - message: "Copied to clipboard", - iconAsset: Assets.svg.copy, - context: context, - ), - ); + if (mounted) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.info, + message: "Copied to clipboard", + iconAsset: Assets.svg.copy, + context: context, + ), + ); + } }, child: MnemonicTable( words: widget.words, @@ -202,9 +202,9 @@ class _ConfirmDeleteState extends ConsumerState { maxHeight: 350, child: Column( children: [ - Row( + const Row( mainAxisAlignment: MainAxisAlignment.end, - children: const [ + children: [ DesktopDialogCloseButton(), ], ), @@ -235,23 +235,25 @@ class _ConfirmDeleteState extends ConsumerState { buttonHeight: ButtonHeight.xl, label: "Continue", onPressed: () async { - final walletsInstance = ref.read(pWallets); - final manager = - ref.read(pWallets).getManager(widget.walletId); + // TODO: [prio=high] wallet deletion - final _managerWalletId = manager.walletId; + // final walletsInstance = ref.read(pWallets); + // final manager = + // ref.read(pWallets).getManager(widget.walletId); // - await ref - .read(walletsServiceChangeNotifierProvider) - .deleteWallet(manager.walletName, true); - - if (mounted) { - Navigator.of(context, rootNavigator: true).pop(true); - } - - // wait for widget tree to dispose of any widgets watching the manager - await Future.delayed(const Duration(seconds: 1)); - walletsInstance.removeWallet(walletId: _managerWalletId); + // final _managerWalletId = manager.walletId; + // // + // await ref + // .read(walletsServiceChangeNotifierProvider) + // .deleteWallet(manager.walletName, true); + // + // if (mounted) { + // Navigator.of(context, rootNavigator: true).pop(true); + // } + // + // // wait for widget tree to dispose of any widgets watching the manager + // await Future.delayed(const Duration(seconds: 1)); + // walletsInstance.removeWallet(walletId: _managerWalletId); }, ), ], diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_attention_delete_wallet.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_attention_delete_wallet.dart index 04e467f98..a80075815 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_attention_delete_wallet.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_attention_delete_wallet.dart @@ -14,6 +14,7 @@ import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/wallet/bip39_wallet.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog_close_button.dart'; import 'package:stackwallet/widgets/desktop/primary_button.dart'; @@ -110,19 +111,21 @@ class _DesktopAttentionDeleteWallet buttonHeight: ButtonHeight.xl, label: "View Backup Key", onPressed: () async { - final words = await ref - .read(pWallets) - .getManager(widget.walletId) - .mnemonic; + final wallet = + ref.read(pWallets).getWallet(widget.walletId); + // TODO: [prio=high] handle other types wallet deletion + if (wallet is Bip39Wallet) { + final words = await wallet.getMnemonicAsWords(); - if (mounted) { - await Navigator.of(context).pushNamed( - DeleteWalletKeysPopup.routeName, - arguments: Tuple2( - widget.walletId, - words, - ), - ); + if (mounted) { + await Navigator.of(context).pushNamed( + DeleteWalletKeysPopup.routeName, + arguments: Tuple2( + widget.walletId, + words, + ), + ); + } } }, ), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_fee_dropdown.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_fee_dropdown.dart index 6741e6dba..88519092b 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_fee_dropdown.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_fee_dropdown.dart @@ -19,7 +19,6 @@ import 'package:stackwallet/pages/token_view/token_view.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/providers/ui/fee_rate_type_state_provider.dart'; import 'package:stackwallet/providers/wallet/public_private_balance_state_provider.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; @@ -28,6 +27,7 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/animated_text.dart'; final tokenFeeSessionCacheProvider = @@ -77,21 +77,23 @@ class _DesktopFeeDropDownState extends ConsumerState { .fast[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.fast.raw!); ref.read(feeSheetSessionCacheProvider).fast[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { - ref.read(feeSheetSessionCacheProvider).fast[amount] = - await (manager.wallet as FiroWallet) - .estimateFeeForPublic(amount, feeRate); + // TODO: [prio=high] firo fees + throw UnimplementedError("Firo public fees"); + // ref.read(feeSheetSessionCacheProvider).fast[amount] = + // await (manager.wallet as FiroWallet) + // .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).fast[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -113,21 +115,23 @@ class _DesktopFeeDropDownState extends ConsumerState { .average[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.regular.raw!); ref.read(feeSheetSessionCacheProvider).average[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { - ref.read(feeSheetSessionCacheProvider).average[amount] = - await (manager.wallet as FiroWallet) - .estimateFeeForPublic(amount, feeRate); + // TODO: [prio=high] firo fees + throw UnimplementedError("Firo public fees"); + // ref.read(feeSheetSessionCacheProvider).average[amount] = + // await (manager.wallet as FiroWallet) + // .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).average[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -149,21 +153,23 @@ class _DesktopFeeDropDownState extends ConsumerState { .slow[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.slow.raw!); ref.read(feeSheetSessionCacheProvider).slow[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { - ref.read(feeSheetSessionCacheProvider).slow[amount] = - await (manager.wallet as FiroWallet) - .estimateFeeForPublic(amount, feeRate); + // TODO: [prio=high] firo fees + throw UnimplementedError("Firo public fees"); + // ref.read(feeSheetSessionCacheProvider).slow[amount] = + // await (manager.wallet as FiroWallet) + // .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).slow[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -195,11 +201,11 @@ class _DesktopFeeDropDownState extends ConsumerState { Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final manager = - ref.watch(pWallets.select((value) => value.getManager(walletId))); + final wallet = + ref.watch(pWallets.select((value) => value.getWallet(walletId))); return FutureBuilder( - future: manager.fees, + future: wallet.fees, builder: (context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) { @@ -321,8 +327,7 @@ class FeeDropDownChild extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { debugPrint("BUILD: $runtimeType : $feeRateType"); - final manager = - ref.watch(pWallets.select((value) => value.getManager(walletId))); + final coin = ref.watch(pWalletCoin(walletId)); if (feeObject == null) { return AnimatedText( @@ -335,7 +340,7 @@ class FeeDropDownChild extends ConsumerWidget { } else { return FutureBuilder( future: feeFor( - coin: manager.coin, + coin: coin, feeRateType: feeRateType, feeRate: feeRateType == FeeRateType.fast ? feeObject!.fast @@ -352,7 +357,7 @@ class FeeDropDownChild extends ConsumerWidget { children: [ Text( "${feeRateType.prettyName} " - "(~${ref.watch(pAmountFormatter(manager.coin)).format( + "(~${ref.watch(pAmountFormatter(coin)).format( snapshot.data!, indicatePrecisionLoss: false, )})", @@ -366,10 +371,10 @@ class FeeDropDownChild extends ConsumerWidget { ), if (feeObject != null) Text( - manager.coin == Coin.ethereum + coin == Coin.ethereum ? "" : estimatedTimeToBeIncludedInNextBlock( - Constants.targetBlockTimeInSeconds(manager.coin), + Constants.targetBlockTimeInSeconds(coin), feeRateType == FeeRateType.fast ? feeObject!.numberOfBlocksFast : feeRateType == FeeRateType.slow diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart index bb8915fb5..5de142848 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart @@ -28,6 +28,8 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/bip39_hd_wallet.dart'; import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart'; import 'package:stackwallet/widgets/custom_loading_overlay.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; @@ -57,53 +59,46 @@ class _DesktopReceiveState extends ConsumerState { late final ClipboardInterface clipboard; Future generateNewAddress() async { - bool shouldPop = false; - unawaited( - showDialog( - context: context, - builder: (_) { - return WillPopScope( - onWillPop: () async => shouldPop, - child: Container( - color: Theme.of(context) - .extension()! - .overlay - .withOpacity(0.5), - child: const CustomLoadingOverlay( - message: "Generating address", - eventBus: null, + final wallet = ref.read(pWallets).getWallet(walletId); + if (wallet is Bip39HDWallet) { + bool shouldPop = false; + unawaited( + showDialog( + context: context, + builder: (_) { + return WillPopScope( + onWillPop: () async => shouldPop, + child: Container( + color: Theme.of(context) + .extension()! + .overlay + .withOpacity(0.5), + child: const CustomLoadingOverlay( + message: "Generating address", + eventBus: null, + ), ), - ), - ); - }, - ), - ); + ); + }, + ), + ); - await ref.read(pWallets).getManager(walletId).generateNewAddress(); + await wallet.generateNewReceivingAddress(); - shouldPop = true; + shouldPop = true; - if (mounted) { - Navigator.of(context, rootNavigator: true).pop(); + if (mounted) { + Navigator.of(context, rootNavigator: true).pop(); + } } } - String receivingAddress = ""; - @override void initState() { walletId = widget.walletId; - coin = ref.read(pWallets).getManager(walletId).coin; + coin = ref.read(pWalletInfo(walletId)).coin; clipboard = widget.clipboard; - WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { - final address = - await ref.read(pWallets).getManager(walletId).currentReceivingAddress; - setState(() { - receivingAddress = address; - }); - }); - super.initState(); } @@ -111,16 +106,7 @@ class _DesktopReceiveState extends ConsumerState { Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - ref.listen( - ref - .read(pWallets) - .getManagerProvider(walletId) - .select((value) => value.currentReceivingAddress), - (previous, next) { - if (next is Future) { - next.then((value) => setState(() => receivingAddress = value)); - } - }); + final receivingAddress = ref.watch(pWalletReceivingAddress(walletId)); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart index 52fe798db..0a0621f68 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart @@ -32,8 +32,7 @@ import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/ui/fee_rate_type_state_provider.dart'; import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart'; import 'package:stackwallet/providers/wallet/public_private_balance_state_provider.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; -import 'package:stackwallet/services/coins/manager.dart'; +import 'package:stackwallet/services/mixins/coin_control_interface.dart'; import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/address_utils.dart'; @@ -51,6 +50,8 @@ import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/animated_text.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; @@ -67,6 +68,8 @@ import 'package:stackwallet/widgets/rounded_container.dart'; import 'package:stackwallet/widgets/stack_text_field.dart'; import 'package:stackwallet/widgets/textfield_icon_button.dart'; +import '../../../../wallets/isar/models/wallet_info.dart'; + class DesktopSend extends ConsumerStatefulWidget { const DesktopSend({ Key? key, @@ -137,28 +140,29 @@ class _DesktopSendState extends ConsumerState { ]; Future previewSend() async { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); final Amount amount = _amountToSend!; final Amount availableBalance; if ((coin == Coin.firo || coin == Coin.firoTestNet)) { if (ref.read(publicPrivateBalanceStateProvider.state).state == "Private") { - availableBalance = - (manager.wallet as FiroWallet).availablePrivateBalance(); + availableBalance = wallet.info.cachedBalance.spendable; + // (manager.wallet as FiroWallet).availablePrivateBalance(); } else { - availableBalance = - (manager.wallet as FiroWallet).availablePublicBalance(); + availableBalance = wallet.info.cachedSecondaryBalance.spendable; + // (manager.wallet as FiroWallet).availablePublicBalance(); } } else { - availableBalance = manager.balance.spendable; + availableBalance = wallet.info.cachedBalance.spendable; + ; } final coinControlEnabled = ref.read(prefsChangeNotifierProvider).enableCoinControl; - if (!(manager.hasCoinControlSupport && coinControlEnabled) || - (manager.hasCoinControlSupport && + if (!(wallet is CoinControlInterface && coinControlEnabled) || + (wallet is CoinControlInterface && coinControlEnabled && ref.read(desktopUseUTXOs).isEmpty)) { // confirm send all @@ -268,7 +272,7 @@ class _DesktopSendState extends ConsumerState { child: Padding( padding: const EdgeInsets.all(32), child: BuildingTransactionDialog( - coin: manager.coin, + coin: wallet.info.coin, onCancel: () { wasCancelled = true; @@ -288,61 +292,64 @@ class _DesktopSendState extends ConsumerState { ), ); - Map txData; - Future> txDataFuture; + TxData txData; + Future txDataFuture; if (isPaynymSend) { - final wallet = manager.wallet as PaynymWalletInterface; + final paynymWallet = wallet as PaynymWalletInterface; final paymentCode = PaymentCode.fromPaymentCode( widget.accountLite!.code, - networkType: wallet.networkType, - ); - final feeRate = ref.read(feeRateTypeStateProvider); - txDataFuture = wallet.preparePaymentCodeSend( - paymentCode: paymentCode, - isSegwit: widget.accountLite!.segwit, - amount: amount, - args: { - "satsPerVByte": isCustomFee ? customFeeRate : null, - "feeRate": feeRate, - "UTXOs": (manager.hasCoinControlSupport && - coinControlEnabled && - ref.read(desktopUseUTXOs).isNotEmpty) - ? ref.read(desktopUseUTXOs) - : null, - }, + networkType: paynymWallet.networkType, ); + throw UnimplementedError("FIXME"); + // TODO: [prio=high] paynym prepare send using TxData + // final feeRate = ref.read(feeRateTypeStateProvider); + // txDataFuture = paynymWallet.preparePaymentCodeSend( + // paymentCode: paymentCode, + // isSegwit: widget.accountLite!.segwit, + // amount: amount, + // args: { + // "satsPerVByte": isCustomFee ? customFeeRate : null, + // "feeRate": feeRate, + // "UTXOs": (wallet is CoinControlInterface && + // coinControlEnabled && + // ref.read(desktopUseUTXOs).isNotEmpty) + // ? ref.read(desktopUseUTXOs) + // : null, + // }, + // ); } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { - txDataFuture = (manager.wallet as FiroWallet).prepareSendPublic( - address: _address!, - amount: amount, - args: { - "feeRate": ref.read(feeRateTypeStateProvider), - "satsPerVByte": isCustomFee ? customFeeRate : null, - "UTXOs": (manager.hasCoinControlSupport && - coinControlEnabled && - ref.read(desktopUseUTXOs).isNotEmpty) - ? ref.read(desktopUseUTXOs) - : null, - }, - ); + throw UnimplementedError("FIXME"); + // TODO: [prio=high] firo prepare send using TxData + // txDataFuture = (manager.wallet as FiroWallet).prepareSendPublic( + // address: _address!, + // amount: amount, + // args: { + // "feeRate": ref.read(feeRateTypeStateProvider), + // "satsPerVByte": isCustomFee ? customFeeRate : null, + // "UTXOs": (wallet is CoinControlInterface && + // coinControlEnabled && + // ref.read(desktopUseUTXOs).isNotEmpty) + // ? ref.read(desktopUseUTXOs) + // : null, + // }, + // ); } else { final memo = isStellar ? memoController.text : null; - txDataFuture = manager.prepareSend( - address: _address!, - amount: amount, - args: { - "memo": memo, - "feeRate": ref.read(feeRateTypeStateProvider), - "satsPerVByte": isCustomFee ? customFeeRate : null, - "UTXOs": (manager.hasCoinControlSupport && + txDataFuture = wallet.prepareSend( + txData: TxData( + recipients: [(address: _address!, amount: amount)], + memo: memo, + feeRateType: ref.read(feeRateTypeStateProvider), + satsPerVByte: isCustomFee ? customFeeRate : null, + utxos: (wallet is CoinControlInterface && coinControlEnabled && ref.read(desktopUseUTXOs).isNotEmpty) ? ref.read(desktopUseUTXOs) : null, - }, + ), ); } @@ -351,17 +358,22 @@ class _DesktopSendState extends ConsumerState { time, ]); - txData = results.first as Map; + txData = results.first as TxData; if (!wasCancelled && mounted) { if (isPaynymSend) { - txData["paynymAccountLite"] = widget.accountLite!; - txData["note"] = _note ?? "PayNym send"; + txData = txData.copyWith( + paynymAccountLite: widget.accountLite!, + note: _note ?? "PayNym send", + ); } else { - txData["address"] = _address; - txData["note"] = _note ?? ""; + txData = txData.copyWith( + note: _note ?? "", + ); if (coin == Coin.epicCash) { - txData['onChainNote'] = _onChainNote ?? ""; + txData = txData.copyWith( + noteOnChain: _onChainNote ?? "", + ); } } // pop building dialog @@ -377,7 +389,7 @@ class _DesktopSendState extends ConsumerState { maxHeight: double.infinity, maxWidth: 580, child: ConfirmTransactionView( - transactionInfo: txData, + txData: txData, walletId: walletId, isPaynymTransaction: isPaynymSend, routeOnSuccessName: DesktopHomeView.routeName, @@ -505,11 +517,16 @@ class _DesktopSendState extends ConsumerState { } } - String? _updateInvalidAddressText(String address, Manager manager) { + String? _updateInvalidAddressText(String address) { if (_data != null && _data!.contactLabel == address) { return null; } - if (address.isNotEmpty && !manager.validateAddress(address)) { + if (address.isNotEmpty && + !ref + .read(pWallets) + .getWallet(walletId) + .cryptoCurrency + .validateAddress(address)) { return "Invalid address"; } return null; @@ -522,7 +539,8 @@ class _DesktopSendState extends ConsumerState { } else { final isValidAddress = ref .read(pWallets) - .getManager(walletId) + .getWallet(walletId) + .cryptoCurrency .validateAddress(address ?? ""); ref.read(previewTxButtonStateProvider.state).state = (isValidAddress && amount != null && amount > Amount.zero); @@ -530,18 +548,18 @@ class _DesktopSendState extends ConsumerState { } Future _firoBalanceFuture( - ChangeNotifierProvider provider, + WalletInfo info, String locale, bool private, ) async { - final wallet = ref.read(provider).wallet as FiroWallet?; - - if (wallet != null) { - Amount? balance; + if (info.coin == Coin.firo || info.coin == Coin.firoTestNet) { + final Amount balance; if (private) { - balance = wallet.availablePrivateBalance(); + balance = info.cachedBalance.spendable; + // balance = wallet.availablePrivateBalance(); } else { - balance = wallet.availablePublicBalance(); + balance = info.cachedSecondaryBalance.spendable; + // balance = wallet.availablePublicBalance(); } return ref.read(pAmountFormatter(coin)).format(balance); } @@ -626,7 +644,8 @@ class _DesktopSendState extends ConsumerState { // now check for non standard encoded basic address } else if (ref .read(pWallets) - .getManager(walletId) + .getWallet(walletId) + .cryptoCurrency .validateAddress(qrResult.rawContent)) { _address = qrResult.rawContent; sendToController.text = _address ?? ""; @@ -733,29 +752,36 @@ class _DesktopSendState extends ConsumerState { } Future sendAllTapped() async { + final info = ref.read(pWalletInfo(walletId)); + if (coin == Coin.firo || coin == Coin.firoTestNet) { - final firoWallet = - ref.read(pWallets).getManager(walletId).wallet as FiroWallet; if (ref.read(publicPrivateBalanceStateProvider.state).state == "Private") { - cryptoAmountController.text = firoWallet - .availablePrivateBalance() - .decimal - .toStringAsFixed(coin.decimals); + cryptoAmountController.text = + info.cachedBalance.spendable.decimal.toStringAsFixed(coin.decimals); + // cryptoAmountController.text = firoWallet + // .availablePrivateBalance() + // .decimal + // .toStringAsFixed(coin.decimals); } else { - cryptoAmountController.text = firoWallet - .availablePublicBalance() - .decimal + cryptoAmountController.text = info + .cachedSecondaryBalance.spendable.decimal .toStringAsFixed(coin.decimals); + // cryptoAmountController.text = firoWallet + // .availablePublicBalance() + // .decimal + // .toStringAsFixed(coin.decimals); } } else { - cryptoAmountController.text = ref - .read(pWallets) - .getManager(walletId) - .balance - .spendable - .decimal - .toStringAsFixed(coin.decimals); + cryptoAmountController.text = + info.cachedBalance.spendable.decimal.toStringAsFixed(coin.decimals); + // cryptoAmountController.text = ref + // .read(pWallets) + // .getWallet(walletId) + // .balance + // .spendable + // .decimal + // .toStringAsFixed(coin.decimals); } } @@ -779,7 +805,7 @@ class _DesktopSendState extends ConsumerState { // _calculateFeesFuture = calculateFees(0); _data = widget.autoFillData; walletId = widget.walletId; - coin = ref.read(pWallets).getManager(walletId).coin; + coin = ref.read(pWalletInfo(walletId)).coin; clipboard = widget.clipboard; scanner = widget.barcodeScanner; isStellar = coin == Coin.stellar || coin == Coin.stellarTestnet; @@ -849,8 +875,6 @@ class _DesktopSendState extends ConsumerState { @override Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); - final provider = ref - .watch(pWallets.select((value) => value.getManagerProvider(walletId))); final String locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); @@ -875,11 +899,7 @@ class _DesktopSendState extends ConsumerState { (value) => value.enableCoinControl, ), ) && - ref.watch( - provider.select( - (value) => value.hasCoinControlSupport, - ), - ); + ref.watch(pWallets).getWallet(walletId) is CoinControlInterface; return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -919,7 +939,11 @@ class _DesktopSendState extends ConsumerState { width: 10, ), FutureBuilder( - future: _firoBalanceFuture(provider, locale, true), + future: _firoBalanceFuture( + ref.watch(pWalletInfo(walletId)), + locale, + true, + ), builder: (context, AsyncSnapshot snapshot) => firoBalanceFutureBuilder( context, @@ -942,7 +966,11 @@ class _DesktopSendState extends ConsumerState { width: 10, ), FutureBuilder( - future: _firoBalanceFuture(provider, locale, false), + future: _firoBalanceFuture( + ref.watch(pWalletInfo(walletId)), + locale, + false, + ), builder: (context, AsyncSnapshot snapshot) => firoBalanceFutureBuilder( context, @@ -1364,7 +1392,6 @@ class _DesktopSendState extends ConsumerState { builder: (_) { final error = _updateInvalidAddressText( _address ?? "", - ref.read(pWallets).getManager(walletId), ); if (error == null || error.isEmpty) { @@ -1519,7 +1546,7 @@ class _DesktopSendState extends ConsumerState { ? FutureBuilder( future: ref.watch( pWallets.select( - (value) => value.getManager(walletId).fees, + (value) => value.getWallet(walletId).fees, ), ), builder: (context, snapshot) { @@ -1540,12 +1567,12 @@ class _DesktopSendState extends ConsumerState { .read(feeSheetSessionCacheProvider) .average[amount] == null) { - final manager = - ref.read(pWallets).getManager(walletId); + final wallet = + ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.regular.raw!); ref @@ -1559,16 +1586,18 @@ class _DesktopSendState extends ConsumerState { .state) .state != "Private") { - ref - .read(feeSheetSessionCacheProvider) - .average[amount] = await (manager.wallet - as FiroWallet) - .estimateFeeForPublic(amount, feeRate); + throw UnimplementedError("FIXME"); + // TODO: [prio=high] firo fee fix + // ref + // .read(feeSheetSessionCacheProvider) + // .average[amount] = await (manager.wallet + // as FiroWallet) + // .estimateFeeForPublic(amount, feeRate); } else { ref .read(feeSheetSessionCacheProvider) .average[amount] = - await manager.estimateFeeFor( + await wallet.estimateFeeFor( amount, feeRate); } } diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart index 508969711..0a127dbac 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart @@ -26,7 +26,6 @@ import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/ui/fee_rate_type_state_provider.dart'; import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/address_utils.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -40,6 +39,7 @@ import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/widgets/custom_buttons/blue_text_button.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog_close_button.dart'; @@ -234,16 +234,20 @@ class _DesktopTokenSendState extends ConsumerState { ), ); - Map txData; - Future> txDataFuture; + TxData txData; + Future txDataFuture; txDataFuture = tokenWallet.prepareSend( - address: _address!, - amount: amount, - args: { - "feeRate": ref.read(feeRateTypeStateProvider), - "nonce": int.tryParse(nonceController.text), - }, + txData: TxData( + recipients: [ + ( + address: _address!, + amount: amount, + ) + ], + feeRateType: ref.read(feeRateTypeStateProvider), + nonce: int.tryParse(nonceController.text), + ), ); final results = await Future.wait([ @@ -251,11 +255,12 @@ class _DesktopTokenSendState extends ConsumerState { time, ]); - txData = results.first as Map; + txData = results.first as TxData; if (!wasCancelled && mounted) { - txData["address"] = _address; - txData["note"] = _note ?? ""; + txData = txData.copyWith( + note: _note ?? "", + ); // pop building dialog Navigator.of( @@ -270,7 +275,7 @@ class _DesktopTokenSendState extends ConsumerState { maxHeight: double.infinity, maxWidth: 580, child: ConfirmTransactionView( - transactionInfo: txData, + txData: txData, walletId: walletId, isTokenTx: true, routeOnSuccessName: DesktopHomeView.routeName, @@ -411,19 +416,25 @@ class _DesktopTokenSendState extends ConsumerState { } } - String? _updateInvalidAddressText(String address, Manager manager) { + String? _updateInvalidAddressText(String address) { if (_data != null && _data!.contactLabel == address) { return null; } - if (address.isNotEmpty && !manager.validateAddress(address)) { + if (address.isNotEmpty && + !ref + .read(pWallets) + .getWallet(walletId) + .cryptoCurrency + .validateAddress(address)) { return "Invalid address"; } return null; } void _updatePreviewButtonState(String? address, Amount? amount) { - final isValidAddress = - ref.read(pWallets).getManager(walletId).validateAddress(address ?? ""); + final wallet = ref.read(pWallets).getWallet(walletId); + + final isValidAddress = wallet.cryptoCurrency.validateAddress(address ?? ""); ref.read(previewTokenTxButtonStateProvider.state).state = (isValidAddress && amount != null && amount > Amount.zero); } @@ -478,7 +489,8 @@ class _DesktopTokenSendState extends ConsumerState { // now check for non standard encoded basic address } else if (ref .read(pWallets) - .getManager(walletId) + .getWallet(walletId) + .cryptoCurrency .validateAddress(qrResult.rawContent)) { _address = qrResult.rawContent; sendToController.text = _address ?? ""; @@ -590,7 +602,7 @@ class _DesktopTokenSendState extends ConsumerState { // _calculateFeesFuture = calculateFees(0); _data = widget.autoFillData; walletId = widget.walletId; - coin = ref.read(pWallets).getManager(walletId).coin; + coin = ref.read(pWallets).getWallet(walletId).info.coin; clipboard = widget.clipboard; scanner = widget.barcodeScanner; @@ -991,7 +1003,6 @@ class _DesktopTokenSendState extends ConsumerState { builder: (_) { final error = _updateInvalidAddressText( _address ?? "", - ref.read(pWallets).getManager(walletId), ); if (error == null || error.isEmpty) { diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart index 72be196a8..c2905a8c0 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart @@ -30,6 +30,9 @@ import 'package:stackwallet/providers/global/paynym_api_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/wallet/my_paynym_account_state_provider.dart'; import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; +import 'package:stackwallet/services/mixins/coin_control_interface.dart'; +import 'package:stackwallet/services/mixins/fusion_wallet_interface.dart'; +import 'package:stackwallet/services/mixins/ordinals_interface.dart'; import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/themes/theme_providers.dart'; @@ -159,10 +162,6 @@ class _DesktopWalletFeaturesState extends ConsumerState { } Future _attemptAnonymize() async { - final managerProvider = ref - .read(pWallets) - .getManagerProvider(widget.walletId); - bool shouldPop = false; unawaited( showDialog( @@ -176,7 +175,8 @@ class _DesktopWalletFeaturesState extends ConsumerState { ), ), ); - final firoWallet = ref.read(managerProvider).wallet as FiroWallet; + final firoWallet = + ref.read(pWallets).getWallet(widget.walletId) as FiroWallet; final publicBalance = firoWallet.availablePublicBalance(); if (publicBalance <= Amount.zero) { @@ -283,10 +283,8 @@ class _DesktopWalletFeaturesState extends ConsumerState { ), ); - final manager = - ref.read(pWallets).getManager(widget.walletId); - - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = + ref.read(pWallets).getWallet(widget.walletId) as PaynymWalletInterface; final code = await wallet.getPaymentCode(isSegwit: false); @@ -348,25 +346,22 @@ class _DesktopWalletFeaturesState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref.watch( - pWallets.select( - (value) => value.getManager(widget.walletId), - ), - ); + final wallet = ref.watch(pWallets).getWallet(widget.walletId); + final coin = wallet.info.coin; - final showMore = manager.hasPaynymSupport || - (manager.hasCoinControlSupport && + final showMore = wallet is PaynymWalletInterface || + (wallet is CoinControlInterface && ref.watch( prefsChangeNotifierProvider.select( (value) => value.enableCoinControl, ), )) || - manager.coin == Coin.firo || - manager.coin == Coin.firoTestNet || - manager.hasWhirlpoolSupport || - manager.coin == Coin.banano || - manager.hasOrdinalsSupport || - manager.hasFusionSupport; + coin == Coin.firo || + coin == Coin.firoTestNet || + // manager.hasWhirlpoolSupport || + coin == Coin.banano || + wallet is OrdinalsInterface || + wallet is FusionWalletInterface; return Row( children: [ diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_summary.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_summary.dart index 7e5a780ed..bde0c7a6f 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_summary.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_summary.dart @@ -16,7 +16,6 @@ import 'package:stackwallet/pages/wallet_view/sub_widgets/wallet_refresh_button. import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_balance_toggle_button.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/providers/wallet/wallet_balance_toggle_state_provider.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -24,6 +23,7 @@ import 'package:stackwallet/utilities/amount/amount_formatter.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/wallet_balance_toggle_state.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; class DesktopWalletSummary extends ConsumerStatefulWidget { const DesktopWalletSummary({ @@ -60,11 +60,7 @@ class _WDesktopWalletSummaryState extends ConsumerState { (value) => value.externalCalls, ), ); - final coin = ref.watch( - pWallets.select( - (value) => value.getManager(widget.walletId).coin, - ), - ); + final coin = ref.watch(pWalletCoin(widget.walletId)); final locale = ref.watch( localeServiceChangeNotifierProvider.select((value) => value.locale)); @@ -88,28 +84,20 @@ class _WDesktopWalletSummaryState extends ConsumerState { Balance balance = widget.isToken ? ref.watch(tokenServiceProvider.select((value) => value!.balance)) - : ref.watch( - pWallets.select((value) => value.getManager(walletId).balance)); + : ref.watch(pWalletBalance(walletId)); Amount balanceToShow; if (coin == Coin.firo || coin == Coin.firoTestNet) { - Balance? balanceSecondary = ref - .watch( - pWallets.select( - (value) => - value.getManager(widget.walletId).wallet as FiroWallet?, - ), - ) - ?.balancePrivate; + final balanceSecondary = ref.watch(pWalletBalanceSecondary(walletId)); final showPrivate = ref.watch(walletPrivateBalanceToggleStateProvider.state).state == WalletBalanceToggleState.available; if (_showAvailable) { balanceToShow = - showPrivate ? balanceSecondary!.spendable : balance.spendable; + showPrivate ? balanceSecondary.spendable : balance.spendable; } else { - balanceToShow = showPrivate ? balanceSecondary!.total : balance.total; + balanceToShow = showPrivate ? balanceSecondary.total : balance.total; } } else { if (_showAvailable) { diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart index a985ee389..757d6c698 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart @@ -13,6 +13,10 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:stackwallet/providers/global/prefs_provider.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/services/mixins/coin_control_interface.dart'; +import 'package:stackwallet/services/mixins/fusion_wallet_interface.dart'; +import 'package:stackwallet/services/mixins/ordinals_interface.dart'; +import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; @@ -50,9 +54,9 @@ class MoreFeaturesDialog extends ConsumerStatefulWidget { class _MoreFeaturesDialogState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref.watch( + final wallet = ref.watch( pWallets.select( - (value) => value.getManager(widget.walletId), + (value) => value.getWallet(widget.walletId), ), ); @@ -81,49 +85,51 @@ class _MoreFeaturesDialogState extends ConsumerState { const DesktopDialogCloseButton(), ], ), - if (manager.coin == Coin.firo || manager.coin == Coin.firoTestNet) + if (wallet.info.coin == Coin.firo || + wallet.info.coin == Coin.firoTestNet) _MoreFeaturesItem( label: "Anonymize funds", detail: "Anonymize funds", iconAsset: Assets.svg.recycle, onPressed: () => widget.onAnonymizeAllPressed?.call(), ), - if (manager.hasWhirlpoolSupport) - _MoreFeaturesItem( - label: "Whirlpool", - detail: "Powerful Bitcoin privacy enhancer", - iconAsset: Assets.svg.whirlPool, - onPressed: () => widget.onWhirlpoolPressed?.call(), - ), - if (manager.hasCoinControlSupport && coinControlPrefEnabled) + // TODO: [prio=med] + // if (manager.hasWhirlpoolSupport) + // _MoreFeaturesItem( + // label: "Whirlpool", + // detail: "Powerful Bitcoin privacy enhancer", + // iconAsset: Assets.svg.whirlPool, + // onPressed: () => widget.onWhirlpoolPressed?.call(), + // ), + if (wallet is CoinControlInterface && coinControlPrefEnabled) _MoreFeaturesItem( label: "Coin control", detail: "Control, freeze, and utilize outputs at your discretion", iconAsset: Assets.svg.coinControl.gamePad, onPressed: () => widget.onCoinControlPressed?.call(), ), - if (manager.hasPaynymSupport) + if (wallet is PaynymWalletInterface) _MoreFeaturesItem( label: "PayNym", detail: "Increased address privacy using BIP47", iconAsset: Assets.svg.robotHead, onPressed: () => widget.onPaynymPressed?.call(), ), - if (manager.hasOrdinalsSupport) + if (wallet is OrdinalsInterface) _MoreFeaturesItem( label: "Ordinals", detail: "View and control your ordinals in Stack", iconAsset: Assets.svg.ordinal, onPressed: () => widget.onOrdinalsPressed?.call(), ), - if (manager.coin == Coin.banano) + if (wallet.info.coin == Coin.banano) _MoreFeaturesItem( label: "MonKey", detail: "Generate Banano MonKey", iconAsset: Assets.svg.monkey, onPressed: () => widget.onMonkeyPressed?.call(), ), - if (manager.hasFusionSupport) + if (wallet is FusionWalletInterface) _MoreFeaturesItem( label: "CashFusion", detail: "Decentralized Bitcoin Cash mixing protocol", diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/my_wallet.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/my_wallet.dart index 96e5661d9..2c2a16c21 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/my_wallet.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/my_wallet.dart @@ -43,8 +43,8 @@ class _MyWalletState extends ConsumerState { @override void initState() { - isEth = - ref.read(pWallets).getManager(widget.walletId).coin == Coin.ethereum; + isEth = ref.read(pWallets).getWallet(widget.walletId).info.coin == + Coin.ethereum; if (isEth && widget.contractAddress == null) { titles.add("Transactions"); @@ -92,13 +92,6 @@ class _MyWalletState extends ConsumerState { ), child: TransactionsList( walletId: widget.walletId, - managerProvider: ref.watch( - pWallets.select( - (value) => value.getManagerProvider( - widget.walletId, - ), - ), - ), ), ), ), diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/network_info_button.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/network_info_button.dart index ccfb19e37..1ba70a0e9 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/network_info_button.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/network_info_button.dart @@ -55,17 +55,17 @@ class _NetworkInfoButtonState extends ConsumerState { @override void initState() { walletId = widget.walletId; - final managerProvider = ref.read(pWallets).getManagerProvider(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); eventBus = widget.eventBus != null ? widget.eventBus! : GlobalEventBus.instance; - if (ref.read(managerProvider).isRefreshing) { + if (wallet.refreshMutex.isLocked) { _currentSyncStatus = WalletSyncStatus.syncing; _currentNodeStatus = NodeConnectionStatus.connected; } else { _currentSyncStatus = WalletSyncStatus.synced; - if (ref.read(managerProvider).isConnected) { + if (wallet.isConnected) { _currentNodeStatus = NodeConnectionStatus.connected; } else { _currentNodeStatus = NodeConnectionStatus.disconnected; diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/unlock_wallet_keys_desktop.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/unlock_wallet_keys_desktop.dart index 12f6c3915..1d6abc70c 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/unlock_wallet_keys_desktop.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/unlock_wallet_keys_desktop.dart @@ -21,6 +21,7 @@ import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/wallet/bip39_wallet.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog.dart'; import 'package:stackwallet/widgets/desktop/desktop_dialog_close_button.dart'; import 'package:stackwallet/widgets/desktop/primary_button.dart'; @@ -56,10 +57,10 @@ class _UnlockWalletKeysDesktopState unawaited( showDialog( context: context, - builder: (context) => Column( + builder: (context) => const Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, - children: const [ + children: [ LoadingIndicator( width: 200, height: 200, @@ -78,8 +79,14 @@ class _UnlockWalletKeysDesktopState if (verified) { Navigator.of(context, rootNavigator: true).pop(); - final words = - await ref.read(pWallets).getManager(widget.walletId).mnemonic; + final wallet = ref.read(pWallets).getWallet(widget.walletId); + + // TODO: [prio=high] handle wallets that don't have a mnemonic + if (wallet is! Bip39Wallet) { + throw Exception("FIXME ~= see todo in code"); + } + + final words = await wallet.getMnemonicAsWords(); if (mounted) { await Navigator.of(context).pushReplacementNamed( @@ -293,11 +300,15 @@ class _UnlockWalletKeysDesktopState if (verified) { Navigator.of(context, rootNavigator: true).pop(); - final words = await ref - .read(pWallets) - .getManager(widget.walletId) - .mnemonic; + final wallet = + ref.read(pWallets).getWallet(widget.walletId); + // TODO: [prio=high] handle wallets that don't have a mnemonic + if (wallet is! Bip39Wallet) { + throw Exception("FIXME ~= see todo in code"); + } + + final words = await wallet.getMnemonicAsWords(); if (mounted) { await Navigator.of(context) .pushReplacementNamed( diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart index fbedaf1ca..426e1f0c7 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/wallet_options_button.dart @@ -17,13 +17,13 @@ import 'package:stackwallet/pages/settings_views/wallet_settings_view/wallet_set import 'package:stackwallet/pages/settings_views/wallet_settings_view/wallet_settings_wallet_settings/xpub_view.dart'; import 'package:stackwallet/pages_desktop_specific/addresses/desktop_wallet_addresses_view.dart'; import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_delete_wallet_dialog.dart'; -import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/route_generator.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; enum _WalletOptions { addressList, @@ -217,12 +217,13 @@ class WalletOptionsPopupMenu extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final manager = - ref.watch(pWallets.select((value) => value.getManager(walletId))); - final bool xpubEnabled = manager.hasXPub; + final coin = ref.watch(pWalletCoin(walletId)); - final bool canChangeRep = - manager.coin == Coin.nano || manager.coin == Coin.banano; + // TODO: [prio=low] + // final bool xpubEnabled = manager.hasXPub; + final bool xpubEnabled = false; + + final bool canChangeRep = coin == Coin.nano || coin == Coin.banano; return Stack( children: [ diff --git a/lib/pages_desktop_specific/ordinals/desktop_ordinal_details_view.dart b/lib/pages_desktop_specific/ordinals/desktop_ordinal_details_view.dart index 267385b8d..c28524635 100644 --- a/lib/pages_desktop_specific/ordinals/desktop_ordinal_details_view.dart +++ b/lib/pages_desktop_specific/ordinals/desktop_ordinal_details_view.dart @@ -18,6 +18,7 @@ import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; import 'package:stackwallet/utilities/assets.dart'; import 'package:stackwallet/utilities/constants.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/utilities/show_loading.dart'; import 'package:stackwallet/utilities/text_styles.dart'; @@ -96,9 +97,6 @@ class _DesktopOrdinalDetailsViewState @override Widget build(BuildContext context) { - final coin = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId).coin)); - return DesktopScaffold( appBar: DesktopAppBar( background: Theme.of(context).extension()!.popupBG, @@ -287,17 +285,24 @@ class _DesktopOrdinalDetailsViewState // ), // // todo: add utxo status const _Divider(), - _DetailsItemWCopy( - title: "Amount", - data: utxo == null - ? "ERROR" - : ref.watch(pAmountFormatter(coin)).format( - Amount( - rawValue: BigInt.from(utxo!.value), - fractionDigits: coin.decimals, + Consumer(builder: (context, ref, _) { + final coin = ref + .watch(pWallets) + .getWallet(widget.walletId) + .info + .coin; + return _DetailsItemWCopy( + title: "Amount", + data: utxo == null + ? "ERROR" + : ref.watch(pAmountFormatter(coin)).format( + Amount( + rawValue: BigInt.from(utxo!.value), + fractionDigits: coin.decimals, + ), ), - ), - ), + ); + }), const _Divider(), _DetailsItemWCopy( title: "Owner address", diff --git a/lib/pages_desktop_specific/ordinals/desktop_ordinals_view.dart b/lib/pages_desktop_specific/ordinals/desktop_ordinals_view.dart index 87c531c8b..effeb143d 100644 --- a/lib/pages_desktop_specific/ordinals/desktop_ordinals_view.dart +++ b/lib/pages_desktop_specific/ordinals/desktop_ordinals_view.dart @@ -213,7 +213,8 @@ class _DesktopOrdinals extends ConsumerState { isDesktop: true, whileFuture: Future.wait([ Future.delayed(const Duration(seconds: 2)), - (ref.read(pWallets).getManager(widget.walletId).wallet + // TODO: [prio=high] FIX CAST as ISSUE + (ref.read(pWallets).getWallet(widget.walletId) as OrdinalsInterface) .refreshInscriptions() ]), diff --git a/lib/providers/global/active_wallet_provider.dart b/lib/providers/global/active_wallet_provider.dart new file mode 100644 index 000000000..b0979e787 --- /dev/null +++ b/lib/providers/global/active_wallet_provider.dart @@ -0,0 +1,3 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +final currentWalletIdProvider = StateProvider((ref) => null); diff --git a/lib/providers/global/wallets_service_provider.dart b/lib/providers/global/wallets_service_provider.dart index 93800f01a..8b90a470b 100644 --- a/lib/providers/global/wallets_service_provider.dart +++ b/lib/providers/global/wallets_service_provider.dart @@ -1,27 +1,27 @@ -/* - * This file is part of Stack Wallet. - * - * Copyright (c) 2023 Cypher Stack - * All Rights Reserved. - * The code is distributed under GPLv3 license, see LICENSE file for details. - * Generated by Cypher Stack on 2023-05-26 - * - */ - -import 'package:flutter/foundation.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:stackwallet/providers/global/secure_store_provider.dart'; -import 'package:stackwallet/services/wallets_service.dart'; - -int _count = 0; - -final walletsServiceChangeNotifierProvider = - ChangeNotifierProvider((ref) { - if (kDebugMode) { - _count++; - } - - return WalletsService( - secureStorageInterface: ref.read(secureStoreProvider), - ); -}); +// /* +// * This file is part of Stack Wallet. +// * +// * Copyright (c) 2023 Cypher Stack +// * All Rights Reserved. +// * The code is distributed under GPLv3 license, see LICENSE file for details. +// * Generated by Cypher Stack on 2023-05-26 +// * +// */ +// +// import 'package:flutter/foundation.dart'; +// import 'package:flutter_riverpod/flutter_riverpod.dart'; +// import 'package:stackwallet/providers/global/secure_store_provider.dart'; +// import 'package:stackwallet/services/wallets_service.dart'; +// +// int _count = 0; +// +// final walletsServiceChangeNotifierProvider = +// ChangeNotifierProvider((ref) { +// if (kDebugMode) { +// _count++; +// } +// +// return WalletsService( +// secureStorageInterface: ref.read(secureStoreProvider), +// ); +// }); diff --git a/lib/providers/providers.dart b/lib/providers/providers.dart index 3e6de2b0d..5f4151d89 100644 --- a/lib/providers/providers.dart +++ b/lib/providers/providers.dart @@ -17,10 +17,8 @@ export './exchange/exchange_form_state_provider.dart'; export './exchange/exchange_send_from_wallet_id_provider.dart'; export './exchange/trade_note_service_provider.dart'; export './exchange/trade_sent_from_stack_lookup_provider.dart'; -export './global/favorites_provider.dart'; export './global/locale_provider.dart'; export './global/node_service_provider.dart'; -export './global/non_favorites_provider.dart'; export './global/notifications_provider.dart'; export './global/prefs_provider.dart'; export './global/price_provider.dart'; diff --git a/lib/route_generator.dart b/lib/route_generator.dart index 3c02b7cbf..f5dbd90fb 100644 --- a/lib/route_generator.dart +++ b/lib/route_generator.dart @@ -10,7 +10,6 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:isar/isar.dart'; import 'package:stackwallet/models/add_wallet_list_entity/add_wallet_list_entity.dart'; import 'package:stackwallet/models/add_wallet_list_entity/sub_classes/eth_token_entity.dart'; @@ -175,12 +174,13 @@ import 'package:stackwallet/pages_desktop_specific/settings/settings_menu/nodes_ import 'package:stackwallet/pages_desktop_specific/settings/settings_menu/security_settings.dart'; import 'package:stackwallet/pages_desktop_specific/settings/settings_menu/syncing_preferences_settings.dart'; import 'package:stackwallet/pages_desktop_specific/settings/settings_menu/tor_settings/tor_settings.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/services/event_bus/events/global/node_connection_status_changed_event.dart'; import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/enums/add_wallet_type_enum.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/choose_coin_view.dart'; import 'package:tuple/tuple.dart'; @@ -1198,11 +1198,11 @@ class RouteGenerator { return _routeError("${settings.name} invalid args: ${args.toString()}"); case NewWalletRecoveryPhraseView.routeName: - if (args is Tuple2>) { + if (args is Tuple2>) { return getRoute( shouldUseMaterialRoute: useMaterialPageRoute, builder: (_) => NewWalletRecoveryPhraseView( - manager: args.item1, + wallet: args.item1, mnemonic: args.item2, ), settings: RouteSettings( @@ -1213,11 +1213,11 @@ class RouteGenerator { return _routeError("${settings.name} invalid args: ${args.toString()}"); case VerifyRecoveryPhraseView.routeName: - if (args is Tuple2>) { + if (args is Tuple2>) { return getRoute( shouldUseMaterialRoute: useMaterialPageRoute, builder: (_) => VerifyRecoveryPhraseView( - manager: args.item1, + wallet: args.item1, mnemonic: args.item2, ), settings: RouteSettings( @@ -1233,12 +1233,11 @@ class RouteGenerator { builder: (_) => const ManageFavoritesView()); case WalletView.routeName: - if (args is Tuple2>) { + if (args is String) { return getRoute( shouldUseMaterialRoute: useMaterialPageRoute, builder: (_) => WalletView( - walletId: args.item1, - managerProvider: args.item2, + walletId: args, ), settings: RouteSettings( name: settings.name, @@ -1463,11 +1462,11 @@ class RouteGenerator { return _routeError("${settings.name} invalid args: ${args.toString()}"); case ConfirmTransactionView.routeName: - if (args is Tuple2, String>) { + if (args is Tuple2) { return getRoute( shouldUseMaterialRoute: useMaterialPageRoute, builder: (_) => ConfirmTransactionView( - transactionInfo: args.item1, + txData: args.item1, walletId: args.item2, ), settings: RouteSettings( @@ -1552,12 +1551,12 @@ class RouteGenerator { return _routeError("${settings.name} invalid args: ${args.toString()}"); case DeleteWalletRecoveryPhraseView.routeName: - if (args is Tuple2>) { + if (args is ({String walletId, List mnemonicWords})) { return getRoute( shouldUseMaterialRoute: useMaterialPageRoute, builder: (_) => DeleteWalletRecoveryPhraseView( - manager: args.item1, - mnemonic: args.item2, + mnemonic: args.mnemonicWords, + walletId: args.walletId, ), settings: RouteSettings( name: settings.name, diff --git a/lib/services/ethereum/ethereum_token_service.dart b/lib/services/ethereum/ethereum_token_service.dart index 239d8770e..e3febd13b 100644 --- a/lib/services/ethereum/ethereum_token_service.dart +++ b/lib/services/ethereum/ethereum_token_service.dart @@ -38,6 +38,7 @@ import 'package:stackwallet/utilities/extensions/extensions.dart'; import 'package:stackwallet/utilities/extensions/impl/contract_abi.dart'; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; import 'package:stackwallet/utilities/logger.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:tuple/tuple.dart'; import 'package:web3dart/web3dart.dart' as web3dart; @@ -73,12 +74,10 @@ class EthTokenWallet extends ChangeNotifier with EthTokenCache { Coin get coin => Coin.ethereum; - Future> prepareSend({ - required String address, - required Amount amount, - Map? args, + Future prepareSend({ + required TxData txData, }) async { - final feeRateType = args?["feeRate"]; + final feeRateType = txData.feeRateType!; int fee = 0; final feeObject = await fees; switch (feeRateType) { @@ -91,6 +90,8 @@ class EthTokenWallet extends ChangeNotifier with EthTokenCache { case FeeRateType.slow: fee = feeObject.slow; break; + case FeeRateType.custom: + throw UnimplementedError("custom eth token fees"); } final feeEstimate = estimateFeeFor(fee); @@ -100,10 +101,13 @@ class EthTokenWallet extends ChangeNotifier with EthTokenCache { final myAddress = await currentReceivingAddress; final myWeb3Address = web3dart.EthereumAddress.fromHex(myAddress); - final nonce = args?["nonce"] as int? ?? + final nonce = txData.nonce ?? await client.getTransactionCount(myWeb3Address, atBlock: const web3dart.BlockNum.pending()); + final amount = txData.recipients!.first.amount; + final address = txData.recipients!.first.address; + final tx = web3dart.Transaction.callContract( contract: _deployedContract, function: _sendFunction, @@ -116,17 +120,13 @@ class EthTokenWallet extends ChangeNotifier with EthTokenCache { nonce: nonce, ); - Map txData = { - "fee": feeEstimate, - "feeInWei": fee, - "address": address, - "recipientAmt": amount, - "ethTx": tx, - "chainId": (await client.getChainId()).toInt(), - "nonce": tx.nonce, - }; - - return txData; + return txData.copyWith( + fee: feeEstimate, + feeInWei: BigInt.from(fee), + web3dartTransaction: tx, + chainId: await client.getChainId(), + nonce: tx.nonce, + ); } Future confirmSend({required Map txData}) async { diff --git a/lib/services/mixins/paynym_wallet_interface.dart b/lib/services/mixins/paynym_wallet_interface.dart index e0c162045..aebfef2b7 100644 --- a/lib/services/mixins/paynym_wallet_interface.dart +++ b/lib/services/mixins/paynym_wallet_interface.dart @@ -33,6 +33,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; import 'package:stackwallet/utilities/format.dart'; import 'package:stackwallet/utilities/logger.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:tuple/tuple.dart'; const String kPCodeKeyPrefix = "pCode_key_"; @@ -108,22 +109,18 @@ mixin PaynymWalletInterface { required int Function({ required int vSize, required int feeRatePerKB, - }) - estimateTxFee, + }) estimateTxFee, required Future> Function({ required String address, required Amount amount, Map? args, - }) - prepareSend, + }) prepareSend, required Future Function({ required String address, - }) - getTxCount, + }) getTxCount, required Future> Function( List utxosToUse, - ) - fetchBuildTxData, + ) fetchBuildTxData, required Future Function() refresh, required Future Function() checkChangeAddressForTransactions, }) { @@ -503,7 +500,7 @@ mixin PaynymWalletInterface { throw PaynymSendException("Exhausted unused send addresses!"); } - Future> prepareNotificationTx({ + Future prepareNotificationTx({ required int selectedTxFeeRate, required String targetPaymentCodeString, int additionalOutputs = 0, @@ -629,17 +626,24 @@ mixin PaynymWalletInterface { ); } - Map transactionObject = { - "hex": txn.item1, - "recipientPaynym": targetPaymentCodeString, - "amount": amountToSend.toAmountAsRaw( - fractionDigits: _coin.decimals, - ), - "fee": feeBeingPaid, - "vSize": txn.item2, - "usedUTXOs": utxoSigningData.map((e) => e.utxo).toList(), - }; - return transactionObject; + final txData = TxData( + raw: txn.item1, + recipients: [ + ( + address: targetPaymentCodeString, + amount: amountToSend.toAmountAsRaw( + fractionDigits: _coin.decimals, + ), + ) + ], + fee: feeBeingPaid.toAmountAsRaw( + fractionDigits: _coin.decimals, + ), + vSize: txn.item2, + utxos: utxoSigningData.map((e) => e.utxo).toSet(), + note: "PayNym connect"); + + return txData; } else { // something broke during fee estimation or the change amount is smaller // than the dust limit. Try without change @@ -651,16 +655,24 @@ mixin PaynymWalletInterface { int feeBeingPaid = satoshisBeingUsed - amountToSend; - Map transactionObject = { - "hex": txn.item1, - "recipientPaynym": targetPaymentCodeString, - "amount": - amountToSend.toAmountAsRaw(fractionDigits: _coin.decimals), - "fee": feeBeingPaid, - "vSize": txn.item2, - "usedUTXOs": utxoSigningData.map((e) => e.utxo).toList(), - }; - return transactionObject; + final txData = TxData( + raw: txn.item1, + recipients: [ + ( + address: targetPaymentCodeString, + amount: amountToSend.toAmountAsRaw( + fractionDigits: _coin.decimals, + ), + ) + ], + fee: feeBeingPaid.toAmountAsRaw( + fractionDigits: _coin.decimals, + ), + vSize: txn.item2, + utxos: utxoSigningData.map((e) => e.utxo).toSet(), + note: "PayNym connect"); + + return txData; } } else if (satoshisBeingUsed - amountToSend >= feeForNoChange) { // since we already checked if we need to add a change output we can just @@ -673,15 +685,24 @@ mixin PaynymWalletInterface { int feeBeingPaid = satoshisBeingUsed - amountToSend; - Map transactionObject = { - "hex": txn.item1, - "recipientPaynym": targetPaymentCodeString, - "amount": amountToSend.toAmountAsRaw(fractionDigits: _coin.decimals), - "fee": feeBeingPaid, - "vSize": txn.item2, - "usedUTXOs": utxoSigningData.map((e) => e.utxo).toList(), - }; - return transactionObject; + final txData = TxData( + raw: txn.item1, + recipients: [ + ( + address: targetPaymentCodeString, + amount: amountToSend.toAmountAsRaw( + fractionDigits: _coin.decimals, + ), + ) + ], + fee: feeBeingPaid.toAmountAsRaw( + fractionDigits: _coin.decimals, + ), + vSize: txn.item2, + utxos: utxoSigningData.map((e) => e.utxo).toSet(), + note: "PayNym connect"); + + return txData; } else { // if we get here we do not have enough funds to cover the tx total so we // check if we have any more available outputs and try again diff --git a/lib/services/wallets.dart b/lib/services/wallets.dart index 31b29cd8d..11e3f04dd 100644 --- a/lib/services/wallets.dart +++ b/lib/services/wallets.dart @@ -17,7 +17,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/sync_type_enum.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/prefs.dart'; -import 'package:stackwallet/wallets/isar_models/wallet_info.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/wallet/wallet.dart'; class Wallets { @@ -31,12 +31,48 @@ class Wallets { bool get hasWallets => _wallets.isNotEmpty; + List get wallets => _wallets.values.toList(); + + List<({Coin coin, List wallets})> get walletsByCoin { + final Map wallets})> map = {}; + + for (final wallet in wallets) { + if (map[wallet.info.coin] == null) { + map[wallet.info.coin] = (coin: wallet.info.coin, wallets: []); + } + + map[wallet.info.coin]!.wallets.add(wallet); + } + + final List<({Coin coin, List wallets})> results = []; + for (final coin in Coin.values) { + if (map[coin] != null) { + results.add(map[coin]!); + } + } + + return results; + } + static bool hasLoaded = false; final Map _wallets = {}; Wallet getWallet(String walletId) => _wallets[walletId]!; + void addWallet(Wallet wallet) { + if (_wallets[wallet.walletId] != null) { + throw Exception( + "Tried to add wallet that already exists, according to it's wallet Id!", + ); + } + _wallets[wallet.walletId] = wallet; + } + + Future deleteWallet(String walletId) async { + throw UnimplementedError("Delete wallet unimplemented"); + } + Future load(Prefs prefs, MainDB mainDB) async { if (hasLoaded) { return; @@ -160,16 +196,16 @@ class Wallets { for (final wallet in wallets) { Logging.instance.log( - "LOADING WALLET: ${wallet.walletInfo.name}:${wallet.walletId} IS VERIFIED: ${wallet.walletInfo.isMnemonicVerified}", + "LOADING WALLET: ${wallet.info.name}:${wallet.walletId} IS VERIFIED: ${wallet.info.isMnemonicVerified}", level: LogLevel.Info, ); - if (wallet.walletInfo.isMnemonicVerified) { + if (wallet.info.isMnemonicVerified) { final shouldSetAutoSync = shouldAutoSyncAll || walletIdsToEnableAutoSync.contains(wallet.walletId); - if (wallet.walletInfo.coin == Coin.monero || - wallet.walletInfo.coin == Coin.wownero) { + if (wallet.info.coin == Coin.monero || + wallet.info.coin == Coin.wownero) { // walletsToInitLinearly.add(Tuple2(manager, shouldSetAutoSync)); } else { walletInitFutures.add(wallet.init().then((value) { diff --git a/lib/wallets/crypto_currency/crypto_currency.dart b/lib/wallets/crypto_currency/crypto_currency.dart index a651a8910..5e43ee51d 100644 --- a/lib/wallets/crypto_currency/crypto_currency.dart +++ b/lib/wallets/crypto_currency/crypto_currency.dart @@ -15,6 +15,10 @@ abstract class CryptoCurrency { CryptoCurrency(this.network); + // override in subclass if the currency has tokens on it's network + // (used for eth currently) + bool get hasTokenSupport => false; + // TODO: [prio=low] require these be overridden in concrete implementations to remove reliance on [coin] int get fractionDigits => coin.decimals; BigInt get satsPerCoin => Constants.satsPerCoin(coin); diff --git a/lib/wallets/isar/models/wallet_info.dart b/lib/wallets/isar/models/wallet_info.dart index 5a383f354..b3d0db877 100644 --- a/lib/wallets/isar/models/wallet_info.dart +++ b/lib/wallets/isar/models/wallet_info.dart @@ -5,6 +5,7 @@ import 'package:stackwallet/models/balance.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/wallets/isar/isar_id_interface.dart'; +import 'package:uuid/uuid.dart'; part 'wallet_info.g.dart'; @@ -24,6 +25,9 @@ class WalletInfo implements IsarId { @enumerated final AddressType mainAddressType; + /// The highest index [mainAddressType] receiving address of the wallet + final String cachedReceivingAddress; + /// Only exposed for Isar. Use the [cachedBalance] getter. // Only exposed for isar as Amount cannot be stored in isar easily final String? cachedBalanceString; @@ -191,6 +195,44 @@ class WalletInfo implements IsarId { } } + /// copies this with a new name and updates the db + Future updateReceivingAddress({ + required String newAddress, + required Isar isar, + }) async { + // only update if there were changes to the name + if (cachedReceivingAddress != newAddress) { + final updated = copyWith( + cachedReceivingAddress: newAddress, + ); + await isar.writeTxn(() async { + await isar.walletInfo.delete(id); + await isar.walletInfo.put(updated); + }); + } + } + + /// copies this with a new name and updates the db + Future setMnemonicVerified({ + required Isar isar, + }) async { + // only update if there were changes to the name + if (!isMnemonicVerified) { + final updated = copyWith( + isMnemonicVerified: true, + ); + await isar.writeTxn(() async { + await isar.walletInfo.delete(id); + await isar.walletInfo.put(updated); + }); + } else { + throw Exception( + "setMnemonicVerified() called on already" + " verified wallet: $name, $walletId", + ); + } + } + //============================================================================ WalletInfo({ @@ -199,6 +241,10 @@ class WalletInfo implements IsarId { required this.name, required this.walletType, required this.mainAddressType, + + // cachedReceivingAddress should never actually be empty in practice as + // on wallet init it will be set + this.cachedReceivingAddress = "", this.favouriteOrderIndex = 0, this.cachedChainHeight = 0, this.isMnemonicVerified = false, @@ -208,6 +254,52 @@ class WalletInfo implements IsarId { Coin.values.map((e) => e.name).contains(coinName), ); + static WalletInfo createNew({ + required Coin coin, + required String name, + }) { + // TODO: make Coin aware of these + // ex. + // walletType = coin.walletType; + // mainAddressType = coin.mainAddressType; + + final AddressType mainAddressType; + switch (coin) { + case Coin.bitcoin: + case Coin.bitcoinTestNet: + mainAddressType = AddressType.p2wpkh; + break; + + case Coin.bitcoincash: + case Coin.bitcoincashTestnet: + mainAddressType = AddressType.p2pkh; + break; + + default: + throw UnimplementedError(); + } + + final WalletType walletType; + switch (coin) { + case Coin.bitcoin: + case Coin.bitcoinTestNet: + case Coin.bitcoincash: + case Coin.bitcoincashTestnet: + walletType = WalletType.bip39HD; + + default: + throw UnimplementedError(); + } + + return WalletInfo( + coinName: coin.name, + walletId: const Uuid().v1(), + name: name, + walletType: walletType, + mainAddressType: mainAddressType, + ); + } + WalletInfo copyWith({ String? coinName, String? name, @@ -215,6 +307,7 @@ class WalletInfo implements IsarId { int? cachedChainHeight, bool? isMnemonicVerified, String? cachedBalanceString, + String? cachedReceivingAddress, Map? otherData, }) { return WalletInfo( @@ -227,6 +320,8 @@ class WalletInfo implements IsarId { cachedChainHeight: cachedChainHeight ?? this.cachedChainHeight, isMnemonicVerified: isMnemonicVerified ?? this.isMnemonicVerified, cachedBalanceString: cachedBalanceString ?? this.cachedBalanceString, + cachedReceivingAddress: + cachedReceivingAddress ?? this.cachedReceivingAddress, otherDataJsonString: otherData == null ? otherDataJsonString : jsonEncode(otherData), )..id = id; diff --git a/lib/wallets/isar/providers/all_wallets_info_provider.dart b/lib/wallets/isar/providers/all_wallets_info_provider.dart new file mode 100644 index 000000000..c6d77c164 --- /dev/null +++ b/lib/wallets/isar/providers/all_wallets_info_provider.dart @@ -0,0 +1,45 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:isar/isar.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; + +final pAllWalletsInfo = Provider((ref) { + if (_globalInstance == null) { + final isar = ref.watch(mainDBProvider).isar; + _globalInstance = _WalletInfoWatcher( + isar.walletInfo.where().findAllSync(), + isar, + ); + } + + return _globalInstance!.value; +}); + +_WalletInfoWatcher? _globalInstance; + +class _WalletInfoWatcher extends ChangeNotifier { + late final StreamSubscription _streamSubscription; + + List _value; + + List get value => _value; + + _WalletInfoWatcher(this._value, Isar isar) { + _streamSubscription = + isar.walletInfo.watchLazy(fireImmediately: true).listen((event) { + isar.walletInfo.where().findAll().then((value) { + _value = value; + notifyListeners(); + }); + }); + } + + @override + void dispose() { + _streamSubscription.cancel(); + super.dispose(); + } +} diff --git a/lib/wallets/isar/providers/favourite_wallets_provider.dart b/lib/wallets/isar/providers/favourite_wallets_provider.dart new file mode 100644 index 000000000..08a3187eb --- /dev/null +++ b/lib/wallets/isar/providers/favourite_wallets_provider.dart @@ -0,0 +1,57 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:isar/isar.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; + +class _Watcher extends ChangeNotifier { + late final StreamSubscription> _streamSubscription; + + List _value; + + List get value => _value; + + _Watcher(this._value, Isar isar) { + _streamSubscription = isar.walletInfo + .filter() + .isFavouriteEqualTo(true) + .watch() + .listen((event) { + _value = event; + notifyListeners(); + }); + } + + @override + void dispose() { + _streamSubscription.cancel(); + super.dispose(); + } +} + +final _wiProvider = ChangeNotifierProvider.autoDispose( + (ref) { + final isar = ref.watch(mainDBProvider).isar; + + final watcher = _Watcher( + isar.walletInfo + .filter() + .isFavouriteEqualTo(true) + .sortByFavouriteOrderIndex() + .findAllSync(), + isar, + ); + + ref.onDispose(() => watcher.dispose()); + + return watcher; + }, +); + +final pFavouriteWalletInfos = Provider.autoDispose( + (ref) { + return ref.watch(_wiProvider).value; + }, +); diff --git a/lib/wallets/isar/providers/wallet_info_provider.dart b/lib/wallets/isar/providers/wallet_info_provider.dart index cc8a5bc28..9285a5ce7 100644 --- a/lib/wallets/isar/providers/wallet_info_provider.dart +++ b/lib/wallets/isar/providers/wallet_info_provider.dart @@ -68,3 +68,10 @@ final pWalletName = Provider.autoDispose.family( .select((value) => (value.value as WalletInfo).name)); }, ); + +final pWalletReceivingAddress = Provider.autoDispose.family( + (ref, walletId) { + return ref.watch(_wiProvider(walletId) + .select((value) => (value.value as WalletInfo).cachedReceivingAddress)); + }, +); diff --git a/lib/wallets/migration/migrate_wallets.dart b/lib/wallets/migration/migrate_wallets.dart index cb0e4623c..7e9ca5274 100644 --- a/lib/wallets/migration/migrate_wallets.dart +++ b/lib/wallets/migration/migrate_wallets.dart @@ -5,7 +5,7 @@ import 'package:stackwallet/db/hive/db.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; -import 'package:stackwallet/wallets/isar_models/wallet_info.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/wallet/supporting/epiccash_wallet_info_extension.dart'; void migrateWallets({ diff --git a/lib/wallets/models/tx_data.dart b/lib/wallets/models/tx_data.dart index b95cd715b..eb25b2561 100644 --- a/lib/wallets/models/tx_data.dart +++ b/lib/wallets/models/tx_data.dart @@ -1,6 +1,8 @@ import 'package:stackwallet/models/isar/models/blockchain_data/utxo.dart'; +import 'package:stackwallet/models/paynym/paynym_account_lite.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart'; +import 'package:web3dart/web3dart.dart' as web3dart; class TxData { final FeeRateType? feeRateType; @@ -18,6 +20,8 @@ class TxData { final String? note; final String? noteOnChain; + final String? memo; + final List<({String address, Amount amount})>? recipients; final Set? utxos; @@ -25,6 +29,15 @@ class TxData { final String? frostMSConfig; + // paynym specific + final PaynymAccountLite? paynymAccountLite; + + // eth token specific + final web3dart.Transaction? web3dartTransaction; + final int? nonce; + final BigInt? chainId; + final BigInt? feeInWei; + TxData({ this.feeRateType, this.feeRateAmount, @@ -36,10 +49,16 @@ class TxData { this.txHash, this.note, this.noteOnChain, + this.memo, this.recipients, this.utxos, this.changeAddress, this.frostMSConfig, + this.paynymAccountLite, + this.web3dartTransaction, + this.nonce, + this.chainId, + this.feeInWei, }); Amount? get amount => recipients != null && recipients!.isNotEmpty @@ -63,10 +82,16 @@ class TxData { String? txHash, String? note, String? noteOnChain, + String? memo, Set? utxos, List<({String address, Amount amount})>? recipients, String? frostMSConfig, String? changeAddress, + PaynymAccountLite? paynymAccountLite, + web3dart.Transaction? web3dartTransaction, + int? nonce, + BigInt? chainId, + BigInt? feeInWei, }) { return TxData( feeRateType: feeRateType ?? this.feeRateType, @@ -79,10 +104,16 @@ class TxData { txHash: txHash ?? this.txHash, note: note ?? this.note, noteOnChain: noteOnChain ?? this.noteOnChain, + memo: memo ?? this.memo, utxos: utxos ?? this.utxos, recipients: recipients ?? this.recipients, frostMSConfig: frostMSConfig ?? this.frostMSConfig, changeAddress: changeAddress ?? this.changeAddress, + paynymAccountLite: paynymAccountLite ?? this.paynymAccountLite, + web3dartTransaction: web3dartTransaction ?? this.web3dartTransaction, + nonce: nonce ?? this.nonce, + chainId: chainId ?? this.chainId, + feeInWei: feeInWei ?? this.feeInWei, ); } @@ -98,9 +129,15 @@ class TxData { 'txHash: $txHash, ' 'note: $note, ' 'noteOnChain: $noteOnChain, ' + 'memo: $memo, ' 'recipients: $recipients, ' 'utxos: $utxos, ' 'frostMSConfig: $frostMSConfig, ' - 'changeAddress: $changeAddress' + 'changeAddress: $changeAddress, ' + 'paynymAccountLite: $paynymAccountLite, ' + 'web3dartTransaction: $web3dartTransaction, ' + 'nonce: $nonce, ' + 'chainId: $chainId, ' + 'feeInWei: $feeInWei, ' '}'; } diff --git a/lib/wallets/wallet/bip39_hd_wallet.dart b/lib/wallets/wallet/bip39_hd_wallet.dart index e317e03d0..674533b97 100644 --- a/lib/wallets/wallet/bip39_hd_wallet.dart +++ b/lib/wallets/wallet/bip39_hd_wallet.dart @@ -12,16 +12,16 @@ import 'package:stackwallet/wallets/wallet/bip39_wallet.dart'; abstract class Bip39HDWallet extends Bip39Wallet { Bip39HDWallet(super.cryptoCurrency); - /// Generates a receiving address of [walletInfo.mainAddressType]. If none + /// Generates a receiving address of [info.mainAddressType]. If none /// are in the current wallet db it will generate at index 0, otherwise the /// highest index found in the current wallet db. Future
generateNewReceivingAddress() async { - final current = await _currentReceivingAddress; + final current = await getCurrentReceivingAddress(); final index = current?.derivationIndex ?? 0; const chain = 0; // receiving address final DerivePathType derivePathType; - switch (walletInfo.mainAddressType) { + switch (info.mainAddressType) { case AddressType.p2pkh: derivePathType = DerivePathType.bip44; break; @@ -47,22 +47,16 @@ abstract class Bip39HDWallet extends Bip39Wallet { ); await mainDB.putAddress(address); + await info.updateReceivingAddress( + newAddress: address.value, + isar: mainDB.isar, + ); return address; } // ========== Private ======================================================== - Future get _currentReceivingAddress async => - await mainDB.isar.addresses - .where() - .walletIdEqualTo(walletId) - .filter() - .typeEqualTo(walletInfo.mainAddressType) - .subTypeEqualTo(AddressSubType.receiving) - .sortByDerivationIndexDesc() - .findFirst(); - Future _generateRootHDNode() async { final seed = bip39.mnemonicToSeed( await getMnemonic(), @@ -167,7 +161,7 @@ abstract class Bip39HDWallet extends Bip39Wallet { pendingSpendable: satoshiBalancePending, ); - await walletInfo.updateBalance(newBalance: balance, isar: mainDB.isar); + await info.updateBalance(newBalance: balance, isar: mainDB.isar); } @override diff --git a/lib/wallets/wallet/bip39_wallet.dart b/lib/wallets/wallet/bip39_wallet.dart index 210538fe8..90f22268b 100644 --- a/lib/wallets/wallet/bip39_wallet.dart +++ b/lib/wallets/wallet/bip39_wallet.dart @@ -7,7 +7,7 @@ abstract class Bip39Wallet extends Wallet { Future getMnemonic() async { final mnemonic = await secureStorageInterface.read( - key: Wallet.mnemonicKey(walletId: walletInfo.walletId), + key: Wallet.mnemonicKey(walletId: info.walletId), ); if (mnemonic == null) { @@ -17,9 +17,14 @@ abstract class Bip39Wallet extends Wallet { return mnemonic; } + Future> getMnemonicAsWords() async { + final mnemonic = await getMnemonic(); + return mnemonic.split(" "); + } + Future getMnemonicPassphrase() async { final mnemonicPassphrase = await secureStorageInterface.read( - key: Wallet.mnemonicPassphraseKey(walletId: walletInfo.walletId), + key: Wallet.mnemonicPassphraseKey(walletId: info.walletId), ); if (mnemonicPassphrase == null) { diff --git a/lib/wallets/wallet/cryptonote_wallet.dart b/lib/wallets/wallet/cryptonote_wallet.dart index 6ba28aa3c..4f68d592c 100644 --- a/lib/wallets/wallet/cryptonote_wallet.dart +++ b/lib/wallets/wallet/cryptonote_wallet.dart @@ -7,7 +7,7 @@ abstract class CryptonoteWallet extends Wallet { Future getMnemonic() async { final mnemonic = await secureStorageInterface.read( - key: Wallet.mnemonicKey(walletId: walletInfo.walletId), + key: Wallet.mnemonicKey(walletId: info.walletId), ); if (mnemonic == null) { diff --git a/lib/wallets/wallet/impl/bitcoin_wallet.dart b/lib/wallets/wallet/impl/bitcoin_wallet.dart index d9ba37010..7830199aa 100644 --- a/lib/wallets/wallet/impl/bitcoin_wallet.dart +++ b/lib/wallets/wallet/impl/bitcoin_wallet.dart @@ -3,6 +3,8 @@ import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; import 'package:stackwallet/services/event_bus/events/global/updated_in_background_event.dart'; import 'package:stackwallet/services/event_bus/global_event_bus.dart'; import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/wallets/crypto_currency/coins/bitcoin.dart'; import 'package:stackwallet/wallets/wallet/bip39_hd_wallet.dart'; import 'package:stackwallet/wallets/wallet/mixins/electrumx_mixin.dart'; @@ -74,7 +76,7 @@ class BitcoinWallet extends Bip39HDWallet with ElectrumXMixin { if (data.isNotEmpty) { GlobalEventBus.instance.fire( UpdatedInBackgroundEvent( - "Transactions updated/added for: $walletId ${walletInfo.name}", + "Transactions updated/added for: $walletId ${info.name}", walletId, ), ); @@ -100,9 +102,19 @@ class BitcoinWallet extends Bip39HDWallet with ElectrumXMixin { @override Future updateChainHeight() async { final height = await fetchChainHeight(); - await walletInfo.updateCachedChainHeight( + await info.updateCachedChainHeight( newHeight: height, isar: mainDB.isar, ); } + + @override + Amount roughFeeEstimate(int inputCount, int outputCount, int feeRatePerKB) { + return Amount( + rawValue: BigInt.from( + ((42 + (272 * inputCount) + (128 * outputCount)) / 4).ceil() * + (feeRatePerKB / 1000).ceil()), + fractionDigits: info.coin.decimals, + ); + } } diff --git a/lib/wallets/wallet/impl/bitcoincash_wallet.dart b/lib/wallets/wallet/impl/bitcoincash_wallet.dart index bd3ab927f..481930955 100644 --- a/lib/wallets/wallet/impl/bitcoincash_wallet.dart +++ b/lib/wallets/wallet/impl/bitcoincash_wallet.dart @@ -10,6 +10,8 @@ import 'package:stackwallet/services/coins/bitcoincash/bch_utils.dart'; import 'package:stackwallet/services/coins/bitcoincash/cashtokens.dart' as cash_tokens; import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/enums/derive_path_type_enum.dart'; import 'package:stackwallet/utilities/extensions/extensions.dart'; import 'package:stackwallet/utilities/logger.dart'; @@ -378,9 +380,19 @@ class BitcoincashWallet extends Bip39HDWallet with ElectrumXMixin { @override Future updateChainHeight() async { final height = await fetchChainHeight(); - await walletInfo.updateCachedChainHeight( + await info.updateCachedChainHeight( newHeight: height, isar: mainDB.isar, ); } + + // TODO: correct formula for bch? + @override + Amount roughFeeEstimate(int inputCount, int outputCount, int feeRatePerKB) { + return Amount( + rawValue: BigInt.from(((181 * inputCount) + (34 * outputCount) + 10) * + (feeRatePerKB / 1000).ceil()), + fractionDigits: info.coin.decimals, + ); + } } diff --git a/lib/wallets/wallet/impl/epiccash_wallet.dart b/lib/wallets/wallet/impl/epiccash_wallet.dart index 31df3594f..a259d84d8 100644 --- a/lib/wallets/wallet/impl/epiccash_wallet.dart +++ b/lib/wallets/wallet/impl/epiccash_wallet.dart @@ -1,5 +1,7 @@ +import 'package:stackwallet/models/paymint/fee_object_model.dart'; import 'package:stackwallet/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart'; import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/test_epic_box_connection.dart'; import 'package:stackwallet/wallets/models/tx_data.dart'; @@ -86,4 +88,14 @@ class EpiccashWallet extends Bip39Wallet { // isar: mainDB.isar, // ); } + + @override + Future estimateFeeFor(Amount amount, int feeRate) { + // TODO: implement estimateFeeFor + throw UnimplementedError(); + } + + @override + // TODO: implement fees + Future get fees => throw UnimplementedError(); } diff --git a/lib/wallets/wallet/mixins/electrumx_mixin.dart b/lib/wallets/wallet/mixins/electrumx_mixin.dart index bfe0a9493..f72b07ad0 100644 --- a/lib/wallets/wallet/mixins/electrumx_mixin.dart +++ b/lib/wallets/wallet/mixins/electrumx_mixin.dart @@ -2,9 +2,11 @@ import 'dart:convert'; import 'package:bip47/src/util.dart'; import 'package:decimal/decimal.dart'; +import 'package:isar/isar.dart'; import 'package:stackwallet/electrumx_rpc/cached_electrumx.dart'; import 'package:stackwallet/electrumx_rpc/electrumx.dart'; import 'package:stackwallet/models/isar/models/isar_models.dart'; +import 'package:stackwallet/models/paymint/fee_object_model.dart'; import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart'; import 'package:stackwallet/services/node_service.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -472,4 +474,139 @@ mixin ElectrumXMixin on Bip39HDWallet { final node = await getCurrentNode(); await updateElectrumX(newNode: node); } + + FeeObject? _cachedFees; + + @override + Future get fees async { + try { + const int f = 1, m = 5, s = 20; + + final fast = await electrumX.estimateFee(blocks: f); + final medium = await electrumX.estimateFee(blocks: m); + final slow = await electrumX.estimateFee(blocks: s); + + final feeObject = FeeObject( + numberOfBlocksFast: f, + numberOfBlocksAverage: m, + numberOfBlocksSlow: s, + fast: Amount.fromDecimal( + fast, + fractionDigits: info.coin.decimals, + ).raw.toInt(), + medium: Amount.fromDecimal( + medium, + fractionDigits: info.coin.decimals, + ).raw.toInt(), + slow: Amount.fromDecimal( + slow, + fractionDigits: info.coin.decimals, + ).raw.toInt(), + ); + + Logging.instance.log("fetched fees: $feeObject", level: LogLevel.Info); + _cachedFees = feeObject; + return _cachedFees!; + } catch (e) { + Logging.instance.log( + "Exception rethrown from _getFees(): $e", + level: LogLevel.Error, + ); + if (_cachedFees == null) { + rethrow; + } else { + return _cachedFees!; + } + } + } + + @override + Future estimateFeeFor(Amount amount, int feeRate) async { + final available = info.cachedBalance.spendable; + final utxos = _spendableUTXOs(await mainDB.getUTXOs(walletId).findAll()); + + if (available == amount) { + return amount - (await _sweepAllEstimate(feeRate, utxos)); + } else if (amount <= Amount.zero || amount > available) { + return roughFeeEstimate(1, 2, feeRate); + } + + Amount runningBalance = Amount( + rawValue: BigInt.zero, + fractionDigits: info.coin.decimals, + ); + int inputCount = 0; + for (final output in utxos) { + if (!output.isBlocked) { + runningBalance += Amount( + rawValue: BigInt.from(output.value), + fractionDigits: info.coin.decimals, + ); + inputCount++; + if (runningBalance > amount) { + break; + } + } + } + + final oneOutPutFee = roughFeeEstimate(inputCount, 1, feeRate); + final twoOutPutFee = roughFeeEstimate(inputCount, 2, feeRate); + + if (runningBalance - amount > oneOutPutFee) { + if (runningBalance - amount > oneOutPutFee + cryptoCurrency.dustLimit) { + final change = runningBalance - amount - twoOutPutFee; + if (change > cryptoCurrency.dustLimit && + runningBalance - amount - change == twoOutPutFee) { + return runningBalance - amount - change; + } else { + return runningBalance - amount; + } + } else { + return runningBalance - amount; + } + } else if (runningBalance - amount == oneOutPutFee) { + return oneOutPutFee; + } else { + return twoOutPutFee; + } + } + + // =========================================================================== + // ========== Interface functions ============================================ + + Amount roughFeeEstimate(int inputCount, int outputCount, int feeRatePerKB); + + // =========================================================================== + // ========== private helpers ================================================ + + List _spendableUTXOs(List utxos) { + return utxos + .where( + (e) => + !e.isBlocked && + e.isConfirmed( + info.cachedChainHeight, + cryptoCurrency.minConfirms, + ), + ) + .toList(); + } + + Future _sweepAllEstimate(int feeRate, List usableUTXOs) async { + final available = usableUTXOs + .map((e) => BigInt.from(e.value)) + .fold(BigInt.zero, (p, e) => p + e); + final inputCount = usableUTXOs.length; + + // transaction will only have 1 output minus the fee + final estimatedFee = roughFeeEstimate(inputCount, 1, feeRate); + + return Amount( + rawValue: available, + fractionDigits: info.coin.decimals, + ) - + estimatedFee; + } + + // =========================================================================== } diff --git a/lib/wallets/wallet/private_key_based_wallet.dart b/lib/wallets/wallet/private_key_based_wallet.dart index abca34c31..74f2afd04 100644 --- a/lib/wallets/wallet/private_key_based_wallet.dart +++ b/lib/wallets/wallet/private_key_based_wallet.dart @@ -7,7 +7,7 @@ abstract class PrivateKeyBasedWallet extends Wallet { Future getPrivateKey() async { final privateKey = await secureStorageInterface.read( - key: Wallet.privateKeyKey(walletId: walletInfo.walletId), + key: Wallet.privateKeyKey(walletId: info.walletId), ); if (privateKey == null) { diff --git a/lib/wallets/wallet/supporting/epiccash_wallet_info_extension.dart b/lib/wallets/wallet/supporting/epiccash_wallet_info_extension.dart index bf92a9110..1b46eb21e 100644 --- a/lib/wallets/wallet/supporting/epiccash_wallet_info_extension.dart +++ b/lib/wallets/wallet/supporting/epiccash_wallet_info_extension.dart @@ -1,7 +1,7 @@ import 'dart:convert'; import 'package:stackwallet/utilities/logger.dart'; -import 'package:stackwallet/wallets/isar_models/wallet_info.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; extension EpiccashWalletInfoExtension on WalletInfo { ExtraEpiccashWalletInfo? get epicData { diff --git a/lib/wallets/wallet/wallet.dart b/lib/wallets/wallet/wallet.dart index 36852a746..5b2a56c84 100644 --- a/lib/wallets/wallet/wallet.dart +++ b/lib/wallets/wallet/wallet.dart @@ -1,13 +1,17 @@ import 'dart:async'; import 'package:isar/isar.dart'; +import 'package:meta/meta.dart'; import 'package:mutex/mutex.dart'; import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/paymint/fee_object_model.dart'; import 'package:stackwallet/services/event_bus/events/global/node_connection_status_changed_event.dart'; import 'package:stackwallet/services/event_bus/events/global/refresh_percent_changed_event.dart'; import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; import 'package:stackwallet/services/event_bus/global_event_bus.dart'; import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; @@ -17,7 +21,7 @@ import 'package:stackwallet/wallets/crypto_currency/coins/bitcoin.dart'; import 'package:stackwallet/wallets/crypto_currency/coins/bitcoincash.dart'; import 'package:stackwallet/wallets/crypto_currency/coins/epiccash.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; -import 'package:stackwallet/wallets/isar_models/wallet_info.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/wallets/wallet/impl/bitcoin_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/bitcoincash_wallet.dart'; @@ -41,7 +45,8 @@ abstract class Wallet { final refreshMutex = Mutex(); - WalletInfo get walletInfo => _walletInfo; + WalletInfo get info => _walletInfo; + bool get isConnected => _isConnected; bool get shouldAutoSync => _shouldAutoSync; set shouldAutoSync(bool shouldAutoSync) { @@ -73,8 +78,8 @@ abstract class Wallet { //============================================================================ // ========== Wallet Info Convenience Getters ================================ - String get walletId => walletInfo.walletId; - WalletType get walletType => walletInfo.walletType; + String get walletId => info.walletId; + WalletType get walletType => info.walletType; /// Attempt to fetch the most recent chain height. /// On failure return the last cached height. @@ -89,7 +94,7 @@ abstract class Wallet { // return regardless of whether it was updated or not as we want a // number even if it isn't the most recent - return walletInfo.cachedChainHeight; + return info.cachedChainHeight; } //============================================================================ @@ -135,7 +140,7 @@ abstract class Wallet { } // Store in db after wallet creation - await wallet.mainDB.isar.walletInfo.put(wallet.walletInfo); + await wallet.mainDB.isar.walletInfo.put(wallet.info); return wallet; } @@ -326,8 +331,6 @@ abstract class Wallet { /// delete all locally stored blockchain data and refetch it. Future recover({required bool isRescan}); - Future pingCheck(); - Future updateNode(); Future updateTransactions(); @@ -337,6 +340,12 @@ abstract class Wallet { /// updates the wallet info's cachedChainHeight Future updateChainHeight(); + Future estimateFeeFor(Amount amount, int feeRate); + + Future get fees; + + Future pingCheck(); + //=========================================== // Should fire events @@ -442,8 +451,26 @@ abstract class Wallet { // TODO: } + @mustCallSuper Future init() async { + final address = await getCurrentReceivingAddress(); + await info.updateReceivingAddress( + newAddress: address!.value, + isar: mainDB.isar, + ); // TODO: make sure subclasses override this if they require some set up // especially xmr/wow/epiccash } + + // =========================================================================== + + Future getCurrentReceivingAddress() async => + await mainDB.isar.addresses + .where() + .walletIdEqualTo(walletId) + .filter() + .typeEqualTo(info.mainAddressType) + .subTypeEqualTo(AddressSubType.receiving) + .sortByDerivationIndexDesc() + .findFirst(); } diff --git a/lib/widgets/coin_card.dart b/lib/widgets/coin_card.dart index bcd42b2e8..98d784190 100644 --- a/lib/widgets/coin_card.dart +++ b/lib/widgets/coin_card.dart @@ -36,7 +36,7 @@ class CoinCard extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final coin = ref.watch( - pWallets.select((value) => value.getManager(walletId).coin), + pWallets.select((value) => value.getWallet(walletId).info.coin), ); final bool hasCardImageBg = (isFavorite) diff --git a/lib/widgets/custom_buttons/paynym_follow_toggle_button.dart b/lib/widgets/custom_buttons/paynym_follow_toggle_button.dart index 34c5d15a1..523cfa8e1 100644 --- a/lib/widgets/custom_buttons/paynym_follow_toggle_button.dart +++ b/lib/widgets/custom_buttons/paynym_follow_toggle_button.dart @@ -67,10 +67,10 @@ class _PaynymFollowToggleButtonState ), ); - final manager = ref.read(pWallets).getManager(widget.walletId); - + // TODO: [prio=high] FIX THIS BAD as CAST // get wallet to access paynym calls - final wallet = manager.wallet as PaynymWalletInterface; + final wallet = + ref.read(pWallets).getWallet(widget.walletId) as PaynymWalletInterface; final followedAccount = await ref .read(paynymAPIProvider) @@ -167,9 +167,9 @@ class _PaynymFollowToggleButtonState ), ); - final manager = ref.read(pWallets).getManager(widget.walletId); - - final wallet = manager.wallet as PaynymWalletInterface; + // TODO: [prio=high] FIX THIS BAD as CAST + final wallet = + ref.read(pWallets).getWallet(widget.walletId) as PaynymWalletInterface; final followedAccount = await ref .read(paynymAPIProvider) diff --git a/lib/widgets/db_watchers/favourite_wallets_watcher.dart b/lib/widgets/db_watchers/favourite_wallets_watcher.dart new file mode 100644 index 000000000..3d4d4a9f4 --- /dev/null +++ b/lib/widgets/db_watchers/favourite_wallets_watcher.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:isar/isar.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; + +class FavouriteWalletsWatcher extends ConsumerWidget { + const FavouriteWalletsWatcher({ + super.key, + required this.builder, + }); + + final Widget Function(BuildContext, List) builder; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final initialInfo = ref + .watch(mainDBProvider) + .isar + .walletInfo + .where() + .filter() + .isFavouriteEqualTo(true) + .findAllSync(); + + return StreamBuilder( + stream: ref + .watch(mainDBProvider) + .isar + .walletInfo + .where() + .filter() + .isFavouriteEqualTo(true) + .watch(), + builder: (context, snapshot) { + return builder(context, snapshot.data ?? initialInfo); + }, + ); + } +} diff --git a/lib/widgets/desktop/desktop_fee_dialog.dart b/lib/widgets/desktop/desktop_fee_dialog.dart index 88ab1cb14..f5828df5c 100644 --- a/lib/widgets/desktop/desktop_fee_dialog.dart +++ b/lib/widgets/desktop/desktop_fee_dialog.dart @@ -55,21 +55,21 @@ class _DesktopFeeDialogState extends ConsumerState { .fast[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.fast.raw!); ref.read(feeSheetSessionCacheProvider).fast[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { ref.read(feeSheetSessionCacheProvider).fast[amount] = - await (manager.wallet as FiroWallet) + await (wallet as FiroWallet) .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).fast[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -91,21 +91,21 @@ class _DesktopFeeDialogState extends ConsumerState { .average[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.regular.raw!); ref.read(feeSheetSessionCacheProvider).average[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { ref.read(feeSheetSessionCacheProvider).average[amount] = - await (manager.wallet as FiroWallet) + await (wallet as FiroWallet) .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).average[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -127,21 +127,21 @@ class _DesktopFeeDialogState extends ConsumerState { .slow[amount] == null) { if (widget.isToken == false) { - final manager = ref.read(pWallets).getManager(walletId); + final wallet = ref.read(pWallets).getWallet(walletId); if (coin == Coin.monero || coin == Coin.wownero) { - final fee = await manager.estimateFeeFor( + final fee = await wallet.estimateFeeFor( amount, MoneroTransactionPriority.slow.raw!); ref.read(feeSheetSessionCacheProvider).slow[amount] = fee; } else if ((coin == Coin.firo || coin == Coin.firoTestNet) && ref.read(publicPrivateBalanceStateProvider.state).state != "Private") { ref.read(feeSheetSessionCacheProvider).slow[amount] = - await (manager.wallet as FiroWallet) + await (wallet as FiroWallet) .estimateFeeForPublic(amount, feeRate); } else { ref.read(feeSheetSessionCacheProvider).slow[amount] = - await manager.estimateFeeFor(amount, feeRate); + await wallet.estimateFeeFor(amount, feeRate); } } else { final tokenWallet = ref.read(tokenServiceProvider)!; @@ -173,7 +173,7 @@ class _DesktopFeeDialogState extends ConsumerState { child: FutureBuilder( future: ref.watch( pWallets.select( - (value) => value.getManager(walletId).fees, + (value) => value.getWallet(walletId).fees, ), ), builder: (context, snapshot) { @@ -311,7 +311,7 @@ class _DesktopFeeItemState extends ConsumerState { if (!widget.isButton) { final coin = ref.watch( pWallets.select( - (value) => value.getManager(widget.walletId).coin, + (value) => value.getWallet(widget.walletId).info.coin, ), ); if ((coin == Coin.firo || coin == Coin.firoTestNet) && @@ -353,8 +353,8 @@ class _DesktopFeeItemState extends ConsumerState { ); } - final manager = ref.watch( - pWallets.select((value) => value.getManager(widget.walletId))); + final wallet = ref.watch( + pWallets.select((value) => value.getWallet(widget.walletId))); if (widget.feeObject == null) { return AnimatedText( @@ -368,7 +368,7 @@ class _DesktopFeeItemState extends ConsumerState { } else { return FutureBuilder( future: widget.feeFor( - coin: manager.coin, + coin: wallet.info.coin, feeRateType: widget.feeRateType, feeRate: widget.feeRateType == FeeRateType.fast ? widget.feeObject!.fast @@ -381,15 +381,15 @@ class _DesktopFeeItemState extends ConsumerState { if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) { feeString = "${widget.feeRateType.prettyName} " - "(~${ref.watch(pAmountFormatter(manager.coin)).format( + "(~${ref.watch(pAmountFormatter(wallet.info.coin)).format( snapshot.data!, indicatePrecisionLoss: false, )})"; - timeString = manager.coin == Coin.ethereum + timeString = wallet.info.coin == Coin.ethereum ? "" : estimatedTimeToBeIncludedInNextBlock( - Constants.targetBlockTimeInSeconds(manager.coin), + Constants.targetBlockTimeInSeconds(wallet.info.coin), widget.feeRateType == FeeRateType.fast ? widget.feeObject!.numberOfBlocksFast : widget.feeRateType == FeeRateType.slow diff --git a/lib/widgets/eth_wallet_radio.dart b/lib/widgets/eth_wallet_radio.dart index 02b6a252e..389d7ff61 100644 --- a/lib/widgets/eth_wallet_radio.dart +++ b/lib/widgets/eth_wallet_radio.dart @@ -33,8 +33,8 @@ class EthWalletRadio extends ConsumerStatefulWidget { class _EthWalletRadioState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); + final wallet = + ref.watch(pWallets.select((value) => value.getWallet(widget.walletId))); return Padding( padding: EdgeInsets.zero, @@ -56,7 +56,7 @@ class _EthWalletRadioState extends ConsumerState { width: 12, ), WalletInfoCoinIcon( - coin: manager.coin, + coin: wallet.info.coin, size: 40, ), const SizedBox( @@ -67,7 +67,7 @@ class _EthWalletRadioState extends ConsumerState { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( - manager.walletName, + wallet.info.name, style: STextStyles.desktopTextExtraSmall(context).copyWith( color: Theme.of(context).extension()!.textDark, diff --git a/lib/widgets/hover_text_field.dart b/lib/widgets/hover_text_field.dart index 09ed4c868..679104537 100644 --- a/lib/widgets/hover_text_field.dart +++ b/lib/widgets/hover_text_field.dart @@ -13,8 +13,8 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; -import 'package:stackwallet/providers/global/wallets_service_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/text_styles.dart'; @@ -46,18 +46,26 @@ class _HoverTextFieldState extends ConsumerState { ); Future onDone() async { - final currentWalletName = - ref.read(pWallets).getManager(widget.walletId).walletName; + final info = ref.read(pWallets).getWallet(widget.walletId).info; + final currentWalletName = info.name; final newName = controller.text; - if (newName != currentWalletName) { - final success = - await ref.read(walletsServiceChangeNotifierProvider).renameWallet( - from: currentWalletName, - to: newName, - shouldNotifyListeners: true, - ); - if (success) { - ref.read(pWallets).getManager(widget.walletId).walletName = newName; + + String? errMessage; + try { + await info.updateName( + newName: newName, + isar: ref.read(mainDBProvider).isar, + ); + } catch (e) { + if (e.toString().contains("Empty wallet name not allowed!")) { + errMessage = "Empty wallet name not allowed."; + } else { + errMessage = e.toString(); + } + } + + if (mounted) { + if (errMessage == null) { unawaited( showFloatingFlushBar( type: FlushBarType.success, @@ -95,8 +103,7 @@ class _HoverTextFieldState extends ConsumerState { focusNode.addListener(listenerFunc); WidgetsBinding.instance.addPostFrameCallback((_) { - controller.text = - ref.read(pWallets).getManager(widget.walletId).walletName; + controller.text = ref.read(pWallets).getWallet(widget.walletId).info.name; }); super.initState(); diff --git a/lib/widgets/managed_favorite.dart b/lib/widgets/managed_favorite.dart index e5359cd20..bb770ee2a 100644 --- a/lib/widgets/managed_favorite.dart +++ b/lib/widgets/managed_favorite.dart @@ -13,8 +13,7 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; -import 'package:stackwallet/providers/providers.dart'; -import 'package:stackwallet/services/coins/firo/firo_wallet.dart'; +import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/themes/coin_icon_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; @@ -23,6 +22,7 @@ import 'package:stackwallet/utilities/constants.dart'; import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/text_styles.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/widgets/custom_buttons/favorite_toggle.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; @@ -41,55 +41,31 @@ class ManagedFavorite extends ConsumerStatefulWidget { class _ManagedFavoriteCardState extends ConsumerState { @override Widget build(BuildContext context) { - final manager = ref - .watch(pWallets.select((value) => value.getManager(widget.walletId))); - debugPrint("BUILD: $runtimeType with walletId ${widget.walletId}"); + final walletId = widget.walletId; + + debugPrint("BUILD: $runtimeType with walletId $walletId"); final isDesktop = Util.isDesktop; - final balance = ref.watch( - pWallets.select( - (value) => value.getManager(widget.walletId).balance, - ), - ); + final coin = ref.watch(pWalletCoin(walletId)); - Amount total = balance.total; - if (manager.coin == Coin.firo || manager.coin == Coin.firoTestNet) { - final balancePrivate = ref.watch( - pWallets.select( - (value) => (value - .getManager( - widget.walletId, - ) - .wallet as FiroWallet) - .balancePrivate, - ), - ); + Amount total = ref.watch(pWalletBalance(walletId)).total; + if (coin == Coin.firo || coin == Coin.firoTestNet) { + final balancePrivate = ref.watch(pWalletBalanceSecondary(walletId)); total += balancePrivate.total; } + final isFavourite = ref.watch(pWalletIsFavourite(walletId)); + return RoundedWhiteContainer( padding: EdgeInsets.all(isDesktop ? 0 : 4.0), child: RawMaterialButton( onPressed: () { - final provider = - ref.read(pWallets).getManagerProvider(manager.walletId); - if (!manager.isFavorite) { - ref.read(favoritesProvider).add(provider, true); - ref.read(nonFavoritesProvider).remove(provider, true); - ref - .read(walletsServiceChangeNotifierProvider) - .addFavorite(manager.walletId); - } else { - ref.read(favoritesProvider).remove(provider, true); - ref.read(nonFavoritesProvider).add(provider, true); - ref - .read(walletsServiceChangeNotifierProvider) - .removeFavorite(manager.walletId); - } - - manager.isFavorite = !manager.isFavorite; + ref.read(pWalletInfo(walletId)).updateIsFavourite( + !isFavourite, + isar: ref.read(mainDBProvider).isar, + ); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( @@ -109,7 +85,7 @@ class _ManagedFavoriteCardState extends ConsumerState { decoration: BoxDecoration( color: Theme.of(context) .extension()! - .colorForCoin(manager.coin) + .colorForCoin(coin) .withOpacity(0.5), borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, @@ -119,7 +95,7 @@ class _ManagedFavoriteCardState extends ConsumerState { padding: EdgeInsets.all(isDesktop ? 6 : 4), child: SvgPicture.file( File( - ref.watch(coinIconProvider(manager.coin)), + ref.watch(coinIconProvider(coin)), ), width: 20, height: 20, @@ -135,7 +111,7 @@ class _ManagedFavoriteCardState extends ConsumerState { children: [ Expanded( child: Text( - manager.walletName, + ref.watch(pWalletName(walletId)), style: STextStyles.titleBold12(context), ), ), @@ -143,19 +119,19 @@ class _ManagedFavoriteCardState extends ConsumerState { child: Text( ref .watch( - pAmountFormatter(manager.coin), + pAmountFormatter(coin), ) .format(total), style: STextStyles.itemSubtitle(context), ), ), Text( - manager.isFavorite + isFavourite ? "Remove from favorites" : "Add to favorites", style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: manager.isFavorite + color: isFavourite ? Theme.of(context) .extension()! .accentColorRed @@ -174,7 +150,7 @@ class _ManagedFavoriteCardState extends ConsumerState { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - manager.walletName, + ref.watch(pWalletName(walletId)), style: STextStyles.titleBold12(context), ), const SizedBox( @@ -183,7 +159,7 @@ class _ManagedFavoriteCardState extends ConsumerState { Text( ref .watch( - pAmountFormatter(manager.coin), + pAmountFormatter(coin), ) .format(total), style: STextStyles.itemSubtitle(context), @@ -196,7 +172,7 @@ class _ManagedFavoriteCardState extends ConsumerState { borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, ), - initialState: manager.isFavorite, + initialState: isFavourite, onChanged: null, ), ], diff --git a/lib/widgets/master_wallet_card.dart b/lib/widgets/master_wallet_card.dart index 6c0ee9a15..7bb5d6566 100644 --- a/lib/widgets/master_wallet_card.dart +++ b/lib/widgets/master_wallet_card.dart @@ -45,7 +45,7 @@ class _MasterWalletCardState extends ConsumerState { @override void initState() { final ethWallet = - ref.read(pWallets).getManager(widget.walletId).wallet as EthereumWallet; + ref.read(pWallets).getWallet(widget.walletId) as EthereumWallet; tokenContractAddresses = ethWallet.getWalletTokenContractAddresses(); diff --git a/lib/widgets/node_card.dart b/lib/widgets/node_card.dart index 038d881ad..e90bba880 100644 --- a/lib/widgets/node_card.dart +++ b/lib/widgets/node_card.dart @@ -18,6 +18,7 @@ import 'package:stackwallet/models/node_model.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart'; import 'package:stackwallet/pages/settings_views/global_settings_view/manage_nodes_views/node_details_view.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/assets.dart'; @@ -61,33 +62,33 @@ class _NodeCardState extends ConsumerState { bool _advancedIsExpanded = false; Future _notifyWalletsOfUpdatedNode(WidgetRef ref) async { - final managers = - ref.read(pWallets).managers.where((e) => e.coin == widget.coin); + final wallets = + ref.read(pWallets).wallets.where((e) => e.info.coin == widget.coin); final prefs = ref.read(prefsChangeNotifierProvider); switch (prefs.syncType) { case SyncingType.currentWalletOnly: - for (final manager in managers) { - if (manager.isActiveWallet) { - manager.updateNode(true); + for (final wallet in wallets) { + if (ref.read(currentWalletIdProvider) == wallet.walletId) { + unawaited(wallet.updateNode().then((value) => wallet.refresh())); } else { - manager.updateNode(false); + unawaited(wallet.updateNode()); } } break; case SyncingType.selectedWalletsAtStartup: final List walletIdsToSync = prefs.walletIdsSyncOnStartup; - for (final manager in managers) { - if (walletIdsToSync.contains(manager.walletId)) { - manager.updateNode(true); + for (final wallet in wallets) { + if (walletIdsToSync.contains(wallet.walletId)) { + unawaited(wallet.updateNode().then((value) => wallet.refresh())); } else { - manager.updateNode(false); + unawaited(wallet.updateNode()); } } break; case SyncingType.allWalletsOnStartup: - for (final manager in managers) { - manager.updateNode(true); + for (final wallet in wallets) { + unawaited(wallet.updateNode().then((value) => wallet.refresh())); } break; } diff --git a/lib/widgets/node_options_sheet.dart b/lib/widgets/node_options_sheet.dart index 18dc455e6..ba43da2f9 100644 --- a/lib/widgets/node_options_sheet.dart +++ b/lib/widgets/node_options_sheet.dart @@ -18,6 +18,7 @@ import 'package:stackwallet/models/node_model.dart'; import 'package:stackwallet/notifications/show_flush_bar.dart'; import 'package:stackwallet/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart'; import 'package:stackwallet/pages/settings_views/global_settings_view/manage_nodes_views/node_details_view.dart'; +import 'package:stackwallet/providers/global/active_wallet_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/services/tor_service.dart'; import 'package:stackwallet/themes/stack_colors.dart'; @@ -47,32 +48,33 @@ class NodeOptionsSheet extends ConsumerWidget { final String popBackToRoute; Future _notifyWalletsOfUpdatedNode(WidgetRef ref) async { - final managers = ref.read(pWallets).managers.where((e) => e.coin == coin); + final wallets = + ref.read(pWallets).wallets.where((e) => e.info.coin == coin); final prefs = ref.read(prefsChangeNotifierProvider); switch (prefs.syncType) { case SyncingType.currentWalletOnly: - for (final manager in managers) { - if (manager.isActiveWallet) { - manager.updateNode(true); + for (final wallet in wallets) { + if (ref.read(currentWalletIdProvider) == wallet.walletId) { + unawaited(wallet.updateNode().then((value) => wallet.refresh())); } else { - manager.updateNode(false); + unawaited(wallet.updateNode()); } } break; case SyncingType.selectedWalletsAtStartup: final List walletIdsToSync = prefs.walletIdsSyncOnStartup; - for (final manager in managers) { - if (walletIdsToSync.contains(manager.walletId)) { - manager.updateNode(true); + for (final wallet in wallets) { + if (walletIdsToSync.contains(wallet.walletId)) { + unawaited(wallet.updateNode().then((value) => wallet.refresh())); } else { - manager.updateNode(false); + unawaited(wallet.updateNode()); } } break; case SyncingType.allWalletsOnStartup: - for (final manager in managers) { - manager.updateNode(true); + for (final wallet in wallets) { + unawaited(wallet.updateNode().then((value) => wallet.refresh())); } break; } diff --git a/lib/widgets/transaction_card.dart b/lib/widgets/transaction_card.dart index 3e3c2ac3e..038101504 100644 --- a/lib/widgets/transaction_card.dart +++ b/lib/widgets/transaction_card.dart @@ -123,7 +123,7 @@ class _TransactionCardState extends ConsumerState { } else { prefix = ""; } - coin = ref.read(pWallets).getManager(widget.walletId).coin; + coin = ref.read(pWallets).getWallet(widget.walletId).info.coin; tokenContract = ref .read(mainDBProvider) @@ -147,8 +147,8 @@ class _TransactionCardState extends ConsumerState { : value.getPrice(coin))) .item1; - final currentHeight = ref.watch( - pWallets.select((value) => value.getManager(walletId).currentHeight)); + final currentHeight = ref.watch(pWallets + .select((value) => value.getWallet(walletId).info.cachedChainHeight)); return Material( color: Theme.of(context).extension()!.popupBG, diff --git a/lib/widgets/wallet_card.dart b/lib/widgets/wallet_card.dart index 0059642be..fcddb9803 100644 --- a/lib/widgets/wallet_card.dart +++ b/lib/widgets/wallet_card.dart @@ -21,7 +21,6 @@ import 'package:stackwallet/providers/db/main_db_provider.dart'; import 'package:stackwallet/providers/global/secure_store_provider.dart'; import 'package:stackwallet/providers/providers.dart'; import 'package:stackwallet/services/coins/ethereum/ethereum_wallet.dart'; -import 'package:stackwallet/services/coins/manager.dart'; import 'package:stackwallet/services/ethereum/ethereum_token_service.dart'; import 'package:stackwallet/services/transaction_notification_tracker.dart'; import 'package:stackwallet/utilities/constants.dart'; @@ -29,12 +28,12 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/show_loading.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; import 'package:stackwallet/widgets/conditional_parent.dart'; import 'package:stackwallet/widgets/desktop/primary_button.dart'; import 'package:stackwallet/widgets/dialogs/basic_dialog.dart'; import 'package:stackwallet/widgets/rounded_white_container.dart'; import 'package:stackwallet/widgets/wallet_info_row/wallet_info_row.dart'; -import 'package:tuple/tuple.dart'; class SimpleWalletCard extends ConsumerWidget { const SimpleWalletCard({ @@ -53,13 +52,14 @@ class SimpleWalletCard extends ConsumerWidget { Future _loadTokenWallet( BuildContext context, WidgetRef ref, - Manager manager, + Wallet wallet, EthContract contract, ) async { ref.read(tokenServiceStateProvider.state).state = EthTokenWallet( token: contract, secureStore: ref.read(secureStoreProvider), - ethWallet: manager.wallet as EthereumWallet, + // TODO: [prio=high] FIX THIS BAD as CAST + ethWallet: wallet as EthereumWallet, tracker: TransactionNotificationTracker( walletId: walletId, ), @@ -95,9 +95,9 @@ class SimpleWalletCard extends ConsumerWidget { void _openWallet(BuildContext context, WidgetRef ref) async { final nav = Navigator.of(context); - final manager = ref.read(pWallets).getManager(walletId); - if (manager.coin == Coin.monero || manager.coin == Coin.wownero) { - await manager.initializeExisting(); + final wallet = ref.read(pWallets).getWallet(walletId); + if (wallet.info.coin == Coin.monero || wallet.info.coin == Coin.wownero) { + await wallet.init(); } if (context.mounted) { if (popPrevious) nav.pop(); @@ -113,10 +113,7 @@ class SimpleWalletCard extends ConsumerWidget { unawaited( nav.pushNamed( WalletView.routeName, - arguments: Tuple2( - walletId, - ref.read(pWallets).getManagerProvider(walletId), - ), + arguments: walletId, ), ); } @@ -127,10 +124,7 @@ class SimpleWalletCard extends ConsumerWidget { final success = await showLoading( whileFuture: _loadTokenWallet( - desktopNavigatorState?.context ?? context, - ref, - manager, - contract), + desktopNavigatorState?.context ?? context, ref, wallet, contract), context: desktopNavigatorState?.context ?? context, opaqueBG: true, message: "Loading ${contract.name}", diff --git a/lib/widgets/wallet_info_row/sub_widgets/wallet_info_row_balance.dart b/lib/widgets/wallet_info_row/sub_widgets/wallet_info_row_balance.dart index cb06e2c75..af0331800 100644 --- a/lib/widgets/wallet_info_row/sub_widgets/wallet_info_row_balance.dart +++ b/lib/widgets/wallet_info_row/sub_widgets/wallet_info_row_balance.dart @@ -34,27 +34,27 @@ class WalletInfoRowBalance extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final manager = - ref.watch(ref.watch(pWallets.notifier).getManagerProvider(walletId)); + final wallet = ref.watch(pWallets).getWallet(walletId); Amount totalBalance; EthContract? contract; if (contractAddress == null) { - totalBalance = manager.balance.total; - if (manager.coin == Coin.firo || manager.coin == Coin.firoTestNet) { + totalBalance = wallet.info.cachedBalance.total; + if (wallet.info.coin == Coin.firo || + wallet.info.coin == Coin.firoTestNet) { totalBalance = - totalBalance + (manager.wallet as FiroWallet).balancePrivate.total; + totalBalance + (wallet as FiroWallet).balancePrivate.total; } contract = null; } else { - final ethWallet = manager.wallet as EthereumWallet; + final ethWallet = wallet as EthereumWallet; contract = MainDB.instance.getEthContractSync(contractAddress!)!; totalBalance = ethWallet.getCachedTokenBalance(contract).total; } return Text( ref - .watch(pAmountFormatter(manager.coin)) + .watch(pAmountFormatter(wallet.info.coin)) .format(totalBalance, ethContract: contract), style: Util.isDesktop ? STextStyles.desktopTextExtraSmall(context).copyWith( diff --git a/lib/widgets/wallet_info_row/wallet_info_row.dart b/lib/widgets/wallet_info_row/wallet_info_row.dart index 86e739165..bed25d102 100644 --- a/lib/widgets/wallet_info_row/wallet_info_row.dart +++ b/lib/widgets/wallet_info_row/wallet_info_row.dart @@ -37,8 +37,7 @@ class WalletInfoRow extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - final manager = - ref.watch(ref.watch(pWallets.notifier).getManagerProvider(walletId)); + final wallet = ref.watch(pWallets).getWallet(walletId); EthContract? contract; if (contractAddress != null) { @@ -58,7 +57,7 @@ class WalletInfoRow extends ConsumerWidget { child: Row( children: [ WalletInfoCoinIcon( - coin: manager.coin, + coin: wallet.info.coin, contractAddress: contractAddress, ), const SizedBox( @@ -86,7 +85,7 @@ class WalletInfoRow extends ConsumerWidget { ], ) : Text( - manager.walletName, + wallet.info.name, style: STextStyles.desktopTextExtraSmall(context) .copyWith( color: Theme.of(context) @@ -124,7 +123,7 @@ class WalletInfoRow extends ConsumerWidget { return Row( children: [ WalletInfoCoinIcon( - coin: manager.coin, + coin: wallet.info.coin, contractAddress: contractAddress, ), const SizedBox( @@ -151,7 +150,7 @@ class WalletInfoRow extends ConsumerWidget { ], ) : Text( - manager.walletName, + wallet.info.name, style: STextStyles.titleBold12(context), ), const SizedBox( diff --git a/pubspec.lock b/pubspec.lock index d7d431c54..72a299951 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1072,7 +1072,7 @@ packages: source: hosted version: "3.0.0" meta: - dependency: transitive + dependency: "direct main" description: name: meta sha256: "3c74dbf8763d36539f114c799d8a2d87343b5067e9d796ca22b5eb8437090ee3" diff --git a/pubspec.yaml b/pubspec.yaml index f72c6b9be..02c97479c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -159,6 +159,7 @@ dependencies: coinlib_flutter: ^1.0.0 convert: ^3.1.1 flutter_hooks: ^0.20.3 + meta: ^1.9.1 dev_dependencies: flutter_test: diff --git a/test/pages/send_view/send_view_test.dart b/test/pages/send_view/send_view_test.dart index b87310e4f..f60fce823 100644 --- a/test/pages/send_view/send_view_test.dart +++ b/test/pages/send_view/send_view_test.dart @@ -52,10 +52,10 @@ void main() { when(wallet.walletName).thenAnswer((_) => "some wallet"); when(wallet.walletId).thenAnswer((_) => "wallet id"); - final manager = Manager(wallet); + final wallet = Manager(wallet); when(mockWallets.getManagerProvider("wallet id")).thenAnswer( (realInvocation) => ChangeNotifierProvider((ref) => manager)); - when(mockWallets.getManager("wallet id")) + when(mockWallets.getWallet"wallet id")) .thenAnswer((realInvocation) => manager); when(mockLocaleService.locale).thenAnswer((_) => "en_US"); @@ -131,10 +131,10 @@ void main() { when(wallet.walletName).thenAnswer((_) => "some wallet"); when(wallet.walletId).thenAnswer((_) => "wallet id"); - final manager = Manager(wallet); + final wallet = Manager(wallet); when(mockWallets.getManagerProvider("wallet id")).thenAnswer( (realInvocation) => ChangeNotifierProvider((ref) => manager)); - when(mockWallets.getManager("wallet id")) + when(mockWallets.getWallet"wallet id")) .thenAnswer((realInvocation) => manager); when(mockLocaleService.locale).thenAnswer((_) => "en_US"); diff --git a/test/screen_tests/address_book_view/subviews/add_address_book_view_screen_test.dart b/test/screen_tests/address_book_view/subviews/add_address_book_view_screen_test.dart index c374f25dc..9a7bc6abd 100644 --- a/test/screen_tests/address_book_view/subviews/add_address_book_view_screen_test.dart +++ b/test/screen_tests/address_book_view/subviews/add_address_book_view_screen_test.dart @@ -27,7 +27,7 @@ import 'package:stackwallet/utilities/barcode_scanner_interface.dart'; ]) void main() { // testWidgets("AddAddressBookEntryView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // // await tester.pumpWidget( @@ -71,7 +71,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -108,7 +108,7 @@ void main() { // }); // // testWidgets("tap cancel", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -145,7 +145,7 @@ void main() { // }); // // testWidgets("tap disabled save button", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -184,7 +184,7 @@ void main() { // }); // // testWidgets("tap scan qr with valid firo uri A", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -245,7 +245,7 @@ void main() { // }); // // testWidgets("tap scan qr throws", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -301,7 +301,7 @@ void main() { // }); // // testWidgets("tap scan qr with valid firo uri B", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -361,7 +361,7 @@ void main() { // }); // // testWidgets("tap scan qr with valid firo address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -422,7 +422,7 @@ void main() { // // testWidgets("tap scan qr with valid firo uri with invalid address", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -481,7 +481,7 @@ void main() { // }); // // testWidgets("tap scan qr with invalid firo address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -539,7 +539,7 @@ void main() { // }); // // testWidgets("enter invalid firo address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -595,7 +595,7 @@ void main() { // }); // // testWidgets("enter valid firo address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -653,7 +653,7 @@ void main() { // }); // // testWidgets("tap paste with a valid firo address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); @@ -710,7 +710,7 @@ void main() { // }); // // testWidgets("tap paste with a invalid firo address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); @@ -764,7 +764,7 @@ void main() { // }); // // testWidgets("tap paste then tap clear address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); @@ -834,7 +834,7 @@ void main() { // }); // // testWidgets("enter name", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -890,7 +890,7 @@ void main() { // }); // // testWidgets("enter a name with invalid firo address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -949,7 +949,7 @@ void main() { // }); // // testWidgets("enter a name with a valid firo address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -1010,7 +1010,7 @@ void main() { // }); // // testWidgets("save a validated contact where address is new", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -1095,7 +1095,7 @@ void main() { // // testWidgets("save a validated contact where address is already in contacts", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); @@ -1178,7 +1178,7 @@ void main() { // }); // // testWidgets("save a validated contact throws", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final scanner = MockBarcodeScannerWrapper(); diff --git a/test/screen_tests/address_book_view/subviews/address_book_entry_details_view_screen_test.dart b/test/screen_tests/address_book_view/subviews/address_book_entry_details_view_screen_test.dart index 1be2e7b89..ed5db84da 100644 --- a/test/screen_tests/address_book_view/subviews/address_book_entry_details_view_screen_test.dart +++ b/test/screen_tests/address_book_view/subviews/address_book_entry_details_view_screen_test.dart @@ -32,7 +32,7 @@ import 'package:stackwallet/services/notes_service.dart'; ]) void main() { // testWidgets("AddressBookDetailsView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -92,7 +92,7 @@ void main() { // testWidgets( // "AddressBookDetailsView loads correctly with three matching wallet transactions history", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); @@ -173,7 +173,7 @@ void main() { // testWidgets( // "AddressBookDetailsView loads correctly with no wallet transaction history", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -230,7 +230,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); @@ -317,7 +317,7 @@ void main() { // // testWidgets("tap options then tap anywhere but the context menu", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); @@ -407,7 +407,7 @@ void main() { // }); // // testWidgets("tap options then tap delete", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); @@ -501,7 +501,7 @@ void main() { // }); // // testWidgets("cancel delete", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); @@ -598,7 +598,7 @@ void main() { // }); // // testWidgets("confirm delete", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); @@ -702,7 +702,7 @@ void main() { // }); // // testWidgets("tap copy address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); @@ -791,7 +791,7 @@ void main() { // }); // // testWidgets("tap edit/pencil icon", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); @@ -879,7 +879,7 @@ void main() { // }); // // testWidgets("tap send", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final notesService = MockNotesService(); // final navigator = mockingjay.MockNavigator(); diff --git a/test/screen_tests/address_book_view/subviews/edit_address_book_entry_view_screen_test.dart b/test/screen_tests/address_book_view/subviews/edit_address_book_entry_view_screen_test.dart index 52808470b..2bce207c0 100644 --- a/test/screen_tests/address_book_view/subviews/edit_address_book_entry_view_screen_test.dart +++ b/test/screen_tests/address_book_view/subviews/edit_address_book_entry_view_screen_test.dart @@ -25,7 +25,7 @@ import 'package:stackwallet/services/coins/manager.dart'; ]) void main() { // testWidgets("EditAddressBookEntryView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -84,7 +84,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -149,7 +149,7 @@ void main() { // }); // // testWidgets("tap cancel", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -215,7 +215,7 @@ void main() { // }); // // testWidgets("tap save with no changes", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -281,7 +281,7 @@ void main() { // }); // // testWidgets("clear and paste new address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); @@ -374,7 +374,7 @@ void main() { // }); // // testWidgets("clear and paste invalid address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); @@ -464,7 +464,7 @@ void main() { // }); // // testWidgets("clear and enter invalid address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -550,7 +550,7 @@ void main() { // }); // // testWidgets("tap save with new address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); @@ -669,7 +669,7 @@ void main() { // }); // // testWidgets("tap save with new name", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // @@ -763,7 +763,7 @@ void main() { // }); // // testWidgets("tap save with an address already in contacts", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); @@ -873,7 +873,7 @@ void main() { // }); // // testWidgets("tap save throws", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); @@ -987,7 +987,7 @@ void main() { // }); // // testWidgets("tap disabled save button", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final addressBookService = MockAddressBookService(); // final navigator = mockingjay.MockNavigator(); // final clipboard = FakeClipboard(); diff --git a/test/screen_tests/lockscreen_view_screen_test.dart b/test/screen_tests/lockscreen_view_screen_test.dart index 067d9bb32..51c08ed4d 100644 --- a/test/screen_tests/lockscreen_view_screen_test.dart +++ b/test/screen_tests/lockscreen_view_screen_test.dart @@ -15,7 +15,7 @@ void main() { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); // final nodeService = MockNodeService(); - // final manager = MockManager(); + // final wallet = MockManager(); // final secureStore = FakeSecureStorage(); // // secureStore.write(key: "walletID", value: "1234"); @@ -63,7 +63,7 @@ void main() { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); // final nodeService = MockNodeService(); - // final manager = MockManager(); + // final wallet = MockManager(); // final secureStore = FakeSecureStorage(); // // secureStore.write(key: "walletID_pin", value: "1234"); @@ -128,7 +128,7 @@ void main() { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); // final nodeService = MockNodeService(); - // final manager = MockManager(); + // final wallet = MockManager(); // final secureStore = FakeSecureStorage(); // // secureStore.write(key: "walletID_pin", value: "1234"); @@ -207,7 +207,7 @@ void main() { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); // final nodeService = MockNodeService(); - // final manager = MockManager(); + // final wallet = MockManager(); // final secureStore = FakeSecureStorage(); // // secureStore.write(key: "walletID_pin", value: "1234"); @@ -270,7 +270,7 @@ void main() { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); // final nodeService = MockNodeService(); - // final manager = MockManager(); + // final wallet = MockManager(); // final secureStore = FakeSecureStorage(); // // mockingjay.when(() => navigator.pop()).thenAnswer((_) async => {}); diff --git a/test/screen_tests/main_view_tests/main_view_screen_testA_test.dart b/test/screen_tests/main_view_tests/main_view_screen_testA_test.dart index f344b523a..8c92cc7e0 100644 --- a/test/screen_tests/main_view_tests/main_view_screen_testA_test.dart +++ b/test/screen_tests/main_view_tests/main_view_screen_testA_test.dart @@ -23,7 +23,7 @@ import 'package:stackwallet/services/wallets_service.dart'; void main() { // testWidgets("tap receive", (tester) async { // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // diff --git a/test/screen_tests/main_view_tests/main_view_screen_testB_test.dart b/test/screen_tests/main_view_tests/main_view_screen_testB_test.dart index 48c2552a6..112495e2a 100644 --- a/test/screen_tests/main_view_tests/main_view_screen_testB_test.dart +++ b/test/screen_tests/main_view_tests/main_view_screen_testB_test.dart @@ -25,7 +25,7 @@ import 'package:stackwallet/services/wallets_service.dart'; void main() { // testWidgets("tap refresh", (tester) async { // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // diff --git a/test/screen_tests/main_view_tests/main_view_screen_testC_test.dart b/test/screen_tests/main_view_tests/main_view_screen_testC_test.dart index 23abe9793..fe8eeaa68 100644 --- a/test/screen_tests/main_view_tests/main_view_screen_testC_test.dart +++ b/test/screen_tests/main_view_tests/main_view_screen_testC_test.dart @@ -23,7 +23,7 @@ import 'package:stackwallet/services/wallets_service.dart'; void main() { // testWidgets("tap send", (tester) async { // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // diff --git a/test/screen_tests/onboarding/backup_key_view_screen_test.dart b/test/screen_tests/onboarding/backup_key_view_screen_test.dart index 28dcdb070..f4bcef367 100644 --- a/test/screen_tests/onboarding/backup_key_view_screen_test.dart +++ b/test/screen_tests/onboarding/backup_key_view_screen_test.dart @@ -18,7 +18,7 @@ import 'package:stackwallet/services/coins/manager.dart'; ]) void main() { // testWidgets("BackupKeyView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer( // (_) async => [ @@ -106,7 +106,7 @@ void main() { // // testWidgets("back button test", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // // mockingjay.when(() => navigator.pop()).thenAnswer((_) async => {}); // @@ -165,7 +165,7 @@ void main() { // // testWidgets("skip button test", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // // mockingjay // .when(() => navigator.pushReplacementNamed("/mainview")) @@ -227,7 +227,7 @@ void main() { // }); // // testWidgets("qrcode button test", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer( // (_) async => [ @@ -287,7 +287,7 @@ void main() { // }); // // testWidgets("copy button test", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer( // (_) async => [ @@ -343,7 +343,7 @@ void main() { // // testWidgets("verify button test", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // // mockingjay // .when(() => navigator.push(mockingjay.any())) diff --git a/test/screen_tests/onboarding/backup_key_warning_view_screen_test.dart b/test/screen_tests/onboarding/backup_key_warning_view_screen_test.dart index 5afc5001b..b134499b5 100644 --- a/test/screen_tests/onboarding/backup_key_warning_view_screen_test.dart +++ b/test/screen_tests/onboarding/backup_key_warning_view_screen_test.dart @@ -64,7 +64,7 @@ void main() { // testWidgets("back button test A", (tester) async { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // // mockingjay // .when(() => @@ -108,7 +108,7 @@ void main() { // testWidgets("back button test B", (tester) async { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // // mockingjay.when(() => navigator.pop()).thenAnswer((_) async => {}); // diff --git a/test/screen_tests/onboarding/create_pin_view_screen_test.dart b/test/screen_tests/onboarding/create_pin_view_screen_test.dart index 276ed7c71..d8ceb5383 100644 --- a/test/screen_tests/onboarding/create_pin_view_screen_test.dart +++ b/test/screen_tests/onboarding/create_pin_view_screen_test.dart @@ -126,7 +126,7 @@ void main() { // testWidgets("Entering matched PINs on a new wallet", (tester) async { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // final nodeService = MockNodeService(); // // final store = FakeSecureStorage(); @@ -218,7 +218,7 @@ void main() { // testWidgets("Wallet init fails on entering matched PINs", (tester) async { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // final nodeService = MockNodeService(); // // final store = FakeSecureStorage(); diff --git a/test/screen_tests/onboarding/restore_wallet_view_screen_test.dart b/test/screen_tests/onboarding/restore_wallet_view_screen_test.dart index 3d2826658..8bde42e78 100644 --- a/test/screen_tests/onboarding/restore_wallet_view_screen_test.dart +++ b/test/screen_tests/onboarding/restore_wallet_view_screen_test.dart @@ -72,7 +72,7 @@ void main() { // testWidgets("back button test A", (tester) async { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // // mockingjay.when(() => navigator.pop()).thenAnswer((_) async => {}); // @@ -111,7 +111,7 @@ void main() { // testWidgets("back button test B", (tester) async { // final navigator = mockingjay.MockNavigator(); // final walletsService = MockWalletsService(); -// final manager = MockManager(); +// final wallet = MockManager(); // // mockingjay // .when(() => @@ -317,7 +317,7 @@ void main() { // // testWidgets("restore a valid mnemonic", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final nodeService = MockNodeService(); // final clipboard = FakeClipboard(); @@ -408,7 +408,7 @@ void main() { // // testWidgets("restore fails and throws", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final nodeService = MockNodeService(); // final clipboard = FakeClipboard(); diff --git a/test/screen_tests/onboarding/verify_backup_key_view_screen_test.dart b/test/screen_tests/onboarding/verify_backup_key_view_screen_test.dart index 5cd74fc60..849537b47 100644 --- a/test/screen_tests/onboarding/verify_backup_key_view_screen_test.dart +++ b/test/screen_tests/onboarding/verify_backup_key_view_screen_test.dart @@ -72,7 +72,7 @@ void main() { // // testWidgets("confirm button empty field", (tester) async { // final screen = VerifyBackupKeyView(); -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer( // (_) async => [ @@ -125,7 +125,7 @@ void main() { // // testWidgets("confirm button invalid word", (tester) async { // final screen = VerifyBackupKeyView(); -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer( // (_) async => [ @@ -181,7 +181,7 @@ void main() { // // testWidgets("confirm button matching word", (tester) async { // final screen = VerifyBackupKeyView(); -// final manager = MockManager(); +// final wallet = MockManager(); // final navigator = mockingjay.MockNavigator(); // // when(manager.mnemonic).thenAnswer( diff --git a/test/screen_tests/settings_view/settings_subviews/currency_view_screen_test.dart b/test/screen_tests/settings_view/settings_subviews/currency_view_screen_test.dart index 425adc602..aa126d3ab 100644 --- a/test/screen_tests/settings_view/settings_subviews/currency_view_screen_test.dart +++ b/test/screen_tests/settings_view/settings_subviews/currency_view_screen_test.dart @@ -14,7 +14,7 @@ import 'package:stackwallet/services/coins/manager.dart'; ]) void main() { // testWidgets("CurrencyView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.fiatCurrency).thenAnswer((_) => "USD"); // @@ -70,7 +70,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final navigator = mockingjay.MockNavigator(); // // when(manager.fiatCurrency).thenAnswer((_) => "USD"); @@ -149,7 +149,7 @@ void main() { // // testWidgets("tap a currency that is not the current currency", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.fiatCurrency).thenAnswer((_) => "USD"); // when(manager.changeFiatCurrency("CAD")).thenAnswer((_) { @@ -212,7 +212,7 @@ void main() { // }); // // testWidgets("tap the currenct currency", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.fiatCurrency).thenAnswer((_) => "USD"); // diff --git a/test/screen_tests/settings_view/settings_subviews/network_settings_subviews/add_custom_node_view_screen_test.dart b/test/screen_tests/settings_view/settings_subviews/network_settings_subviews/add_custom_node_view_screen_test.dart index 2cab4d3ea..7848bfae5 100644 --- a/test/screen_tests/settings_view/settings_subviews/network_settings_subviews/add_custom_node_view_screen_test.dart +++ b/test/screen_tests/settings_view/settings_subviews/network_settings_subviews/add_custom_node_view_screen_test.dart @@ -415,7 +415,7 @@ void main() { // }); // // testWidgets("tap enabled test where connection fails", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.testNetworkConnection(any)).thenAnswer((_) async => false); // @@ -482,7 +482,7 @@ void main() { // }); // // testWidgets("tap enabled test where connection succeeds", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.testNetworkConnection(any)).thenAnswer((_) async => true); // @@ -550,7 +550,7 @@ void main() { // // testWidgets("tap enabled save where save and node creation succeeds", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final nodeService = MockNodeService(); // final navigator = mockingjay.MockNavigator(); // @@ -643,7 +643,7 @@ void main() { // // testWidgets("tap enabled save where save and node creation fails", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final nodeService = MockNodeService(); // final navigator = mockingjay.MockNavigator(); // @@ -738,7 +738,7 @@ void main() { // // testWidgets("tap enabled save where save and connection test fails", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final nodeService = MockNodeService(); // final navigator = mockingjay.MockNavigator(); // @@ -896,7 +896,7 @@ void main() { // testWidgets( // "tap enabled save where save fails due to attempting to save duplicate default node", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final nodeService = MockNodeService(); // final navigator = mockingjay.MockNavigator(); // @@ -971,7 +971,7 @@ void main() { // // testWidgets("tap enabled save where save fails due to an invalid tcp port", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final nodeService = MockNodeService(); // final navigator = mockingjay.MockNavigator(); // diff --git a/test/screen_tests/settings_view/settings_subviews/network_settings_subviews/node_details_view_screen_test.dart b/test/screen_tests/settings_view/settings_subviews/network_settings_subviews/node_details_view_screen_test.dart index ce967933a..ad8cff6ad 100644 --- a/test/screen_tests/settings_view/settings_subviews/network_settings_subviews/node_details_view_screen_test.dart +++ b/test/screen_tests/settings_view/settings_subviews/network_settings_subviews/node_details_view_screen_test.dart @@ -363,7 +363,7 @@ void main() { // // testWidgets("tap test connection fails", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.testNetworkConnection(any)).thenAnswer((_) async => false); // @@ -430,7 +430,7 @@ void main() { // // testWidgets("tap test connection succeeds", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.testNetworkConnection(any)).thenAnswer((_) async => true); // diff --git a/test/screen_tests/settings_view/settings_subviews/wallet_backup_view_screen_test.dart b/test/screen_tests/settings_view/settings_subviews/wallet_backup_view_screen_test.dart index e1894eaaf..f9aecc7d9 100644 --- a/test/screen_tests/settings_view/settings_subviews/wallet_backup_view_screen_test.dart +++ b/test/screen_tests/settings_view/settings_subviews/wallet_backup_view_screen_test.dart @@ -22,7 +22,7 @@ import 'package:stackwallet/services/coins/manager.dart'; ]) void main() { // testWidgets("WalletBackupView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer((_) async => [ // "some", @@ -97,7 +97,7 @@ void main() { // }); // // testWidgets("WalletBackupView loads correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer((_) async => [ // "some", @@ -185,7 +185,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final navigator = mockingjay.MockNavigator(); // // when(manager.mnemonic).thenAnswer((_) async => [ @@ -286,7 +286,7 @@ void main() { // }); // // testWidgets("tap copy", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final clipboard = FakeClipboard(); // // when(manager.mnemonic).thenAnswer((_) async => [ @@ -389,7 +389,7 @@ void main() { // }); // // testWidgets("tap qr code", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer((_) async => [ // "some", diff --git a/test/screen_tests/settings_view/settings_subviews/wallet_settings_subviews/rescan_warning_view_screen_test.dart b/test/screen_tests/settings_view/settings_subviews/wallet_settings_subviews/rescan_warning_view_screen_test.dart index b45e43123..ad7bf42e3 100644 --- a/test/screen_tests/settings_view/settings_subviews/wallet_settings_subviews/rescan_warning_view_screen_test.dart +++ b/test/screen_tests/settings_view/settings_subviews/wallet_settings_subviews/rescan_warning_view_screen_test.dart @@ -43,7 +43,7 @@ void main() { // }); // // testWidgets("WalletDeleteMnemonicView loads correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer( // (_) async => [ @@ -139,7 +139,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final navigator = mockingjay.MockNavigator(); // // when(manager.mnemonic).thenAnswer( @@ -206,7 +206,7 @@ void main() { // }); // // testWidgets("show qr code", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer( // (_) async => [ @@ -285,7 +285,7 @@ void main() { // }); // // testWidgets("copy backup key", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final clipboard = FakeClipboard(); // // when(manager.mnemonic).thenAnswer( @@ -356,7 +356,7 @@ void main() { // }); // // testWidgets("tap continue then cancel", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.mnemonic).thenAnswer( // (_) async => [ @@ -433,7 +433,7 @@ void main() { // }); // // testWidgets("tap continue then rescan", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final navigator = mockingjay.MockNavigator(); // // mockingjay @@ -531,7 +531,7 @@ void main() { // }); // // testWidgets("tap continue and rescan throws", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final navigator = mockingjay.MockNavigator(); // // mockingjay.when(() => navigator.pop()).thenAnswer((_) async => {}); diff --git a/test/screen_tests/settings_view/settings_subviews/wallet_settings_subviews/wallet_delete_mnemonic_view_screen_test.dart b/test/screen_tests/settings_view/settings_subviews/wallet_settings_subviews/wallet_delete_mnemonic_view_screen_test.dart index e18e04e2e..81a3b6624 100644 --- a/test/screen_tests/settings_view/settings_subviews/wallet_settings_subviews/wallet_delete_mnemonic_view_screen_test.dart +++ b/test/screen_tests/settings_view/settings_subviews/wallet_settings_subviews/wallet_delete_mnemonic_view_screen_test.dart @@ -45,7 +45,7 @@ void main() { // }); // // testWidgets("WalletDeleteMnemonicView loads correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // // when(manager.mnemonic).thenAnswer( @@ -146,7 +146,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -218,7 +218,7 @@ void main() { // }); // // testWidgets("show qr code", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // // when(manager.mnemonic).thenAnswer( @@ -301,7 +301,7 @@ void main() { // }); // // testWidgets("copy backup key", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final clipboard = FakeClipboard(); // @@ -377,7 +377,7 @@ void main() { // }); // // testWidgets("tap continue then cancel", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // // when(manager.mnemonic).thenAnswer( @@ -458,7 +458,7 @@ void main() { // }); // // testWidgets("tap continue then delete last wallet", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -564,7 +564,7 @@ void main() { // // testWidgets("tap continue then delete with more than one remaining wallet", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // diff --git a/test/screen_tests/settings_view/settings_subviews/wallet_settings_view_screen_test.dart b/test/screen_tests/settings_view/settings_subviews/wallet_settings_view_screen_test.dart index 228472202..98b1ad4b9 100644 --- a/test/screen_tests/settings_view/settings_subviews/wallet_settings_view_screen_test.dart +++ b/test/screen_tests/settings_view/settings_subviews/wallet_settings_view_screen_test.dart @@ -29,7 +29,7 @@ import 'package:stackwallet/utilities/biometrics.dart'; ]) void main() { // testWidgets("WalletSettingsView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // // await tester.pumpWidget( @@ -69,7 +69,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -110,7 +110,7 @@ void main() { // }); // // testWidgets("tap change pin", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -157,7 +157,7 @@ void main() { // }); // // testWidgets("tap rename wallet", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -210,7 +210,7 @@ void main() { // }); // // testWidgets("tap delete wallet and cancel", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -266,7 +266,7 @@ void main() { // }); // // testWidgets("tap delete wallet and continue", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -330,7 +330,7 @@ void main() { // }); // // testWidgets("tap clear cache and cancel", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -386,7 +386,7 @@ void main() { // }); // // testWidgets("tap clear cache and confirm succeeds", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // final client = MockCachedElectrumX(); @@ -453,7 +453,7 @@ void main() { // }); // // testWidgets("tap clear cache and confirm fails", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // final client = MockCachedElectrumX(); @@ -520,7 +520,7 @@ void main() { // }); // // testWidgets("tap rescan wallet and cancel", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -573,7 +573,7 @@ void main() { // }); // // testWidgets("tap rescan wallet and continue", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -634,7 +634,7 @@ void main() { // }); // // testWidgets("biometrics not available on device", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // final localAuth = MockLocalAuthentication(); @@ -705,7 +705,7 @@ void main() { // }); // // testWidgets("tap to disable biometrics", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // final localAuth = MockLocalAuthentication(); @@ -764,7 +764,7 @@ void main() { // }); // // testWidgets("tap to enable biometrics succeeds", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // final localAuth = MockLocalAuthentication(); @@ -847,7 +847,7 @@ void main() { // // testWidgets("tap to enable biometrics and cancel system settings dialog", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // final localAuth = MockLocalAuthentication(); @@ -945,7 +945,7 @@ void main() { // // testWidgets("tap to enable biometrics and open and enable system settings", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // final localAuth = MockLocalAuthentication(); @@ -1058,7 +1058,7 @@ void main() { // testWidgets( // "tap to enable biometrics and open but do not enable system settings", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // final localAuth = MockLocalAuthentication(); diff --git a/test/screen_tests/settings_view/settings_view_screen_test.dart b/test/screen_tests/settings_view/settings_view_screen_test.dart index 1f60540ba..8fca67414 100644 --- a/test/screen_tests/settings_view/settings_view_screen_test.dart +++ b/test/screen_tests/settings_view/settings_view_screen_test.dart @@ -88,7 +88,7 @@ void main() { // }); // // testWidgets("tap log out and confirm log out", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -154,7 +154,7 @@ void main() { // }); // // testWidgets("tap log out and cancel log out", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final walletsService = MockWalletsService(); // final navigator = mockingjay.MockNavigator(); // @@ -338,7 +338,7 @@ void main() { // // testWidgets("tap wallet settings", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // // mockingjay // .when(() => navigator.push(mockingjay.any())) diff --git a/test/screen_tests/transaction_subviews/transaction_search_results_view_screen_test.dart b/test/screen_tests/transaction_subviews/transaction_search_results_view_screen_test.dart index d32b514fd..c154ee30d 100644 --- a/test/screen_tests/transaction_subviews/transaction_search_results_view_screen_test.dart +++ b/test/screen_tests/transaction_subviews/transaction_search_results_view_screen_test.dart @@ -25,7 +25,7 @@ void main() { // testWidgets( // "TransactionSearchResultsView builds correctly without any transactions", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.transactionData) // .thenAnswer((_) async => transactionDataFromJsonChunks); @@ -66,7 +66,7 @@ void main() { // // testWidgets("TransactionSearchResultsView builds correctly with two results", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // @@ -132,7 +132,7 @@ void main() { // }); // // testWidgets("tap back", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final navigator = mockingjay.MockNavigator(); // final localeService = MockLocaleService(); @@ -201,7 +201,7 @@ void main() { // // testWidgets("TransactionSearchResultsView builds correctly with one result", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // @@ -273,7 +273,7 @@ void main() { // // testWidgets("TransactionSearchResultsView builds correctly with zero results", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.transactionData) // .thenAnswer((_) async => transactionDataFromJsonChunks); diff --git a/test/screen_tests/wallet_view/confirm_send_view_screen_test.dart b/test/screen_tests/wallet_view/confirm_send_view_screen_test.dart index 5f59b4e6b..73f1fc762 100644 --- a/test/screen_tests/wallet_view/confirm_send_view_screen_test.dart +++ b/test/screen_tests/wallet_view/confirm_send_view_screen_test.dart @@ -22,7 +22,7 @@ import 'package:stackwallet/services/notes_service.dart'; ]) void main() { // testWidgets("ConfirmSendView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // // when(manager.useBiometrics).thenAnswer((_) async => true); @@ -63,7 +63,7 @@ void main() { // }); // // testWidgets("confirm wrong pin", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final secureStore = FakeSecureStorage(); // @@ -124,7 +124,7 @@ void main() { // }); // // testWidgets("confirm correct pin but send fails", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final secureStore = FakeSecureStorage(); // final navigator = mockingjay.MockNavigator(); @@ -212,7 +212,7 @@ void main() { // }); // // testWidgets("confirm correct pin and send succeeds", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final secureStore = FakeSecureStorage(); // final navigator = mockingjay.MockNavigator(); diff --git a/test/screen_tests/wallet_view/receive_view_screen_test.dart b/test/screen_tests/wallet_view/receive_view_screen_test.dart index 7ef2cc226..4cf9ef2e6 100644 --- a/test/screen_tests/wallet_view/receive_view_screen_test.dart +++ b/test/screen_tests/wallet_view/receive_view_screen_test.dart @@ -19,7 +19,7 @@ import 'package:stackwallet/services/coins/manager.dart'; ]) void main() { // testWidgets("ReceiveView builds without loading address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final clipboard = FakeClipboard(); // // when(manager.currentReceivingAddress).thenAnswer(((_) async => null) as Future? Function(Invocation)); @@ -56,7 +56,7 @@ void main() { // }); // // testWidgets("ReceiveView builds correctly and loads address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final clipboard = FakeClipboard(); // // when(manager.currentReceivingAddress) @@ -96,7 +96,7 @@ void main() { // }); // // testWidgets("tap copy address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final clipboard = FakeClipboard(); // // when(manager.currentReceivingAddress) @@ -158,7 +158,7 @@ void main() { // tester.binding.defaultBinaryMessenger // .setMockMethodCallHandler(channel, handler); // -// final manager = MockManager(); +// final wallet = MockManager(); // final clipboard = FakeClipboard(); // // when(manager.currentReceivingAddress) @@ -266,7 +266,7 @@ void main() { // tester.binding.defaultBinaryMessenger // .setMockMethodCallHandler(channel, handler); // -// final manager = MockManager(); +// final wallet = MockManager(); // final clipboard = FakeClipboard(); // // when(manager.currentReceivingAddress) @@ -348,7 +348,7 @@ void main() { // tester.binding.defaultBinaryMessenger // .setMockMethodCallHandler(channel, handler); // -// final manager = MockManager(); +// final wallet = MockManager(); // final clipboard = FakeClipboard(); // // when(manager.currentReceivingAddress) diff --git a/test/screen_tests/wallet_view/send_view_screen_test.dart b/test/screen_tests/wallet_view/send_view_screen_test.dart index 99824d06f..04d9f8b1c 100644 --- a/test/screen_tests/wallet_view/send_view_screen_test.dart +++ b/test/screen_tests/wallet_view/send_view_screen_test.dart @@ -29,7 +29,7 @@ import 'package:stackwallet/utilities/barcode_scanner_interface.dart'; ]) void main() { // testWidgets("SendView builds correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // // when(manager.coinTicker).thenAnswer((_) => "FIRO"); @@ -88,7 +88,7 @@ void main() { // }); // // testWidgets("SendView loads correctly", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // // when(manager.coinTicker).thenAnswer((_) => "FIRO"); @@ -157,7 +157,7 @@ void main() { // addTearDown(tester.binding.window.clearPhysicalSizeTestValue); // addTearDown(tester.binding.window.clearDevicePixelRatioTestValue); // -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // // when(manager.coinTicker).thenAnswer((_) => "FIRO"); @@ -219,7 +219,7 @@ void main() { // }); // // testWidgets("SendView load fails to fetch data", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // // when(manager.coinTicker).thenAnswer((_) => "FIRO"); @@ -279,7 +279,7 @@ void main() { // }); // // testWidgets("paste and clear a valid address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // @@ -339,7 +339,7 @@ void main() { // }); // // testWidgets("tap fee tooltips", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // @@ -403,7 +403,7 @@ void main() { // }); // // testWidgets("paste and clear an invalid address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // @@ -462,7 +462,7 @@ void main() { // }); // // testWidgets("enter and clear a valid address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // @@ -521,7 +521,7 @@ void main() { // }); // // testWidgets("enter an invalid address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // @@ -574,7 +574,7 @@ void main() { // }); // // testWidgets("enter a firo amount", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // @@ -626,7 +626,7 @@ void main() { // }); // // testWidgets("tap available to autofill maximum amount", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // @@ -684,7 +684,7 @@ void main() { // }); // // testWidgets("enter a fiat amount", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // @@ -736,7 +736,7 @@ void main() { // }); // // testWidgets("tap addressbook icon", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final navigator = mockingjay.MockNavigator(); @@ -796,7 +796,7 @@ void main() { // // testWidgets("tap scan qr code icon and do not give camera permissions", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); @@ -851,7 +851,7 @@ void main() { // }); // // testWidgets("tap scan qr code for basic address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); @@ -908,7 +908,7 @@ void main() { // }); // // testWidgets("tap scan qr code for firo uri", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); @@ -968,7 +968,7 @@ void main() { // }); // // testWidgets("attempt send to own address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); @@ -1032,7 +1032,7 @@ void main() { // }); // // testWidgets("attempt send to invalid address", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); @@ -1089,7 +1089,7 @@ void main() { // }); // // testWidgets("attempt send more than available balance", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); @@ -1151,7 +1151,7 @@ void main() { // }); // // testWidgets("attempt valid send succeeds", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); @@ -1228,7 +1228,7 @@ void main() { // }); // // testWidgets("attempt valid send fails", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); @@ -1305,7 +1305,7 @@ void main() { // }); // // testWidgets("autofill args send", (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final clipboard = FakeClipboard(); // final scanner = MockBarcodeScannerWrapper(); diff --git a/test/screen_tests/wallet_view/wallet_view_screen_test.dart b/test/screen_tests/wallet_view/wallet_view_screen_test.dart index 8fc858ea5..1f2ac4623 100644 --- a/test/screen_tests/wallet_view/wallet_view_screen_test.dart +++ b/test/screen_tests/wallet_view/wallet_view_screen_test.dart @@ -30,7 +30,7 @@ import 'package:stackwallet/services/notes_service.dart'; void main() { // testWidgets("WalletView builds correctly with no transactions", // (tester) async { -// final manager = MockManager(); +// final wallet = MockManager(); // // when(manager.coinTicker).thenAnswer((_) => "FIRO"); // when(manager.fiatCurrency).thenAnswer((_) => "USD"); @@ -91,7 +91,7 @@ void main() { // testWidgets("WalletView builds correctly with transaction history", // (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // @@ -181,7 +181,7 @@ void main() { // // testWidgets("tap tx search", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // @@ -253,7 +253,7 @@ void main() { // // testWidgets("scroll transactions and test pull down refresh", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // @@ -326,7 +326,7 @@ void main() { // // testWidgets("node events", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // @@ -407,7 +407,7 @@ void main() { // // testWidgets("select full/available balances", (tester) async { // final navigator = mockingjay.MockNavigator(); -// final manager = MockManager(); +// final wallet = MockManager(); // final notesService = MockNotesService(); // final localeService = MockLocaleService(); // diff --git a/test/services/coins/manager_test.dart b/test/services/coins/manager_test.dart index fcc246882..e8c06f031 100644 --- a/test/services/coins/manager_test.dart +++ b/test/services/coins/manager_test.dart @@ -24,7 +24,7 @@ Amount _a(int i) => Amount.fromDecimal( @GenerateMocks([FiroWallet, ElectrumX]) void main() { test("Manager should have a backgroundRefreshListener on initialization", () { - final manager = Manager(MockFiroWallet()); + final wallet = Manager(MockFiroWallet()); expect(manager.hasBackgroundRefreshListener, true); }); @@ -32,7 +32,7 @@ void main() { test("get coin", () { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.coin).thenAnswer((_) => Coin.firo); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(manager.coin, Coin.firo); }); @@ -47,7 +47,7 @@ void main() { numberOfBlocksSlow: 2, numberOfBlocksAverage: 3)); - final manager = Manager(wallet); + final wallet = Manager(wallet); final feeObject = await manager.fees; @@ -63,7 +63,7 @@ void main() { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.maxFee).thenAnswer((_) async => 10); - final manager = Manager(wallet); + final wallet = Manager(wallet); final fee = await manager.maxFee; @@ -75,7 +75,7 @@ void main() { when(wallet.currentReceivingAddress) .thenAnswer((_) async => "Some address string"); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(await manager.currentReceivingAddress, "Some address string"); }); @@ -95,7 +95,7 @@ void main() { (_) => balance, ); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(manager.balance, balance); }); @@ -132,7 +132,7 @@ void main() { tx, ]); - final manager = Manager(wallet); + final wallet = Manager(wallet); final result = await manager.transactions; @@ -145,7 +145,7 @@ void main() { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.refresh()).thenAnswer((_) => Future(() => {})); - final manager = Manager(wallet); + final wallet = Manager(wallet); await manager.refresh(); @@ -155,7 +155,7 @@ void main() { test("get walletName", () { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.walletName).thenAnswer((_) => "Some wallet name"); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(manager.walletName, "Some wallet name"); }); @@ -164,7 +164,7 @@ void main() { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.walletId).thenAnswer((_) => "Some wallet ID"); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(manager.walletId, "Some wallet ID"); }); @@ -174,7 +174,7 @@ void main() { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.validateAddress("a valid address")).thenAnswer((_) => true); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(manager.validateAddress("a valid address"), true); }); @@ -184,7 +184,7 @@ void main() { when(wallet.validateAddress("an invalid address")) .thenAnswer((_) => false); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(manager.validateAddress("an invalid address"), false); }); @@ -195,7 +195,7 @@ void main() { when(wallet.mnemonic) .thenAnswer((_) async => ["Some", "seed", "word", "list"]); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(await manager.mnemonic, ["Some", "seed", "word", "list"]); }); @@ -204,7 +204,7 @@ void main() { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.testNetworkConnection()).thenAnswer((_) async => true); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(await manager.testNetworkConnection(), true); }); @@ -219,7 +219,7 @@ void main() { height: 0)) .thenAnswer((realInvocation) => Future(() => {})); - final manager = Manager(wallet); + final wallet = Manager(wallet); await manager.recoverFromMnemonic( mnemonic: "Some valid mnemonic", @@ -244,7 +244,7 @@ void main() { height: 0)) .thenThrow(Exception("Invalid mnemonic")); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect( () => manager.recoverFromMnemonic( @@ -271,7 +271,7 @@ void main() { height: 0)) .thenThrow(Error()); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect( () => manager.recoverFromMnemonic( @@ -296,7 +296,7 @@ void main() { when(wallet.walletId).thenAnswer((realInvocation) => "some id"); when(wallet.walletName).thenAnswer((realInvocation) => "some name"); - final manager = Manager(wallet); + final wallet = Manager(wallet); await manager.exitCurrentWallet(); @@ -313,7 +313,7 @@ void main() { when(wallet.walletId).thenAnswer((realInvocation) => "some id"); when(wallet.walletName).thenAnswer((realInvocation) => "some name"); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(() => manager.dispose(), returnsNormally); }); @@ -322,7 +322,7 @@ void main() { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.fullRescan(20, 1000)).thenAnswer((_) async {}); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(() => manager.fullRescan(20, 1000), returnsNormally); }); @@ -331,7 +331,7 @@ void main() { final CoinServiceAPI wallet = MockFiroWallet(); when(wallet.fullRescan(20, 1000)).thenThrow(Exception()); - final manager = Manager(wallet); + final wallet = Manager(wallet); expect(() => manager.fullRescan(20, 1000), throwsA(isA())); }); @@ -340,7 +340,7 @@ void main() { // final CoinServiceAPI wallet = MockFiroWallet(); // when(wallet.exit()).thenAnswer((realInvocation) => Future(() => {})); // - // final manager = Manager(wallet); + // final wallet = Manager(wallet); // // expect( // () => GlobalEventBus.instance.fire(UpdatedInBackgroundEvent( diff --git a/test/widget_tests/managed_favorite_test.dart b/test/widget_tests/managed_favorite_test.dart index cc7c0711c..b4295f475 100644 --- a/test/widget_tests/managed_favorite_test.dart +++ b/test/widget_tests/managed_favorite_test.dart @@ -71,8 +71,8 @@ void main() { (_) => 8, ); - final manager = Manager(wallet); - when(wallets.getManager("some wallet id")) + final wallet = Manager(wallet); + when(wallets.getWallet"some wallet id")) .thenAnswer((realInvocation) => manager); when(manager.balance).thenAnswer( (realInvocation) => Balance( @@ -140,9 +140,9 @@ void main() { (_) => AmountUnit.normal, ); - final manager = Manager(wallet); + final wallet = Manager(wallet); - when(wallets.getManager("some wallet id")) + when(wallets.getWallet"some wallet id")) .thenAnswer((realInvocation) => manager); when(manager.balance).thenAnswer( (realInvocation) => Balance( @@ -231,9 +231,9 @@ void main() { (_) => 8, ); - final manager = Manager(wallet); + final wallet = Manager(wallet); - when(wallets.getManager("some wallet id")) + when(wallets.getWallet"some wallet id")) .thenAnswer((realInvocation) => manager); when(manager.isFavorite).thenAnswer((realInvocation) => true); diff --git a/test/widget_tests/table_view/table_view_row_test.dart b/test/widget_tests/table_view/table_view_row_test.dart index a4ccbf7b3..2fd9180a7 100644 --- a/test/widget_tests/table_view/table_view_row_test.dart +++ b/test/widget_tests/table_view/table_view_row_test.dart @@ -59,7 +59,7 @@ void main() { ), ); - final manager = Manager(wallet); + final wallet = Manager(wallet); when(mockWallet.getWalletIdsFor(coin: Coin.bitcoin)) .thenAnswer((realInvocation) => ["Wallet id 1", "wallet id 2"]); diff --git a/test/widget_tests/transaction_card_test.dart b/test/widget_tests/transaction_card_test.dart index 80a6a9b0c..6342264ba 100644 --- a/test/widget_tests/transaction_card_test.dart +++ b/test/widget_tests/transaction_card_test.dart @@ -115,7 +115,7 @@ void main() { when(wallet.coin).thenAnswer((_) => Coin.firo); - when(wallets.getManager("wallet-id")) + when(wallets.getWallet"wallet-id")) .thenAnswer((realInvocation) => Manager(wallet)); when(wallet.storedChainHeight).thenAnswer((_) => 6000000); @@ -271,7 +271,7 @@ void main() { (_) => null, ); - when(wallets.getManager("wallet-id")) + when(wallets.getWallet"wallet-id")) .thenAnswer((realInvocation) => Manager(wallet)); // await tester.pumpWidget( @@ -400,7 +400,7 @@ void main() { when(wallet.coin).thenAnswer((_) => Coin.firo); - when(wallets.getManager("wallet-id")) + when(wallets.getWallet"wallet-id")) .thenAnswer((realInvocation) => Manager(wallet)); when(wallet.storedChainHeight).thenAnswer((_) => 6000000); @@ -535,7 +535,7 @@ void main() { when(wallet.coin).thenAnswer((_) => Coin.firo); - when(wallets.getManager("wallet id")) + when(wallets.getWallet"wallet id")) .thenAnswer((realInvocation) => Manager(wallet)); when(wallet.storedChainHeight).thenAnswer((_) => 6000000); diff --git a/test/widget_tests/wallet_card_test.dart b/test/widget_tests/wallet_card_test.dart index fec6f44f0..b5d239ba8 100644 --- a/test/widget_tests/wallet_card_test.dart +++ b/test/widget_tests/wallet_card_test.dart @@ -62,7 +62,7 @@ void main() { ); final wallets = MockWallets(); - final manager = Manager(wallet); + final wallet = Manager(wallet); mockito.when(wallets.getManagerProvider("wallet id")).thenAnswer( (realInvocation) => ChangeNotifierProvider((ref) => manager)); diff --git a/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.dart b/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.dart index f429500aa..930aebdfc 100644 --- a/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.dart +++ b/test/widget_tests/wallet_info_row/sub_widgets/wallet_info_row_balance_future_test.dart @@ -47,7 +47,7 @@ void main() { ), ); - final manager = Manager(wallet); + final wallet = Manager(wallet); when(wallets.getManagerProvider("some-wallet-id")).thenAnswer( (realInvocation) => ChangeNotifierProvider((ref) => manager)); diff --git a/test/widget_tests/wallet_info_row/wallet_info_row_test.dart b/test/widget_tests/wallet_info_row/wallet_info_row_test.dart index d7ab446d0..9cc0d6c40 100644 --- a/test/widget_tests/wallet_info_row/wallet_info_row_test.dart +++ b/test/widget_tests/wallet_info_row/wallet_info_row_test.dart @@ -58,7 +58,7 @@ void main() { ), ); - final manager = Manager(wallet); + final wallet = Manager(wallet); when(wallets.getManagerProvider("some-wallet-id")).thenAnswer( (realInvocation) => ChangeNotifierProvider((ref) => manager));