From 31224b637f96f995ff1508db5961e12c17721f78 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Fri, 20 Nov 2026 14:05:20 -0600 Subject: [PATCH 1/3] refactor: share Epic and MWC slatepack UI --- .../drivers/desktop_driver.dart | 15 +- lib/models/epic_slatepack_models.dart | 116 --- lib/models/mwc_slatepack_models.dart | 116 --- lib/models/slatepack_models.dart | 178 ++++ .../epic_finalize_view.dart | 338 ------- lib/pages/finalize_view/finalize_view.dart | 338 ------- lib/pages/receive_view/receive_view.dart | 188 +--- .../epic_slatepack_entry_dialog.dart | 219 ----- .../epic_slatepack_import_dialog.dart | 316 ------- .../mwc_slatepack_import_dialog.dart | 361 -------- .../sub_widgets/slatepack_entry_dialog.dart | 239 ++--- .../send_view/confirm_transaction_view.dart | 248 +----- lib/pages/send_view/send_view.dart | 399 +++------ .../sub_widgets/epic_slatepack_dialog.dart | 175 ---- .../sub_widgets/mwc_slatepack_dialog.dart | 214 ----- .../slatepack_cancel_transaction_dialog.dart | 56 ++ lib/pages/slatepack/slatepack_dialog.dart | 371 ++++++++ .../slatepack/slatepack_import_flow.dart | 486 ++++++++++ .../slatepack/slatepack_input_field.dart | 271 ++++++ lib/pages/slatepack/slatepack_popup.dart | 91 ++ lib/pages/slatepack/slatepack_qr.dart | 77 ++ lib/pages/slatepack/slatepack_send_flow.dart | 188 ++++ .../slatepack/slatepack_summary_dialog.dart | 109 +++ lib/pages/slatepack/slatepack_view.dart | 175 ++++ .../transaction_details_view.dart | 138 +-- .../tx_v2/transaction_v2_details_view.dart | 137 ++- lib/pages/wallet_view/wallet_view.dart | 40 +- .../sub_widgets/desktop_receive.dart | 490 +++------- .../wallet_view/sub_widgets/desktop_send.dart | 411 ++------- .../wallet_view/sub_widgets/my_wallet.dart | 23 +- .../ui/preview_tx_button_state_provider.dart | 102 +-- lib/route_generator.dart | 17 +- .../enums/epic_transaction_method.dart | 48 - .../enums/mwc_transaction_method.dart | 70 -- lib/utilities/enums/slatepack_method.dart | 23 + lib/utilities/exception_message.dart | 3 + lib/utilities/route_presentation.dart | 108 +++ lib/utilities/slatepack_terms.dart | 21 + lib/utilities/slatepack_text.dart | 21 + .../crypto_currency/coins/epiccash.dart | 15 +- .../coins/mimblewimblecoin.dart | 21 +- lib/wallets/wallet/impl/epiccash_wallet.dart | 219 ++--- .../wallet/impl/mimblewimblecoin_wallet.dart | 220 +++-- .../slatepack_interface.dart | 375 ++++++++ lib/widgets/epic_txs_method_toggle.dart | 67 -- lib/widgets/mwc_txs_method_toggle.dart | 67 -- lib/widgets/slatepack_method_toggle.dart | 71 ++ .../interfaces/libepiccash_interface.dart | 6 +- lib/wl_gen/interfaces/libmwc_interface.dart | 2 +- test/pages/send_view/send_views_test.dart | 49 + .../pages/send_view/support/fake_wallets.dart | 86 ++ .../send_view/support/send_view_cases.dart | 4 +- .../desktop_receive_slatepack_test.dart | 103 +++ ...tepack_cancel_transaction_dialog_test.dart | 154 ++++ .../slatepack/slatepack_dialog_test.dart | 310 +++++++ .../slatepack/slatepack_import_flow_test.dart | 843 ++++++++++++++++++ .../slatepack/slatepack_input_field_test.dart | 122 +++ test/pages/slatepack/slatepack_qr_test.dart | 84 ++ .../slatepack/slatepack_send_flow_test.dart | 358 ++++++++ test/pages/slatepack/slatepack_view_test.dart | 116 +++ test/utilities/route_presentation_test.dart | 89 ++ .../mimblewimble_slate_inspection_test.dart | 395 ++++++++ .../widgets/slatepack_method_toggle_test.dart | 70 ++ .../wallet_navigation_bar_item_test.dart | 54 ++ ...C_libepiccash_interface_impl.template.dart | 23 +- .../MWC_libmwc_interface_impl.template.dart | 17 +- 66 files changed, 6313 insertions(+), 4563 deletions(-) delete mode 100644 lib/models/epic_slatepack_models.dart delete mode 100644 lib/models/mwc_slatepack_models.dart create mode 100644 lib/models/slatepack_models.dart delete mode 100644 lib/pages/epic_finalize_view/epic_finalize_view.dart delete mode 100644 lib/pages/finalize_view/finalize_view.dart delete mode 100644 lib/pages/receive_view/sub_widgets/epic_slatepack_entry_dialog.dart delete mode 100644 lib/pages/receive_view/sub_widgets/epic_slatepack_import_dialog.dart delete mode 100644 lib/pages/receive_view/sub_widgets/mwc_slatepack_import_dialog.dart delete mode 100644 lib/pages/send_view/sub_widgets/epic_slatepack_dialog.dart delete mode 100644 lib/pages/send_view/sub_widgets/mwc_slatepack_dialog.dart create mode 100644 lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart create mode 100644 lib/pages/slatepack/slatepack_dialog.dart create mode 100644 lib/pages/slatepack/slatepack_import_flow.dart create mode 100644 lib/pages/slatepack/slatepack_input_field.dart create mode 100644 lib/pages/slatepack/slatepack_popup.dart create mode 100644 lib/pages/slatepack/slatepack_qr.dart create mode 100644 lib/pages/slatepack/slatepack_send_flow.dart create mode 100644 lib/pages/slatepack/slatepack_summary_dialog.dart create mode 100644 lib/pages/slatepack/slatepack_view.dart delete mode 100644 lib/utilities/enums/epic_transaction_method.dart delete mode 100644 lib/utilities/enums/mwc_transaction_method.dart create mode 100644 lib/utilities/enums/slatepack_method.dart create mode 100644 lib/utilities/exception_message.dart create mode 100644 lib/utilities/route_presentation.dart create mode 100644 lib/utilities/slatepack_terms.dart create mode 100644 lib/utilities/slatepack_text.dart create mode 100644 lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart delete mode 100644 lib/widgets/epic_txs_method_toggle.dart delete mode 100644 lib/widgets/mwc_txs_method_toggle.dart create mode 100644 lib/widgets/slatepack_method_toggle.dart create mode 100644 test/pages/slatepack/desktop_receive_slatepack_test.dart create mode 100644 test/pages/slatepack/slatepack_cancel_transaction_dialog_test.dart create mode 100644 test/pages/slatepack/slatepack_dialog_test.dart create mode 100644 test/pages/slatepack/slatepack_import_flow_test.dart create mode 100644 test/pages/slatepack/slatepack_input_field_test.dart create mode 100644 test/pages/slatepack/slatepack_qr_test.dart create mode 100644 test/pages/slatepack/slatepack_send_flow_test.dart create mode 100644 test/pages/slatepack/slatepack_view_test.dart create mode 100644 test/utilities/route_presentation_test.dart create mode 100644 test/wallets/mimblewimble_slate_inspection_test.dart create mode 100644 test/widgets/slatepack_method_toggle_test.dart create mode 100644 test/widgets/wallet_navigation_bar_item_test.dart diff --git a/integration_test/wallet_creation/drivers/desktop_driver.dart b/integration_test/wallet_creation/drivers/desktop_driver.dart index f70052bbde..09d5fced7c 100644 --- a/integration_test/wallet_creation/drivers/desktop_driver.dart +++ b/integration_test/wallet_creation/drivers/desktop_driver.dart @@ -8,7 +8,7 @@ import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub import 'package:stackwallet/pages_desktop_specific/password/create_password_view.dart'; import 'package:stackwallet/pages_desktop_specific/password/desktop_login_view.dart'; import 'package:stackwallet/wallets/wallet/wallet.dart'; -import 'package:stackwallet/widgets/mwc_txs_method_toggle.dart'; +import 'package:stackwallet/widgets/slatepack_method_toggle.dart'; import 'package:stackwallet/widgets/toggle.dart'; import 'package:stackwallet/widgets/wallet_card.dart'; @@ -92,16 +92,17 @@ class DesktopDriver extends PlatformDriver { ); final receive = find.byType(DesktopReceive); await ui.waitFor(receive); - final mwcMode = find.descendant( + final methodToggle = find.descendant( of: receive, - matching: find.byType(MwcTxsMethodToggle), + matching: find.byType(SlatepackMethodToggle), ); - if (mwcMode.evaluate().isNotEmpty) { + if (methodToggle.evaluate().isNotEmpty) { final toggle = ui.tester.widget( - find.descendant(of: mwcMode, matching: find.byType(Toggle)), + find.descendant(of: methodToggle, matching: find.byType(Toggle)), ); - // MWC defaults to Slatepack, which does not display the MQS address. - if (!toggle.isOn) await ui.tap(mwcMode); + // MWC defaults to manual Slatepack mode, where the MQS address is + // intentionally hidden. Switch to Automatic before checking it. + if (!toggle.isOn) await ui.tap(methodToggle); } await selectPrimaryAddress(wallet, receive); final displayed = find.descendant( diff --git a/lib/models/epic_slatepack_models.dart b/lib/models/epic_slatepack_models.dart deleted file mode 100644 index 6df4cc70cf..0000000000 --- a/lib/models/epic_slatepack_models.dart +++ /dev/null @@ -1,116 +0,0 @@ -class EpicSlatepackResult { - final bool success; - final String? error; - final String? slatepack; - final String? slateJson; - final bool? wasEncrypted; - final String? recipientAddress; - - EpicSlatepackResult({ - required this.success, - this.error, - this.slatepack, - this.slateJson, - this.wasEncrypted, - this.recipientAddress, - }); - - @override - String toString() { - return "EpicSlatepackResult(" - "success: $success, " - "error: $error, " - "slatepack: $slatepack, " - "slateJson: $slateJson, " - "wasEncrypted: $wasEncrypted, " - "recipientAddress: $recipientAddress" - ")"; - } -} - -class EpicSlatepackDecodeResult { - final bool success; - final String? error; - final String? slateJson; - final bool? wasEncrypted; - final String? senderAddress; - final String? recipientAddress; - - EpicSlatepackDecodeResult({ - required this.success, - this.error, - this.slateJson, - this.wasEncrypted, - this.senderAddress, - this.recipientAddress, - }); - - @override - String toString() { - return "EpicSlatepackDecodeResult(" - "success: $success, " - "error: $error, " - "slateJson: $slateJson, " - "wasEncrypted: $wasEncrypted, " - "senderAddress: $senderAddress, " - "recipientAddress: $recipientAddress" - ")"; - } -} - -class EpicReceiveResult { - final bool success; - final String? error; - final String? slateId; - final String? commitId; - final String? responseSlatepack; - final bool? wasEncrypted; - final String? recipientAddress; - - EpicReceiveResult({ - required this.success, - this.error, - this.slateId, - this.commitId, - this.responseSlatepack, - this.wasEncrypted, - this.recipientAddress, - }); - - @override - String toString() { - return "EpicReceiveResult(" - "success: $success, " - "error: $error, " - "slateId: $slateId, " - "commitId: $commitId, " - "responseSlatepack: $responseSlatepack, " - "wasEncrypted: $wasEncrypted, " - "recipientAddress: $recipientAddress" - ")"; - } -} - -class EpicFinalizeResult { - final bool success; - final String? error; - final String? slateId; - final String? commitId; - - EpicFinalizeResult({ - required this.success, - this.error, - this.slateId, - this.commitId, - }); - - @override - String toString() { - return "EpicFinalizeResult(" - "success: $success, " - "error: $error, " - "slateId: $slateId, " - "commitId: $commitId" - ")"; - } -} diff --git a/lib/models/mwc_slatepack_models.dart b/lib/models/mwc_slatepack_models.dart deleted file mode 100644 index 8b5c05b832..0000000000 --- a/lib/models/mwc_slatepack_models.dart +++ /dev/null @@ -1,116 +0,0 @@ -class SlatepackResult { - final bool success; - final String? error; - final String? slatepack; - final String? slateJson; - final bool? wasEncrypted; - final String? recipientAddress; - - SlatepackResult({ - required this.success, - this.error, - this.slatepack, - this.slateJson, - this.wasEncrypted, - this.recipientAddress, - }); - - @override - String toString() { - return "SlatepackResult(" - "success: $success, " - "error: $error, " - "slatepack: $slatepack, " - "slateJson: $slateJson, " - "wasEncrypted: $wasEncrypted, " - "recipientAddress: $recipientAddress" - ")"; - } -} - -class SlatepackDecodeResult { - final bool success; - final String? error; - final String? slateJson; - final bool? wasEncrypted; - final String? senderAddress; - final String? recipientAddress; - - SlatepackDecodeResult({ - required this.success, - this.error, - this.slateJson, - this.wasEncrypted, - this.senderAddress, - this.recipientAddress, - }); - - @override - String toString() { - return "SlatepackDecodeResult(" - "success: $success, " - "error: $error, " - "slateJson: $slateJson, " - "wasEncrypted: $wasEncrypted, " - "senderAddress: $senderAddress, " - "recipientAddress: $recipientAddress" - ")"; - } -} - -class ReceiveResult { - final bool success; - final String? error; - final String? slateId; - final String? commitId; - final String? responseSlatepack; - final bool? wasEncrypted; - final String? recipientAddress; - - ReceiveResult({ - required this.success, - this.error, - this.slateId, - this.commitId, - this.responseSlatepack, - this.wasEncrypted, - this.recipientAddress, - }); - - @override - String toString() { - return "ReceiveResult(" - "success: $success, " - "error: $error, " - "slateId: $slateId, " - "commitId: $commitId, " - "responseSlatepack: $responseSlatepack, " - "wasEncrypted: $wasEncrypted, " - "recipientAddress: $recipientAddress" - ")"; - } -} - -class FinalizeResult { - final bool success; - final String? error; - final String? slateId; - final String? commitId; - - FinalizeResult({ - required this.success, - this.error, - this.slateId, - this.commitId, - }); - - @override - String toString() { - return "FinalizeResult(" - "success: $success, " - "error: $error, " - "slateId: $slateId, " - "commitId: $commitId" - ")"; - } -} diff --git a/lib/models/slatepack_models.dart b/lib/models/slatepack_models.dart new file mode 100644 index 0000000000..c326908bba --- /dev/null +++ b/lib/models/slatepack_models.dart @@ -0,0 +1,178 @@ +import '../utilities/amount/amount.dart'; + +/// Where a slate is in its round trip. S is a standard send, I an invoice. +enum SlateState { + s1("S1"), + s2("S2"), + s3("S3"), + i1("I1"), + i2("I2"), + i3("I3"), + unknown("Unknown"); + + const SlateState(this.code); + + /// "S1", "I2" and so on, as libwallet names them. + final String code; + + bool get isInvoice => this == i1 || this == i2 || this == i3; + + static SlateState fromCode(String? code) { + final upper = code?.trim().toUpperCase(); + return values.firstWhere((e) => e.code == upper, orElse: () => unknown); + } +} + +/// What a wallet can tell about a slatepack without acting on it. +class SlateInspection { + const SlateInspection({ + required this.state, + required this.slateId, + this.slateJson, + this.amount, + this.fee, + this.senderAddress, + this.recipientAddress, + this.isEncrypted = false, + this.ttlCutoffHeight, + }); + + final SlateState state; + final String slateId; + + /// Decoded slate passed to receive/finalize so an armored Slatepack is not + /// decoded over FFI a second time. + final String? slateJson; + + /// Null when the slate does not carry it. Grin's S2 and I2 decode with 0; + /// look the amount up with localTxForSlate instead. + final Amount? amount; + final Amount? fee; + final String? senderAddress; + final String? recipientAddress; + final bool isEncrypted; + final int? ttlCutoffHeight; + + @override + String toString() { + return "SlateInspection(" + "state: ${state.code}, " + "slateId: $slateId, " + "amount: $amount, " + "fee: $fee, " + "senderAddress: $senderAddress, " + "recipientAddress: $recipientAddress, " + "isEncrypted: $isEncrypted, " + "ttlCutoffHeight: $ttlCutoffHeight" + ")"; + } +} + +class SlatepackResult { + final bool success; + final String? error; + final String? slatepack; + final String? slateJson; + final bool? wasEncrypted; + final String? recipientAddress; + final SlateState state; + final String? slateId; + final Amount? amount; + final Amount? fee; + + SlatepackResult({ + required this.success, + this.error, + this.slatepack, + this.slateJson, + this.wasEncrypted, + this.recipientAddress, + this.state = SlateState.unknown, + this.slateId, + this.amount, + this.fee, + }); + + @override + String toString() { + return "SlatepackResult(" + "success: $success, " + "error: $error, " + "slatepack: $slatepack, " + "slateJson: $slateJson, " + "wasEncrypted: $wasEncrypted, " + "recipientAddress: $recipientAddress, " + "state: ${state.code}, " + "slateId: $slateId, " + "amount: $amount, " + "fee: $fee" + ")"; + } +} + +enum SlatepackDecodeFailure { invalidInput, walletUnavailable } + +class SlatepackDecodeResult { + final bool success; + final String? slateJson; + final bool? wasEncrypted; + final String? senderAddress; + final String? recipientAddress; + final SlatepackDecodeFailure? failure; + + SlatepackDecodeResult({ + required this.success, + this.slateJson, + this.wasEncrypted, + this.senderAddress, + this.recipientAddress, + this.failure, + }); + + @override + String toString() { + return "SlatepackDecodeResult(" + "success: $success, " + "slateJson: $slateJson, " + "wasEncrypted: $wasEncrypted, " + "senderAddress: $senderAddress, " + "recipientAddress: $recipientAddress, " + "failure: $failure" + ")"; + } +} + +class FinalizeResult { + final bool success; + final String? error; + final String? slateId; + final String? commitId; + + /// Whether the finalized transaction reached the node. Null means the + /// installed native plugin predates explicit broadcast status reporting. + final bool? posted; + + /// Null for Epic Cash and MWC. + final String? kernelExcess; + + FinalizeResult({ + required this.success, + this.error, + this.slateId, + this.commitId, + this.posted, + this.kernelExcess, + }); + + @override + String toString() { + return "FinalizeResult(" + "success: $success, " + "error: $error, " + "slateId: $slateId, " + "commitId: $commitId, " + "posted: $posted, " + "kernelExcess: $kernelExcess" + ")"; + } +} diff --git a/lib/pages/epic_finalize_view/epic_finalize_view.dart b/lib/pages/epic_finalize_view/epic_finalize_view.dart deleted file mode 100644 index 13abb38d6e..0000000000 --- a/lib/pages/epic_finalize_view/epic_finalize_view.dart +++ /dev/null @@ -1,338 +0,0 @@ -/* - * 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 2026-01-12 - * - */ - -import 'dart:async'; - -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../../notifications/show_flush_bar.dart'; -import '../../providers/global/barcode_scanner_provider.dart'; -import '../../providers/global/wallets_provider.dart'; -import '../../themes/stack_colors.dart'; -import '../../utilities/barcode_scanner_interface.dart'; -import '../../utilities/clipboard_interface.dart'; -import '../../utilities/constants.dart'; -import '../../utilities/logger.dart'; -import '../../utilities/show_loading.dart'; -import '../../utilities/text_styles.dart'; -import '../../utilities/util.dart'; -import '../../wallets/wallet/impl/epiccash_wallet.dart'; -import '../../widgets/background.dart'; -import '../../widgets/conditional_parent.dart'; -import '../../widgets/custom_buttons/app_bar_icon_button.dart'; -import '../../widgets/desktop/primary_button.dart'; -import '../../widgets/icon_widgets/clipboard_icon.dart'; -import '../../widgets/icon_widgets/qrcode_icon.dart'; -import '../../widgets/icon_widgets/x_icon.dart'; -import '../../widgets/stack_dialog.dart'; -import '../../widgets/stack_text_field.dart'; -import '../../widgets/textfield_icon_button.dart'; - -class EpicFinalizeView extends ConsumerStatefulWidget { - const EpicFinalizeView({ - super.key, - required this.walletId, - this.clipboard = const ClipboardWrapper(), - }); - - static const String routeName = "/epicFinalizeView"; - - final String walletId; - final ClipboardInterface clipboard; - - @override - ConsumerState createState() => _EpicFinalizeViewState(); -} - -class _EpicFinalizeViewState extends ConsumerState { - late final TextEditingController _slateController; - late final FocusNode _slateFocusNode; - - bool _slateToggleFlag = false; - - Future _pasteSlatepack() async { - final ClipboardData? data = await widget.clipboard.getData( - Clipboard.kTextPlain, - ); - if (data?.text != null && data!.text!.isNotEmpty) { - _slateController.text = data.text!; - setState(() { - _slateToggleFlag = _slateController.text.isNotEmpty; - }); - } - } - - Future _scanQr() async { - try { - if (!Util.isDesktop && _slateFocusNode.hasFocus) { - _slateFocusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); - } - - if (mounted) { - final qrResult = await ref.read(pBarcodeScanner).scan(context: context); - if (qrResult.rawContent != null && qrResult.rawContent!.isNotEmpty) { - _slateController.text = qrResult.rawContent!; - setState(() { - _slateToggleFlag = _slateController.text.isNotEmpty; - }); - } - } - } on PlatformException catch (e, s) { - if (mounted) { - try { - await checkCamPermDeniedMobileAndOpenAppSettings( - context, - logging: Logging.instance, - ); - } catch (e, s) { - Logging.instance.e( - "Failed to check cam permissions", - error: e, - stackTrace: s, - ); - } - } else { - Logging.instance.e( - "Failed to get camera permissions while trying to scan qr code in SendView: ", - error: e, - stackTrace: s, - ); - } - } - } - - Future _finalize() async { - // add delay for showloading exception catching hack fix - await Future.delayed(const Duration(seconds: 1)); - - final wallet = - ref.read(pWallets).getWallet(widget.walletId) as EpiccashWallet; - - final decoded = await wallet.decodeSlatepack(_slateController.text); - if (!decoded.success) { - throw Exception(decoded.error ?? "Failed to decode slate"); - } - - final analysis = await wallet.analyzeSlatepack(_slateController.text); - if (analysis.status != "S2") { - throw Exception("Invalid slate type: ${analysis.status}"); - } - - final result = await wallet.finalizeSlatepack(_slateController.text); - - if (!result.success) { - throw Exception( - result.error ?? "Finalize failed without providing an error???", - ); - } - } - - Future _finalizePressed() async { - if (!Util.isDesktop && _slateFocusNode.hasFocus) { - _slateFocusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); - } - if (mounted) { - Exception? ex; - await showLoading( - whileFuture: _finalize(), - context: context, - message: "Finalizing slate...", - rootNavigator: Util.isDesktop, - onException: (e) => ex = e, - ); - - if (mounted) { - if (ex != null) { - await showDialog( - context: context, - builder: (context) => StackOkDialog( - desktopPopRootNavigator: Util.isDesktop, - title: "Slate finalize error", - message: ex?.toString() ?? "Unexpected result without exception", - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - } else { - setState(() { - _slateController.text = ""; - }); - unawaited( - showFloatingFlushBar( - type: FlushBarType.success, - message: "Transaction finalized and broadcast successfully!", - context: context, - ), - ); - } - } - } - } - - @override - void initState() { - super.initState(); - _slateController = TextEditingController(); - _slateFocusNode = FocusNode(); - } - - @override - void dispose() { - _slateController.dispose(); - _slateFocusNode.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - debugPrint("BUILD: $runtimeType"); - - return ConditionalParent( - condition: !Util.isDesktop, - builder: (child) => Background( - child: Scaffold( - backgroundColor: Theme.of( - context, - ).extension()!.background, - appBar: AppBar( - leading: AppBarBackButton( - onPressed: () { - Navigator.of(context).pop(); - }, - ), - title: Text( - "Finalize slate", - style: STextStyles.navBarTitle(context), - ), - ), - body: SafeArea( - child: LayoutBuilder( - builder: (context, constraints) { - return SingleChildScrollView( - child: ConstrainedBox( - constraints: BoxConstraints( - minHeight: constraints.maxHeight, - ), - child: IntrinsicHeight( - child: Padding( - padding: EdgeInsets.symmetric( - horizontal: Constants.size.standardPadding, - ), - child: child, - ), - ), - ), - ); - }, - ), - ), - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - ClipRRect( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - child: TextField( - minLines: 1, - maxLines: 5, - key: const Key("epicFinalizeSlateFieldKey"), - controller: _slateController, - readOnly: false, - autocorrect: false, - enableSuggestions: false, - toolbarOptions: const ToolbarOptions( - copy: false, - cut: false, - paste: true, - selectAll: false, - ), - onChanged: (newValue) { - setState(() { - _slateToggleFlag = newValue.isNotEmpty; - }); - }, - focusNode: _slateFocusNode, - style: STextStyles.field(context), - decoration: - standardInputDecoration( - "Enter Response Slate JSON", - _slateFocusNode, - context, - desktopMed: true, - ).copyWith( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: - 12, // Adjust vertical padding for better alignment - ), - suffixIcon: Padding( - padding: _slateController.text.isEmpty - ? const EdgeInsets.only(right: 8) - : const EdgeInsets.only(right: 0), - child: UnconstrainedBox( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - _slateToggleFlag - ? TextFieldIconButton( - key: const Key( - "epicSlateFinalizeClearFieldButtonKey", - ), - onTap: () { - _slateController.text = ""; - setState(() { - _slateToggleFlag = false; - }); - }, - child: const XIcon(), - ) - : TextFieldIconButton( - key: const Key( - "epicSlateFinalizePasteFieldButtonKey", - ), - onTap: _pasteSlatepack, - child: _slateController.text.isEmpty - ? const ClipboardIcon() - : const XIcon(), - ), - if (_slateController.text.isEmpty) - TextFieldIconButton( - semanticsLabel: - "Scan QR Button. Opens Camera For Scanning QR Code.", - key: const Key("sendViewScanQrButtonKey"), - onTap: _scanQr, - child: const QrCodeIcon(), - ), - ], - ), - ), - ), - ), - ), - ), - Util.isDesktop ? const SizedBox(height: 24) : const Spacer(), - PrimaryButton( - label: "Finalize Slate", - enabled: _slateToggleFlag, - onPressed: _slateToggleFlag ? _finalizePressed : null, - ), - - if (!Util.isDesktop) SizedBox(height: Constants.size.standardPadding), - ], - ), - ); - } -} diff --git a/lib/pages/finalize_view/finalize_view.dart b/lib/pages/finalize_view/finalize_view.dart deleted file mode 100644 index 65fb50a1be..0000000000 --- a/lib/pages/finalize_view/finalize_view.dart +++ /dev/null @@ -1,338 +0,0 @@ -/* - * 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 'dart:async'; - -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../../notifications/show_flush_bar.dart'; -import '../../providers/global/barcode_scanner_provider.dart'; -import '../../providers/global/wallets_provider.dart'; -import '../../themes/stack_colors.dart'; -import '../../utilities/barcode_scanner_interface.dart'; -import '../../utilities/clipboard_interface.dart'; -import '../../utilities/constants.dart'; -import '../../utilities/logger.dart'; -import '../../utilities/show_loading.dart'; -import '../../utilities/text_styles.dart'; -import '../../utilities/util.dart'; -import '../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; -import '../../widgets/background.dart'; -import '../../widgets/conditional_parent.dart'; -import '../../widgets/custom_buttons/app_bar_icon_button.dart'; -import '../../widgets/desktop/primary_button.dart'; -import '../../widgets/icon_widgets/clipboard_icon.dart'; -import '../../widgets/icon_widgets/qrcode_icon.dart'; -import '../../widgets/icon_widgets/x_icon.dart'; -import '../../widgets/stack_dialog.dart'; -import '../../widgets/stack_text_field.dart'; -import '../../widgets/textfield_icon_button.dart'; - -class FinalizeView extends ConsumerStatefulWidget { - const FinalizeView({ - super.key, - required this.walletId, - this.clipboard = const ClipboardWrapper(), - }); - - static const String routeName = "/finalizeView"; - - final String walletId; - final ClipboardInterface clipboard; - - @override - ConsumerState createState() => _FinalizeViewState(); -} - -class _FinalizeViewState extends ConsumerState { - late final TextEditingController _slateController; - late final FocusNode _slateFocusNode; - - bool _slateToggleFlag = false; - - Future _pasteSlatepack() async { - final ClipboardData? data = await widget.clipboard.getData( - Clipboard.kTextPlain, - ); - if (data?.text != null && data!.text!.isNotEmpty) { - _slateController.text = data.text!; - setState(() { - _slateToggleFlag = _slateController.text.isNotEmpty; - }); - } - } - - Future _scanQr() async { - try { - if (!Util.isDesktop && _slateFocusNode.hasFocus) { - _slateFocusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); - } - - if (mounted) { - final qrResult = await ref.read(pBarcodeScanner).scan(context: context); - if (qrResult.rawContent != null && qrResult.rawContent!.isNotEmpty) { - _slateController.text = qrResult.rawContent!; - setState(() { - _slateToggleFlag = _slateController.text.isNotEmpty; - }); - } - } - } on PlatformException catch (e, s) { - if (mounted) { - try { - await checkCamPermDeniedMobileAndOpenAppSettings( - context, - logging: Logging.instance, - ); - } catch (e, s) { - Logging.instance.e( - "Failed to check cam permissions", - error: e, - stackTrace: s, - ); - } - } else { - Logging.instance.e( - "Failed to get camera permissions while trying to scan qr code in SendView: ", - error: e, - stackTrace: s, - ); - } - } - } - - Future _finalize() async { - // add delay for showloading exception catching hack fix - await Future.delayed(const Duration(seconds: 1)); - - final wallet = - ref.read(pWallets).getWallet(widget.walletId) as MimblewimblecoinWallet; - - final decoded = await wallet.decodeSlatepack(_slateController.text); - if (!decoded.success) { - throw Exception(decoded.error ?? "Failed to decode slatepack"); - } - - final analysis = await wallet.analyzeSlatepack(_slateController.text); - if (analysis.status != "S2") { - throw Exception("Invalid slatepack type: ${analysis.status}"); - } - - final result = await wallet.finalizeSlatepack(_slateController.text); - - if (!result.success) { - throw Exception( - result.error ?? "Finalize failed without providing an error???", - ); - } - } - - Future _finalizePressed() async { - if (!Util.isDesktop && _slateFocusNode.hasFocus) { - _slateFocusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); - } - if (mounted) { - Exception? ex; - await showLoading( - whileFuture: _finalize(), - context: context, - message: "Finalizing slatepack...", - rootNavigator: Util.isDesktop, - onException: (e) => ex = e, - ); - - if (mounted) { - if (ex != null) { - await showDialog( - context: context, - builder: (context) => StackOkDialog( - desktopPopRootNavigator: Util.isDesktop, - title: "Slatepack finalize error", - message: ex?.toString() ?? "Unexpected result without exception", - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - } else { - setState(() { - _slateController.text = ""; - }); - unawaited( - showFloatingFlushBar( - type: FlushBarType.success, - message: "Transaction finalized and broadcast successfully!", - context: context, - ), - ); - } - } - } - } - - @override - void initState() { - super.initState(); - _slateController = TextEditingController(); - _slateFocusNode = FocusNode(); - } - - @override - void dispose() { - _slateController.dispose(); - _slateFocusNode.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - debugPrint("BUILD: $runtimeType"); - - return ConditionalParent( - condition: !Util.isDesktop, - builder: (child) => Background( - child: Scaffold( - backgroundColor: Theme.of( - context, - ).extension()!.background, - appBar: AppBar( - leading: AppBarBackButton( - onPressed: () { - Navigator.of(context).pop(); - }, - ), - title: Text( - "Finalize slatepack", - style: STextStyles.navBarTitle(context), - ), - ), - body: SafeArea( - child: LayoutBuilder( - builder: (context, constraints) { - return SingleChildScrollView( - child: ConstrainedBox( - constraints: BoxConstraints( - minHeight: constraints.maxHeight, - ), - child: IntrinsicHeight( - child: Padding( - padding: EdgeInsets.symmetric( - horizontal: Constants.size.standardPadding, - ), - child: child, - ), - ), - ), - ); - }, - ), - ), - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - ClipRRect( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - child: TextField( - minLines: 1, - maxLines: 5, - key: const Key("finalizeSlatepackFieldKey"), - controller: _slateController, - readOnly: false, - autocorrect: false, - enableSuggestions: false, - toolbarOptions: const ToolbarOptions( - copy: false, - cut: false, - paste: true, - selectAll: false, - ), - onChanged: (newValue) { - setState(() { - _slateToggleFlag = newValue.isNotEmpty; - }); - }, - focusNode: _slateFocusNode, - style: STextStyles.field(context), - decoration: - standardInputDecoration( - "Enter Final Slatepack Message", - _slateFocusNode, - context, - desktopMed: true, - ).copyWith( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: - 12, // Adjust vertical padding for better alignment - ), - suffixIcon: Padding( - padding: _slateController.text.isEmpty - ? const EdgeInsets.only(right: 8) - : const EdgeInsets.only(right: 0), - child: UnconstrainedBox( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - _slateToggleFlag - ? TextFieldIconButton( - key: const Key( - "slateFinalizeClearFieldButtonKey", - ), - onTap: () { - _slateController.text = ""; - setState(() { - _slateToggleFlag = false; - }); - }, - child: const XIcon(), - ) - : TextFieldIconButton( - key: const Key( - "slateFinalizePasteFieldButtonKey", - ), - onTap: _pasteSlatepack, - child: _slateController.text.isEmpty - ? const ClipboardIcon() - : const XIcon(), - ), - if (_slateController.text.isEmpty) - TextFieldIconButton( - semanticsLabel: - "Scan QR Button. Opens Camera For Scanning QR Code.", - key: const Key("sendViewScanQrButtonKey"), - onTap: _scanQr, - child: const QrCodeIcon(), - ), - ], - ), - ), - ), - ), - ), - ), - Util.isDesktop ? const SizedBox(height: 24) : const Spacer(), - PrimaryButton( - label: "Finalize Slatepack", - enabled: _slateToggleFlag, - onPressed: _slateToggleFlag ? _finalizePressed : null, - ), - - if (!Util.isDesktop) SizedBox(height: Constants.size.standardPadding), - ], - ), - ); - } -} diff --git a/lib/pages/receive_view/receive_view.dart b/lib/pages/receive_view/receive_view.dart index 61f8ae5fbe..51875505eb 100644 --- a/lib/pages/receive_view/receive_view.dart +++ b/lib/pages/receive_view/receive_view.dart @@ -29,17 +29,17 @@ import '../../utilities/clipboard_interface.dart'; import '../../utilities/constants.dart'; import '../../utilities/enums/derive_path_type_enum.dart'; import '../../utilities/show_loading.dart'; +import '../../utilities/slatepack_terms.dart'; import '../../utilities/text_styles.dart'; import '../../wallets/crypto_currency/crypto_currency.dart'; import '../../wallets/isar/providers/wallet_info_provider.dart'; import '../../wallets/wallet/impl/bitcoin_wallet.dart'; -import '../../wallets/wallet/impl/epiccash_wallet.dart'; -import '../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../wallets/wallet/intermediate/bip39_hd_wallet.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/bcash_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/extended_keys_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/multi_address_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/view_only_option_interface.dart'; import '../../widgets/background.dart'; @@ -49,15 +49,11 @@ import '../../widgets/custom_buttons/blue_text_button.dart'; import '../../widgets/custom_loading_overlay.dart'; import '../../widgets/desktop/primary_button.dart'; import '../../widgets/desktop/secondary_button.dart'; -import '../../widgets/dialogs/s_dialog.dart'; import '../../widgets/qr.dart'; import '../../widgets/rounded_white_container.dart'; -import '../../widgets/stack_dialog.dart'; import 'addresses/wallet_addresses_view.dart'; import 'generate_receiving_uri_qr_code_view.dart'; -import 'sub_widgets/epic_slatepack_entry_dialog.dart'; -import 'sub_widgets/epic_slatepack_import_dialog.dart'; -import 'sub_widgets/mwc_slatepack_import_dialog.dart'; +import '../slatepack/slatepack_import_flow.dart'; import 'sub_widgets/slatepack_entry_dialog.dart'; class ReceiveView extends ConsumerStatefulWidget { @@ -85,6 +81,7 @@ class _ReceiveViewState extends ConsumerState { late final bool _supportsSpark; late final bool _showMultiType; late bool supportsMweb; + SlatepackTerms? _slatepackTerms; int _currentIndex = 0; @@ -93,125 +90,16 @@ class _ReceiveViewState extends ConsumerState { final Map> _addressSubMap = {}; Future _importSlatepack() async { - final slatepackString = await showDialog( - context: context, - builder: (context) => const SlatepackEntryDialog(), - ); - - if (slatepackString == null) return; - if (mounted) { - final wallet = - ref.read(pWallets).getWallet(walletId) as MimblewimblecoinWallet; - - Exception? ex; - final result = await showLoading( - whileFuture: wallet.fullDecodeSlatepack(slatepackString), - context: context, - message: "Decoding slatepack...", - onException: (e) => ex = e, - ); - - if (result == null || ex != null) { - if (mounted) { - await showDialog( - context: context, - builder: (context) => StackOkDialog( - title: "Slatepack receive error", - message: ex?.toString() ?? "Unexpected result without exception", - ), - ); - } - return; - } + final wallet = ref.read(pWallets).getWallet(walletId) as SlatepackInterface; - if (mounted) { - final response = - await showDialog<({String responseSlatepack, bool wasEncrypted})>( - context: context, - builder: (context) => SDialog( - child: MwcSlatepackImportDialog( - walletId: widget.walletId, - clipboard: widget.clipboard, - rawSlatepack: result.raw, - decoded: result.result, - slatepackType: result.type, - ), - ), - ); - - if (mounted && response != null) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => SlatepackResponseDialog( - responseSlatepack: response.responseSlatepack, - wasEncrypted: response.wasEncrypted, - ), - ); - } - } - } - } - - Future _importEpicSlatepack() async { - final slatepackString = await showDialog( + final text = await showSlatepackEntryDialog( context: context, - builder: (context) => const EpicSlatepackEntryDialog(), + terms: wallet.slatepackTerms, + clipboard: widget.clipboard, ); + if (text == null || text.trim().isEmpty || !mounted) return; - if (slatepackString == null) return; - if (mounted) { - final wallet = - ref.read(pWallets).getWallet(walletId) as EpiccashWallet; - - Exception? ex; - final result = await showLoading( - whileFuture: wallet.fullDecodeSlatepack(slatepackString), - context: context, - message: "Decoding slate...", - onException: (e) => ex = e, - ); - - if (result == null || ex != null) { - if (mounted) { - await showDialog( - context: context, - builder: (context) => StackOkDialog( - title: "Slate receive error", - message: ex?.toString() ?? "Unexpected result without exception", - ), - ); - } - return; - } - - if (mounted) { - final response = - await showDialog<({String responseSlatepack, bool wasEncrypted})>( - context: context, - builder: (context) => SDialog( - child: EpicSlatepackImportDialog( - walletId: widget.walletId, - clipboard: widget.clipboard, - rawSlatepack: result.raw, - decoded: result.result, - slatepackType: result.type, - ), - ), - ); - - if (mounted && response != null) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => EpicSlatepackResponseDialog( - responseSlatepack: response.responseSlatepack, - wasEncrypted: response.wasEncrypted, - ), - ); - } - } - } + await SlatepackImportFlow.run(context: context, wallet: wallet, text: text); } Future generateNewAddress() async { @@ -226,9 +114,10 @@ class _ReceiveViewState extends ConsumerState { return WillPopScope( onWillPop: () async => shouldPop, child: Container( - color: Theme.of( - context, - ).extension()!.overlay.withOpacity(0.5), + color: Theme.of(context) + .extension()! + .overlay + .withOpacity(0.5), child: const CustomLoadingOverlay( message: "Generating address", eventBus: null, @@ -285,9 +174,8 @@ class _ReceiveViewState extends ConsumerState { shouldPop = true; if (mounted) { - Navigator.of( - context, - ).popUntil(ModalRoute.withName(ReceiveView.routeName)); + Navigator.of(context) + .popUntil(ModalRoute.withName(ReceiveView.routeName)); setState(() { _addressMap[_walletAddressTypes[_currentIndex]] = @@ -308,9 +196,10 @@ class _ReceiveViewState extends ConsumerState { return WillPopScope( onWillPop: () async => shouldPop, child: Container( - color: Theme.of( - context, - ).extension()!.overlay.withOpacity(0.5), + color: Theme.of(context) + .extension()! + .overlay + .withOpacity(0.5), child: const CustomLoadingOverlay( message: "Generating address", eventBus: null, @@ -392,6 +281,9 @@ class _ReceiveViewState extends ConsumerState { clipboard = widget.clipboard; final wallet = ref.read(pWallets).getWallet(walletId); _supportsSpark = wallet is SparkInterface; + if (wallet is SlatepackInterface) { + _slatepackTerms = wallet.slatepackTerms; + } supportsMweb = wallet is MwebInterface && !wallet.info.isViewOnly && @@ -553,17 +445,16 @@ class _ReceiveViewState extends ConsumerState { child: AspectRatio( aspectRatio: 1, child: AppBarIconButton( - semanticsLabel: - "Address List Pop-up Button. Opens A Pop-up For Address List Button.", + semanticsLabel: "Address List Pop-up Button. Opens A Pop-up For Address List Button.", key: const Key("walletNetworkSettingsAddNewNodeViewButton"), size: 36, shadows: const [], color: Theme.of(context).extension()!.background, icon: SvgPicture.asset( Assets.svg.verticalEllipsis, - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, width: 20, height: 20, ), @@ -580,9 +471,9 @@ class _ReceiveViewState extends ConsumerState { right: 10, child: Container( decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.popupBG, + color: Theme.of(context) + .extension()! + .popupBG, borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, ), @@ -651,9 +542,9 @@ class _ReceiveViewState extends ConsumerState { Text( "Address type", style: STextStyles.w500_14(context).copyWith( - color: Theme.of( - context, - ).extension()!.infoItemLabel, + color: Theme.of(context) + .extension()! + .infoItemLabel, ), ), const SizedBox(height: 10), @@ -820,22 +711,13 @@ class _ReceiveViewState extends ConsumerState { ? generateNewSparkAddress : generateNewAddress, ), - // MWC Slatepack import button. - if (coin is Mimblewimblecoin) ...[ + if (_slatepackTerms != null) ...[ const SizedBox(height: 12), SecondaryButton( - label: "Import Slatepack", + label: "Import ${_slatepackTerms!.title}", onPressed: _importSlatepack, ), ], - // Epic Cash Slate import button. - if (coin is Epiccash) ...[ - const SizedBox(height: 12), - SecondaryButton( - label: "Import Slate", - onPressed: _importEpicSlatepack, - ), - ], const SizedBox(height: 30), RoundedWhiteContainer( child: Padding( diff --git a/lib/pages/receive_view/sub_widgets/epic_slatepack_entry_dialog.dart b/lib/pages/receive_view/sub_widgets/epic_slatepack_entry_dialog.dart deleted file mode 100644 index c3583e7c49..0000000000 --- a/lib/pages/receive_view/sub_widgets/epic_slatepack_entry_dialog.dart +++ /dev/null @@ -1,219 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../../../providers/global/barcode_scanner_provider.dart'; -import '../../../themes/stack_colors.dart'; -import '../../../utilities/barcode_scanner_interface.dart'; -import '../../../utilities/clipboard_interface.dart'; -import '../../../utilities/constants.dart'; -import '../../../utilities/logger.dart'; -import '../../../utilities/text_styles.dart'; -import '../../../widgets/desktop/primary_button.dart'; -import '../../../widgets/desktop/secondary_button.dart'; -import '../../../widgets/icon_widgets/clipboard_icon.dart'; -import '../../../widgets/icon_widgets/qrcode_icon.dart'; -import '../../../widgets/icon_widgets/x_icon.dart'; -import '../../../widgets/stack_dialog.dart'; -import '../../../widgets/stack_text_field.dart'; -import '../../../widgets/textfield_icon_button.dart'; - -class EpicSlatepackEntryDialog extends ConsumerStatefulWidget { - const EpicSlatepackEntryDialog({ - super.key, - this.clipboard = const ClipboardWrapper(), - }); - - final ClipboardInterface clipboard; - - @override - ConsumerState createState() => - _EpicSlatepackEntryDialogState(); -} - -class _EpicSlatepackEntryDialogState extends ConsumerState { - final _receiveSlateController = TextEditingController(); - final _slateFocusNode = FocusNode(); - - bool _slateToggleFlag = false; - - Future _pasteSlatepack() async { - final ClipboardData? data = await widget.clipboard.getData( - Clipboard.kTextPlain, - ); - if (data?.text != null && data!.text!.isNotEmpty) { - _receiveSlateController.text = data.text!; - setState(() { - _slateToggleFlag = _receiveSlateController.text.isNotEmpty; - }); - } - } - - Future _scanQr() async { - try { - if (_slateFocusNode.hasFocus) { - _slateFocusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); - } - - if (mounted) { - final qrResult = await ref.read(pBarcodeScanner).scan(context: context); - if (qrResult.rawContent != null && qrResult.rawContent!.isNotEmpty) { - _receiveSlateController.text = qrResult.rawContent!; - setState(() { - _slateToggleFlag = _receiveSlateController.text.isNotEmpty; - }); - } - } - } on PlatformException catch (e, s) { - if (mounted) { - try { - await checkCamPermDeniedMobileAndOpenAppSettings( - context, - logging: Logging.instance, - ); - } catch (e, s) { - Logging.instance.e( - "Failed to check cam permissions", - error: e, - stackTrace: s, - ); - } - } else { - Logging.instance.e( - "Failed to get camera permissions while trying to scan qr code in SendView: ", - error: e, - stackTrace: s, - ); - } - } - } - - @override - void dispose() { - _receiveSlateController.dispose(); - _slateFocusNode.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return StackDialogBase( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - "Receive Slate", - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textFieldActiveSearchIconRight, - ), - textAlign: TextAlign.left, - ), - const SizedBox(height: 12), - ClipRRect( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - child: TextField( - minLines: 1, - maxLines: 5, - key: const Key("receiveViewEpicSlateFieldKey"), - controller: _receiveSlateController, - readOnly: false, - autocorrect: false, - enableSuggestions: false, - toolbarOptions: const ToolbarOptions( - copy: false, - cut: false, - paste: true, - selectAll: false, - ), - onChanged: (newValue) { - setState(() { - _slateToggleFlag = newValue.isNotEmpty; - }); - }, - focusNode: _slateFocusNode, - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textFieldActiveText, - height: 1.8, - ), - decoration: - standardInputDecoration( - "Enter Slate JSON", - _slateFocusNode, - context, - desktopMed: true, - ).copyWith( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: - 12, // Adjust vertical padding for better alignment - ), - suffixIcon: Padding( - padding: _receiveSlateController.text.isEmpty - ? const EdgeInsets.only(right: 8) - : const EdgeInsets.only(right: 0), - child: UnconstrainedBox( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - _slateToggleFlag - ? TextFieldIconButton( - key: const Key( - "receiveViewClearEpicSlateFieldButtonKey", - ), - onTap: () { - _receiveSlateController.text = ""; - setState(() { - _slateToggleFlag = false; - }); - }, - child: const XIcon(), - ) - : TextFieldIconButton( - key: const Key( - "receiveViewPasteEpicSlateFieldButtonKey", - ), - onTap: _pasteSlatepack, - child: _receiveSlateController.text.isEmpty - ? const ClipboardIcon() - : const XIcon(), - ), - if (_receiveSlateController.text.isEmpty) - TextFieldIconButton( - semanticsLabel: - "Scan QR Button. Opens Camera For Scanning QR Code.", - key: const Key("sendViewScanQrButtonKey"), - onTap: _scanQr, - child: const QrCodeIcon(), - ), - ], - ), - ), - ), - ), - ), - ), - const SizedBox(height: 16), - PrimaryButton( - label: "Import", - enabled: _slateToggleFlag, - onPressed: !_slateToggleFlag - ? null - : () => Navigator.of(context).pop(_receiveSlateController.text), - ), - const SizedBox(height: 16), - SecondaryButton( - label: "Cancel", - onPressed: Navigator.of(context).pop, - ), - ], - ), - ); - } -} diff --git a/lib/pages/receive_view/sub_widgets/epic_slatepack_import_dialog.dart b/lib/pages/receive_view/sub_widgets/epic_slatepack_import_dialog.dart deleted file mode 100644 index 769a58a94f..0000000000 --- a/lib/pages/receive_view/sub_widgets/epic_slatepack_import_dialog.dart +++ /dev/null @@ -1,316 +0,0 @@ -import 'dart:convert'; - -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../../../models/epic_slatepack_models.dart'; -import '../../../providers/global/wallets_provider.dart'; -import '../../../themes/stack_colors.dart'; -import '../../../utilities/amount/amount.dart'; -import '../../../utilities/amount/amount_formatter.dart'; -import '../../../utilities/clipboard_interface.dart'; -import '../../../utilities/show_loading.dart'; -import '../../../utilities/text_styles.dart'; -import '../../../utilities/util.dart'; -import '../../../wallets/isar/providers/wallet_info_provider.dart'; -import '../../../wallets/wallet/impl/epiccash_wallet.dart'; -import '../../../widgets/conditional_parent.dart'; -import '../../../widgets/custom_buttons/simple_copy_button.dart'; -import '../../../widgets/desktop/desktop_dialog_close_button.dart'; -import '../../../widgets/desktop/primary_button.dart'; -import '../../../widgets/desktop/secondary_button.dart'; -import '../../../widgets/detail_item.dart'; -import '../../../widgets/dialogs/s_dialog.dart'; -import '../../../widgets/rounded_white_container.dart'; -import '../../../widgets/stack_dialog.dart'; - -class EpicSlatepackImportDialog extends ConsumerStatefulWidget { - const EpicSlatepackImportDialog({ - super.key, - required this.walletId, - required this.rawSlatepack, - required this.decoded, - required this.slatepackType, - this.clipboard = const ClipboardWrapper(), - }); - - final String walletId; - final String rawSlatepack; - final EpicSlatepackDecodeResult decoded; - final String slatepackType; - final ClipboardInterface clipboard; - - @override - ConsumerState createState() => - _EpicSlatepackImportDialogState(); -} - -class _EpicSlatepackImportDialogState - extends ConsumerState { - Future<({String responseSlatepack, bool wasEncrypted})> - _processSlatepack() async { - // add delay for showloading exception catching hack fix - await Future.delayed(const Duration(seconds: 1)); - - final wallet = - ref.read(pWallets).getWallet(widget.walletId) as EpiccashWallet; - - // Determine action based on slatepack type. - if (widget.slatepackType.contains("S1")) { - // This is an initial slatepack - receive it and create response. - final result = await wallet.receiveSlatepack(widget.rawSlatepack); - - if (result.success && result.responseSlatepack != null) { - return ( - responseSlatepack: result.responseSlatepack!, - wasEncrypted: result.wasEncrypted ?? false, - ); - } else { - throw Exception(result.error ?? 'Failed to process slatepack'); - } - } else { - throw Exception('Unsupported slatepack type: ${widget.slatepackType}'); - } - } - - Future _processPressed() async { - Exception? ex; - final result = await showLoading( - whileFuture: _processSlatepack(), - context: context, - message: "Processing slate...", - onException: (e) => ex = e, - ); - - if (result == null || ex != null) { - if (mounted) { - await showDialog( - context: context, - useRootNavigator: true, - builder: - (context) => StackOkDialog( - desktopPopRootNavigator: true, - maxWidth: Util.isDesktop ? 400 : null, - title: "Slate receive error", - message: - ex?.toString() ?? "Unexpected result without exception", - ), - ); - } - return; - } - - if (mounted) { - Navigator.of(context).pop(result); - } - } - - late final Amount? _amount; - - @override - void initState() { - final map = jsonDecode(widget.decoded.slateJson!) as Map; - - final rawAmount = BigInt.tryParse(map["amount"].toString()); - _amount = - rawAmount == null - ? null - : Amount( - rawValue: rawAmount, - fractionDigits: - ref.read(pWalletCoin(widget.walletId)).fractionDigits, - ); - - super.initState(); - } - - @override - Widget build(BuildContext context) { - final isDesktop = Util.isDesktop; - - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (isDesktop) - // Header with title and close button. - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Padding( - padding: const EdgeInsets.only(left: 32), - child: Text( - "Import Slate", - style: STextStyles.pageTitleH2(context), - ), - ), - const DesktopDialogCloseButton(), - ], - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: isDesktop ? 32 : 24), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - ConditionalParent( - condition: isDesktop, - builder: - (child) => RoundedWhiteContainer( - borderColor: - isDesktop - ? Theme.of( - context, - ).extension()!.backgroundAppBar - : null, - padding: const EdgeInsets.all(0), - child: child, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (!isDesktop) - Padding( - padding: const EdgeInsets.only(top: 24, bottom: 24), - child: Text( - "Import slate", - style: STextStyles.pageTitleH2(context), - ), - ), - - if (_amount != null) - DetailItem( - title: "Amount", - detail: ref - .watch( - pAmountFormatter( - ref.watch(pWalletCoin(widget.walletId)), - ), - ) - .format(_amount), - ), - ], - ), - ), - const SizedBox(height: 24), - ConditionalParent( - condition: isDesktop, - builder: - (child) => Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [child], - ), - child: PrimaryButton( - width: isDesktop ? 220 : null, - - buttonHeight: isDesktop ? ButtonHeight.l : null, - label: "Process", - onPressed: _processPressed, - ), - ), - if (!isDesktop) const SizedBox(height: 12), - if (!isDesktop) - SecondaryButton( - label: "Cancel", - onPressed: Navigator.of(context).pop, - ), - ], - ), - ), - isDesktop ? const SizedBox(height: 32) : const SizedBox(height: 24), - ], - ); - } -} - -class EpicSlatepackResponseDialog extends StatelessWidget { - const EpicSlatepackResponseDialog({ - super.key, - required this.responseSlatepack, - required this.wasEncrypted, - }); - - final String responseSlatepack; - final bool wasEncrypted; - - @override - Widget build(BuildContext context) { - return SDialog( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Header with title and close button. - if (Util.isDesktop) - Padding( - padding: const EdgeInsets.only(left: 32), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - "Response Slate", - style: STextStyles.pageTitleH2(context), - ), - const DesktopDialogCloseButton(), - ], - ), - ), - Padding( - padding: - Util.isDesktop - ? const EdgeInsets.only(left: 32, right: 32, bottom: 32) - : const EdgeInsets.only(left: 24, right: 24, bottom: 24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (!Util.isDesktop) const SizedBox(height: 24), - Text( - "Return this slate to the sender to complete the transaction.", - style: STextStyles.pageTitleH2(context), - ), - const SizedBox(height: 24), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - "Response slate", - style: STextStyles.itemSubtitle(context), - ), - SimpleCopyButton(data: responseSlatepack), - ], - ), - const SizedBox(height: 8), - ConditionalParent( - condition: !Util.isDesktop, - builder: - (child) => SizedBox( - height: 220, - child: SingleChildScrollView(child: child), - ), - child: SelectableText( - responseSlatepack, - style: STextStyles.w500_14(context), - ), - ), - const SizedBox(height: 24), - ConditionalParent( - condition: Util.isDesktop, - builder: - (child) => Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [child], - ), - child: PrimaryButton( - label: "Done", - width: Util.isDesktop ? 220 : null, - buttonHeight: Util.isDesktop ? ButtonHeight.l : null, - onPressed: Navigator.of(context).pop, - ), - ), - ], - ), - ), - ], - ), - ); - } -} diff --git a/lib/pages/receive_view/sub_widgets/mwc_slatepack_import_dialog.dart b/lib/pages/receive_view/sub_widgets/mwc_slatepack_import_dialog.dart deleted file mode 100644 index 6b1bc060d8..0000000000 --- a/lib/pages/receive_view/sub_widgets/mwc_slatepack_import_dialog.dart +++ /dev/null @@ -1,361 +0,0 @@ -import 'dart:convert'; - -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../../../models/mwc_slatepack_models.dart'; -import '../../../providers/global/wallets_provider.dart'; -import '../../../themes/stack_colors.dart'; -import '../../../utilities/amount/amount.dart'; -import '../../../utilities/amount/amount_formatter.dart'; -import '../../../utilities/clipboard_interface.dart'; -import '../../../utilities/show_loading.dart'; -import '../../../utilities/text_styles.dart'; -import '../../../utilities/util.dart'; -import '../../../wallets/isar/providers/wallet_info_provider.dart'; -import '../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; -import '../../../widgets/conditional_parent.dart'; -import '../../../widgets/custom_buttons/simple_copy_button.dart'; -import '../../../widgets/desktop/desktop_dialog_close_button.dart'; -import '../../../widgets/desktop/primary_button.dart'; -import '../../../widgets/desktop/secondary_button.dart'; -import '../../../widgets/detail_item.dart'; -import '../../../widgets/dialogs/s_dialog.dart'; -import '../../../widgets/rounded_white_container.dart'; -import '../../../widgets/stack_dialog.dart'; - -class MwcSlatepackImportDialog extends ConsumerStatefulWidget { - const MwcSlatepackImportDialog({ - super.key, - required this.walletId, - required this.rawSlatepack, - required this.decoded, - required this.slatepackType, - this.clipboard = const ClipboardWrapper(), - }); - - final String walletId; - final String rawSlatepack; - final SlatepackDecodeResult decoded; - final String slatepackType; - final ClipboardInterface clipboard; - - @override - ConsumerState createState() => - _MwcSlatepackImportDialogState(); -} - -class _MwcSlatepackImportDialogState - extends ConsumerState { - Future<({String responseSlatepack, bool wasEncrypted})> - _processSlatepack() async { - // add delay for showloading exception catching hack fix - await Future.delayed(const Duration(seconds: 1)); - - final wallet = - ref.read(pWallets).getWallet(widget.walletId) as MimblewimblecoinWallet; - - // Determine action based on slatepack type. - if (widget.slatepackType.contains("S1")) { - // This is an initial slatepack - receive it and create response. - final result = await wallet.receiveSlatepack(widget.rawSlatepack); - - if (result.success && result.responseSlatepack != null) { - return ( - responseSlatepack: result.responseSlatepack!, - wasEncrypted: result.wasEncrypted ?? false, - ); - } else { - throw Exception(result.error ?? 'Failed to process slatepack'); - } - } else { - throw Exception('Unsupported slatepack type: ${widget.slatepackType}'); - } - } - - Future _processPressed() async { - Exception? ex; - final result = await showLoading( - whileFuture: _processSlatepack(), - context: context, - message: "Processing slatepack...", - onException: (e) => ex = e, - ); - - if (result == null || ex != null) { - if (mounted) { - await showDialog( - context: context, - useRootNavigator: true, - builder: - (context) => StackOkDialog( - desktopPopRootNavigator: true, - maxWidth: Util.isDesktop ? 400 : null, - title: "Slatepack receive error", - message: - ex?.toString() ?? "Unexpected result without exception", - ), - ); - } - return; - } - - if (mounted) { - Navigator.of(context).pop(result); - } - } - - late final Amount? _amount; - - // late final Amount? _fee; - - @override - void initState() { - final map = jsonDecode(widget.decoded.slateJson!) as Map; - - final rawAmount = BigInt.tryParse(map["amount"].toString()); - _amount = - rawAmount == null - ? null - : Amount( - rawValue: rawAmount, - fractionDigits: - ref.read(pWalletCoin(widget.walletId)).fractionDigits, - ); - - // final rawFee = BigInt.tryParse(map["fee"].toString()); - // _fee = - // rawFee == null - // ? null - // : Amount( - // rawValue: rawFee, - // fractionDigits: - // ref.read(pWalletCoin(widget.walletId)).fractionDigits, - // ); - - super.initState(); - } - - @override - Widget build(BuildContext context) { - final isDesktop = Util.isDesktop; - - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (isDesktop) - // Header with title and close button. - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Padding( - padding: const EdgeInsets.only(left: 32), - child: Text( - "Import Slatepack", - style: STextStyles.pageTitleH2(context), - ), - ), - const DesktopDialogCloseButton(), - ], - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: isDesktop ? 32 : 24), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - ConditionalParent( - condition: isDesktop, - builder: - (child) => RoundedWhiteContainer( - borderColor: - isDesktop - ? Theme.of( - context, - ).extension()!.backgroundAppBar - : null, - padding: const EdgeInsets.all(0), - child: child, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (!isDesktop) - Padding( - padding: const EdgeInsets.only(top: 24, bottom: 24), - child: Text( - "Import slatepack", - style: STextStyles.pageTitleH2(context), - ), - ), - - // DetailItem(title: "Type", detail: widget.slatepackType), - // const DetailDivider(), - // DetailItem( - // title: "Encrypted", - // detail: (widget.decoded.wasEncrypted ?? false).toString(), - // ), - // if (widget.decoded.senderAddress != null) - // const DetailDivider(), - // if (widget.decoded.senderAddress != null) - // DetailItem( - // title: "From", - // detail: widget.decoded.senderAddress!, - // ), - // if (widget.decoded.recipientAddress != null) - // const DetailDivider(), - // if (widget.decoded.recipientAddress != null) - // DetailItem( - // title: "To", - // detail: widget.decoded.recipientAddress!, - // ), - // if (_amount != null) const DetailDivider(), - if (_amount != null) - DetailItem( - title: "Amount", - detail: ref - .watch( - pAmountFormatter( - ref.watch(pWalletCoin(widget.walletId)), - ), - ) - .format(_amount), - ), - // if (_fee != null) const DetailDivider(), - // if (_fee != null) - // DetailItem( - // title: "Fee", - // detail: ref - // .watch( - // pAmountFormatter( - // ref.watch(pWalletCoin(widget.walletId)), - // ), - // ) - // .format(_fee), - // ), - ], - ), - ), - const SizedBox(height: 24), - ConditionalParent( - condition: isDesktop, - builder: - (child) => Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [child], - ), - child: PrimaryButton( - width: isDesktop ? 220 : null, - - buttonHeight: isDesktop ? ButtonHeight.l : null, - label: "Process", - onPressed: _processPressed, - ), - ), - if (!isDesktop) const SizedBox(height: 12), - if (!isDesktop) - SecondaryButton( - label: "Cancel", - onPressed: Navigator.of(context).pop, - ), - ], - ), - ), - isDesktop ? const SizedBox(height: 32) : const SizedBox(height: 24), - ], - ); - } -} - -class SlatepackResponseDialog extends StatelessWidget { - const SlatepackResponseDialog({ - super.key, - required this.responseSlatepack, - required this.wasEncrypted, - }); - - final String responseSlatepack; - final bool wasEncrypted; - - @override - Widget build(BuildContext context) { - return SDialog( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Header with title and close button. - if (Util.isDesktop) - Padding( - padding: const EdgeInsets.only(left: 32), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - "Response Slatepack", - style: STextStyles.pageTitleH2(context), - ), - const DesktopDialogCloseButton(), - ], - ), - ), - Padding( - padding: - Util.isDesktop - ? const EdgeInsets.only(left: 32, right: 32, bottom: 32) - : const EdgeInsets.only(left: 24, right: 24, bottom: 24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (!Util.isDesktop) const SizedBox(height: 24), - Text( - "Return this slatepack to the sender to complete the transaction.", - style: STextStyles.pageTitleH2(context), - ), - const SizedBox(height: 24), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - "Response slatepack", - style: STextStyles.itemSubtitle(context), - ), - SimpleCopyButton(data: responseSlatepack), - ], - ), - const SizedBox(height: 8), - ConditionalParent( - condition: !Util.isDesktop, - builder: - (child) => SizedBox( - height: 220, - child: SingleChildScrollView(child: child), - ), - child: SelectableText( - responseSlatepack, - style: STextStyles.w500_14(context), - ), - ), - const SizedBox(height: 24), - ConditionalParent( - condition: Util.isDesktop, - builder: - (child) => Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [child], - ), - child: PrimaryButton( - label: "Done", - width: Util.isDesktop ? 220 : null, - buttonHeight: Util.isDesktop ? ButtonHeight.l : null, - onPressed: Navigator.of(context).pop, - ), - ), - ], - ), - ), - ], - ), - ); - } -} diff --git a/lib/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart b/lib/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart index 941e7755f0..e4eb92809b 100644 --- a/lib/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart +++ b/lib/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart @@ -1,219 +1,82 @@ import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../../../providers/global/barcode_scanner_provider.dart'; import '../../../themes/stack_colors.dart'; -import '../../../utilities/barcode_scanner_interface.dart'; import '../../../utilities/clipboard_interface.dart'; -import '../../../utilities/constants.dart'; -import '../../../utilities/logger.dart'; +import '../../../utilities/slatepack_terms.dart'; import '../../../utilities/text_styles.dart'; import '../../../widgets/desktop/primary_button.dart'; import '../../../widgets/desktop/secondary_button.dart'; -import '../../../widgets/icon_widgets/clipboard_icon.dart'; -import '../../../widgets/icon_widgets/qrcode_icon.dart'; -import '../../../widgets/icon_widgets/x_icon.dart'; -import '../../../widgets/stack_dialog.dart'; -import '../../../widgets/stack_text_field.dart'; -import '../../../widgets/textfield_icon_button.dart'; +import '../../slatepack/slatepack_input_field.dart'; +import '../../slatepack/slatepack_popup.dart'; -class SlatepackEntryDialog extends ConsumerStatefulWidget { +Future showSlatepackEntryDialog({ + required BuildContext context, + required SlatepackTerms terms, + ClipboardInterface clipboard = const ClipboardWrapper(), +}) => showSlatepackPopup( + context: context, + child: SlatepackEntryDialog(terms: terms, clipboard: clipboard), +); + +/// Asks for a slatepack on mobile and pops with the text. +class SlatepackEntryDialog extends StatefulWidget { const SlatepackEntryDialog({ super.key, + required this.terms, this.clipboard = const ClipboardWrapper(), }); + final SlatepackTerms terms; final ClipboardInterface clipboard; @override - ConsumerState createState() => - _SlatepackEntryDialogState(); + State createState() => _SlatepackEntryDialogState(); } -class _SlatepackEntryDialogState extends ConsumerState { - final _receiveSlateController = TextEditingController(); - final _slateFocusNode = FocusNode(); - - bool _slateToggleFlag = false; - - Future _pasteSlatepack() async { - final ClipboardData? data = await widget.clipboard.getData( - Clipboard.kTextPlain, - ); - if (data?.text != null && data!.text!.isNotEmpty) { - _receiveSlateController.text = data.text!; - setState(() { - _slateToggleFlag = _receiveSlateController.text.isNotEmpty; - }); - } - } - - Future _scanQr() async { - try { - if (_slateFocusNode.hasFocus) { - _slateFocusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); - } +class _SlatepackEntryDialogState extends State { + final _controller = TextEditingController(); - if (mounted) { - final qrResult = await ref.read(pBarcodeScanner).scan(context: context); - if (qrResult.rawContent != null && qrResult.rawContent!.isNotEmpty) { - _receiveSlateController.text = qrResult.rawContent!; - setState(() { - _slateToggleFlag = _receiveSlateController.text.isNotEmpty; - }); - } - } - } on PlatformException catch (e, s) { - if (mounted) { - try { - await checkCamPermDeniedMobileAndOpenAppSettings( - context, - logging: Logging.instance, - ); - } catch (e, s) { - Logging.instance.e( - "Failed to check cam permissions", - error: e, - stackTrace: s, - ); - } - } else { - Logging.instance.e( - "Failed to get camera permissions while trying to scan qr code in SendView: ", - error: e, - stackTrace: s, - ); - } - } - } + bool get _hasText => _controller.text.trim().isNotEmpty; @override void dispose() { - _receiveSlateController.dispose(); - _slateFocusNode.dispose(); + _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { - return StackDialogBase( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text( - "Receive Slatepack", - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textFieldActiveSearchIconRight, - ), - textAlign: TextAlign.left, - ), - const SizedBox(height: 12), - ClipRRect( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - child: TextField( - minLines: 1, - maxLines: 5, - key: const Key("receiveViewSlatepackFieldKey"), - controller: _receiveSlateController, - readOnly: false, - autocorrect: false, - enableSuggestions: false, - toolbarOptions: const ToolbarOptions( - copy: false, - cut: false, - paste: true, - selectAll: false, - ), - onChanged: (newValue) { - setState(() { - _slateToggleFlag = newValue.isNotEmpty; - }); - }, - focusNode: _slateFocusNode, - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textFieldActiveText, - height: 1.8, - ), - decoration: - standardInputDecoration( - "Enter Slatepack Message", - _slateFocusNode, - context, - desktopMed: true, - ).copyWith( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: - 12, // Adjust vertical padding for better alignment - ), - suffixIcon: Padding( - padding: _receiveSlateController.text.isEmpty - ? const EdgeInsets.only(right: 8) - : const EdgeInsets.only(right: 0), - child: UnconstrainedBox( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - _slateToggleFlag - ? TextFieldIconButton( - key: const Key( - "receiveViewClearSlatepackFieldButtonKey", - ), - onTap: () { - _receiveSlateController.text = ""; - setState(() { - _slateToggleFlag = false; - }); - }, - child: const XIcon(), - ) - : TextFieldIconButton( - key: const Key( - "receiveViewPasteSlatepackFieldButtonKey", - ), - onTap: _pasteSlatepack, - child: _receiveSlateController.text.isEmpty - ? const ClipboardIcon() - : const XIcon(), - ), - if (_receiveSlateController.text.isEmpty) - TextFieldIconButton( - semanticsLabel: - "Scan QR Button. Opens Camera For Scanning QR Code.", - key: const Key("sendViewScanQrButtonKey"), - onTap: _scanQr, - child: const QrCodeIcon(), - ), - ], - ), - ), - ), - ), - ), - ), - const SizedBox(height: 16), - PrimaryButton( - label: "Import", - enabled: _slateToggleFlag, - onPressed: !_slateToggleFlag - ? null - : () => Navigator.of(context).pop(_receiveSlateController.text), - ), - const SizedBox(height: 16), - SecondaryButton( - label: "Cancel", - onPressed: Navigator.of(context).pop, + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + "Import ${widget.terms.title}", + style: STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textFieldActiveSearchIconRight, ), - ], - ), + textAlign: TextAlign.left, + ), + const SizedBox(height: 12), + SlatepackInputField( + controller: _controller, + hint: "Enter ${widget.terms.payload}", + terms: widget.terms, + clipboard: widget.clipboard, + onChanged: (_) => setState(() {}), + ), + const SizedBox(height: 16), + PrimaryButton( + label: "Import", + enabled: _hasText, + onPressed: _hasText + ? () => Navigator.of(context).pop(_controller.text.trim()) + : null, + ), + const SizedBox(height: 16), + SecondaryButton(label: "Cancel", onPressed: Navigator.of(context).pop), + ], ); } } diff --git a/lib/pages/send_view/confirm_transaction_view.dart b/lib/pages/send_view/confirm_transaction_view.dart index ba495cdd74..f045094c69 100644 --- a/lib/pages/send_view/confirm_transaction_view.dart +++ b/lib/pages/send_view/confirm_transaction_view.dart @@ -9,7 +9,6 @@ */ import 'dart:async'; -import 'dart:convert'; import 'dart:io'; import 'package:decimal/decimal.dart'; @@ -44,12 +43,11 @@ import '../../wallets/isar/providers/eth/current_token_wallet_provider.dart'; import '../../wallets/isar/providers/solana/current_sol_token_wallet_provider.dart'; import '../../wallets/isar/providers/wallet_info_provider.dart'; import '../../wallets/models/tx_data.dart'; -import '../../wallets/wallet/impl/epiccash_wallet.dart'; import '../../wallets/wallet/impl/firo_wallet.dart'; -import '../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../wallets/wallet/impl/solana_wallet.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/ordinals_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../widgets/background.dart'; import '../../widgets/conditional_parent.dart'; import '../../widgets/custom_buttons/app_bar_icon_button.dart'; @@ -65,9 +63,7 @@ import '../../widgets/textfield_icon_button.dart'; import '../../wl_gen/interfaces/libepiccash_interface.dart'; import '../pinpad_views/lock_screen_view.dart'; import '../wallet_view/wallet_view.dart'; -import 'sub_widgets/epic_slatepack_dialog.dart'; import 'sub_widgets/multi_recipient.dart'; -import 'sub_widgets/mwc_slatepack_dialog.dart'; import 'sub_widgets/sending_transaction_dialog.dart'; import 'sub_widgets/split_transaction_warning.dart'; @@ -156,165 +152,6 @@ class _ConfirmTransactionViewState } } - /// Handle MWC slatepack creation for manual exchange. - Future _handleMwcSlatepackCreation( - BuildContext context, - MimblewimblecoinWallet wallet, - ) async { - try { - // Close the progress dialog first. - Navigator.of(context).pop(); - - // Get recipient information from txData. - final recipient = widget.txData.recipients?.first; - if (recipient == null) { - throw Exception('No recipient found in transaction data'); - } - - // Create slatepack. - final slatepackResult = await wallet.createSlatepack( - amount: recipient.amount, - recipientAddress: recipient.address.isNotEmpty - ? recipient.address - : null, - message: onChainNoteController.text.isNotEmpty - ? onChainNoteController.text - : null, - encrypt: recipient - .address - .isNotEmpty, // Encrypt if we have a recipient address. - ); - - if (!slatepackResult.success || slatepackResult.slatepack == null) { - throw Exception(slatepackResult.error ?? 'Failed to create slatepack'); - } - - // Show slatepack dialog. - if (context.mounted) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => - MwcSlatepackDialog(slatepackResult: slatepackResult), - ); - - // After slatepack dialog is closed, navigate back to wallet. - if (context.mounted) { - widget.onSuccess.call(); - if (widget.onSuccessInsteadOfRouteOnSuccess == null) { - Navigator.of(context) - .popUntil(ModalRoute.withName(routeOnSuccessName)); - } else { - widget.onSuccessInsteadOfRouteOnSuccess!.call(); - } - } - } - } catch (e, s) { - Logging.instance.e('Failed to create MWC slatepack: $e\n$s'); - - if (context.mounted) { - // Show user-friendly error message. - final errorMessage = e.toString().contains('insufficient funds') - ? 'Insufficient funds for this transaction' - : e.toString().contains('wallet not open') - ? 'Wallet not accessible. Please restart the app.' - : 'Failed to create slatepack: ${e.toString()}'; - - await showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('Slatepack Creation Failed'), - content: Text(errorMessage), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: const Text('OK'), - ), - ], - ), - ); - } - } - } - - /// Handle Epic Cash slate creation for manual exchange. - Future _handleEpicSlatepackCreation( - BuildContext context, - EpiccashWallet wallet, - ) async { - try { - // Close the progress dialog first. - Navigator.of(context).pop(); - - // Get recipient information from txData. - final recipient = widget.txData.recipients?.first; - if (recipient == null) { - throw Exception('No recipient found in transaction data'); - } - - // Create slatepack. - final slatepackResult = await wallet.createSlatepack( - amount: recipient.amount, - recipientAddress: recipient.address.isNotEmpty - ? recipient.address - : null, - message: onChainNoteController.text.isNotEmpty - ? onChainNoteController.text - : null, - ); - - if (!slatepackResult.success || slatepackResult.slatepack == null) { - throw Exception(slatepackResult.error ?? 'Failed to create slate'); - } - - // Show slatepack dialog. - if (context.mounted) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => - EpicSlatepackDialog(slatepackResult: slatepackResult), - ); - - // After slatepack dialog is closed, navigate back to wallet. - if (context.mounted) { - widget.onSuccess.call(); - if (widget.onSuccessInsteadOfRouteOnSuccess == null) { - Navigator.of(context) - .popUntil(ModalRoute.withName(routeOnSuccessName)); - } else { - widget.onSuccessInsteadOfRouteOnSuccess!.call(); - } - } - } - } catch (e, s) { - Logging.instance.e('Failed to create Epic Cash slate: $e\n$s'); - - if (context.mounted) { - // Show user-friendly error message. - final errorMessage = e.toString().contains('insufficient funds') - ? 'Insufficient funds for this transaction' - : e.toString().contains('wallet not open') - ? 'Wallet not accessible. Please restart the app.' - : 'Failed to create slate: ${e.toString()}'; - - await showDialog( - context: context, - builder: (context) => AlertDialog( - title: const Text('Slate Creation Failed'), - content: Text(errorMessage), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: const Text('OK'), - ), - ], - ), - ); - } - } - } - Future _attemptSend(BuildContext context) async { final wallet = ref.read(pWallets).getWallet(walletId); final coin = wallet.info.coin; @@ -392,54 +229,14 @@ class _ConfirmTransactionViewState break; } } else { - if (coin is Mimblewimblecoin) { - // Check if this is a slatepack transaction (manual exchange). - final otherDataMap = widget.txData.otherData != null - ? jsonDecode(widget.txData.otherData!) - : null; - final transactionMethod = - otherDataMap?['transactionMethod'] as String?; - - if (transactionMethod == 'slatepack') { - // Handle slatepack creation instead of direct send. - await _handleMwcSlatepackCreation( - context, - wallet as MimblewimblecoinWallet, - ); - closeSendingDialog(); - return; // Exit early, don't continue with normal transaction flow. - } else { - // Handle MWCMQS or HTTP transactions normally. - txDataFuture = wallet.confirmSend( - txData: widget.txData.copyWith( - noteOnChain: onChainNoteController.text, - ), - ); - } - } else if (coin is Epiccash) { - // Check if this is a slatepack transaction (manual exchange). - final epicOtherDataMap = widget.txData.otherData != null - ? jsonDecode(widget.txData.otherData!) - : null; - final epicTransactionMethod = - epicOtherDataMap?['transactionMethod'] as String?; - - if (epicTransactionMethod == 'slatepack') { - // Handle slatepack creation instead of direct send. - await _handleEpicSlatepackCreation( - context, - wallet as EpiccashWallet, - ); - closeSendingDialog(); - return; // Exit early, don't continue with normal transaction flow. - } else { - // Handle Epicbox transactions normally. - txDataFuture = wallet.confirmSend( - txData: widget.txData.copyWith( - noteOnChain: onChainNoteController.text, - ), - ); - } + if (wallet is SlatepackInterface) { + txDataFuture = wallet.confirmSend( + txData: widget.txData.copyWith( + noteOnChain: wallet.supportsOnChainNote + ? onChainNoteController.text + : null, + ), + ); } else { txDataFuture = wallet.confirmSend(txData: widget.txData); } @@ -691,6 +488,9 @@ class _ConfirmTransactionViewState final feeRate = formatApproximateFeeRate(fee?.raw, widget.txData.vSize); + final slatepackWallet = wallet is SlatepackInterface ? wallet : null; + final showOnChainNote = slatepackWallet?.supportsOnChainNote ?? false; + return ConditionalParent( condition: !isDesktop, builder: (child) => Background( @@ -910,11 +710,11 @@ class _ConfirmTransactionViewState ], ), ), - if ((coin is Epiccash || coin is Mimblewimblecoin) && - widget.txData.noteOnChain!.isNotEmpty) + if (showOnChainNote && + (widget.txData.noteOnChain ?? "").isNotEmpty) const SizedBox(height: 12), - if ((coin is Epiccash || coin is Mimblewimblecoin) && - widget.txData.noteOnChain!.isNotEmpty) + if (showOnChainNote && + (widget.txData.noteOnChain ?? "").isNotEmpty) RoundedWhiteContainer( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -939,9 +739,7 @@ class _ConfirmTransactionViewState crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( - (coin is Epiccash || coin is Mimblewimblecoin) - ? "Local Note" - : "Note", + slatepackWallet != null ? "Local Note" : "Note", style: STextStyles.smallMed12(context), ), const SizedBox(height: 4), @@ -1355,15 +1153,14 @@ class _ConfirmTransactionViewState mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (coin is Epiccash || coin is Mimblewimblecoin) + if (showOnChainNote) Text( "On chain Note", style: STextStyles.smallMed12(context), textAlign: TextAlign.left, ), - if (coin is Epiccash || coin is Mimblewimblecoin) - const SizedBox(height: 8), - if (coin is Epiccash || coin is Mimblewimblecoin) + if (showOnChainNote) const SizedBox(height: 8), + if (showOnChainNote) ClipRRect( borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, @@ -1408,10 +1205,9 @@ class _ConfirmTransactionViewState ), ), ), - if (coin is Epiccash || coin is Mimblewimblecoin) - const SizedBox(height: 12), + if (showOnChainNote) const SizedBox(height: 12), SelectableText( - (coin is Epiccash || coin is Mimblewimblecoin) + slatepackWallet != null ? "Local Note (optional)" : "Note (optional)", style: STextStyles.desktopTextExtraSmall(context) diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index 78cf9b87e8..3c40737955 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -19,10 +19,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:tuple/tuple.dart'; -import '../../models/epic_slatepack_models.dart'; import '../../models/input.dart'; import '../../models/isar/models/isar_models.dart'; -import '../../models/mwc_slatepack_models.dart'; import '../../models/paynym/paynym_account_lite.dart'; import '../../models/send_view_auto_fill_data.dart'; import '../../notifications/show_flush_bar.dart'; @@ -52,46 +50,42 @@ import '../../utilities/eth_commons.dart'; import '../../utilities/extensions/extensions.dart'; import '../../utilities/logger.dart'; import '../../utilities/prefs.dart'; -import '../../utilities/show_loading.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; import '../../wallets/crypto_currency/crypto_currency.dart'; import '../../wallets/isar/providers/wallet_info_provider.dart'; import '../../wallets/models/tx_data.dart'; -import '../../wallets/wallet/impl/epiccash_wallet.dart'; import '../../wallets/wallet/impl/firo_wallet.dart'; -import '../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../wallets/wallet/impl/salvium_wallet.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/coin_control_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; import '../../widgets/background.dart'; import '../../widgets/calculating_future_builder.dart'; import '../../widgets/custom_buttons/app_bar_icon_button.dart'; import '../../widgets/custom_buttons/blue_text_button.dart'; import '../../widgets/dialogs/firo_exchange_address_dialog.dart'; -import '../../widgets/epic_txs_method_toggle.dart'; import '../../widgets/eth_fee_form.dart'; import '../../widgets/fee_slider.dart'; import '../../widgets/icon_widgets/addressbook_icon.dart'; import '../../widgets/icon_widgets/clipboard_icon.dart'; import '../../widgets/icon_widgets/qrcode_icon.dart'; import '../../widgets/icon_widgets/x_icon.dart'; -import '../../widgets/mwc_txs_method_toggle.dart'; +import '../../widgets/slatepack_method_toggle.dart'; import '../../widgets/rounded_white_container.dart'; import '../../widgets/stack_dialog.dart'; import '../../widgets/stack_text_field.dart'; import '../../widgets/textfield_icon_button.dart'; import '../address_book_views/address_book_view.dart'; import '../coin_control/coin_control_view.dart'; +import '../slatepack/slatepack_send_flow.dart'; import 'confirm_transaction_view.dart'; import 'frost_ms/recipient.dart'; import 'sub_widgets/building_transaction_dialog.dart'; import 'sub_widgets/dual_balance_selection_sheet.dart'; -import 'sub_widgets/epic_slatepack_dialog.dart'; import 'sub_widgets/multi_recipient.dart'; -import 'sub_widgets/mwc_slatepack_dialog.dart'; import 'sub_widgets/transaction_fee_selection_sheet.dart'; class SendView extends ConsumerStatefulWidget { @@ -141,6 +135,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { late final bool hasOptionalMemo; late final bool isFiro; late final bool isEth; + SlatepackInterface? _slatepackWallet; Amount? _cachedAmountToSend; String? _addressValue; @@ -707,180 +702,6 @@ class _SendViewState extends ConsumerState with SendFeeForm { if (hasFees && coin is! Xelis) followFeeAmount(amount); } - Future _createSlatepack() async { - // wait for keyboard to disappear - FocusScope.of(context).unfocus(); - await Future.delayed(const Duration(milliseconds: 100)); - - try { - if (mounted) { - final wallet = - ref.read(pWallets).getWallet(walletId) as MimblewimblecoinWallet; - - final amount = ref.read(pSendAmount)!; - - Future wrappedFutureWithDelay() async { - await Future.delayed(const Duration(seconds: 1)); - return wallet.createSlatepack( - amount: amount, - recipientAddress: null, - // No specific recipient for manual slatepack. - message: onChainNoteController.text.isNotEmpty == true - ? onChainNoteController.text - : null, - encrypt: false, // No encryption without recipient address. - ); - } - - // Create slatepack. - Exception? ex; - final slatepackResult = await showLoading( - whileFuture: wrappedFutureWithDelay(), - context: context, - message: "Building slatepack...", - delay: const Duration(seconds: 2), - onException: (e) => ex = e, - ); - - if (slatepackResult == null || - !slatepackResult.success || - slatepackResult.slatepack == null || - ex != null) { - String error = - ex?.toString() ?? - slatepackResult?.error ?? - 'Failed to create slatepack'; - if (error.startsWith("Exception:")) { - error = error.replaceFirst("Exception:", "").trim(); - } - throw Exception(error); - } - - // refresh asap to show the pending slate tx in history - unawaited(() async { - await Future.delayed(Duration.zero); - await wallet.refresh(); - }()); - - // Show slatepack dialog. - if (mounted) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => StackDialogBase( - child: MwcSlatepackDialog(slatepackResult: slatepackResult), - ), - ); - - // Clear form after slatepack dialog is closed. - clearSendForm(); - } - } - } catch (e, s) { - Logging.instance.e( - 'Failed to create MWC slatepack on mobile', - error: e, - stackTrace: s, - ); - - if (mounted) { - await showDialog( - context: context, - builder: (context) => StackOkDialog( - title: "Slatepack Creation Failed", - message: e.toString(), - ), - ); - } - } - } - - Future _createEpicSlatepack() async { - // wait for keyboard to disappear - FocusScope.of(context).unfocus(); - await Future.delayed(const Duration(milliseconds: 100)); - - try { - if (mounted) { - final wallet = ref.read(pWallets).getWallet(walletId) as EpiccashWallet; - - final amount = ref.read(pSendAmount)!; - - Future wrappedFutureWithDelay() async { - await Future.delayed(const Duration(seconds: 1)); - return wallet.createSlatepack( - amount: amount, - recipientAddress: null, - // No specific recipient for manual slatepack. - message: onChainNoteController.text.isNotEmpty == true - ? onChainNoteController.text - : null, - ); - } - - // Create slatepack. - Exception? ex; - final slatepackResult = await showLoading( - whileFuture: wrappedFutureWithDelay(), - context: context, - message: "Building slate...", - delay: const Duration(seconds: 2), - onException: (e) => ex = e, - ); - - if (slatepackResult == null || - !slatepackResult.success || - slatepackResult.slatepack == null || - ex != null) { - String error = - ex?.toString() ?? - slatepackResult?.error ?? - 'Failed to create slate'; - if (error.startsWith("Exception:")) { - error = error.replaceFirst("Exception:", "").trim(); - } - throw Exception(error); - } - - // refresh asap to show the pending slate tx in history - unawaited(() async { - await Future.delayed(Duration.zero); - await wallet.refresh(); - }()); - - // Show slatepack dialog. - if (mounted) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => StackDialogBase( - child: EpicSlatepackDialog(slatepackResult: slatepackResult), - ), - ); - - // Clear form after slatepack dialog is closed. - clearSendForm(); - } - } - } catch (e, s) { - Logging.instance.e( - 'Failed to create Epic Cash slate on mobile', - error: e, - stackTrace: s, - ); - - if (mounted) { - await showDialog( - context: context, - builder: (context) => StackOkDialog( - title: "Slate Creation Failed", - message: e.toString(), - ), - ); - } - } - } - /// Looks up the OpenAlias in the address field. Returns null if the lookup /// failed or was cancelled. Future _resolveOpenAlias(String application) async { @@ -931,11 +752,15 @@ class _SendViewState extends ConsumerState with SendFeeForm { // wait for keyboard to disappear FocusScope.of(context).unfocus(); await Future.delayed(const Duration(milliseconds: 100)); + if (!mounted) return; final wallet = ref.read(pWallets).getWallet(walletId); + final isSlatepackSend = + wallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); String? openAlias; String? resolvedAddress; final application = coin.openAliasApplication; if (application != null && + !isSlatepackSend && !coin.validateAddress(_address ?? "") && isOpenAlias(_address ?? "")) { var resolved = _openAlias; @@ -952,6 +777,20 @@ class _SendViewState extends ConsumerState with SendFeeForm { late final recipientAddress = resolvedAddress ?? _address!; final Amount amount = ref.read(pSendAmount)!; + if (isSlatepackSend) { + final created = await SlatepackSendFlow.run( + context: context, + wallet: wallet, + amount: amount, + message: onChainNoteController.text, + localNote: noteController.text, + db: ref.read(mainDBProvider), + format: ref.read(pAmountFormatter(wallet.cryptoCurrency)).format, + ); + if (created && mounted) clearSendForm(); + return; + } + final Amount availableBalance; if (isFiro || ref.read(pWalletInfo(walletId)).isMwebEnabled) { switch (ref.read(publicPrivateBalanceStateProvider.state).state) { @@ -1382,6 +1221,19 @@ class _SendViewState extends ConsumerState with SendFeeForm { void _onFeeSelectPressed() => showFeeSheet(this); + void _formatEpicCashAddress() { + var address = sendToController.text.trim(); + if (address.isEmpty) return; + if (address.contains("\n")) { + address = address.substring(0, address.indexOf("\n")); + } + final formatted = AddressUtils().formatEpicCashAddress(address); + _address = formatted; + if (sendToController.text != formatted) { + sendToController.text = formatted; + } + } + @override void initState() { coin = widget.coin; @@ -1393,6 +1245,10 @@ class _SendViewState extends ConsumerState with SendFeeForm { walletId = widget.walletId; fees = SendFeeRates(ref.read, walletId: walletId, isToken: false); clipboard = widget.clipboard; + final wallet = ref.read(pWallets).getWallet(walletId); + if (wallet is SlatepackInterface) { + _slatepackWallet = wallet; + } WidgetsBinding.instance.addPostFrameCallback((_) { ref.refresh(pIsExchangeAddress); @@ -1409,6 +1265,9 @@ class _SendViewState extends ConsumerState with SendFeeForm { onChainNoteController = TextEditingController(); feeController = TextEditingController(); memoController = TextEditingController(); + if (coin is Epiccash) { + sendToController.addListener(_formatEpicCashAddress); + } onCryptoAmountChanged = _cryptoAmountChanged; cryptoAmountController.addListener(onCryptoAmountChanged); @@ -1455,6 +1314,9 @@ class _SendViewState extends ConsumerState with SendFeeForm { _ethFee.dispose(); cryptoAmountController.removeListener(onCryptoAmountChanged); + if (coin is Epiccash) { + sendToController.removeListener(_formatEpicCashAddress); + } sendToController.dispose(); cryptoAmountController.dispose(); @@ -1509,7 +1371,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { // ethFee is checked in the ValueListenableBuilder around the preview // button so fee keystrokes don't rebuild this whole view. final previewEnabled = - ref.watch(pPreviewTxButtonEnabled(coin)) && + ref.watch(pPreviewTxButtonEnabled(walletId)) && (ref.watch(pOpReturnData) == null || balType != BalanceType.private); final needsEthFee = isEth && isCustomFee; @@ -1548,24 +1410,6 @@ class _SendViewState extends ConsumerState with SendFeeForm { } }); - // add listener for epic cash to strip http:// and https:// prefixes if the address also ocntains an @ symbol (indicating an epicbox address) - if (coin is Epiccash) { - sendToController.addListener(() { - _address = sendToController.text.trim(); - - if (_address != null && _address!.isNotEmpty) { - _address = _address!.trim(); - if (_address!.contains("\n")) { - _address = _address!.substring(0, _address!.indexOf("\n")); - } - - sendToController.text = AddressUtils().formatEpicCashAddress( - _address!, - ); - } - }); - } - Decimal? price; if (ref.watch(prefsChangeNotifierProvider.select((s) => s.externalCalls))) { price = ref.watch( @@ -1575,11 +1419,13 @@ class _SendViewState extends ConsumerState with SendFeeForm { ); } - final isMwcSlatepack = - coin is Mimblewimblecoin && ref.watch(pIsSlatepack(widget.walletId)); - final isEpicSlatepack = - coin is Epiccash && ref.watch(pIsSlatepack(widget.walletId)); - final isSlatepackMode = isMwcSlatepack || isEpicSlatepack; + final isSlatepackMode = ref.watch(pIsSlatepack(widget.walletId)); + final wallet = ref.watch( + pWallets.select((value) => value.getWallet(walletId)), + ); + // Preserve the existing mobile UI: Epic exposes its on-chain note field; + // MWC only exposed that field on desktop before this refactor. + final showOnChainNote = coin is Epiccash; return Background( child: Scaffold( @@ -1736,20 +1582,13 @@ class _SendViewState extends ConsumerState with SendFeeForm { ), const SizedBox(height: 16), - // MWC Transaction Method Selector. - if (coin is Mimblewimblecoin) ...[ - const SizedBox( - height: 40, - child: MwcTxsMethodToggle(), - ), - const SizedBox(height: 16), - ], - - // Epic Cash Transaction Method Selector. - if (coin is Epiccash) ...[ - const SizedBox( + if (_slatepackWallet?.hasSlatepackMethodToggle ?? + false) ...[ + SizedBox( height: 40, - child: EpicTxsMethodToggle(), + child: SlatepackMethodToggle( + walletId: walletId, + ), ), const SizedBox(height: 16), ], @@ -2096,58 +1935,63 @@ class _SendViewState extends ConsumerState with SendFeeForm { ), ), ), - Builder( - builder: (_) { - final String? error; - - if (_address == null || _address!.isEmpty) { - error = null; - } else if (isFiro) { - if (_data != null && - _data.contactLabel == _address) { - error = null; - } else if (!ref.watch(pValidSendToAddress) && - !ref.watch(pValidSparkSendToAddress)) { - error = "Invalid address"; - } else { - error = null; - } - } else { - if (_data != null && - _data.contactLabel == _address) { + if (!isSlatepackMode) + Builder( + builder: (_) { + final String? error; + + if (_address == null || _address!.isEmpty) { error = null; - } else if (!ref.watch(pValidSendToAddress)) { - error = "Invalid address"; + } else if (isFiro) { + if (_data != null && + _data.contactLabel == _address) { + error = null; + } else if (!ref.watch( + pValidSendToAddress, + ) && + !ref.watch(pValidSparkSendToAddress)) { + error = "Invalid address"; + } else { + error = null; + } } else { - error = null; + if (_data != null && + _data.contactLabel == _address) { + error = null; + } else if (!ref.watch( + pValidSendToAddress, + )) { + error = "Invalid address"; + } else { + error = null; + } } - } - if (error == null || error.isEmpty) { - return Container(); - } else { - return Align( - alignment: Alignment.topLeft, - child: Padding( - padding: const EdgeInsets.only( - left: 12.0, - top: 4.0, - ), - child: Text( - error, - textAlign: TextAlign.left, - style: STextStyles.label(context) - .copyWith( - color: Theme.of(context) - .extension()! - .textError, - ), + if (error == null || error.isEmpty) { + return Container(); + } else { + return Align( + alignment: Alignment.topLeft, + child: Padding( + padding: const EdgeInsets.only( + left: 12.0, + top: 4.0, + ), + child: Text( + error, + textAlign: TextAlign.left, + style: STextStyles.label(context) + .copyWith( + color: Theme.of(context) + .extension()! + .textError, + ), + ), ), - ), - ); - } - }, - ), + ); + } + }, + ), if (isFiro || isMwebEnabled) const SizedBox(height: 12), if (isFiro || isMwebEnabled) @@ -2514,14 +2358,14 @@ class _SendViewState extends ConsumerState with SendFeeForm { ), ), const SizedBox(height: 12), - if (coin is Epiccash) + if (showOnChainNote) Text( "On chain Note", style: STextStyles.smallMed12(context), textAlign: TextAlign.left, ), - if (coin is Epiccash) const SizedBox(height: 8), - if (coin is Epiccash) + if (showOnChainNote) const SizedBox(height: 8), + if (showOnChainNote) ClipRRect( borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, @@ -2571,10 +2415,10 @@ class _SendViewState extends ConsumerState with SendFeeForm { ), ), ), - if (coin is Epiccash || coin is Mimblewimblecoin) + if (_slatepackWallet != null) const SizedBox(height: 12), Text( - (coin is Epiccash || coin is Mimblewimblecoin) + _slatepackWallet != null ? "Local Note (optional)" : "Note (optional)", style: STextStyles.smallMed12(context), @@ -2793,11 +2637,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { (!needsEthFee || ethFee != null); return TextButton( onPressed: enabled - ? isMwcSlatepack - ? _createSlatepack - : isEpicSlatepack - ? _createEpicSlatepack - : _previewTransaction + ? _previewTransaction : null, style: enabled ? Theme.of(context) @@ -2811,8 +2651,9 @@ class _SendViewState extends ConsumerState with SendFeeForm { context, ), child: Text( - isSlatepackMode - ? "Create slate" + isSlatepackMode && + wallet is SlatepackInterface + ? "Create ${wallet.slatepackTerms.noun}" : "Preview", style: STextStyles.button(context), ), diff --git a/lib/pages/send_view/sub_widgets/epic_slatepack_dialog.dart b/lib/pages/send_view/sub_widgets/epic_slatepack_dialog.dart deleted file mode 100644 index 7bcf97022f..0000000000 --- a/lib/pages/send_view/sub_widgets/epic_slatepack_dialog.dart +++ /dev/null @@ -1,175 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:flutter_svg/flutter_svg.dart'; - -import '../../../models/epic_slatepack_models.dart'; -import '../../../notifications/show_flush_bar.dart'; -import '../../../themes/stack_colors.dart'; -import '../../../utilities/assets.dart'; -import '../../../utilities/clipboard_interface.dart'; -import '../../../utilities/text_styles.dart'; -import '../../../utilities/util.dart'; -import '../../../widgets/conditional_parent.dart'; -import '../../../widgets/desktop/desktop_dialog_close_button.dart'; -import '../../../widgets/desktop/primary_button.dart'; -import '../../../widgets/qr.dart'; -import '../../../widgets/rounded_container.dart'; -import '../../../widgets/rounded_white_container.dart'; - -class EpicSlatepackDialog extends ConsumerStatefulWidget { - const EpicSlatepackDialog({ - super.key, - required this.slatepackResult, - this.clipboard = const ClipboardWrapper(), - }); - - final EpicSlatepackResult slatepackResult; - final ClipboardInterface clipboard; - - @override - ConsumerState createState() => _EpicSlatepackDialogState(); -} - -class _EpicSlatepackDialogState extends ConsumerState { - void _copySlatepack() { - widget.clipboard.setData( - ClipboardData(text: widget.slatepackResult.slatepack!), - ); - showFloatingFlushBar( - type: FlushBarType.info, - message: "Slate copied to clipboard", - iconAsset: Assets.svg.copy, - context: context, - ); - } - - void _shareSlatepack() { - // TODO: Implement file sharing for desktop platforms. - showFloatingFlushBar( - type: FlushBarType.info, - message: "Share functionality coming soon", - context: context, - ); - } - - @override - Widget build(BuildContext context) { - return ConditionalParent( - condition: Util.isDesktop, - builder: - (child) => Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Header with title and close button. - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Padding( - padding: const EdgeInsets.only(left: 32), - child: Text( - "Send Slate", - style: STextStyles.pageTitleH2(context), - ), - ), - const DesktopDialogCloseButton(), - ], - ), - Padding(padding: const EdgeInsets.all(32), child: child), - ], - ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - // Instructions. - RoundedContainer( - color: - Theme.of(context).extension()!.textFieldDefaultBG, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "Next Steps:", - style: STextStyles.label( - context, - ).copyWith(fontWeight: FontWeight.w600), - ), - const SizedBox(height: 8), - Text( - "1. Share this slate with the recipient\n" - "2. Wait for them to return the response slate\n" - "3. Import their response to finalize the transaction", - style: STextStyles.w400_14(context), - ), - ], - ), - ), - - const SizedBox(height: 12), - - // QR Code view. - Center( - child: QR( - data: widget.slatepackResult.slatepack!, - size: 220, - ), - ), - - const SizedBox(height: 12), - - // Slatepack text view. - RoundedWhiteContainer( - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Row( - children: [ - Text("Slate", style: STextStyles.itemSubtitle(context)), - const Spacer(), - GestureDetector( - onTap: _copySlatepack, - child: Row( - children: [ - SvgPicture.asset( - Assets.svg.copy, - width: 10, - height: 10, - color: - Theme.of( - context, - ).extension()!.infoItemIcons, - ), - const SizedBox(width: 4), - Text("Copy", style: STextStyles.link2(context)), - ], - ), - ), - ], - ), - const SizedBox(height: 8), - Container( - constraints: const BoxConstraints( - maxHeight: 200, - minHeight: 100, - ), - child: SingleChildScrollView( - child: SelectableText( - widget.slatepackResult.slatepack!, - style: STextStyles.w400_14( - context, - ).copyWith(fontFamily: 'monospace'), - ), - ), - ), - ], - ), - ), - - if (!Util.isDesktop) - PrimaryButton(label: "Done", onPressed: Navigator.of(context).pop), - ], - ), - ); - } -} diff --git a/lib/pages/send_view/sub_widgets/mwc_slatepack_dialog.dart b/lib/pages/send_view/sub_widgets/mwc_slatepack_dialog.dart deleted file mode 100644 index ec57cf0a53..0000000000 --- a/lib/pages/send_view/sub_widgets/mwc_slatepack_dialog.dart +++ /dev/null @@ -1,214 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:flutter_svg/flutter_svg.dart'; - -import '../../../models/mwc_slatepack_models.dart'; -import '../../../notifications/show_flush_bar.dart'; -import '../../../themes/stack_colors.dart'; -import '../../../utilities/assets.dart'; -import '../../../utilities/clipboard_interface.dart'; -import '../../../utilities/text_styles.dart'; -import '../../../utilities/util.dart'; -import '../../../widgets/conditional_parent.dart'; -import '../../../widgets/desktop/desktop_dialog_close_button.dart'; -import '../../../widgets/desktop/primary_button.dart'; -import '../../../widgets/qr.dart'; -import '../../../widgets/rounded_container.dart'; -import '../../../widgets/rounded_white_container.dart'; - -class MwcSlatepackDialog extends ConsumerStatefulWidget { - const MwcSlatepackDialog({ - super.key, - required this.slatepackResult, - this.clipboard = const ClipboardWrapper(), - }); - - final SlatepackResult slatepackResult; - final ClipboardInterface clipboard; - - @override - ConsumerState createState() => _MwcSlatepackDialogState(); -} - -class _MwcSlatepackDialogState extends ConsumerState { - void _copySlatepack() { - widget.clipboard.setData( - ClipboardData(text: widget.slatepackResult.slatepack!), - ); - showFloatingFlushBar( - type: FlushBarType.info, - message: "Slatepack copied to clipboard", - iconAsset: Assets.svg.copy, - context: context, - ); - } - - void _shareSlatepack() { - // TODO: Implement file sharing for desktop platforms. - showFloatingFlushBar( - type: FlushBarType.info, - message: "Share functionality coming soon", - context: context, - ); - } - - @override - Widget build(BuildContext context) { - return ConditionalParent( - condition: Util.isDesktop, - builder: - (child) => Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Header with title and close button. - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Padding( - padding: const EdgeInsets.only(left: 32), - child: Text( - "Send Slatepack", - style: STextStyles.pageTitleH2(context), - ), - ), - const DesktopDialogCloseButton(), - ], - ), - Padding(padding: const EdgeInsets.all(32), child: child), - ], - ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - // Instructions. - RoundedContainer( - color: - Theme.of(context).extension()!.textFieldDefaultBG, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - "Next Steps:", - style: STextStyles.label( - context, - ).copyWith(fontWeight: FontWeight.w600), - ), - const SizedBox(height: 8), - Text( - "1. Share this slatepack with the recipient\n" - "2. Wait for them to return the response slatepack\n" - "3. Import their response to finalize the transaction", - style: STextStyles.w400_14(context), - ), - ], - ), - ), - - // Encryption status. - // we don't encrypt so ignore for now - // if (widget.slatepackResult.wasEncrypted == true) - // Container( - // padding: const EdgeInsets.symmetric( - // horizontal: 12, - // vertical: 8, - // ), - // decoration: BoxDecoration( - // color: Theme.of( - // context, - // ).extension()!.infoItemIcons.withOpacity(0.1), - // borderRadius: BorderRadius.circular(8), - // ), - // child: Row( - // mainAxisSize: MainAxisSize.min, - // children: [ - // Icon( - // Icons.lock, - // size: 16, - // color: - // Theme.of( - // context, - // ).extension()!.infoItemIcons, - // ), - // const SizedBox(width: 8), - // Text( - // "Encrypted for recipient", - // style: STextStyles.label(context).copyWith( - // color: - // Theme.of( - // context, - // ).extension()!.infoItemIcons, - // ), - // ), - // ], - // ), - // ), - const SizedBox(height: 12), - - // QR Code view. - Center( - child: QR( - data: widget.slatepackResult.slatepack!, - size: 220, - // errorCorrectionLevel: QrErrorCorrectLevel.M, - ), - ), - - const SizedBox(height: 12), - - // Slatepack text view. - RoundedWhiteContainer( - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Row( - children: [ - Text("Slatepack", style: STextStyles.itemSubtitle(context)), - const Spacer(), - GestureDetector( - onTap: _copySlatepack, - child: Row( - children: [ - SvgPicture.asset( - Assets.svg.copy, - width: 10, - height: 10, - color: - Theme.of( - context, - ).extension()!.infoItemIcons, - ), - const SizedBox(width: 4), - Text("Copy", style: STextStyles.link2(context)), - ], - ), - ), - ], - ), - const SizedBox(height: 8), - Container( - constraints: const BoxConstraints( - maxHeight: 200, - minHeight: 100, - ), - child: SingleChildScrollView( - child: SelectableText( - widget.slatepackResult.slatepack!, - style: STextStyles.w400_14( - context, - ).copyWith(fontFamily: 'monospace'), - ), - ), - ), - ], - ), - ), - - if (!Util.isDesktop) - PrimaryButton(label: "Done", onPressed: Navigator.of(context).pop), - ], - ), - ); - } -} diff --git a/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart new file mode 100644 index 0000000000..ef8a62ccaa --- /dev/null +++ b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; + +import '../../themes/stack_colors.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../widgets/desktop/primary_button.dart'; +import '../../widgets/desktop/secondary_button.dart'; +import '../../widgets/stack_dialog.dart'; + +bool canCancelSlateTransaction({ + required String? slateId, + required bool isCancelled, + required int confirmations, +}) => slateId?.isNotEmpty == true && !isCancelled && confirmations < 1; + +class SlatepackCancelTransactionDialog extends StatelessWidget { + const SlatepackCancelTransactionDialog({super.key}); + + @override + Widget build(BuildContext context) { + return StackDialogBase( + width: Util.isDesktop ? 400 : null, + padding: EdgeInsets.all(Util.isDesktop ? 24 : 16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + "Cancel this transaction?", + style: Util.isDesktop + ? STextStyles.desktopH3(context) + : STextStyles.pageTitleH2(context), + ), + const SizedBox(height: 12), + Text( + "This cancels the transaction in this wallet. It may not prevent " + "another party from completing or broadcasting it.", + style: STextStyles.smallMed14(context).copyWith( + color: Theme.of(context).extension()!.textDark3, + ), + ), + const SizedBox(height: 20), + SecondaryButton( + label: "Go back", + onPressed: () => Navigator.of(context).pop(false), + ), + const SizedBox(height: 8), + PrimaryButton( + label: "Cancel it", + onPressed: () => Navigator.of(context).pop(true), + ), + ], + ), + ); + } +} diff --git a/lib/pages/slatepack/slatepack_dialog.dart b/lib/pages/slatepack/slatepack_dialog.dart new file mode 100644 index 0000000000..fc74f91a6f --- /dev/null +++ b/lib/pages/slatepack/slatepack_dialog.dart @@ -0,0 +1,371 @@ +import 'dart:convert'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_svg/flutter_svg.dart'; +import 'package:share_plus/share_plus.dart'; + +import '../../models/slatepack_models.dart'; +import '../../notifications/show_flush_bar.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/assets.dart'; +import '../../utilities/clipboard_interface.dart'; +import '../../utilities/logger.dart'; +import '../../utilities/slatepack_terms.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../widgets/desktop/primary_button.dart'; +import '../../widgets/desktop/secondary_button.dart'; +import '../../widgets/detail_item.dart'; +import '../../widgets/rounded_container.dart'; +import '../../widgets/rounded_white_container.dart'; +import 'slatepack_popup.dart'; +import 'slatepack_qr.dart'; + +String slatepackMonospaceFontFamily(TargetPlatform platform) => + switch (platform) { + TargetPlatform.iOS || TargetPlatform.macOS => 'Menlo', + TargetPlatform.windows => 'Consolas', + TargetPlatform.android || + TargetPlatform.fuchsia || + TargetPlatform.linux => 'monospace', + }; + +/// Shows a slatepack the user has to pass to the other party. +Future showSlatepackDialog({ + required BuildContext context, + required SlatepackTerms terms, + required SlatepackResult result, + required bool supportsEncryption, + String? formattedAmount, + String? formattedFee, +}) { + return showSlatepackPopup( + context: context, + barrierDismissible: false, + child: SlatepackDialog.fromResult( + terms: terms, + result: result, + showEncryptionStatus: supportsEncryption, + formattedAmount: formattedAmount, + formattedFee: formattedFee, + ), + ); +} + +/// One dialog for every slatepack the wallet hands out (S1, S2, I1, I2): +/// copy, share, save to file, and a QR code when the text is short enough. +class SlatepackDialog extends StatelessWidget { + const SlatepackDialog({ + super.key, + required this.terms, + required this.slatepack, + required this.state, + this.slateId, + this.isEncrypted = false, + this.showEncryptionStatus = true, + this.formattedAmount, + this.formattedFee, + this.clipboard = const ClipboardWrapper(), + }); + + factory SlatepackDialog.fromResult({ + Key? key, + required SlatepackTerms terms, + required SlatepackResult result, + ClipboardInterface clipboard = const ClipboardWrapper(), + bool showEncryptionStatus = true, + String? formattedAmount, + String? formattedFee, + }) => SlatepackDialog( + key: key, + terms: terms, + slatepack: result.slatepack!, + state: result.state, + slateId: result.slateId, + isEncrypted: result.wasEncrypted ?? false, + showEncryptionStatus: showEncryptionStatus, + formattedAmount: formattedAmount, + formattedFee: formattedFee, + clipboard: clipboard, + ); + + final SlatepackTerms terms; + final String slatepack; + final SlateState state; + final String? slateId; + final bool isEncrypted; + final bool showEncryptionStatus; + final String? formattedAmount; + final String? formattedFee; + final ClipboardInterface clipboard; + + String get title => switch (state) { + SlateState.s1 => "Send ${terms.title}", + SlateState.s2 => "Response ${terms.title}", + SlateState.i1 => "Invoice ${terms.title}", + SlateState.i2 => "Payment ${terms.title}", + _ => terms.title, + }; + + String get instructions => switch (state) { + SlateState.s1 => + "1. Share this ${terms.noun} with the recipient\n" + "2. Wait for them to return the response ${terms.noun}\n" + "3. Import their response on the " + "${terms.title} screen to finalize the " + "transaction\n\n" + "The funds stay locked until the transaction is finalized or " + "cancelled.", + SlateState.s2 => + "Return this ${terms.noun} to the sender. They finalize and broadcast " + "the transaction.", + SlateState.i1 => + "1. Share this invoice with the payer\n" + "2. Wait for them to return the payment ${terms.noun}\n" + "3. Import it on the ${terms.title} screen to finalize the payment", + SlateState.i2 => + "Return this ${terms.noun} to the payee. They finalize and broadcast " + "the payment. The funds stay locked until then.", + _ => "Pass this ${terms.noun} to the other party.", + }; + + /// `..`, e.g. `0436...a1.S1.slatepack`. + String get fileName { + final id = (slateId == null || slateId!.isEmpty) ? terms.noun : slateId!; + final suffix = state == SlateState.unknown ? "" : ".${state.code}"; + return "$id$suffix.${terms.fileExtension}"; + } + + Future _copy(BuildContext context) async { + await clipboard.setData(ClipboardData(text: slatepack)); + if (context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.info, + message: "${terms.title} copied to clipboard", + iconAsset: Assets.svg.copy, + context: context, + ); + } + } + + /// [context] is the Share button's. An iPad anchors the share sheet to the + /// button's rect and will not open it without one. + Future _share(BuildContext context) async { + final box = context.findRenderObject(); + final origin = box is RenderBox && box.hasSize + ? box.localToGlobal(Offset.zero) & box.size + : null; + try { + await SharePlus.instance.share( + ShareParams( + text: slatepack, + subject: title, + sharePositionOrigin: origin, + ), + ); + } catch (e, s) { + Logging.instance.e( + "Sharing ${terms.noun} failed", + error: e, + stackTrace: s, + ); + } + } + + Future _save(BuildContext context) async { + try { + final path = await FilePicker.platform.saveFile( + dialogTitle: "Save ${terms.noun}", + fileName: fileName, + bytes: Uint8List.fromList(utf8.encode(slatepack)), + lockParentWindow: true, + ); + if (path != null && context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.success, + message: "Saved to $path", + context: context, + ); + } + } catch (e, s) { + Logging.instance.e( + "Saving ${terms.noun} failed", + error: e, + stackTrace: s, + ); + if (context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.warning, + message: "Could not save the ${terms.noun}: $e", + context: context, + ); + } + } + } + + Widget _icon(BuildContext context, String asset) => SvgPicture.asset( + asset, + width: 14, + height: 14, + colorFilter: ColorFilter.mode( + Theme.of(context).extension()!.buttonTextSecondary, + BlendMode.srcIn, + ), + ); + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).extension()!; + final isDesktop = Util.isDesktop; + + return SlatepackPopupLayout( + title: title, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + RoundedContainer( + color: colors.textFieldDefaultBG, + child: Text(instructions, style: STextStyles.w400_14(context)), + ), + const SizedBox(height: 12), + if (showEncryptionStatus) ...[ + Row( + children: [ + SvgPicture.asset( + isEncrypted ? Assets.svg.lock : Assets.svg.lockOpen, + width: 14, + height: 14, + colorFilter: ColorFilter.mode( + colors.infoItemIcons, + BlendMode.srcIn, + ), + ), + const SizedBox(width: 8), + Flexible( + child: Text( + isEncrypted + ? "Encrypted to the other party's address" + : "Not encrypted", + style: STextStyles.label(context), + ), + ), + ], + ), + const SizedBox(height: 12), + ], + if (formattedAmount != null || formattedFee != null) ...[ + RoundedWhiteContainer( + borderColor: isDesktop ? colors.backgroundAppBar : null, + padding: EdgeInsets.zero, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (formattedAmount != null) + DetailItem(title: "Amount", detail: formattedAmount!), + if (formattedAmount != null && formattedFee != null) + const DetailDivider(), + if (formattedFee != null) + DetailItem(title: "Fee", detail: formattedFee!), + ], + ), + ), + const SizedBox(height: 12), + ], + Center( + child: SlatepackQr(data: slatepack, noun: terms.noun), + ), + const SizedBox(height: 12), + RoundedWhiteContainer( + borderColor: isDesktop ? colors.backgroundAppBar : null, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(terms.title, style: STextStyles.itemSubtitle(context)), + const SizedBox(height: 8), + ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 200), + child: SingleChildScrollView( + child: SelectableText( + slatepack, + style: STextStyles.w400_14(context).copyWith( + fontFamily: slatepackMonospaceFontFamily( + Theme.of(context).platform, + ), + ), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 16), + LayoutBuilder( + builder: (context, constraints) { + final scaledText = MediaQuery.textScalerOf(context).scale(14); + final useTwoRows = + !isDesktop && (constraints.maxWidth < 300 || scaledText > 14); + + final copy = SecondaryButton( + label: "Copy", + buttonHeight: isDesktop ? ButtonHeight.l : null, + icon: _icon(context, Assets.svg.copy), + onPressed: () => _copy(context), + ); + final share = Builder( + builder: (context) => SecondaryButton( + label: "Share", + icon: _icon(context, Assets.svg.share), + onPressed: () => _share(context), + ), + ); + final save = SecondaryButton( + label: "Save", + buttonHeight: isDesktop ? ButtonHeight.l : null, + icon: _icon(context, Assets.svg.downloadFolder), + onPressed: () => _save(context), + ); + + if (useTwoRows) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded(child: copy), + const SizedBox(width: 12), + Expanded(child: share), + ], + ), + const SizedBox(height: 12), + save, + ], + ); + } + + return Row( + children: [ + Expanded(child: copy), + if (!isDesktop) ...[ + const SizedBox(width: 12), + Expanded(child: share), + ], + const SizedBox(width: 12), + Expanded(child: save), + ], + ); + }, + ), + const SizedBox(height: 16), + PrimaryButton( + label: "Done", + buttonHeight: isDesktop ? ButtonHeight.l : null, + onPressed: Navigator.of(context).pop, + ), + ], + ), + ); + } +} diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart new file mode 100644 index 0000000000..26d1935ada --- /dev/null +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -0,0 +1,486 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../models/slatepack_models.dart'; +import '../../notifications/show_flush_bar.dart'; +import '../../utilities/amount/amount.dart'; +import '../../utilities/exception_message.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/logger.dart'; +import '../../utilities/route_presentation.dart'; +import '../../utilities/slatepack_text.dart'; +import '../../utilities/util.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../../widgets/custom_loading_overlay.dart'; +import '../../widgets/stack_dialog.dart'; +import 'slatepack_dialog.dart'; +import 'slatepack_popup.dart'; +import 'slatepack_summary_dialog.dart'; + +/// Where an imported slatepack goes. +enum SlatepackRoute { + /// S1: answer it with an S2. + receive, + + /// S2: finalize our send. + finalizeSend, + + /// S3 or I3: nothing left to do. + alreadyFinalized, + + /// I1 or I2. Epic Cash and MWC do not support invoice slates. + invoicesUnsupported, + + /// State could not be worked out. + unsupported, +} + +/// Takes any slatepack the user pastes, scans or opens, works out what it +/// is and sends it to the matching screen. +abstract final class SlatepackImportFlow { + // This lookup is local-only. A short defensive bound prevents a damaged + // database or application shutdown from holding an import screen forever. + static const _receiveHistoryLookupTimeout = Duration(seconds: 3); + static const _finalizeHistoryLookupTimeout = Duration(seconds: 3); + + static SlatepackRoute routeFor(SlateState state) => switch (state) { + SlateState.s1 => SlatepackRoute.receive, + SlateState.s2 => SlatepackRoute.finalizeSend, + SlateState.i1 || SlateState.i2 => SlatepackRoute.invoicesUnsupported, + SlateState.s3 || SlateState.i3 => SlatepackRoute.alreadyFinalized, + SlateState.unknown => SlatepackRoute.unsupported, + }; + + /// The slatepack in [text] without what came along with it. A pasted or + /// scanned message often has a greeting, a quote or blank lines around the + /// armored slatepack, so only the part from its begin marker to its end + /// marker is kept. Text without such a frame, like a JSON slate, is only + /// trimmed. + static String normalize(String text) => SlatepackText.normalize(text); + + /// Returns true once the slatepack has been acted on, so the caller can + /// clear its input. + static Future run({ + required BuildContext context, + required SlatepackInterface wallet, + required String text, + }) async { + final terms = wallet.slatepackTerms; + final slatepack = normalize(text); + + final read = await _withLoading( + context, + "Reading ${terms.noun}...", + () async { + final inspection = await wallet.inspectSlatepack(slatepack); + final route = routeFor(inspection.state); + var historyLookupTimedOut = false; + final needsLocalHistory = + route == SlatepackRoute.receive || + route == SlatepackRoute.finalizeSend; + final local = needsLocalHistory + ? await wallet + .localTxForSlate(inspection.slateId) + .timeout( + route == SlatepackRoute.receive + ? _receiveHistoryLookupTimeout + : _finalizeHistoryLookupTimeout, + onTimeout: () { + historyLookupTimedOut = true; + Logging.instance.w( + "Timed out looking up local transaction for slate " + "${inspection.slateId}", + ); + return null; + }, + ) + : null; + return ( + inspection: inspection, + route: route, + // Only the wallet that started a send can finalize it. + local: local, + historyLookupTimedOut: historyLookupTimedOut, + ); + }, + errorTitle: "Could not read ${terms.noun}", + ); + if (read == null || !context.mounted) return false; + + final inspection = read.inspection; + final route = read.route; + + switch (route) { + case SlatepackRoute.receive: + if (read.historyLookupTimedOut) { + await _message( + context, + "Could not check wallet history", + "The wallet is busy. Try importing this ${terms.noun} again.", + ); + return false; + } + final local = read.local; + if (local?.isCancelled == true) { + final reason = local?.isSend == true + ? "This transaction was cancelled. A cancelled send cannot be " + "received or finalized." + : "This transaction's earlier receive was cancelled. Ask the " + "sender to create a new transaction."; + await _message(context, "Cannot receive this ${terms.noun}", reason); + return false; + } + if (local?.isSend == true) { + await _message( + context, + "Cannot receive this ${terms.noun}", + "This wallet created the transaction. Share this ${terms.noun} " + "with the other party, then import their response instead.", + ); + return false; + } + if (local != null) { + await _message( + context, + "Cannot receive this ${terms.noun}", + "This transaction is already in this wallet's history.", + ); + return false; + } + return _receive(context, wallet, slatepack, inspection); + + case SlatepackRoute.finalizeSend: + final local = read.local; + if (local != null && !local.isSend) { + await _message( + context, + "Cannot finalize this ${terms.noun}", + "This ${terms.noun} belongs to a transaction this wallet " + "received, not one it started. Only the wallet that " + "started a send can finalize it.", + ); + return false; + } + if (local?.isCancelled == true) { + await _message( + context, + "Cannot finalize this ${terms.noun}", + "This transaction was cancelled. A cancelled send cannot be " + "finalized.", + ); + return false; + } + return _finalize( + context, + wallet, + slatepack, + inspection, + amount: local?.amount ?? inspection.amount, + fee: local?.fee ?? inspection.fee, + historyWarning: local == null, + historyLookupTimedOut: read.historyLookupTimedOut, + ); + + case SlatepackRoute.invoicesUnsupported: + await _message( + context, + "Invoices not supported", + "This ${terms.noun} is part of an invoice. " + "${wallet.cryptoCurrency.prettyName} wallets do not support " + "invoices.", + ); + return false; + + case SlatepackRoute.alreadyFinalized: + await _message( + context, + "Already finalized", + "This ${terms.noun} is already finalized. There is nothing left " + "to do with it.", + ); + return false; + + case SlatepackRoute.unsupported: + await _message( + context, + "Unsupported ${terms.noun}", + "Could not tell which step of a transaction this ${terms.noun} " + "belongs to.", + ); + return false; + } + } + + static Future _receive( + BuildContext context, + SlatepackInterface wallet, + String text, + SlateInspection inspection, + ) async { + final terms = wallet.slatepackTerms; + + final confirmed = await showSlatepackPopup( + context: context, + child: SlatepackSummaryDialog( + title: "Receive ${terms.noun}", + coin: wallet.cryptoCurrency, + actionLabel: "Receive", + amount: inspection.amount, + details: [ + if (inspection.senderAddress != null) + ( + RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(inspection.senderAddress!) + ? "Sender key" + : "From", + inspection.senderAddress!, + ), + if (wallet.supportsSlatepackEncryption) + ("Encrypted", inspection.isEncrypted ? "Yes" : "No"), + if (inspection.ttlCutoffHeight != null) + ("Expires at block", inspection.ttlCutoffHeight.toString()), + if (inspection.slateId.isNotEmpty) ("Slate ID", inspection.slateId), + ], + ), + ); + if (confirmed != true || !context.mounted) return false; + + // Looked up before the wallet is asked, so the response can still be + // shown if the screen that started the import is gone by then. + final root = Navigator.of(context, rootNavigator: true); + + final result = await _withLoading( + context, + "Processing ${terms.noun}...", + () async { + final r = await wallet.receiveSlatepack(text, inspection: inspection); + if (!r.success || r.slatepack == null) { + throw Exception(r.error ?? "Failed to receive ${terms.noun}"); + } + return r; + }, + errorTitle: "${terms.title} receive error", + ); + if (result == null) return false; + + // The transaction is received now and the sender cannot finalize it + // without the response, so the response is shown wherever it still can + // be. + if (context.mounted) { + await showSlatepackDialog( + context: context, + terms: terms, + result: result, + supportsEncryption: wallet.supportsSlatepackEncryption, + ); + } else if (root.mounted) { + Logging.instance.w( + "Received ${terms.noun} ${result.slateId} after the screen that " + "imported it had closed. Showing the response from the root " + "navigator.", + ); + await showSlatepackDialog( + context: root.context, + terms: terms, + result: result, + supportsEncryption: wallet.supportsSlatepackEncryption, + ); + } else { + Logging.instance.e( + "Received ${terms.noun} ${result.slateId} but there was nowhere left " + "to show the response.", + ); + } + return true; + } + + static Future _finalize( + BuildContext context, + SlatepackInterface wallet, + String text, + SlateInspection inspection, { + required Amount? amount, + required Amount? fee, + required bool historyWarning, + required bool historyLookupTimedOut, + }) async { + final terms = wallet.slatepackTerms; + + final noValues = amount == null && fee == null; + final String? warning; + if (!historyWarning) { + warning = null; + } else if (historyLookupTimedOut) { + warning = noValues + ? "This wallet's history could not be checked because the wallet " + "is busy. The amount and fee are unavailable. Verify this " + "${terms.noun} with the other party before finalizing." + : "This wallet's history could not be checked because the wallet " + "is busy. Values shown below come from the imported " + "${terms.noun}; values not shown are unavailable. Review " + "them with the other party before finalizing."; + } else { + warning = noValues + ? "No matching send was found in this wallet's history. The " + "amount and fee are unavailable. Verify this " + "${terms.noun} with the other party before finalizing." + : "No matching send was found in this wallet's history. " + "Values shown below come from the imported " + "${terms.noun}; values not shown are unavailable. " + "Review them with the other party before finalizing."; + } + + // An S2 may carry amount 0, so the summary shows [amount] and [fee] from + // our own record of the send. + final confirmed = await showSlatepackPopup( + context: context, + child: SlatepackSummaryDialog( + title: "Finalize ${terms.noun}", + coin: wallet.cryptoCurrency, + actionLabel: "Finalize", + amount: amount, + fee: fee, + warning: warning, + details: [ + if (inspection.slateId.isNotEmpty) ("Slate ID", inspection.slateId), + if (wallet.supportsSlatepackEncryption) + ("Encrypted", inspection.isEncrypted ? "Yes" : "No"), + ], + ), + ); + if (confirmed != true || !context.mounted) return false; + + final result = await _withLoading( + context, + "Finalizing ${terms.noun}...", + () async { + final r = await wallet.finalizeSlatepack(text, inspection: inspection); + if (!r.success) { + throw Exception(r.error ?? "Finalize failed"); + } + return r; + }, + errorTitle: "${terms.title} finalize error", + ); + if (result == null) return false; + + if (!context.mounted) { + Logging.instance.w( + "Finalized ${terms.noun} ${inspection.slateId} after the screen that " + "imported it had closed. Broadcast: ${result.posted}.", + ); + return true; + } + + if (result.posted == true) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.success, + message: "Transaction finalized and broadcast", + context: context, + ), + ); + } else if (result.posted == false) { + await _message( + context, + "Finalized, not broadcast", + "The transaction is finalized but the node did not accept it yet. " + "Check the node connection and transaction history before " + "creating a replacement.", + ); + } else { + await _message( + context, + "Transaction finalized", + "The native wallet finalized the transaction, but its broadcast " + "result is unavailable. Check transaction history and the node " + "connection before creating a replacement.", + ); + } + return true; + } + + /// Runs [action] under a loading overlay. Shows the error and returns null + /// when it throws. + static Future _withLoading( + BuildContext context, + String message, + Future Function() action, { + required String errorTitle, + }) async { + // The overlay is this flow's own route on the root navigator, so it can + // be taken down again even if the screen that started the import is gone + // by the time the wallet answers. + final root = Navigator.of(context, rootNavigator: true); + final overlayColor = Theme.of(context) + .extension()! + .overlay + .withValues(alpha: 0.6); + final overlay = CurrentAwareDialogRoute( + context: context, + barrierDismissible: false, + themes: InheritedTheme.capture(from: context, to: root.context), + builder: (_) => PopScope( + canPop: false, + child: Container( + color: overlayColor, + child: CustomLoadingOverlay(message: message, eventBus: null), + ), + ), + ); + unawaited(root.push(overlay)); + + T? result; + Object? error; + try { + // MWC's native calls can block synchronously, so wait until the route is + // fully visible rather than merely built at zero transition opacity. + await waitForRoutePresentation(overlay); + result = await action(); + } catch (e, s) { + Logging.instance.w(errorTitle, error: e, stackTrace: s); + error = e; + } + + if (root.mounted && overlay.isActive) { + await overlay.waitUntilCurrent(); + } + if (root.mounted && overlay.isActive) { + if (overlay.isCurrent) { + root.pop(); + } else { + root.removeRoute(overlay); + } + } + + if (error != null || result == null) { + // An error is worth showing even after the importing screen closed. + final text = error == null + ? "Unexpected result without an error" + : stripExceptionPrefixes(error); + if (context.mounted) { + await _message(context, errorTitle, text); + } else if (root.mounted) { + await _message(root.context, errorTitle, text); + } + return null; + } + return result; + } + + static Future _message( + BuildContext context, + String title, + String message, + ) { + return showDialog( + context: context, + builder: (_) => StackOkDialog( + title: title, + message: message, + desktopPopRootNavigator: Util.isDesktop, + maxWidth: Util.isDesktop ? 400 : null, + ), + ); + } +} diff --git a/lib/pages/slatepack/slatepack_input_field.dart b/lib/pages/slatepack/slatepack_input_field.dart new file mode 100644 index 0000000000..9f3880288a --- /dev/null +++ b/lib/pages/slatepack/slatepack_input_field.dart @@ -0,0 +1,271 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_svg/flutter_svg.dart'; + +import '../../notifications/show_flush_bar.dart'; +import '../../providers/global/barcode_scanner_provider.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/assets.dart'; +import '../../utilities/barcode_scanner_interface.dart'; +import '../../utilities/clipboard_interface.dart'; +import '../../utilities/constants.dart'; +import '../../utilities/exception_message.dart'; +import '../../utilities/logger.dart'; +import '../../utilities/slatepack_terms.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../widgets/desktop/qr_code_scanner_dialog.dart'; +import '../../widgets/icon_widgets/clipboard_icon.dart'; +import '../../widgets/icon_widgets/qrcode_icon.dart'; +import '../../widgets/icon_widgets/x_icon.dart'; +import '../../widgets/stack_text_field.dart'; +import '../../widgets/textfield_icon_button.dart'; + +/// Largest file accepted as a slatepack. Real ones are a few KB. +const kSlatepackFileMaxBytes = 256 * 1024; + +/// Text field for a slatepack with paste, scan and open-file buttons. +class SlatepackInputField extends ConsumerStatefulWidget { + const SlatepackInputField({ + super.key, + required this.controller, + required this.hint, + required this.terms, + this.onChanged, + this.focusNode, + this.clipboard = const ClipboardWrapper(), + }); + + final TextEditingController controller; + final String hint; + final SlatepackTerms terms; + final void Function(String)? onChanged; + final FocusNode? focusNode; + final ClipboardInterface clipboard; + + @override + ConsumerState createState() => + _SlatepackInputFieldState(); +} + +class _SlatepackInputFieldState extends ConsumerState { + late final FocusNode _focusNode; + + bool get _isEmpty => widget.controller.text.isEmpty; + + void _set(String text) { + if (!mounted) return; + widget.controller.text = text; + widget.onChanged?.call(text); + setState(() {}); + } + + Future _paste() async { + final ClipboardData? data = await widget.clipboard.getData( + Clipboard.kTextPlain, + ); + final text = data?.text?.trim(); + if (text != null && text.isNotEmpty) { + _set(text); + } + } + + Future _scan() async { + try { + if (Platform.isAndroid || Platform.isIOS) { + if (_focusNode.hasFocus) { + _focusNode.unfocus(); + await Future.delayed(const Duration(milliseconds: 75)); + } + if (!mounted) return; + final result = await ref.read(pBarcodeScanner).scan(context: context); + final text = result.rawContent?.trim(); + if (text != null && text.isNotEmpty) { + _set(text); + } + } else { + final text = await showDialog( + context: context, + builder: (context) => const QrCodeScannerDialog(), + ); + if (text != null && text.trim().isNotEmpty) { + _set(text.trim()); + } + } + } on PlatformException catch (e, s) { + if (mounted) { + try { + await checkCamPermDeniedMobileAndOpenAppSettings( + context, + logging: Logging.instance, + ); + } catch (e, s) { + Logging.instance.e( + "Failed to check cam permissions", + error: e, + stackTrace: s, + ); + } + } else { + Logging.instance.w( + "Camera permission error while scanning a ${widget.terms.noun}", + error: e, + stackTrace: s, + ); + } + } + } + + Future _openFile() async { + try { + final result = await FilePicker.platform.pickFiles( + dialogTitle: "Open ${widget.terms.noun} file", + lockParentWindow: true, + ); + final picked = result?.files.singleOrNull; + if (picked == null) return; + + if (picked.size > kSlatepackFileMaxBytes) { + throw Exception( + "File is too large (${picked.size} bytes). " + "A ${widget.terms.noun} file is at most " + "$kSlatepackFileMaxBytes bytes.", + ); + } + + final List bytes = + picked.bytes ?? await File(picked.path!).readAsBytes(); + if (bytes.length > kSlatepackFileMaxBytes) { + throw Exception("File is too large to be a ${widget.terms.noun}."); + } + + final text = utf8.decode(bytes).trim(); + if (text.isEmpty) { + throw Exception("The file is empty."); + } + _set(text); + } on FormatException catch (_) { + _showError("That file is not a text file."); + } catch (e, s) { + Logging.instance.w( + "Opening ${widget.terms.noun} file failed", + error: e, + stackTrace: s, + ); + _showError(stripExceptionPrefixes(e)); + } + } + + void _showError(String message) { + if (!mounted) return; + showFloatingFlushBar( + type: FlushBarType.warning, + message: message, + context: context, + ); + } + + @override + void initState() { + super.initState(); + _focusNode = widget.focusNode ?? FocusNode(); + } + + @override + void dispose() { + if (widget.focusNode == null) { + _focusNode.dispose(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).extension()!; + final label = Util.isDesktop ? widget.hint : widget.terms.title; + + return ClipRRect( + borderRadius: BorderRadius.circular(Constants.size.circularBorderRadius), + child: TextField( + key: const Key("slatepackInputField"), + minLines: 1, + maxLines: 5, + controller: widget.controller, + focusNode: _focusNode, + autocorrect: false, + enableSuggestions: false, + onChanged: (value) { + widget.onChanged?.call(value); + setState(() {}); + }, + style: Util.isDesktop + ? STextStyles.desktopTextExtraSmall(context) + .copyWith(color: colors.textFieldActiveText, height: 1.8) + : STextStyles.field(context), + decoration: + standardInputDecoration( + label, + _focusNode, + context, + desktopMed: true, + ).copyWith( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + suffixIcon: Padding( + padding: _isEmpty + ? const EdgeInsets.only(right: 8) + : EdgeInsets.zero, + child: UnconstrainedBox( + child: Row( + children: _isEmpty + ? [ + TextFieldIconButton( + key: const Key("slatepackPasteButton"), + semanticsLabel: "Paste", + onTap: _paste, + child: const ClipboardIcon(), + ), + TextFieldIconButton( + key: const Key("slatepackScanButton"), + semanticsLabel: "Scan QR code", + onTap: _scan, + child: const QrCodeIcon(), + ), + TextFieldIconButton( + key: const Key("slatepackFileButton"), + semanticsLabel: "Open file", + onTap: _openFile, + child: SvgPicture.asset( + Assets.svg.file, + width: 17, + height: 17, + colorFilter: ColorFilter.mode( + colors.textDark3, + BlendMode.srcIn, + ), + ), + ), + ] + : [ + TextFieldIconButton( + key: const Key("slatepackClearButton"), + semanticsLabel: "Clear", + onTap: () => _set(""), + child: const XIcon(), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/pages/slatepack/slatepack_popup.dart b/lib/pages/slatepack/slatepack_popup.dart new file mode 100644 index 0000000000..4bc00185b4 --- /dev/null +++ b/lib/pages/slatepack/slatepack_popup.dart @@ -0,0 +1,91 @@ +import 'package:flutter/material.dart'; + +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../widgets/desktop/desktop_dialog.dart'; +import '../../widgets/desktop/desktop_dialog_close_button.dart'; +import '../../widgets/stack_dialog.dart'; + +/// Shows a slatepack screen as a dialog: a [DesktopDialog] on desktop, a +/// bottom sheet style [StackDialogBase] on mobile. +Future showSlatepackPopup({ + required BuildContext context, + required Widget child, + bool barrierDismissible = true, +}) { + return showDialog( + context: context, + barrierDismissible: barrierDismissible, + // StackDialogBase and DesktopDialog already apply their own safe-area + // layout. + useSafeArea: false, + builder: (context) { + final mediaInset = MediaQuery.viewInsetsOf(context).bottom; + // Dialog routes can expose a MediaQuery with consumed insets. Read the + // owning view as well so the mobile popup still follows the IME. + final viewInset = MediaQueryData.fromView(View.of(context)) + .viewInsets + .bottom; + final keyboardInset = mediaInset > viewInset ? mediaInset : viewInset; + final popup = Util.isDesktop + ? DesktopDialog(maxWidth: 700, maxHeight: null, child: child) + : StackDialogBase(keyboardPaddingAmount: keyboardInset, child: child); + return barrierDismissible ? popup : PopScope(canPop: false, child: popup); + }, + ); +} + +/// Title and body for a slatepack popup. On desktop the title row carries a +/// close button and the body scrolls. +class SlatepackPopupLayout extends StatelessWidget { + const SlatepackPopupLayout({ + super.key, + required this.title, + required this.child, + }); + + final String title; + final Widget child; + + @override + Widget build(BuildContext context) { + if (Util.isDesktop) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: Padding( + padding: const EdgeInsets.only(left: 32), + child: Text(title, style: STextStyles.desktopH3(context)), + ), + ), + const DesktopDialogCloseButton(), + ], + ), + Flexible( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.only(left: 32, right: 32, bottom: 32), + child: child, + ), + ), + ), + ], + ); + } + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(title, style: STextStyles.pageTitleH2(context)), + const SizedBox(height: 16), + child, + ], + ); + } +} diff --git a/lib/pages/slatepack/slatepack_qr.dart b/lib/pages/slatepack/slatepack_qr.dart new file mode 100644 index 0000000000..2423c8eff5 --- /dev/null +++ b/lib/pages/slatepack/slatepack_qr.dart @@ -0,0 +1,77 @@ +import 'dart:convert'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../../themes/stack_colors.dart'; +import '../../utilities/text_styles.dart'; +import '../../widgets/qr.dart'; +import '../../widgets/rounded_container.dart'; + +/// Most bytes one QR code holds: version 40 in byte mode at error correction +/// level L, which is the level [QR] draws at. Anything up to that is drawn. A +/// code near the limit is dense, and tapping it shows it full size. +const kSlatepackQrMaxBytes = 2953; + +bool slatepackFitsQr(String text) => + utf8.encode(text).length <= kSlatepackQrMaxBytes; + +/// QR code for a slatepack, or a note when it is too long for one. Tapping +/// the code shows it full size. +class SlatepackQr extends StatelessWidget { + const SlatepackQr({ + super.key, + required this.data, + required this.noun, + this.size = 220, + }); + + final String data; + + /// "slate" or "slatepack", for the too-long note. + final String noun; + final double size; + + Future _enlarge(BuildContext context) { + final screen = MediaQuery.of(context).size; + final side = math.min(math.min(screen.width, screen.height) - 64, 640.0); + return showDialog( + context: context, + builder: (dialogContext) => GestureDetector( + onTap: () => Navigator.of(dialogContext).pop(), + child: Center( + child: QR(data: data, size: side), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + if (!slatepackFitsQr(data)) { + return RoundedContainer( + key: const Key("slatepackQrTooLong"), + color: Theme.of(context).extension()!.textFieldDefaultBG, + child: Text( + "This $noun is too long for a QR code. " + "Copy or save it instead.", + style: STextStyles.label(context), + textAlign: TextAlign.center, + ), + ); + } + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + GestureDetector( + key: const Key("slatepackQrCode"), + onTap: () => _enlarge(context), + child: QR(data: data, size: size), + ), + const SizedBox(height: 4), + Text("Tap to enlarge", style: STextStyles.label(context)), + ], + ); + } +} diff --git a/lib/pages/slatepack/slatepack_send_flow.dart b/lib/pages/slatepack/slatepack_send_flow.dart new file mode 100644 index 0000000000..2b6fcd6305 --- /dev/null +++ b/lib/pages/slatepack/slatepack_send_flow.dart @@ -0,0 +1,188 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../db/isar/main_db.dart'; +import '../../models/isar/models/transaction_note.dart'; +import '../../models/slatepack_models.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/amount/amount.dart'; +import '../../utilities/exception_message.dart'; +import '../../utilities/logger.dart'; +import '../../utilities/route_presentation.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../../widgets/custom_loading_overlay.dart'; +import '../../widgets/stack_dialog.dart'; +import 'slatepack_dialog.dart'; + +/// Creates a manual Epic or MWC slate directly from either send screen. +/// +/// A manual slate is the first step of an interactive transaction, not a +/// transaction ready to approve and broadcast. It therefore bypasses the +/// normal fee estimate, confirmation and PIN flow and shows the wallet's +/// actual amount and fee after creation. +abstract final class SlatepackSendFlow { + static Future run({ + required BuildContext context, + required SlatepackInterface wallet, + required Amount amount, + required String message, + required String localNote, + required MainDB db, + required String Function(Amount) format, + }) async { + final terms = wallet.slatepackTerms; + final root = Navigator.of(context, rootNavigator: true); + final overlayColor = Theme.of(context) + .extension()! + .overlay + .withValues(alpha: 0.6); + final overlay = CurrentAwareDialogRoute( + context: context, + barrierDismissible: false, + themes: InheritedTheme.capture(from: context, to: root.context), + builder: (_) => PopScope( + canPop: false, + child: Container( + color: overlayColor, + child: CustomLoadingOverlay( + message: "Building ${terms.noun}...", + eventBus: null, + ), + ), + ), + ); + + unawaited(root.push(overlay)); + + SlatepackResult? result; + Object? error; + var noteSaved = localNote.isEmpty; + try { + // Some native MWC calls block synchronously. Do not start one while the + // keyboard or another route is still animating away. + await waitForRoutePresentation(overlay); + result = await wallet.createSlatepack( + amount: amount, + message: wallet.supportsOnChainNote && message.isNotEmpty + ? message + : null, + ); + if (!result.success || (result.slatepack?.trim().isEmpty ?? true)) { + throw Exception( + stripExceptionPrefixes( + result.error ?? "Failed to create ${terms.noun}", + ), + ); + } + + final slateId = result.slateId; + final createdAmount = result.amount; + final createdFee = result.fee; + if (slateId == null || + slateId.isEmpty || + createdAmount == null || + createdFee == null) { + final cancelError = slateId == null || slateId.isEmpty + ? "it has no slate id" + : await wallet.cancelPendingTransactionAndPost(slateId); + final outcome = cancelError.isEmpty + ? "The transaction was cancelled." + : "The transaction could not be cancelled ($cancelError). " + "Cancel it from its details before trying again."; + throw Exception( + "The wallet did not return the ${terms.noun}'s complete amount, " + "fee, and identifier. $outcome", + ); + } + + if (createdAmount != amount) { + final cancelError = await wallet.cancelPendingTransactionAndPost( + slateId, + ); + final outcome = cancelError.isEmpty + ? "The transaction was cancelled." + : "The transaction could not be cancelled ($cancelError). " + "Cancel it from its details before trying again."; + throw Exception( + "The ${terms.noun} was created for ${format(createdAmount)} instead " + "of the requested ${format(amount)}. $outcome", + ); + } + + if (!noteSaved) { + try { + await db.putTransactionNote( + TransactionNote( + walletId: wallet.walletId, + txid: slateId, + value: localNote, + ), + ); + noteSaved = true; + } catch (e, s) { + Logging.instance.w( + "Could not save the local note for $slateId", + error: e, + stackTrace: s, + ); + } + } + } catch (e, s) { + error = e; + Logging.instance.w( + "Could not create the ${terms.noun}", + error: e, + stackTrace: s, + ); + } + + if (root.mounted && overlay.isActive) { + await overlay.waitUntilCurrent(); + } + if (root.mounted && overlay.isActive) { + if (overlay.isCurrent) { + root.pop(); + } else { + root.removeRoute(overlay); + } + } + + final resultContext = root.context; + if (!resultContext.mounted) return false; + + if (error != null || result == null) { + await showDialog( + context: resultContext, + builder: (context) => StackOkDialog( + title: "Could not create the ${terms.noun}", + message: stripExceptionPrefixes( + error ?? "Failed to create ${terms.noun}", + ), + ), + ); + return false; + } + + await showSlatepackDialog( + context: resultContext, + terms: terms, + result: result, + supportsEncryption: wallet.supportsSlatepackEncryption, + formattedAmount: format(result.amount!), + formattedFee: format(result.fee!), + ); + if (!noteSaved && resultContext.mounted) { + await showDialog( + context: resultContext, + builder: (context) => const StackOkDialog( + title: "Local note not saved", + message: + "The transaction was created successfully, but its local " + "note could not be saved.", + ), + ); + } + return true; + } +} diff --git a/lib/pages/slatepack/slatepack_summary_dialog.dart b/lib/pages/slatepack/slatepack_summary_dialog.dart new file mode 100644 index 0000000000..ea651c9541 --- /dev/null +++ b/lib/pages/slatepack/slatepack_summary_dialog.dart @@ -0,0 +1,109 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../themes/stack_colors.dart'; +import '../../utilities/amount/amount.dart'; +import '../../utilities/amount/amount_formatter.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../wallets/crypto_currency/crypto_currency.dart'; +import '../../widgets/desktop/primary_button.dart'; +import '../../widgets/desktop/secondary_button.dart'; +import '../../widgets/detail_item.dart'; +import '../../widgets/rounded_container.dart'; +import '../../widgets/rounded_white_container.dart'; +import 'slatepack_popup.dart'; + +/// What an imported slatepack will do, with a button to go ahead. Pops true +/// when the user confirms. +class SlatepackSummaryDialog extends ConsumerWidget { + const SlatepackSummaryDialog({ + super.key, + required this.title, + required this.coin, + required this.actionLabel, + this.amount, + this.fee, + this.warning, + this.details = const [], + }); + + final String title; + final CryptoCurrency coin; + final String actionLabel; + final Amount? amount; + final Amount? fee; + final String? warning; + + /// Extra label and value rows shown under the amount and fee. + final List<(String, String)> details; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final isDesktop = Util.isDesktop; + final colors = Theme.of(context).extension()!; + final formatter = ref.watch(pAmountFormatter(coin)); + + final rows = <(String, String)>[ + if (amount != null) ("Amount", formatter.format(amount!)), + if (fee != null) ("Fee", formatter.format(fee!)), + ...details, + ]; + + return SlatepackPopupLayout( + title: title, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (warning != null) ...[ + RoundedContainer( + key: const Key("slatepackHistoryWarning"), + color: colors.warningBackground, + child: Text( + warning!, + style: STextStyles.smallMed14(context) + .copyWith(color: colors.warningForeground), + ), + ), + const SizedBox(height: 16), + ], + RoundedWhiteContainer( + padding: EdgeInsets.zero, + borderColor: isDesktop ? colors.backgroundAppBar : null, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) const DetailDivider(), + DetailItem(title: rows[i].$1, detail: rows[i].$2), + ], + ], + ), + ), + const SizedBox(height: 24), + Row( + children: [ + Expanded( + child: SecondaryButton( + label: "Cancel", + buttonHeight: isDesktop ? ButtonHeight.l : null, + onPressed: () => Navigator.of(context).pop(false), + ), + ), + const SizedBox(width: 16), + Expanded( + child: PrimaryButton( + label: actionLabel, + buttonHeight: isDesktop ? ButtonHeight.l : null, + onPressed: () => Navigator.of(context).pop(true), + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/pages/slatepack/slatepack_view.dart b/lib/pages/slatepack/slatepack_view.dart new file mode 100644 index 0000000000..951a3cb205 --- /dev/null +++ b/lib/pages/slatepack/slatepack_view.dart @@ -0,0 +1,175 @@ +/* + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../providers/global/wallets_provider.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/clipboard_interface.dart'; +import '../../utilities/constants.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../../widgets/background.dart'; +import '../../widgets/conditional_parent.dart'; +import '../../widgets/custom_buttons/app_bar_icon_button.dart'; +import '../../widgets/desktop/primary_button.dart'; +import 'slatepack_import_flow.dart'; +import 'slatepack_input_field.dart'; + +/// The manual slate-exchange screen: takes a slate or slatepack and hands it to +/// [SlatepackImportFlow], which works out whether to receive or finalize. +class SlatepackView extends ConsumerStatefulWidget { + const SlatepackView({ + super.key, + required this.walletId, + this.clipboard = const ClipboardWrapper(), + }); + + static const String routeName = "/slatepackView"; + + final String walletId; + final ClipboardInterface clipboard; + + @override + ConsumerState createState() => _SlatepackViewState(); +} + +class _SlatepackViewState extends ConsumerState { + late final TextEditingController _controller; + late final FocusNode _focusNode; + late final SlatepackInterface _wallet; + + /// True while a slatepack is being imported, so a second press of Continue + /// cannot start the import again. + bool _importing = false; + + bool get _hasText => _controller.text.trim().isNotEmpty; + + Future _continuePressed() async { + if (_importing) return; + setState(() => _importing = true); + try { + if (!Util.isDesktop && _focusNode.hasFocus) { + _focusNode.unfocus(); + await Future.delayed(const Duration(milliseconds: 75)); + } + if (!mounted) return; + + final done = await SlatepackImportFlow.run( + context: context, + wallet: _wallet, + text: _controller.text, + ); + if (done && mounted) { + setState(() => _controller.text = ""); + } + } finally { + _importing = false; + if (mounted) setState(() {}); + } + } + + @override + void initState() { + super.initState(); + _controller = TextEditingController(); + _focusNode = FocusNode(); + _wallet = + ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; + } + + @override + void dispose() { + _controller.dispose(); + _focusNode.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + debugPrint("BUILD: $runtimeType"); + final terms = _wallet.slatepackTerms; + + return ConditionalParent( + condition: !Util.isDesktop, + builder: (child) => Background( + child: Scaffold( + backgroundColor: Theme.of(context) + .extension()! + .background, + appBar: AppBar( + leading: AppBarBackButton( + onPressed: () { + Navigator.of(context).pop(); + }, + ), + title: Text(terms.title, style: STextStyles.navBarTitle(context)), + ), + body: SafeArea( + child: LayoutBuilder( + builder: (context, constraints) { + return SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints( + minHeight: constraints.maxHeight, + ), + child: IntrinsicHeight( + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: Constants.size.standardPadding, + ), + child: child, + ), + ), + ), + ); + }, + ), + ), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + "Paste, scan or open a ${terms.noun} you were sent. It is " + "received or finalized depending on what it is.", + style: Util.isDesktop + ? STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textSubtitle1, + ) + : STextStyles.label(context), + ), + const SizedBox(height: 12), + SlatepackInputField( + controller: _controller, + focusNode: _focusNode, + hint: "Enter ${terms.payload}", + terms: terms, + clipboard: widget.clipboard, + onChanged: (_) => setState(() {}), + ), + Util.isDesktop ? const SizedBox(height: 24) : const Spacer(), + PrimaryButton( + label: "Continue", + buttonHeight: Util.isDesktop ? ButtonHeight.l : null, + enabled: _hasText && !_importing, + onPressed: _hasText && !_importing ? _continuePressed : null, + ), + if (!Util.isDesktop) SizedBox(height: Constants.size.standardPadding), + ], + ), + ); + } +} 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 b38935dadf..d68e5d31b4 100644 --- a/lib/pages/wallet_view/transaction_views/transaction_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/transaction_details_view.dart @@ -37,8 +37,7 @@ import '../../../utilities/util.dart'; import '../../../wallets/crypto_currency/crypto_currency.dart'; import '../../../wallets/crypto_currency/intermediate/nano_currency.dart'; import '../../../wallets/isar/providers/wallet_info_provider.dart'; -import '../../../wallets/wallet/impl/epiccash_wallet.dart'; -import '../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; +import '../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../../widgets/background.dart'; import '../../../widgets/conditional_parent.dart'; import '../../../widgets/custom_buttons/app_bar_icon_button.dart'; @@ -275,16 +274,16 @@ class _TransactionDetailsViewState child: Text( "Cancel", style: STextStyles.button(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorDark, + color: Theme.of(context) + .extension()! + .accentColorDark, ), ), ), rightButton: TextButton( - style: Theme.of( - context, - ).extension()!.getPrimaryEnabledButtonStyle(context), + style: Theme.of(context) + .extension()! + .getPrimaryEnabledButtonStyle(context), onPressed: () { Navigator.of(context).pop(true); }, @@ -398,9 +397,9 @@ class _TransactionDetailsViewState appBar: isDesktop ? null : AppBar( - backgroundColor: Theme.of( - context, - ).extension()!.background, + backgroundColor: Theme.of(context) + .extension()! + .background, leading: AppBarBackButton( onPressed: () async { // if (FocusScope.of(context).hasFocus) { @@ -445,9 +444,9 @@ class _TransactionDetailsViewState builder: (child) { return RoundedWhiteContainer( borderColor: isDesktop - ? Theme.of( - context, - ).extension()!.backgroundAppBar + ? Theme.of(context) + .extension()! + .backgroundAppBar : null, padding: const EdgeInsets.all(0), child: child, @@ -896,15 +895,14 @@ class _TransactionDetailsViewState ) : GestureDetector( onTap: () { - Navigator.of( - context, - ).pushNamed( - EditNoteView.routeName, - arguments: Tuple2( - _transaction.txid, - walletId, - ), - ); + Navigator.of(context) + .pushNamed( + EditNoteView.routeName, + arguments: Tuple2( + _transaction.txid, + walletId, + ), + ); }, child: Row( children: [ @@ -1487,16 +1485,16 @@ class _TransactionDetailsViewState unawaited( showDialog( context: context, - builder: (_) => StackOkDialog( - title: - "Could not open in block explorer", - message: - "Failed to open \"${uri.toString()}\"", - maxWidth: - Util.isDesktop - ? 400 - : null, - ), + builder: (_) => + StackOkDialog( + title: "Could not open in block explorer", + message: + "Failed to open \"${uri.toString()}\"", + maxWidth: + Util.isDesktop + ? 400 + : null, + ), ), ); } @@ -1699,66 +1697,15 @@ class _TransactionDetailsViewState onPressed: () async { final wallet = ref.read(pWallets).getWallet(walletId); - if (wallet is EpiccashWallet) { - final String? id = _transaction.slateId; - if (id == null) { - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: "Could not find Epic transaction ID", - context: context, - ), - ); - return; - } - - unawaited( - showDialog( - barrierDismissible: false, - context: context, - builder: (_) => - const CancellingTransactionProgressDialog(), - ), - ); - - final result = await wallet - .cancelPendingTransactionAndPost(id); - - if (context.mounted) { - // pop progress dialog - Navigator.of(context).pop(); - - if (result.isEmpty) { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Transaction cancelled", - maxWidth: Util.isDesktop ? 400 : null, - onOkPressed: (_) { - Navigator.of(context).popUntil( - ModalRoute.withName(WalletView.routeName), - ); - }, - ), - ); - } else { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Failed to cancel transaction", - message: result, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - } - } - } else if (wallet is MimblewimblecoinWallet) { + if (wallet is SlatepackInterface) { final String? id = _transaction.slateId; if (id == null) { unawaited( showFloatingFlushBar( type: FlushBarType.warning, - message: "Could not find MWC transaction ID", + message: + "Could not find " + "${wallet.cryptoCurrency.ticker} transaction ID", context: context, ), ); @@ -1810,7 +1757,8 @@ class _TransactionDetailsViewState showFloatingFlushBar( type: FlushBarType.warning, message: - "ERROR: Wallet type is not Epic Cash or MimbleWimbleCoin", + "ERROR: This wallet cannot cancel " + "slatepack transactions", context: context, ), ); @@ -1853,9 +1801,9 @@ class IconCopyButton extends StatelessWidget { height: 26, width: 26, child: RawMaterialButton( - fillColor: Theme.of( - context, - ).extension()!.buttonBackSecondary, + fillColor: Theme.of(context) + .extension()! + .buttonBackSecondary, elevation: 0, hoverElevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)), @@ -1895,9 +1843,9 @@ class IconPencilButton extends StatelessWidget { height: 26, width: 26, child: RawMaterialButton( - fillColor: Theme.of( - context, - ).extension()!.buttonBackSecondary, + fillColor: Theme.of(context) + .extension()! + .buttonBackSecondary, elevation: 0, hoverElevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)), 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 c6eb3706ff..1ae13a8b07 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 @@ -34,6 +34,7 @@ import '../../../../utilities/block_explorers.dart'; import '../../../../utilities/constants.dart'; import '../../../../utilities/format.dart'; import '../../../../utilities/logger.dart'; +import '../../../../utilities/route_presentation.dart'; import '../../../../utilities/show_loading.dart'; import '../../../../utilities/text_styles.dart'; import '../../../../utilities/util.dart'; @@ -41,10 +42,9 @@ import '../../../../wallets/crypto_currency/crypto_currency.dart'; import '../../../../wallets/crypto_currency/intermediate/nano_currency.dart'; import '../../../../wallets/isar/models/spark_coin.dart'; import '../../../../wallets/isar/providers/wallet_info_provider.dart'; -import '../../../../wallets/wallet/impl/epiccash_wallet.dart'; -import '../../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/rbf_interface.dart'; +import '../../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; import '../../../../widgets/background.dart'; import '../../../../widgets/conditional_parent.dart'; @@ -60,6 +60,7 @@ import '../../../../widgets/icon_widgets/pencil_icon.dart'; import '../../../../widgets/rounded_white_container.dart'; import '../../../../widgets/stack_dialog.dart'; import '../../../../widgets/tx_key_widget.dart'; +import '../../../slatepack/slatepack_cancel_transaction_dialog.dart'; import '../../sub_widgets/tx_icon.dart'; import '../../wallet_view.dart'; import '../dialogs/cancelling_transaction_progress_dialog.dart'; @@ -100,6 +101,8 @@ class _TransactionV2DetailsViewState late final Contract? tokenContract; late final bool supportsRbf; late final bool hasTxKeyProbably; + late final bool isSlatepackWallet; + late final bool showOnChainNote; bool get isTokenTx => tokenContract != null; @@ -204,6 +207,9 @@ class _TransactionV2DetailsViewState walletId = widget.walletId; final wallet = ref.read(pWallets).getWallet(walletId); + isSlatepackWallet = wallet is SlatepackInterface; + showOnChainNote = + wallet is SlatepackInterface && wallet.supportsOnChainNote; hasTxKeyProbably = (wallet is CryptonoteWallet) && @@ -880,11 +886,11 @@ class _TransactionV2DetailsViewState ], ), ), - if (coin is Epiccash || coin is Mimblewimblecoin) + if (showOnChainNote) isDesktop ? const _Divider() : const SizedBox(height: 12), - if (coin is Epiccash || coin is Mimblewimblecoin) + if (showOnChainNote) RoundedWhiteContainer( padding: isDesktop ? const EdgeInsets.all(16) @@ -934,8 +940,7 @@ class _TransactionV2DetailsViewState MainAxisAlignment.spaceBetween, children: [ Text( - (coin is Epiccash || - coin is Mimblewimblecoin) + isSlatepackWallet ? "Local Note" : "Note ", style: labelStyle, @@ -1405,11 +1410,11 @@ class _TransactionV2DetailsViewState // ], // ), // ), - if (coin is Epiccash || coin is Mimblewimblecoin) + if (isSlatepackWallet) isDesktop ? const _Divider() : const SizedBox(height: 12), - if (coin is Epiccash || coin is Mimblewimblecoin) + if (isSlatepackWallet) RoundedWhiteContainer( padding: isDesktop ? const EdgeInsets.all(16) @@ -1464,9 +1469,14 @@ class _TransactionV2DetailsViewState ), ), ), - if ((coin is Epiccash || coin is Mimblewimblecoin) && - _transaction.getConfirmations(currentHeight) < 1 && - _transaction.isCancelled == false) + if (isSlatepackWallet && + canCancelSlateTransaction( + slateId: _transaction.slateId, + isCancelled: _transaction.isCancelled, + confirmations: _transaction.getConfirmations( + currentHeight, + ), + )) const SizedBox(height: 40), ], ), @@ -1474,9 +1484,12 @@ class _TransactionV2DetailsViewState ), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: - ((coin is Epiccash || coin is Mimblewimblecoin) && - _transaction.getConfirmations(currentHeight) < 1 && - _transaction.isCancelled == false) + (isSlatepackWallet && + canCancelSlateTransaction( + slateId: _transaction.slateId, + isCancelled: _transaction.isCancelled, + confirmations: _transaction.getConfirmations(currentHeight), + )) ? ConditionalParent( condition: isDesktop, builder: (child) => Padding( @@ -1497,87 +1510,49 @@ class _TransactionV2DetailsViewState onPressed: () async { final wallet = ref.read(pWallets).getWallet(walletId); - if (wallet is EpiccashWallet) { + if (wallet is SlatepackInterface) { final String? id = _transaction.slateId; if (id == null) { unawaited( showFloatingFlushBar( type: FlushBarType.warning, - message: "Could not find Epic transaction ID", + message: + "Could not find " + "${wallet.cryptoCurrency.ticker} transaction ID", context: context, ), ); return; } - unawaited( - showDialog( - barrierDismissible: false, - context: context, - builder: (_) => - const CancellingTransactionProgressDialog(), - ), + final proceed = await showDialog( + context: context, + builder: (_) => + const SlatepackCancelTransactionDialog(), ); + if (proceed != true || !context.mounted) return; - final result = await wallet - .cancelPendingTransactionAndPost(id); - if (context.mounted) { - // Pop progress dialog. - Navigator.of(context).pop(); - - if (result.isEmpty) { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Transaction cancelled", - onOkPressed: (_) { - Navigator.of(context).popUntil( - ModalRoute.withName(WalletView.routeName), - ); - }, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - unawaited(wallet.refresh()); - } else { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Failed to cancel transaction", - message: result, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - } - } - } else if (wallet is MimblewimblecoinWallet) { - final String? id = _transaction.slateId; - if (id == null) { - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: "Could not find MWC transaction ID", - context: context, - ), - ); - return; - } - - unawaited( - showDialog( - barrierDismissible: false, - context: context, - builder: (_) => - const CancellingTransactionProgressDialog(), - ), + final navigator = Navigator.of( + context, + rootNavigator: true, ); + final progressRoute = CurrentAwareDialogRoute( + context: context, + barrierDismissible: false, + builder: (_) => + const CancellingTransactionProgressDialog(), + ); + unawaited(navigator.push(progressRoute)); + await waitForRoutePresentation(progressRoute); final result = await wallet .cancelPendingTransactionAndPost(id); - if (context.mounted) { - // pop progress dialog - Navigator.of(context).pop(); - + final canPresentResult = + await dismissCurrentAwareDialogRoute( + navigator: navigator, + route: progressRoute, + ); + if (canPresentResult && context.mounted) { if (result.isEmpty) { await showDialog( context: context, @@ -1608,8 +1583,8 @@ class _TransactionV2DetailsViewState showFloatingFlushBar( type: FlushBarType.warning, message: - "ERROR: Wallet type is not " - "Epic Cash or MimbleWimbleCoin", + "ERROR: This wallet cannot cancel " + "slatepack transactions", context: context, ), ); @@ -1617,7 +1592,7 @@ class _TransactionV2DetailsViewState } }, child: Text( - "Cancel Transaction", + "Cancel transaction", style: STextStyles.button(context), ), ), diff --git a/lib/pages/wallet_view/wallet_view.dart b/lib/pages/wallet_view/wallet_view.dart index 9ced7e8546..ca07cbff62 100644 --- a/lib/pages/wallet_view/wallet_view.dart +++ b/lib/pages/wallet_view/wallet_view.dart @@ -50,13 +50,12 @@ import '../../wallets/crypto_currency/crypto_currency.dart'; import '../../wallets/crypto_currency/intermediate/frost_currency.dart'; import '../../wallets/isar/providers/wallet_info_provider.dart'; import '../../wallets/wallet/impl/bitcoin_frost_wallet.dart'; -import '../../wallets/wallet/impl/epiccash_wallet.dart'; import '../../wallets/wallet/impl/firo_wallet.dart'; -import '../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../wallets/wallet/impl/namecoin_wallet.dart'; import '../../wallets/wallet/impl/salvium_wallet.dart'; import '../../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../../wallets/wallet/intermediate/lib_salvium_wallet.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/cash_fusion_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/coin_control_interface.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; @@ -92,9 +91,8 @@ import '../buy_view/buy_in_wallet_view.dart'; import '../cashfusion/cashfusion_view.dart'; import '../churning/churning_view.dart'; import '../coin_control/coin_control_view.dart'; -import '../epic_finalize_view/epic_finalize_view.dart'; import '../exchange_view/wallet_initiated_exchange_view.dart'; -import '../finalize_view/finalize_view.dart'; +import '../slatepack/slatepack_view.dart'; import '../masternodes/masternodes_home_view.dart'; import '../monkey/monkey_view.dart'; import '../namecoin_names/namecoin_names_home_view.dart'; @@ -1011,30 +1009,28 @@ class _WalletViewState extends ConsumerState { } }, ), - if (wallet is MimblewimblecoinWallet) + if (wallet is SlatepackInterface) WalletNavigationBarItemData( - label: "Finalize", - icon: const FinalizeNavIcon(), - onTap: () { - if (mounted) { - unawaited( - Navigator.of(context).pushNamed( - FinalizeView.routeName, - arguments: walletId, - ), - ); - } - }, - ), - if (wallet is EpiccashWallet) - WalletNavigationBarItemData( - label: "Finalize", + label: wallet.slatepackTerms.title, + overrideText: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + wallet.slatepackTerms.title, + maxLines: 1, + softWrap: false, + style: STextStyles.buttonSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .bottomNavText, + ), + ), + ), icon: const FinalizeNavIcon(), onTap: () { if (mounted) { unawaited( Navigator.of(context).pushNamed( - EpicFinalizeView.routeName, + SlatepackView.routeName, arguments: walletId, ), ); 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 eb354eb1e0..e03703cde9 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 @@ -22,8 +22,8 @@ import '../../../../models/isar/models/isar_models.dart'; import '../../../../models/keys/view_only_wallet_data.dart'; import '../../../../notifications/show_flush_bar.dart'; import '../../../../pages/receive_view/generate_receiving_uri_qr_code_view.dart'; -import '../../../../pages/receive_view/sub_widgets/epic_slatepack_import_dialog.dart'; -import '../../../../pages/receive_view/sub_widgets/mwc_slatepack_import_dialog.dart'; +import '../../../../pages/slatepack/slatepack_import_flow.dart'; +import '../../../../pages/slatepack/slatepack_input_field.dart'; import '../../../../providers/providers.dart'; import '../../../../providers/ui/preview_tx_button_state_provider.dart'; import '../../../../route_generator.dart'; @@ -34,19 +34,18 @@ import '../../../../utilities/clipboard_interface.dart'; import '../../../../utilities/constants.dart'; import '../../../../utilities/enums/derive_path_type_enum.dart'; import '../../../../utilities/show_loading.dart'; +import '../../../../utilities/slatepack_terms.dart'; import '../../../../utilities/text_styles.dart'; import '../../../../utilities/util.dart'; import '../../../../wallets/crypto_currency/crypto_currency.dart'; -import '../../../../wallets/isar/providers/eth/current_token_wallet_provider.dart'; import '../../../../wallets/isar/providers/wallet_info_provider.dart'; import '../../../../wallets/wallet/impl/bitcoin_wallet.dart'; -import '../../../../wallets/wallet/impl/epiccash_wallet.dart'; -import '../../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../../../wallets/wallet/intermediate/bip39_hd_wallet.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/bcash_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/extended_keys_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/multi_address_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; +import '../../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/view_only_option_interface.dart'; import '../../../../widgets/conditional_parent.dart'; @@ -55,16 +54,9 @@ import '../../../../widgets/custom_loading_overlay.dart'; import '../../../../widgets/desktop/desktop_dialog.dart'; import '../../../../widgets/desktop/primary_button.dart'; import '../../../../widgets/desktop/secondary_button.dart'; -import '../../../../widgets/dialogs/s_dialog.dart'; -import '../../../../widgets/icon_widgets/clipboard_icon.dart'; -import '../../../../widgets/icon_widgets/x_icon.dart'; -import '../../../../widgets/epic_txs_method_toggle.dart'; -import '../../../../widgets/mwc_txs_method_toggle.dart'; +import '../../../../widgets/slatepack_method_toggle.dart'; import '../../../../widgets/qr.dart'; import '../../../../widgets/rounded_white_container.dart'; -import '../../../../widgets/stack_dialog.dart'; -import '../../../../widgets/stack_text_field.dart'; -import '../../../../widgets/textfield_icon_button.dart'; class DesktopReceive extends ConsumerStatefulWidget { const DesktopReceive({ @@ -89,12 +81,10 @@ class _DesktopReceiveState extends ConsumerState { late final bool supportsSpark; late bool supportsMweb; late final bool showMultiType; - late final bool isMimblewimblecoin; - late final bool isEpiccash; - late TextEditingController _receiveSlateController; - String? _slate; - bool _slateToggleFlag = false; - final _slateFocusNode = FocusNode(); + late final bool usesSlatepacks; + late final TextEditingController _receiveSlateController; + late final SlatepackTerms _slatepackTerms; + bool _importingSlatepack = false; int _currentIndex = 0; @@ -102,134 +92,23 @@ class _DesktopReceiveState extends ConsumerState { final Map _addressMap = {}; final Map> _addressSubMap = {}; - Future _pasteSlatepack() async { - final ClipboardData? data = await clipboard.getData(Clipboard.kTextPlain); - if (data?.text != null && data!.text!.isNotEmpty) { - _slate = data.text; - _receiveSlateController.text = _slate!; - setState(() { - _slateToggleFlag = _receiveSlateController.text.isNotEmpty; - }); - } - } - - Future _onReceiveSlatePressed() async { - final wallet = - ref.read(pWallets).getWallet(walletId) as MimblewimblecoinWallet; - - Exception? ex; - final result = await showLoading( - whileFuture: wallet.fullDecodeSlatepack(_receiveSlateController.text), - context: context, - message: "Decoding slatepack...", - rootNavigator: Util.isDesktop, - onException: (e) => ex = e, - ); - - if (result == null || ex != null) { - if (mounted) { - await showDialog( - context: context, - useRootNavigator: true, - builder: (context) => StackOkDialog( - desktopPopRootNavigator: true, - title: "Slatepack receive error", - message: ex?.toString() ?? "Unexpected result without exception", - maxWidth: 400, - ), - ); - } - return; - } - - if (mounted) { - final response = - await showDialog<({String responseSlatepack, bool wasEncrypted})>( - context: context, - builder: (context) => SDialog( - child: SizedBox( - width: 700, - child: MwcSlatepackImportDialog( - walletId: widget.walletId, - clipboard: widget.clipboard, - rawSlatepack: result.raw, - decoded: result.result, - slatepackType: result.type, - ), - ), - ), - ); - - if (mounted && response != null) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => SlatepackResponseDialog( - responseSlatepack: response.responseSlatepack, - wasEncrypted: response.wasEncrypted, - ), - ); - } - } - } - - Future _onEpicReceiveSlatePressed() async { - final wallet = - ref.read(pWallets).getWallet(walletId) as EpiccashWallet; - - Exception? ex; - final result = await showLoading( - whileFuture: wallet.fullDecodeSlatepack(_receiveSlateController.text), - context: context, - message: "Decoding slatepack...", - rootNavigator: Util.isDesktop, - onException: (e) => ex = e, - ); - - if (result == null || ex != null) { - if (mounted) { - await showDialog( - context: context, - useRootNavigator: true, - builder: (context) => StackOkDialog( - desktopPopRootNavigator: true, - title: "Slatepack receive error", - message: ex?.toString() ?? "Unexpected result without exception", - maxWidth: 400, - ), - ); - } - return; - } - - if (mounted) { - final response = - await showDialog<({String responseSlatepack, bool wasEncrypted})>( - context: context, - builder: (context) => SDialog( - child: SizedBox( - width: 700, - child: EpicSlatepackImportDialog( - walletId: widget.walletId, - clipboard: widget.clipboard, - rawSlatepack: result.raw, - decoded: result.result, - slatepackType: result.type, - ), - ), - ), - ); - - if (mounted && response != null) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => EpicSlatepackResponseDialog( - responseSlatepack: response.responseSlatepack, - wasEncrypted: response.wasEncrypted, - ), - ); + Future _onImportSlatepackPressed() async { + if (_importingSlatepack) return; + setState(() => _importingSlatepack = true); + try { + final wallet = + ref.read(pWallets).getWallet(walletId) as SlatepackInterface; + final done = await SlatepackImportFlow.run( + context: context, + wallet: wallet, + text: _receiveSlateController.text, + ); + if (done && mounted) { + setState(() => _receiveSlateController.text = ""); } + } finally { + _importingSlatepack = false; + if (mounted) setState(() {}); } } @@ -244,9 +123,10 @@ class _DesktopReceiveState extends ConsumerState { return WillPopScope( onWillPop: () async => shouldPop, child: Container( - color: Theme.of( - context, - ).extension()!.overlay.withOpacity(0.5), + color: Theme.of(context) + .extension()! + .overlay + .withOpacity(0.5), child: const CustomLoadingOverlay( message: "Generating address", eventBus: null, @@ -323,9 +203,10 @@ class _DesktopReceiveState extends ConsumerState { return WillPopScope( onWillPop: () async => shouldPop, child: Container( - color: Theme.of( - context, - ).extension()!.overlay.withOpacity(0.5), + color: Theme.of(context) + .extension()! + .overlay + .withOpacity(0.5), child: const CustomLoadingOverlay( message: "Generating address", eventBus: null, @@ -414,8 +295,10 @@ class _DesktopReceiveState extends ConsumerState { !wallet.info.isViewOnly && wallet.info.isMwebEnabled; - isMimblewimblecoin = wallet is MimblewimblecoinWallet; - isEpiccash = wallet is EpiccashWallet; + usesSlatepacks = wallet is SlatepackInterface; + _slatepackTerms = wallet is SlatepackInterface + ? wallet.slatepackTerms + : SlatepackTerms.slatepack; if (wallet is ViewOnlyOptionInterface && wallet.isViewOnly) { showMultiType = false; @@ -536,6 +419,8 @@ class _DesktopReceiveState extends ConsumerState { final wallet = ref.watch( pWallets.select((value) => value.getWallet(walletId)), ); + final isSlatepackMode = + wallet is SlatepackInterface && ref.watch(pIsSlatepack(walletId)); final bool canGen; if (wallet is ViewOnlyOptionInterface && @@ -551,63 +436,34 @@ class _DesktopReceiveState extends ConsumerState { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const SizedBox(height: 4), - if (isMimblewimblecoin) + if (wallet is SlatepackInterface && wallet.hasSlatepackMethodToggle) Padding( padding: const EdgeInsets.all(0), child: Container( decoration: BoxDecoration( color: - Theme.of( - context, - ).extension()?.textFieldDefaultBG ?? + Theme.of(context) + .extension() + ?.textFieldDefaultBG ?? Colors.white, // Fallback color borderRadius: BorderRadius.circular(8), border: Border.all( color: - Theme.of( - context, - ).extension()?.backgroundAppBar ?? + Theme.of(context) + .extension() + ?.backgroundAppBar ?? Colors.grey, // Fallback color width: 1, ), ), - child: const SizedBox( - height: - 60, // Provide an explicit height to avoid infinite constraints - child: MwcTxsMethodToggle(), - ), - ), - ), - if (isEpiccash) - Padding( - padding: const EdgeInsets.all(0), - child: Container( - decoration: BoxDecoration( - color: - Theme.of( - context, - ).extension()?.textFieldDefaultBG ?? - Colors.white, // Fallback color - borderRadius: BorderRadius.circular(8), - border: Border.all( - color: - Theme.of( - context, - ).extension()?.backgroundAppBar ?? - Colors.grey, // Fallback color - width: 1, - ), - ), - child: const SizedBox( - height: - 60, // Provide an explicit height to avoid infinite constraints - child: EpicTxsMethodToggle(), + child: SizedBox( + height: 60, // Provide an explicit height to avoid infinite constraints + child: SlatepackMethodToggle(walletId: walletId), ), ), ), - if (!((isMimblewimblecoin || isEpiccash) && ref.watch(pIsSlatepack(widget.walletId)))) - const SizedBox(height: 20), - if (!((isMimblewimblecoin || isEpiccash) && ref.watch(pIsSlatepack(widget.walletId)))) + const SizedBox(height: 20), + if (!isSlatepackMode) ...[ ConditionalParent( condition: showMultiType, builder: (child) => Column( @@ -652,9 +508,9 @@ class _DesktopReceiveState extends ConsumerState { ), buttonStyleData: ButtonStyleData( decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.textFieldDefaultBG, + color: Theme.of(context) + .extension()! + .textFieldDefaultBG, borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, ), @@ -664,9 +520,9 @@ class _DesktopReceiveState extends ConsumerState { offset: const Offset(0, -10), elevation: 0, decoration: BoxDecoration( - color: Theme.of( - context, - ).extension()!.textFieldDefaultBG, + color: Theme.of(context) + .extension()! + .textFieldDefaultBG, borderRadius: BorderRadius.circular( Constants.size.circularBorderRadius, ), @@ -699,9 +555,9 @@ class _DesktopReceiveState extends ConsumerState { child: Container( decoration: BoxDecoration( border: Border.all( - color: Theme.of( - context, - ).extension()!.backgroundAppBar, + color: Theme.of(context) + .extension()! + .backgroundAppBar, width: 1, ), borderRadius: BorderRadius.circular( @@ -726,9 +582,9 @@ class _DesktopReceiveState extends ConsumerState { Assets.svg.copy, width: 15, height: 15, - color: Theme.of( - context, - ).extension()!.infoItemIcons, + color: Theme.of(context) + .extension()! + .infoItemIcons, ), const SizedBox(width: 4), Text("Copy", style: STextStyles.link2(context)), @@ -746,9 +602,9 @@ class _DesktopReceiveState extends ConsumerState { STextStyles.desktopTextExtraExtraSmall( context, ).copyWith( - color: Theme.of( - context, - ).extension()!.textDark, + color: Theme.of(context) + .extension()! + .textDark, ), ), ), @@ -762,166 +618,31 @@ class _DesktopReceiveState extends ConsumerState { ), ), - if (canGen) const SizedBox(height: 20), + if (canGen) const SizedBox(height: 20), - if (canGen) - SecondaryButton( - buttonHeight: ButtonHeight.l, - onPressed: - supportsMweb && - _walletAddressTypes[_currentIndex] == AddressType.mweb - ? generateNewMwebAddress - : supportsSpark && - _walletAddressTypes[_currentIndex] == AddressType.spark - ? generateNewSparkAddress - : generateNewAddress, - label: "Generate new address", - ), - const SizedBox(height: 20), - if ((isMimblewimblecoin || isEpiccash) && ref.watch(pIsSlatepack(widget.walletId))) - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Label Text - Text( - "Receive Slatepack", - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textFieldActiveSearchIconRight, - ), - textAlign: TextAlign.left, - ), - const SizedBox(height: 8), - ClipRRect( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - child: TextField( - minLines: 1, - maxLines: 5, - key: const Key("receiveViewSlatepackFieldKey"), - controller: _receiveSlateController, - readOnly: false, - autocorrect: false, - enableSuggestions: false, - toolbarOptions: const ToolbarOptions( - copy: false, - cut: false, - paste: true, - selectAll: false, - ), - onChanged: (newValue) { - _slate = newValue; - setState(() { - _slateToggleFlag = newValue.isNotEmpty; - }); - }, - focusNode: _slateFocusNode, - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.textFieldActiveText, - height: 1.8, - ), - decoration: - standardInputDecoration( - "Enter Slatepack Message", - _slateFocusNode, - context, - desktopMed: true, - ).copyWith( - contentPadding: const EdgeInsets.symmetric( - horizontal: 16, - vertical: - 12, // Adjust vertical padding for better alignment - ), - suffixIcon: Padding( - padding: _receiveSlateController.text.isEmpty - ? const EdgeInsets.only(right: 8) - : const EdgeInsets.only(right: 0), - child: UnconstrainedBox( - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - _slateToggleFlag - ? TextFieldIconButton( - key: const Key( - "receiveViewClearSlatepackFieldButtonKey", - ), - onTap: () { - _receiveSlateController.text = ""; - _slate = ""; - setState(() { - _slateToggleFlag = false; - }); - }, - child: const XIcon(), - ) - : TextFieldIconButton( - key: const Key( - "receiveViewPasteSlatepackFieldButtonKey", - ), - onTap: _pasteSlatepack, - child: - _receiveSlateController.text.isEmpty - ? const ClipboardIcon() - : const XIcon(), - ), - ], - ), - ), - ), - ), - ), - ), - ], - ) - //Padding( - // padding: const EdgeInsets.symmetric(vertical: 8.0), - // child: TextField( - // maxLines: 8, // Set to a higher number to make the height larger - // minLines: 5, // Allow it to shrink if input is small - // decoration: InputDecoration( - // labelText: 'Enter Slatepack Message', - // alignLabelWithHint: true, - // border: OutlineInputBorder( - // borderRadius: BorderRadius.circular(8), - // ), - // filled: true, - // fillColor: Theme.of(context).extension()?.textFieldDefaultBG ?? Colors.white, - // contentPadding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 12.0), - // ), - // onChanged: (value) { - // // Handle text input changes (e.g., store in a state variable) - // debugPrint('Slatepack Message: $value'); - // }, - // ), - //) - else + if (canGen) + SecondaryButton( + buttonHeight: ButtonHeight.l, + onPressed: + supportsMweb && + _walletAddressTypes[_currentIndex] == AddressType.mweb + ? generateNewMwebAddress + : supportsSpark && + _walletAddressTypes[_currentIndex] == AddressType.spark + ? generateNewSparkAddress + : generateNewAddress, + label: "Generate new address", + ), + const SizedBox(height: 20), Center( child: QR( data: AddressUtils.buildUriString(coin.uriScheme, address, {}), size: 200, ), ), - const SizedBox(height: 32), + const SizedBox(height: 32), - // TODO: create transparent button class to account for hover - // Conditional logic for 'Submit' button or QR code - if ((isMimblewimblecoin || isEpiccash) && ref.watch(pIsSlatepack(widget.walletId))) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8.0), - child: PrimaryButton( - buttonHeight: ButtonHeight.l, - label: "Receive Slatepack", - enabled: _slateToggleFlag, - onPressed: _slateToggleFlag - ? (isEpiccash ? _onEpicReceiveSlatePressed : _onReceiveSlatePressed) - : null, - ), - ) - else + // TODO: create transparent button class to account for hover GestureDetector( onTap: () async { if (Util.isDesktop) { @@ -986,23 +707,56 @@ class _DesktopReceiveState extends ConsumerState { Assets.svg.qrcode, width: 14, height: 16, - color: Theme.of( - context, - ).extension()!.accentColorBlue, + color: Theme.of(context) + .extension()! + .accentColorBlue, ), const SizedBox(width: 8), Text( "Create new QR code", style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of( - context, - ).extension()!.accentColorBlue, + color: Theme.of(context) + .extension()! + .accentColorBlue, ), ), ], ), ), ), + ], + if (isSlatepackMode) ...[ + Text( + "Import ${_slatepackTerms.title}", + style: STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textFieldActiveSearchIconRight, + ), + textAlign: TextAlign.left, + ), + const SizedBox(height: 8), + SlatepackInputField( + controller: _receiveSlateController, + hint: "Enter ${_slatepackTerms.payload}", + terms: _slatepackTerms, + clipboard: clipboard, + onChanged: (_) => setState(() {}), + ), + const SizedBox(height: 16), + PrimaryButton( + buttonHeight: ButtonHeight.l, + label: "Import ${_slatepackTerms.title}", + enabled: + _receiveSlateController.text.trim().isNotEmpty && + !_importingSlatepack, + onPressed: + _receiveSlateController.text.trim().isNotEmpty && + !_importingSlatepack + ? _onImportSlatepackPressed + : null, + ), + ], ], ); } 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 ebbd81514b..977cee09e4 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 @@ -18,20 +18,17 @@ import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; -import '../../../../models/epic_slatepack_models.dart'; import '../../../../models/isar/models/blockchain_data/address.dart'; import '../../../../models/isar/models/blockchain_data/utxo.dart'; import '../../../../models/isar/models/contact_entry.dart'; -import '../../../../models/mwc_slatepack_models.dart'; import '../../../../models/paynym/paynym_account_lite.dart'; import '../../../../models/send_view_auto_fill_data.dart'; import '../../../../notifications/show_flush_bar.dart'; import '../../../../pages/send_view/confirm_transaction_view.dart'; import '../../../../pages/send_view/frost_ms/recipient.dart'; import '../../../../pages/send_view/sub_widgets/building_transaction_dialog.dart'; -import '../../../../pages/send_view/sub_widgets/epic_slatepack_dialog.dart'; import '../../../../pages/send_view/sub_widgets/multi_recipient.dart'; -import '../../../../pages/send_view/sub_widgets/mwc_slatepack_dialog.dart'; +import '../../../../pages/slatepack/slatepack_send_flow.dart'; import '../../../../providers/providers.dart'; import '../../../../providers/ui/fee_rate_type_state_provider.dart'; import '../../../../providers/ui/preview_tx_button_state_provider.dart'; @@ -54,19 +51,17 @@ import '../../../../utilities/enums/fee_rate_type_enum.dart'; import '../../../../utilities/integer_input.dart'; import '../../../../utilities/logger.dart'; import '../../../../utilities/prefs.dart'; -import '../../../../utilities/show_loading.dart'; import '../../../../utilities/text_styles.dart'; import '../../../../utilities/util.dart'; import '../../../../wallets/crypto_currency/crypto_currency.dart'; import '../../../../wallets/isar/providers/wallet_info_provider.dart'; import '../../../../wallets/models/tx_data.dart'; -import '../../../../wallets/wallet/impl/epiccash_wallet.dart'; import '../../../../wallets/wallet/impl/firo_wallet.dart'; -import '../../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import '../../../../wallets/wallet/impl/salvium_wallet.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/coin_control_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/mweb_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/paynym_interface.dart'; +import '../../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart'; import '../../../../widgets/custom_buttons/blue_text_button.dart'; import '../../../../widgets/desktop/desktop_dialog.dart'; @@ -76,13 +71,12 @@ import '../../../../widgets/desktop/qr_code_scanner_dialog.dart'; import '../../../../widgets/desktop/secondary_button.dart'; import '../../../../widgets/desktop/simple_desktop_dialog.dart'; import '../../../../widgets/dialogs/firo_exchange_address_dialog.dart'; -import '../../../../widgets/epic_txs_method_toggle.dart'; import '../../../../widgets/eth_fee_form.dart'; import '../../../../widgets/icon_widgets/addressbook_icon.dart'; import '../../../../widgets/icon_widgets/clipboard_icon.dart'; import '../../../../widgets/icon_widgets/qrcode_icon.dart'; import '../../../../widgets/icon_widgets/x_icon.dart'; -import '../../../../widgets/mwc_txs_method_toggle.dart'; +import '../../../../widgets/slatepack_method_toggle.dart'; import '../../../../widgets/rounded_container.dart'; import '../../../../widgets/stack_text_field.dart'; import '../../../../widgets/textfield_icon_button.dart'; @@ -130,8 +124,22 @@ class _DesktopSendState extends ConsumerState { final _nonceFocusNode = FocusNode(); late final bool hasOptionalMemo; - late final bool isMimblewimblecoin; - late final bool isEpiccash; + late final bool usesSlatepacks; + + void _formatMimblewimbleAddress() { + var address = sendToController.text.trim(); + if (address.isEmpty) return; + if (address.contains("\n")) { + address = address.substring(0, address.indexOf("\n")); + } + final formatted = coin is Epiccash + ? formatAddress(address) + : formatAddressMwc(address); + _address = formatted; + if (sendToController.text != formatted) { + sendToController.text = formatted; + } + } String? _note; String? _onChainNote; @@ -200,255 +208,6 @@ class _DesktopSendState extends ConsumerState { } } - /// Handle MWC slatepack creation for desktop. - Future _handleDesktopSlatepackCreation( - MimblewimblecoinWallet wallet, - ) async { - try { - final amount = ref.read(pSendAmount)!; - - Future wrappedFutureWithDelay() async { - await Future.delayed(const Duration(seconds: 1)); - return wallet.createSlatepack( - amount: amount, - recipientAddress: null, // No specific recipient for manual slatepack. - message: _onChainNote?.isNotEmpty == true ? _onChainNote : null, - encrypt: false, // No encryption without recipient address. - ); - } - - // Create slatepack. - Exception? ex; - final slatepackResult = await showLoading( - whileFuture: wrappedFutureWithDelay(), - context: context, - rootNavigator: true, - message: "Building slatepack...", - delay: const Duration(seconds: 2), - onException: (e) => ex = e, - ); - - if (slatepackResult == null || - !slatepackResult.success || - slatepackResult.slatepack == null || - ex != null) { - String error = - ex?.toString() ?? - slatepackResult?.error ?? - 'Failed to create slatepack'; - if (error.startsWith("Exception:")) { - error = error.replaceFirst("Exception:", "").trim(); - } - throw Exception(error); - } - - // refresh asap to show the pending slate tx in history - unawaited(() async { - await Future.delayed(Duration.zero); - await wallet.refresh(); - }()); - - // Show slatepack dialog. - if (mounted) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => DesktopDialog( - maxHeight: double.infinity, - maxWidth: 700, - child: MwcSlatepackDialog(slatepackResult: slatepackResult), - ), - ); - - // Clear form after slatepack dialog is closed. - clearSendForm(); - } - } catch (e, s) { - Logging.instance.e( - 'Failed to create MWC slatepack on desktop', - error: e, - stackTrace: s, - ); - - if (mounted) { - await showDialog( - context: context, - builder: (context) => DesktopDialog( - maxWidth: 450, - maxHeight: double.infinity, - child: Padding( - padding: const EdgeInsets.only(left: 32, bottom: 32), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - 'Slatepack Creation Failed', - style: STextStyles.desktopH3(context), - ), - const DesktopDialogCloseButton(), - ], - ), - const SizedBox(height: 12), - Padding( - padding: const EdgeInsets.only(right: 32), - child: Text( - 'Failed to create slatepack: $e', - textAlign: TextAlign.left, - style: STextStyles.desktopTextExtraExtraSmall(context) - .copyWith(fontSize: 18), - ), - ), - const SizedBox(height: 40), - Padding( - padding: const EdgeInsets.only(right: 32), - child: Row( - children: [ - Expanded( - child: PrimaryButton( - buttonHeight: ButtonHeight.l, - label: 'OK', - onPressed: () => Navigator.of(context).pop(), - ), - ), - ], - ), - ), - ], - ), - ), - ), - ); - } - } - } - - /// Handle Epic Cash slate creation for desktop. - Future _handleDesktopEpicSlatepackCreation( - EpiccashWallet wallet, - ) async { - try { - final amount = ref.read(pSendAmount)!; - - Future wrappedFutureWithDelay() async { - await Future.delayed(const Duration(seconds: 1)); - return wallet.createSlatepack( - amount: amount, - recipientAddress: null, // No specific recipient for manual slatepack. - message: _onChainNote?.isNotEmpty == true ? _onChainNote : null, - ); - } - - // Create slatepack. - Exception? ex; - final slatepackResult = await showLoading( - whileFuture: wrappedFutureWithDelay(), - context: context, - rootNavigator: true, - message: "Building slate...", - delay: const Duration(seconds: 2), - onException: (e) => ex = e, - ); - - if (slatepackResult == null || - !slatepackResult.success || - slatepackResult.slatepack == null || - ex != null) { - String error = - ex?.toString() ?? - slatepackResult?.error ?? - 'Failed to create slate'; - if (error.startsWith("Exception:")) { - error = error.replaceFirst("Exception:", "").trim(); - } - throw Exception(error); - } - - // refresh asap to show the pending slate tx in history - unawaited(() async { - await Future.delayed(Duration.zero); - await wallet.refresh(); - }()); - - // Show slatepack dialog. - if (mounted) { - await showDialog( - context: context, - barrierDismissible: false, - builder: (context) => DesktopDialog( - maxHeight: double.infinity, - maxWidth: 700, - child: EpicSlatepackDialog(slatepackResult: slatepackResult), - ), - ); - - // Clear form after slatepack dialog is closed. - clearSendForm(); - } - } catch (e, s) { - Logging.instance.e( - 'Failed to create Epic Cash slate on desktop', - error: e, - stackTrace: s, - ); - - if (mounted) { - await showDialog( - context: context, - builder: (context) => DesktopDialog( - maxWidth: 450, - maxHeight: double.infinity, - child: Padding( - padding: const EdgeInsets.only(left: 32, bottom: 32), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - 'Slate Creation Failed', - style: STextStyles.desktopH3(context), - ), - const DesktopDialogCloseButton(), - ], - ), - const SizedBox(height: 12), - Padding( - padding: const EdgeInsets.only(right: 32), - child: Text( - 'Failed to create slate: $e', - textAlign: TextAlign.left, - style: STextStyles.desktopTextExtraExtraSmall(context) - .copyWith(fontSize: 18), - ), - ), - const SizedBox(height: 40), - Padding( - padding: const EdgeInsets.only(right: 32), - child: Row( - children: [ - Expanded( - child: PrimaryButton( - buttonHeight: ButtonHeight.l, - label: 'OK', - onPressed: () => Navigator.of(context).pop(), - ), - ), - ], - ), - ), - ], - ), - ), - ), - ); - } - } - } - /// Looks up the OpenAlias in the address field. Returns null if the lookup /// failed or was cancelled. Future _resolveOpenAlias(String application) async { @@ -509,10 +268,13 @@ class _DesktopSendState extends ConsumerState { final nonce = nonceInput.value; final wallet = ref.read(pWallets).getWallet(walletId); + final isSlatepackSend = + wallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); String? openAlias; String? resolvedAddress; final application = coin.openAliasApplication; if (application != null && + !isSlatepackSend && !coin.validateAddress(_address ?? "") && isOpenAlias(_address ?? "")) { var resolved = _openAlias; @@ -528,19 +290,21 @@ class _DesktopSendState extends ConsumerState { } late final recipientAddress = resolvedAddress ?? _address!; - // Handle MWC slatepack transactions directly. - if (isMimblewimblecoin && ref.read(pIsSlatepack(widget.walletId))) { - await _handleDesktopSlatepackCreation(wallet as MimblewimblecoinWallet); - return; - } - - // Handle Epic Cash slatepack transactions directly. - if (isEpiccash && ref.read(pIsSlatepack(widget.walletId))) { - await _handleDesktopEpicSlatepackCreation(wallet as EpiccashWallet); + final Amount amount = ref.read(pSendAmount)!; + if (isSlatepackSend) { + final created = await SlatepackSendFlow.run( + context: context, + wallet: wallet, + amount: amount, + message: _onChainNote ?? "", + localNote: _note ?? "", + db: ref.read(mainDBProvider), + format: ref.read(pAmountFormatter(wallet.cryptoCurrency)).format, + ); + if (created && mounted) clearSendForm(); return; } - final Amount amount = ref.read(pSendAmount)!; final Amount availableBalance; if (coin is Firo || ref.read(pWalletInfo(walletId)).isMwebEnabled) { switch (ref.read(publicPrivateBalanceStateProvider.state).state) { @@ -867,10 +631,7 @@ class _DesktopSendState extends ConsumerState { ); } else { txData = txData.copyWith(note: _note ?? ""); - if (coin is Epiccash) { - txData = txData.copyWith(noteOnChain: _onChainNote ?? ""); - } - if (coin is Mimblewimblecoin) { + if (wallet is SlatepackInterface && wallet.supportsOnChainNote) { txData = txData.copyWith(noteOnChain: _onChainNote ?? ""); } } @@ -1567,14 +1328,17 @@ class _DesktopSendState extends ConsumerState { clipboard = widget.clipboard; hasOptionalMemo = coin is Stellar || coin is Solana; - isMimblewimblecoin = coin is Mimblewimblecoin; - isEpiccash = coin is Epiccash; + usesSlatepacks = + ref.read(pWallets).getWallet(walletId) is SlatepackInterface; sendToController = TextEditingController(); cryptoAmountController = TextEditingController(); baseAmountController = TextEditingController(); memoController = TextEditingController(); nonceController = TextEditingController(); + if (coin is Epiccash || coin is Mimblewimblecoin) { + sendToController.addListener(_formatMimblewimbleAddress); + } onCryptoAmountChanged = _cryptoAmountChanged; cryptoAmountController.addListener(onCryptoAmountChanged); @@ -1628,6 +1392,9 @@ class _DesktopSendState extends ConsumerState { @override void dispose() { cryptoAmountController.removeListener(onCryptoAmountChanged); + if (coin is Epiccash || coin is Mimblewimblecoin) { + sendToController.removeListener(_formatMimblewimbleAddress); + } _ethFee.dispose(); _feeAmount.dispose(); @@ -1675,42 +1442,14 @@ class _DesktopSendState extends ConsumerState { }); // ethFee is checked in the ValueListenableBuilder around the preview // button so fee keystrokes don't rebuild this whole view. - final previewEnabled = ref.watch(pPreviewTxButtonEnabled(coin)); + final previewEnabled = ref.watch(pPreviewTxButtonEnabled(walletId)); final needsEthFee = coin is Ethereum && isCustomFee; - - // add listener for epic cash to strip http:// and https:// prefixes if the address also ocntains an @ symbol (indicating an epicbox address) - if (coin is Epiccash) { - sendToController.addListener(() { - _address = sendToController.text; - - if (_address != null && _address!.isNotEmpty) { - _address = _address!.trim(); - if (_address!.contains("\n")) { - _address = _address!.substring(0, _address!.indexOf("\n")); - } - - sendToController.text = formatAddress(_address!); - } - }); - } + final wallet = ref.watch( + pWallets.select((value) => value.getWallet(walletId)), + ); final balType = ref.watch(publicPrivateBalanceStateProvider); - if (coin is Mimblewimblecoin) { - sendToController.addListener(() { - _address = sendToController.text; - - if (_address != null && _address!.isNotEmpty) { - _address = _address!.trim(); - if (_address!.contains("\n")) { - _address = _address!.substring(0, _address!.indexOf("\n")); - } - - sendToController.text = formatAddressMwc(_address!); - } - }); - } - final isMwebEnabled = ref.watch( pWalletInfo(walletId).select((s) => s.isMwebEnabled), ); @@ -1746,34 +1485,7 @@ class _DesktopSendState extends ConsumerState { children: [ const SizedBox(height: 4), if (showPrivateBalance) const SizedBox(height: 4), - if (isMimblewimblecoin) - Padding( - padding: const EdgeInsets.only(bottom: 16), - child: Container( - decoration: BoxDecoration( - color: - Theme.of(context) - .extension() - ?.textFieldDefaultBG ?? - Colors.white, // Fallback color - borderRadius: BorderRadius.circular(8), - border: Border.all( - color: - Theme.of(context) - .extension() - ?.backgroundAppBar ?? - Colors.grey, // Fallback color - width: 1, - ), - ), - child: const SizedBox( - height: 60, // Provide an explicit height to avoid infinite constraints - child: MwcTxsMethodToggle(), - ), - ), - ), - - if (isEpiccash) + if (wallet is SlatepackInterface && wallet.hasSlatepackMethodToggle) Padding( padding: const EdgeInsets.only(bottom: 16), child: Container( @@ -1793,9 +1505,9 @@ class _DesktopSendState extends ConsumerState { width: 1, ), ), - child: const SizedBox( + child: SizedBox( height: 60, // Provide an explicit height to avoid infinite constraints - child: EpicTxsMethodToggle(), + child: SlatepackMethodToggle(walletId: walletId), ), ), ), @@ -2099,8 +1811,7 @@ class _DesktopSendState extends ConsumerState { ), const SizedBox(height: 20), if (!isPaynymSend && - !((isMimblewimblecoin || isEpiccash) && - ref.watch(pIsSlatepack(widget.walletId)))) + !(usesSlatepacks && ref.watch(pIsSlatepack(widget.walletId)))) Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -2121,8 +1832,7 @@ class _DesktopSendState extends ConsumerState { ], ), if (!isPaynymSend && - !((isMimblewimblecoin || isEpiccash) && - ref.watch(pIsSlatepack(widget.walletId)))) + !(usesSlatepacks && ref.watch(pIsSlatepack(widget.walletId)))) const SizedBox(height: 10), if (_recipientIndexes != null) RecipientForms( @@ -2136,8 +1846,7 @@ class _DesktopSendState extends ConsumerState { onMessage: (message) => _note = message, ), if (!isPaynymSend && - !((isMimblewimblecoin || isEpiccash) && - ref.watch(pIsSlatepack(widget.walletId))) && + !(usesSlatepacks && ref.watch(pIsSlatepack(widget.walletId))) && _recipientIndexes == null) ClipRRect( borderRadius: BorderRadius.circular( @@ -2322,8 +2031,7 @@ class _DesktopSendState extends ConsumerState { ), ), if (!isPaynymSend && - !((isMimblewimblecoin || isEpiccash) && - ref.watch(pIsSlatepack(widget.walletId)))) + !(usesSlatepacks && ref.watch(pIsSlatepack(widget.walletId)))) Builder( builder: (_) { final String? error; @@ -2342,10 +2050,9 @@ class _DesktopSendState extends ConsumerState { } else { if (_data != null && _data.contactLabel == _address) { error = null; - } else if ((coin is Mimblewimblecoin || coin is Epiccash) && + } else if (usesSlatepacks && ref.watch(pIsSlatepack(widget.walletId))) { - // For MWC/Epic slatepack transactions, address validation is not required. - // TODO: When implementing encrypted slatepacks, address validation will be required. + // Slatepack sends have no address to validate. error = null; } else if (!ref.watch(pValidSendToAddress)) { error = "Invalid address"; @@ -2576,8 +2283,10 @@ class _DesktopSendState extends ConsumerState { (!needsEthFee || ethFee != null); return PrimaryButton( buttonHeight: ButtonHeight.l, - label: ref.watch(pIsSlatepack(widget.walletId)) - ? "Create slatepack" + label: + ref.watch(pIsSlatepack(widget.walletId)) && + wallet is SlatepackInterface + ? "Create ${wallet.slatepackTerms.noun}" : "Preview send", enabled: enabled, onPressed: enabled ? previewSend : null, 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 dad37c3356..ce534063cc 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 @@ -12,15 +12,15 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../../frost_route_generator.dart'; -import '../../../../pages/epic_finalize_view/epic_finalize_view.dart'; -import '../../../../pages/finalize_view/finalize_view.dart'; import '../../../../pages/send_view/frost_ms/frost_send_view.dart'; +import '../../../../pages/slatepack/slatepack_view.dart'; import '../../../../pages/wallet_view/transaction_views/tx_v2/transaction_v2_list.dart'; import '../../../../providers/global/wallets_provider.dart'; import '../../../../utilities/clipboard_interface.dart'; import '../../../../wallets/crypto_currency/crypto_currency.dart'; import '../../../../wallets/wallet/impl/bitcoin_frost_wallet.dart'; import '../../../../wallets/wallet/impl/solana_wallet.dart' show SolanaWallet; +import '../../../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../../../wallets/wallet/wallet_mixin_interfaces/view_only_option_interface.dart'; import '../../../../widgets/custom_tab_view.dart'; import '../../../../widgets/desktop/secondary_button.dart'; @@ -49,8 +49,7 @@ class _MyWalletState extends ConsumerState { late final bool isSolana; late final CryptoCurrency coin; late final bool isFrost; - late final bool isMimblewimblecoin; - late final bool isEpiccash; + late final bool usesSlatepacks; late final bool isViewOnly; @override @@ -60,11 +59,10 @@ class _MyWalletState extends ConsumerState { isFrost = wallet is BitcoinFrostWallet; isEth = coin is Ethereum; isSolana = wallet is SolanaWallet; - isMimblewimblecoin = coin is Mimblewimblecoin; - isEpiccash = coin is Epiccash; + usesSlatepacks = wallet is SlatepackInterface; - if (isMimblewimblecoin || isEpiccash) { - titles.add("Finalize"); + if (wallet is SlatepackInterface) { + titles.add(wallet.slatepackTerms.title); } if ((isEth || isSolana) && widget.contractAddress == null) { @@ -184,15 +182,10 @@ class _MyWalletState extends ConsumerState { contractAddress: widget.contractAddress, ), ), - if (isMimblewimblecoin) + if (usesSlatepacks) Padding( padding: const EdgeInsets.all(20), - child: FinalizeView(walletId: widget.walletId), - ), - if (isEpiccash) - Padding( - padding: const EdgeInsets.all(20), - child: EpicFinalizeView(walletId: widget.walletId), + child: SlatepackView(walletId: widget.walletId), ), if ((isEth || isSolana) && widget.contractAddress == null) diff --git a/lib/providers/ui/preview_tx_button_state_provider.dart b/lib/providers/ui/preview_tx_button_state_provider.dart index 285d4b8781..1b5d4540f6 100644 --- a/lib/providers/ui/preview_tx_button_state_provider.dart +++ b/lib/providers/ui/preview_tx_button_state_provider.dart @@ -11,10 +11,11 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../utilities/amount/amount.dart'; -import '../../utilities/enums/epic_transaction_method.dart'; -import '../../utilities/enums/mwc_transaction_method.dart'; +import '../../utilities/enums/slatepack_method.dart'; import '../../wallets/crypto_currency/crypto_currency.dart'; import '../../wallets/isar/providers/wallet_info_provider.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import '../global/wallets_provider.dart'; import '../wallet/public_private_balance_state_provider.dart'; final pSendAmount = StateProvider.autoDispose((_) => null); @@ -25,73 +26,54 @@ final pIsExchangeAddress = StateProvider((_) => false); final pOpReturnData = StateProvider.autoDispose((_) => null); -// MWC Transaction Method Provider. -final pSelectedMwcTransactionMethod = StateProvider( - (_) => MwcTransactionMethod.slatepack, -); - -// Epic Cash Transaction Method Provider. -final pSelectedEpicTransactionMethod = StateProvider( - (_) => EpicTransactionMethod.epicbox, +// Selected exchange method per slatepack wallet, null for other wallets. +// Starts at the wallet's default (Epic Cash: epicbox, MWC: slatepack). +final pSelectedSlatepackMethod = StateProvider.family( + (ref, walletId) { + final wallet = ref.read(pWallets).getWallet(walletId); + return wallet is SlatepackInterface ? wallet.supportedMethods.first : null; + }, ); final pIsSlatepack = Provider.family((ref, walletId) { - final coin = ref.watch(pWalletCoin(walletId)); - if (coin is Mimblewimblecoin) { - return ref.watch(pSelectedMwcTransactionMethod) == - MwcTransactionMethod.slatepack; - } - if (coin is Epiccash) { - return ref.watch(pSelectedEpicTransactionMethod) == - EpicTransactionMethod.slatepack; - } - - return false; + return ref.watch(pSelectedSlatepackMethod(walletId)) == + SlatepackMethod.slatepack; }); -final pPreviewTxButtonEnabled = Provider.autoDispose.family( - (ref, coin) { - final amount = ref.watch(pSendAmount) ?? Amount.zero; - final opReturnData = ref.watch(pOpReturnData); - - if (coin is! Firo && opReturnData != null) { - return false; - } - - // For MWC slatepack transactions, address validation is not required. - if (coin is Mimblewimblecoin) { - final selectedMethod = ref.watch(pSelectedMwcTransactionMethod); - if (selectedMethod == MwcTransactionMethod.slatepack) { - return amount > Amount.zero; - } - } +final pPreviewTxButtonEnabled = Provider.autoDispose.family(( + ref, + walletId, +) { + final coin = ref.watch(pWalletCoin(walletId)); + final amount = ref.watch(pSendAmount) ?? Amount.zero; + final opReturnData = ref.watch(pOpReturnData); - // For Epic Cash slatepack transactions, address validation is not required. - if (coin is Epiccash) { - final selectedMethod = ref.watch(pSelectedEpicTransactionMethod); - if (selectedMethod == EpicTransactionMethod.slatepack) { - return amount > Amount.zero; - } - } + if (coin is! Firo && opReturnData != null) { + return false; + } - if (coin is Firo) { - final firoType = ref.watch(publicPrivateBalanceStateProvider); - switch (firoType) { - case BalanceType.private: - return (ref.watch(pValidSendToAddress) || - ref.watch(pValidSparkSendToAddress)) && - !ref.watch(pIsExchangeAddress) && - opReturnData == null && - amount > Amount.zero; + // Slatepack transactions have no address to validate. + if (ref.watch(pIsSlatepack(walletId))) { + return amount > Amount.zero; + } - case BalanceType.public: - return ref.watch(pValidSendToAddress) && amount > Amount.zero; - } - } else { - return ref.watch(pValidSendToAddress) && amount > Amount.zero; + if (coin is Firo) { + final firoType = ref.watch(publicPrivateBalanceStateProvider); + switch (firoType) { + case BalanceType.private: + return (ref.watch(pValidSendToAddress) || + ref.watch(pValidSparkSendToAddress)) && + !ref.watch(pIsExchangeAddress) && + opReturnData == null && + amount > Amount.zero; + + case BalanceType.public: + return ref.watch(pValidSendToAddress) && amount > Amount.zero; } - }, -); + } else { + return ref.watch(pValidSendToAddress) && amount > Amount.zero; + } +}); final previewTokenTxButtonStateProvider = StateProvider.autoDispose((_) { return false; diff --git a/lib/route_generator.dart b/lib/route_generator.dart index 99cfe112b7..ba6ae2ce0f 100644 --- a/lib/route_generator.dart +++ b/lib/route_generator.dart @@ -72,7 +72,6 @@ import 'pages/churning/churning_progress_view.dart'; import 'pages/churning/churning_view.dart'; import 'pages/coin_control/coin_control_view.dart'; import 'pages/coin_control/utxo_details_view.dart'; -import 'pages/epic_finalize_view/epic_finalize_view.dart'; import 'pages/exchange_view/choose_address_from_stack_view.dart'; import 'pages/exchange_view/edit_trade_note_view.dart'; import 'pages/exchange_view/exchange_step_views/step_1_view.dart'; @@ -82,7 +81,6 @@ import 'pages/exchange_view/exchange_step_views/step_4_view.dart'; import 'pages/exchange_view/send_from_view.dart'; import 'pages/exchange_view/trade_details_view.dart'; import 'pages/exchange_view/wallet_initiated_exchange_view.dart'; -import 'pages/finalize_view/finalize_view.dart'; import 'pages/generic/single_field_edit_view.dart'; import 'pages/home_view/home_view.dart'; import 'pages/intro_view.dart'; @@ -114,6 +112,7 @@ import 'pages/salvium_stake/salvium_create_stake_view.dart'; import 'pages/send_view/confirm_transaction_view.dart'; import 'pages/send_view/frost_ms/frost_send_view.dart'; import 'pages/send_view/send_view.dart'; +import 'pages/slatepack/slatepack_view.dart'; import 'pages/send_view/sol_token_send_view.dart'; import 'pages/send_view/token_send_view.dart'; import 'pages/settings_views/global_settings_view/about_view.dart'; @@ -2071,21 +2070,11 @@ class RouteGenerator { } return _routeError("${settings.name} invalid args: ${args.toString()}"); - case FinalizeView.routeName: + case SlatepackView.routeName: if (args is String) { return getRoute( shouldUseMaterialRoute: useMaterialPageRoute, - builder: (_) => FinalizeView(walletId: args), - settings: RouteSettings(name: settings.name), - ); - } - return _routeError("${settings.name} invalid args: ${args.toString()}"); - - case EpicFinalizeView.routeName: - if (args is String) { - return getRoute( - shouldUseMaterialRoute: useMaterialPageRoute, - builder: (_) => EpicFinalizeView(walletId: args), + builder: (_) => SlatepackView(walletId: args), settings: RouteSettings(name: settings.name), ); } diff --git a/lib/utilities/enums/epic_transaction_method.dart b/lib/utilities/enums/epic_transaction_method.dart deleted file mode 100644 index 4ef30afc1f..0000000000 --- a/lib/utilities/enums/epic_transaction_method.dart +++ /dev/null @@ -1,48 +0,0 @@ -/// Enum to represent different Epic Cash transaction methods. -enum EpicTransactionMethod { - /// Manual slate exchange (copy/paste, QR codes, files). - slatepack, - - /// Automatic transaction via Epicbox. - epicbox; - - /// Human readable name for the transaction method. - String get displayName { - switch (this) { - case EpicTransactionMethod.slatepack: - return 'Slatepack'; - case EpicTransactionMethod.epicbox: - return 'Epicbox'; - } - } - - /// Description of how the transaction method works. - String get description { - switch (this) { - case EpicTransactionMethod.slatepack: - return 'Manual exchange via text, QR codes, or files'; - case EpicTransactionMethod.epicbox: - return 'Automatic exchange via Epicbox messaging'; - } - } - - /// Whether this method requires manual intervention. - bool get isManual { - switch (this) { - case EpicTransactionMethod.slatepack: - return true; - case EpicTransactionMethod.epicbox: - return false; - } - } - - /// Whether this method works offline. - bool get worksOffline { - switch (this) { - case EpicTransactionMethod.slatepack: - return true; - case EpicTransactionMethod.epicbox: - return false; - } - } -} diff --git a/lib/utilities/enums/mwc_transaction_method.dart b/lib/utilities/enums/mwc_transaction_method.dart deleted file mode 100644 index 4b24ad37f7..0000000000 --- a/lib/utilities/enums/mwc_transaction_method.dart +++ /dev/null @@ -1,70 +0,0 @@ -/// Enum to represent different MWC transaction methods. -enum MwcTransactionMethod { - /// Manual slatepack exchange (copy/paste, QR codes, files). - slatepack, - - /// Automatic transaction via MWCMQS. - mwcmqs; - - // /// Direct HTTP/HTTPS to recipient's wallet. - // http, - // - // /// Unknown or unsupported method. - // unknown; - - /// Human readable name for the transaction method. - String get displayName { - switch (this) { - case MwcTransactionMethod.slatepack: - return 'Slatepack'; - case MwcTransactionMethod.mwcmqs: - return 'MWCMQS'; - // case MwcTransactionMethod.http: - // return 'HTTP'; - // case MwcTransactionMethod.unknown: - // return 'Unknown'; - } - } - - /// Description of how the transaction method works. - String get description { - switch (this) { - case MwcTransactionMethod.slatepack: - return 'Manual exchange via text, QR codes, or files'; - case MwcTransactionMethod.mwcmqs: - return 'Automatic exchange via MWCMQS messaging'; - // case MwcTransactionMethod.http: - // return 'Direct connection to recipient wallet'; - // case MwcTransactionMethod.unknown: - // return 'Unsupported transaction method'; - } - } - - /// Whether this method requires manual intervention. - bool get isManual { - switch (this) { - case MwcTransactionMethod.slatepack: - return true; - case MwcTransactionMethod.mwcmqs: - return false; - // case MwcTransactionMethod.http: - // return false; - // case MwcTransactionMethod.unknown: - // return true; - } - } - - /// Whether this method works offline. - bool get worksOffline { - switch (this) { - case MwcTransactionMethod.slatepack: - return true; - case MwcTransactionMethod.mwcmqs: - return false; - // case MwcTransactionMethod.http: - // return false; - // case MwcTransactionMethod.unknown: - // return false; - } - } -} diff --git a/lib/utilities/enums/slatepack_method.dart b/lib/utilities/enums/slatepack_method.dart new file mode 100644 index 0000000000..a9b3006523 --- /dev/null +++ b/lib/utilities/enums/slatepack_method.dart @@ -0,0 +1,23 @@ +/// How a Mimblewimble transaction is exchanged with the other party. +enum SlatepackMethod { + /// Manual slatepack exchange (copy/paste, QR codes, files). + slatepack("Slatepack"), + + /// Automatic exchange through the coin's relay server (epicbox, mwcmqs). + relay("Automatic"), + + /// Direct send to the recipient's listener (http(s), Tor). + http("Address"); + + const SlatepackMethod(this.label); + + /// Label on the method toggle. + final String label; + + static SlatepackMethod? fromName(String? name) { + for (final m in values) { + if (m.name == name) return m; + } + return null; + } +} diff --git a/lib/utilities/exception_message.dart b/lib/utilities/exception_message.dart new file mode 100644 index 0000000000..6a6732b845 --- /dev/null +++ b/lib/utilities/exception_message.dart @@ -0,0 +1,3 @@ +/// Removes one or more Dart [Exception.toString] prefixes from [error]. +String stripExceptionPrefixes(Object error) => + error.toString().replaceFirst(RegExp(r'^(?:Exception:\s*)+'), ''); diff --git a/lib/utilities/route_presentation.dart b/lib/utilities/route_presentation.dart new file mode 100644 index 0000000000..10eb33b5e9 --- /dev/null +++ b/lib/utilities/route_presentation.dart @@ -0,0 +1,108 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +/// A dialog route that can wait until a newer route, such as the app lock +/// screen, has been dismissed. Results must not be pushed above a lock route. +class CurrentAwareDialogRoute extends DialogRoute { + CurrentAwareDialogRoute({ + required super.context, + required super.builder, + super.barrierDismissible, + super.useSafeArea, + super.themes, + }); + + final List> _currentWaiters = []; + + void _completeCurrentWaiters() { + for (final waiter in _currentWaiters.toList()) { + if (!waiter.isCompleted) waiter.complete(); + } + } + + Future waitUntilCurrent() async { + if (!isActive || isCurrent) return; + final waiter = Completer(); + _currentWaiters.add(waiter); + await Future.any([waiter.future, popped]); + _currentWaiters.remove(waiter); + } + + @override + void didChangeNext(Route? nextRoute) { + super.didChangeNext(nextRoute); + if (nextRoute == null) { + _completeCurrentWaiters(); + } + } + + @override + void didPopNext(Route nextRoute) { + super.didPopNext(nextRoute); + _completeCurrentWaiters(); + } + + @override + void dispose() { + _completeCurrentWaiters(); + _currentWaiters.clear(); + super.dispose(); + } +} + +/// Dismisses [route] only after routes above it (notably the app lock) leave. +/// +/// Returns false when the route was removed while waiting, so callers do not +/// present a result dialog above whatever replaced it. +Future dismissCurrentAwareDialogRoute({ + required NavigatorState navigator, + required CurrentAwareDialogRoute route, +}) async { + await route.waitUntilCurrent(); + if (!navigator.mounted || !route.isActive || !route.isCurrent) return false; + navigator.pop(); + return true; +} + +/// Completes after [route] has finished appearing. +/// +/// Some native wallet calls do synchronous work before returning their +/// Future. Waiting for the first frame is not enough for a transition route: +/// its contents can be built while the route opacity is still zero. +Future waitForRoutePresentation(TransitionRoute route) async { + await WidgetsBinding.instance.endOfFrame; + + final animation = route.animation; + if (animation == null) { + return; + } + + if (animation.status == AnimationStatus.completed) { + await WidgetsBinding.instance.endOfFrame; + return; + } + + final completer = Completer(); + void listener(AnimationStatus status) { + if ((status == AnimationStatus.completed || + status == AnimationStatus.dismissed) && + !completer.isCompleted) { + completer.complete(); + } + } + + animation.addStatusListener(listener); + try { + final appeared = await Future.any([ + completer.future.then((_) => true), + route.popped.then((_) => false), + ]); + if (appeared && animation.status == AnimationStatus.completed) { + // Animation completion precedes the paint of its final frame. + await WidgetsBinding.instance.endOfFrame; + } + } finally { + animation.removeStatusListener(listener); + } +} diff --git a/lib/utilities/slatepack_terms.dart b/lib/utilities/slatepack_terms.dart new file mode 100644 index 0000000000..e4aa66a33b --- /dev/null +++ b/lib/utilities/slatepack_terms.dart @@ -0,0 +1,21 @@ +/// Wording the slatepack screens use for the payload being exchanged. Epic +/// Cash passes raw slate JSON around while MWC uses armored slatepacks. A +/// wallet picks its terms through SlatepackInterface.slatepackTerms. +enum SlatepackTerms { + slate("slate", "Slate JSON", "slate"), + slatepack("slatepack", "Slatepack Message", "slatepack"); + + const SlatepackTerms(this.noun, this.payload, this.fileExtension); + + /// "slate" or "slatepack". + final String noun; + + /// What the user is asked to paste, e.g. "Slatepack Message". + final String payload; + + /// Extension used when this coin's payload is saved to a file. + final String fileExtension; + + /// [noun] with a capital, for titles. + String get title => "${noun[0].toUpperCase()}${noun.substring(1)}"; +} diff --git a/lib/utilities/slatepack_text.dart b/lib/utilities/slatepack_text.dart new file mode 100644 index 0000000000..b9ab3e897e --- /dev/null +++ b/lib/utilities/slatepack_text.dart @@ -0,0 +1,21 @@ +/// Parsing shared by Slatepack entry points and MWC format checks. +abstract final class SlatepackText { + static final RegExp _armoredFrame = RegExp( + r"BEGINSLATE(PACK|_BIN)\.[\s\S]*?ENDSLATE\1\.?", + ); + + /// Whether [text] consists of exactly one armored Slatepack frame. + static bool isArmored(String text) { + final trimmed = text.trim(); + return _armoredFrame.firstMatch(trimmed)?.group(0) == trimmed; + } + + /// Removes surrounding prose from an armored Slatepack. + /// + /// Plain slate JSON and unrecognized text are only trimmed. + static String normalize(String text) { + final trimmed = text.trim(); + if (trimmed.startsWith("{")) return trimmed; + return _armoredFrame.firstMatch(trimmed)?.group(0) ?? trimmed; + } +} diff --git a/lib/wallets/crypto_currency/coins/epiccash.dart b/lib/wallets/crypto_currency/coins/epiccash.dart index 97c1b18d3a..9dc848c362 100644 --- a/lib/wallets/crypto_currency/coins/epiccash.dart +++ b/lib/wallets/crypto_currency/coins/epiccash.dart @@ -4,7 +4,7 @@ import '../../../models/isar/models/blockchain_data/address.dart'; import '../../../models/node_model.dart'; import '../../../utilities/default_nodes.dart'; import '../../../utilities/enums/derive_path_type_enum.dart'; -import '../../../utilities/enums/epic_transaction_method.dart'; +import '../../../utilities/enums/slatepack_method.dart'; import '../../../wl_gen/interfaces/libepiccash_interface.dart'; import '../crypto_currency.dart'; import '../intermediate/bip39_currency.dart'; @@ -156,14 +156,15 @@ class Epiccash extends Bip39Currency { } /// Detect transaction type based on address/data format. - EpicTransactionMethod getTransactionMethod(String addressOrData) { + SlatepackMethod getTransactionMethod(String addressOrData) { if (isSlateJson(addressOrData)) { - return EpicTransactionMethod.slatepack; - } else if (isEpicboxAddress(addressOrData) || - isHttpAddress(addressOrData)) { - return EpicTransactionMethod.epicbox; + return SlatepackMethod.slatepack; + } else if (isHttpAddress(addressOrData)) { + return SlatepackMethod.http; + } else if (isEpicboxAddress(addressOrData)) { + return SlatepackMethod.relay; } else { - throw Exception("Unknown EpicTransactionMethod found!"); + throw Exception("Unknown SlatepackMethod found!"); } } diff --git a/lib/wallets/crypto_currency/coins/mimblewimblecoin.dart b/lib/wallets/crypto_currency/coins/mimblewimblecoin.dart index 2ed274b35c..c4fe31ad99 100644 --- a/lib/wallets/crypto_currency/coins/mimblewimblecoin.dart +++ b/lib/wallets/crypto_currency/coins/mimblewimblecoin.dart @@ -2,7 +2,8 @@ import '../../../models/isar/models/blockchain_data/address.dart'; import '../../../models/node_model.dart'; import '../../../utilities/default_nodes.dart'; import '../../../utilities/enums/derive_path_type_enum.dart'; -import '../../../utilities/enums/mwc_transaction_method.dart'; +import '../../../utilities/enums/slatepack_method.dart'; +import '../../../utilities/slatepack_text.dart'; import '../../../wl_gen/interfaces/libmwc_interface.dart'; import '../crypto_currency.dart'; import '../intermediate/bip39_currency.dart'; @@ -57,13 +58,7 @@ class Mimblewimblecoin extends Bip39Currency { } /// Check if data is a slatepack. - bool isSlatepack(String data) { - return data.trim().startsWith('BEGINSLATE') && - (data.trim().endsWith('ENDSLATEPACK') || - data.trim().endsWith('ENDSLATEPACK.') || - data.trim().endsWith('ENDSLATE_BIN') || - data.trim().endsWith('ENDSLATE_BIN.')); - } + bool isSlatepack(String data) => SlatepackText.isArmored(data); /// Check if address is MWCMQS format. bool isMwcmqsAddress(String address) { @@ -71,16 +66,14 @@ class Mimblewimblecoin extends Bip39Currency { } /// Detect transaction type based on address/data format. - MwcTransactionMethod getTransactionMethod(String addressOrData) { + SlatepackMethod getTransactionMethod(String addressOrData) { if (isSlatepack(addressOrData)) { - return MwcTransactionMethod.slatepack; + return SlatepackMethod.slatepack; } else if (isMwcmqsAddress(addressOrData)) { - return MwcTransactionMethod.mwcmqs; + return SlatepackMethod.relay; // } else if (isHttpAddress(addressOrData)) { - // return MwcTransactionMethod.http; } else { - throw Exception("Unknown MwcTransactionMethod found!"); - // return MwcTransactionMethod.unknown; + throw Exception("Unknown SlatepackMethod found!"); } } diff --git a/lib/wallets/wallet/impl/epiccash_wallet.dart b/lib/wallets/wallet/impl/epiccash_wallet.dart index 4212299207..d6f3a8117b 100644 --- a/lib/wallets/wallet/impl/epiccash_wallet.dart +++ b/lib/wallets/wallet/impl/epiccash_wallet.dart @@ -12,7 +12,6 @@ import 'package:web_socket_channel/web_socket_channel.dart'; import '../../../exceptions/main_db/main_db_exception.dart'; import '../../../exceptions/wallet/node_tor_mismatch_config_exception.dart'; import '../../../models/balance.dart'; -import '../../../models/epic_slatepack_models.dart'; import '../../../models/epicbox_config_model.dart'; import '../../../models/isar/models/blockchain_data/address.dart'; import '../../../models/isar/models/blockchain_data/transaction.dart'; @@ -22,6 +21,7 @@ import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; import '../../../models/isar/models/transaction_note.dart'; import '../../../models/node_model.dart'; import '../../../models/paymint/fee_object_model.dart'; +import '../../../models/slatepack_models.dart'; import '../../../pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart'; import '../../../services/event_bus/events/global/blocks_remaining_event.dart'; import '../../../services/event_bus/events/global/node_connection_status_changed_event.dart'; @@ -31,8 +31,10 @@ import '../../../services/event_bus/global_event_bus.dart'; import '../../../utilities/amount/amount.dart'; import '../../../utilities/default_epicboxes.dart'; import '../../../utilities/dynamic_object.dart'; +import '../../../utilities/enums/slatepack_method.dart'; import '../../../utilities/flutter_secure_storage_interface.dart'; import '../../../utilities/logger.dart'; +import '../../../utilities/slatepack_terms.dart'; import '../../../utilities/stack_file_system.dart'; import '../../../utilities/test_epic_box_connection.dart'; import '../../../utilities/tor_plain_net_option_enum.dart'; @@ -42,11 +44,17 @@ import '../../models/tx_data.dart'; import '../intermediate/bip39_wallet.dart'; import '../supporting/epiccash_wallet_info_extension.dart'; import '../supporting/restore_progress.dart'; +import '../wallet_mixin_interfaces/slatepack_interface.dart'; + +/// Epic's pinned native API broadcasts inside finalize and throws when that +/// broadcast fails. Older result objects omit the redundant `posted` field. +@visibleForTesting +bool epicFinalizeBroadcastResult(bool? posted) => posted ?? true; // // refactor of https://github.com/cypherstack/stack_wallet/blob/1d9fb4cd069f22492ece690ac788e05b8f8b1209/lib/services/coins/epiccash/epiccash_wallet.dart // -class EpiccashWallet extends Bip39Wallet { +class EpiccashWallet extends Bip39Wallet with SlatepackInterface { EpiccashWallet(CryptoCurrencyNetwork network) : super(Epiccash(network)); final syncMutex = Mutex(); @@ -56,6 +64,35 @@ class EpiccashWallet extends Bip39Wallet { DynamicObject? _wallet; double highestPercent = 0; + + @override + List get supportedMethods => const [ + SlatepackMethod.relay, + SlatepackMethod.slatepack, + ]; + + @override + bool get supportsOnChainNote => true; + + @override + SlatepackTerms get slatepackTerms => SlatepackTerms.slate; + + @override + Map get slatepackTransactionMetadata => + info.epicData?.slatesToCommits ?? const {}; + + @override + Future updateSlatepackTransactionMetadata( + Map metadata, + ) async { + final data = info.epicData; + if (data == null) return; + await info.updateExtraEpiccashWalletInfo( + epicData: data.copyWith(slatesToCommits: metadata), + isar: mainDB.isar, + ); + } + Future get getSyncPercent async { final int lastScannedBlock = info.epicData?.lastScannedBlock ?? 0; final _chainHeight = await chainHeight; @@ -136,6 +173,7 @@ class EpiccashWallet extends Bip39Wallet { } /// returns an empty String on success, error message on failure + @override Future cancelPendingTransactionAndPost(String txSlateId) async { try { _hackedCheckTorNodePrefs(); @@ -147,6 +185,7 @@ class EpiccashWallet extends Bip39Wallet { wallet: _wallet!, transactionId: txSlateId, ); + if (result.isEmpty) await rememberPendingSlateCancelled(txSlateId); Logging.instance.d("cancel $txSlateId result: $result"); return result; } catch (e, s) { @@ -191,11 +230,11 @@ class EpiccashWallet extends Bip39Wallet { // ================= Slatepack Operations =================================== /// Create a slatepack for sending Epic Cash. - Future createSlatepack({ + @override + Future createSlatepack({ required Amount amount, String? recipientAddress, String? message, - int? minimumConfirmations, }) async { try { _hackedCheckTorNodePrefs(); @@ -208,33 +247,40 @@ class EpiccashWallet extends Bip39Wallet { amount: amount.raw.toInt(), address: 'slate', // Not used in slate mode. secretKeyIndex: 0, - minimumConfirmations: - minimumConfirmations ?? cryptoCurrency.minConfirms, + minimumConfirmations: cryptoCurrency.minConfirms, note: message ?? '', returnSlate: true, ); - return EpicSlatepackResult( + final inspection = inspectSlateJsonString(result.slateJson); + final slatepack = SlatepackResult( success: true, slatepack: result.slateJson, slateJson: result.slateJson, wasEncrypted: false, recipientAddress: recipientAddress, + state: SlateState.s1, + slateId: result.slateId, + amount: inspection?.amount, + fee: inspection?.fee, ); + await rememberPendingSlateSend(slatepack); + return slatepack; } catch (e, s) { Logging.instance.e('Failed to create slatepack: $e\n$s'); - return EpicSlatepackResult(success: false, error: e.toString()); + return SlatepackResult(success: false, error: e.toString()); } } /// Decode a slatepack/slate JSON. - Future decodeSlatepack(String slateJson) async { + @override + Future decodeSlatepack(String slateJson) async { try { // For Epic Cash, slates are already JSON, so we parse directly. // Validate that the JSON is valid. jsonDecode(slateJson); - return EpicSlatepackDecodeResult( + return SlatepackDecodeResult( success: true, slateJson: slateJson, wasEncrypted: false, @@ -243,41 +289,19 @@ class EpiccashWallet extends Bip39Wallet { ); } catch (e, s) { Logging.instance.e('Failed to decode slatepack: $e\n$s'); - return EpicSlatepackDecodeResult(success: false, error: e.toString()); - } - } - - /// Full decode of a slatepack including type analysis. - Future<({EpicSlatepackDecodeResult result, String type, String raw})?> - fullDecodeSlatepack(String slateJson) async { - // Add delay for showloading exception catching hack fix. - await Future.delayed(const Duration(seconds: 1)); - - if (slateJson.isEmpty) { - return null; - } - - // Attempt to decode. - final decoded = await decodeSlatepack(slateJson); - - if (decoded.success) { - final analysis = await analyzeSlatepack(slateJson); - - final String slatepackType = switch (analysis.status) { - 'S1' => "S1 (Initial Send)", - 'S2' => "S2 (Response)", - 'S3' => "S3 (Finalized)", - _ => "Unknown", - }; - - return (result: decoded, type: slatepackType, raw: slateJson); - } else { - throw Exception(decoded.error ?? "Failed to decode slatepack"); + return SlatepackDecodeResult( + success: false, + failure: SlatepackDecodeFailure.invalidInput, + ); } } /// Receive a slatepack and return response slate JSON. - Future receiveSlatepack(String slateJson) async { + @override + Future receiveSlatepack( + String slateJson, { + required SlateInspection inspection, + }) async { try { _hackedCheckTorNodePrefs(); if (_wallet == null) { @@ -287,25 +311,33 @@ class EpiccashWallet extends Bip39Wallet { // Receive and get updated slate JSON. final received = await libEpic.txReceive( wallet: _wallet!, - slateJson: slateJson, + slateJson: inspection.slateJson ?? slateJson, ); - return EpicReceiveResult( + final responseInspection = inspectSlateJsonString(received.slateJson); + return SlatepackResult( success: true, + slatepack: received.slateJson, + slateJson: received.slateJson, slateId: received.slateId, - commitId: received.commitId, - responseSlatepack: received.slateJson, wasEncrypted: false, recipientAddress: null, + state: SlateState.s2, + amount: responseInspection?.amount ?? inspection.amount, + fee: responseInspection?.fee ?? inspection.fee, ); } catch (e, s) { Logging.instance.e('Failed to receive slatepack: $e\n$s'); - return EpicReceiveResult(success: false, error: e.toString()); + return SlatepackResult(success: false, error: e.toString()); } } /// Finalize a slatepack (sender step 3). - Future finalizeSlatepack(String slateJson) async { + @override + Future finalizeSlatepack( + String slateJson, { + required SlateInspection inspection, + }) async { try { _hackedCheckTorNodePrefs(); if (_wallet == null) { @@ -315,103 +347,18 @@ class EpiccashWallet extends Bip39Wallet { // Finalize transaction. final finalized = await libEpic.txFinalize( wallet: _wallet!, - slateJson: slateJson, + slateJson: inspection.slateJson ?? slateJson, ); - return EpicFinalizeResult( + return FinalizeResult( success: true, slateId: finalized.slateId, commitId: finalized.commitId, + posted: epicFinalizeBroadcastResult(finalized.posted), ); } catch (e, s) { Logging.instance.e('Failed to finalize slatepack: $e\n$s'); - return EpicFinalizeResult(success: false, error: e.toString()); - } - } - - /// Analyze a slatepack and determine transaction type and metadata. - Future< - ({ - String type, - String status, - String? amount, - bool wasEncrypted, - String? senderAddress, - String? recipientAddress, - String slateId, - }) - > - analyzeSlatepack(String slateJson) async { - try { - // Parse the slate JSON to extract metadata. - final slateData = jsonDecode(slateJson); - final String slateId = "${slateData['id'] ?? ''}"; - final String? amountStr = slateData['amount']?.toString(); - - Logging.instance.d('Analyzed slatepack with ID: $slateId'); - - // Determine slate status from the slate structure. - String status = 'Unknown'; - String type = 'Unknown'; - - // Check participant data to determine slate status. - final List? participants = - slateData['participant_data'] as List?; - if (participants != null && participants.isNotEmpty) { - // Count how many participants have signatures. - int signedParticipants = 0; - for (final participant in participants) { - if (participant['part_sig'] != null) { - signedParticipants++; - } - } - - // Determine status based on signatures and participant count. - if (signedParticipants == 0) { - status = 'S1'; - type = 'Outgoing'; // Initial send slate - this is outgoing. - } else if (signedParticipants == 1) { - status = 'S2'; - type = 'Incoming'; // Response slate - this means we're receiving. - } else if (signedParticipants >= participants.length) { - status = 'S3'; - type = - 'Outgoing'; // Finalized slate - completed outgoing transaction. - } - } - - // Fallback: check for explicit 'sta' field (some slates may have this). - if (status == 'Unknown' && slateData['sta'] != null) { - status = "${slateData['sta']}"; - if (status == 'S1') { - type = 'Outgoing'; - } else if (status == 'S2') { - type = 'Incoming'; - } else if (status == 'S3') { - type = 'Outgoing'; - } - } - - return ( - type: type, - status: status, - amount: amountStr, - wasEncrypted: false, - senderAddress: null, - recipientAddress: null, - slateId: slateId, - ); - } catch (e) { - // If we can't decode it, return unknown. - return ( - type: 'Unknown', - status: 'Unknown', - amount: null, - wasEncrypted: false, - senderAddress: null, - recipientAddress: null, - slateId: '', - ); + return FinalizeResult(success: false, error: e.toString()); } } diff --git a/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart b/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart index 721773da6d..0fc40ae1fc 100644 --- a/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart +++ b/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart @@ -14,10 +14,10 @@ import '../../../models/isar/models/blockchain_data/transaction.dart'; import '../../../models/isar/models/blockchain_data/v2/input_v2.dart'; import '../../../models/isar/models/blockchain_data/v2/output_v2.dart'; import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; -import '../../../models/mwc_slatepack_models.dart'; import '../../../models/mwcmqs_config_model.dart'; import '../../../models/node_model.dart'; import '../../../models/paymint/fee_object_model.dart'; +import '../../../models/slatepack_models.dart'; import '../../../pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart'; import '../../../services/event_bus/events/global/blocks_remaining_event.dart'; import '../../../services/event_bus/events/global/node_connection_status_changed_event.dart'; @@ -26,8 +26,10 @@ import '../../../services/event_bus/events/global/wallet_sync_status_changed_eve import '../../../services/event_bus/global_event_bus.dart'; import '../../../utilities/amount/amount.dart'; import '../../../utilities/default_mwcmqs.dart'; +import '../../../utilities/enums/slatepack_method.dart'; import '../../../utilities/flutter_secure_storage_interface.dart'; import '../../../utilities/logger.dart'; +import '../../../utilities/slatepack_terms.dart'; import '../../../utilities/stack_file_system.dart'; import '../../../utilities/test_mwcmqs_connection.dart'; import '../../../wl_gen/interfaces/libmwc_interface.dart'; @@ -36,8 +38,18 @@ import '../../models/tx_data.dart'; import '../intermediate/bip39_wallet.dart'; import '../supporting/mimblewimblecoin_wallet_info_extension.dart'; import '../supporting/restore_progress.dart'; +import '../wallet_mixin_interfaces/slatepack_interface.dart'; -class MimblewimblecoinWallet extends Bip39Wallet { +class _SlatepackWalletUnavailable implements Exception { + const _SlatepackWalletUnavailable(this.cause); + + final Object cause; + + @override + String toString() => cause.toString(); +} + +class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { MimblewimblecoinWallet(CryptoCurrencyNetwork network) : super(Mimblewimblecoin(network)); @@ -52,6 +64,38 @@ class MimblewimblecoinWallet extends Bip39Wallet { String? _walletHandle; double highestPercent = 0; + + @override + List get supportedMethods => const [ + SlatepackMethod.slatepack, + SlatepackMethod.relay, + ]; + + @override + bool get supportsOnChainNote => true; + + @override + bool get supportsSlatepackEncryption => true; + + @override + SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; + + @override + Map get slatepackTransactionMetadata => + info.mimblewimblecoinData?.slatesToCommits ?? const {}; + + @override + Future updateSlatepackTransactionMetadata( + Map metadata, + ) async { + final data = info.mimblewimblecoinData; + if (data == null) return; + await info.updateExtraMimblewimblecoinWalletInfo( + mimblewimblecoinData: data.copyWith(slatesToCommits: metadata), + isar: mainDB.isar, + ); + } + Future get getSyncPercent async { final int lastScannedBlock = info.mimblewimblecoinData?.lastScannedBlock ?? 0; @@ -132,6 +176,7 @@ class MimblewimblecoinWallet extends Bip39Wallet { } /// Returns an empty String on success, error message on failure. + @override Future cancelPendingTransactionAndPost(String txSlateId) async { try { final String wallet = await _ensureWalletOpen(); @@ -140,6 +185,7 @@ class MimblewimblecoinWallet extends Bip39Wallet { wallet: wallet, transactionId: txSlateId, ); + if (result.isEmpty) await rememberPendingSlateCancelled(txSlateId); Logging.instance.i("cancel $txSlateId result: $result"); return result; } catch (e, s) { @@ -176,12 +222,11 @@ class MimblewimblecoinWallet extends Bip39Wallet { // ================= Slatepack Operations =================================== /// Create a slatepack for sending MWC. + @override Future createSlatepack({ required Amount amount, String? recipientAddress, String? message, - bool encrypt = false, - int? minimumConfirmations, }) async { try { final handle = await _ensureWalletOpen(); @@ -190,8 +235,7 @@ class MimblewimblecoinWallet extends Bip39Wallet { final s1Json = await libMwc.txInit( wallet: handle, amount: amount.raw.toInt(), - minimumConfirmations: - minimumConfirmations ?? cryptoCurrency.minConfirms, + minimumConfirmations: cryptoCurrency.minConfirms, selectionStrategyIsAll: false, message: message ?? '', ); @@ -200,80 +244,40 @@ class MimblewimblecoinWallet extends Bip39Wallet { final encoded = await libMwc.encodeSlatepack( slateJson: s1Json, recipientAddress: recipientAddress, - encrypt: encrypt, + encrypt: recipientAddress != null, wallet: handle, ); - return SlatepackResult( + final inspection = inspectSlateJsonString(s1Json); + final slatepack = SlatepackResult( success: true, slatepack: encoded.slatepack, slateJson: s1Json, wasEncrypted: encoded.wasEncrypted, recipientAddress: encoded.recipientAddress, + state: SlateState.s1, + slateId: inspection?.slateId, + amount: inspection?.amount, + fee: inspection?.fee, ); + await rememberPendingSlateSend(slatepack); + return slatepack; } catch (e, s) { Logging.instance.e('Failed to create slatepack: $e\n$s'); return SlatepackResult(success: false, error: e.toString()); } } - // this isn't nearly the best way to handle this but better than copy pasting - // this function in two places (mobile and desktop widgets)... - Future<({SlatepackDecodeResult result, String type, String raw})?> - fullDecodeSlatepack(String slatepack) async { - // add delay for showloading exception catching hack fix - await Future.delayed(const Duration(seconds: 1)); - - if (slatepack.isEmpty) { - return null; - } - - // Basic format validation. - final coin = cryptoCurrency as Mimblewimblecoin; - if (!coin.isSlatepack(slatepack)) { - throw Exception("Invalid slatepack format"); - } - - // Attempt to decode. - final decoded = await decodeSlatepack(slatepack); - - if (decoded.success) { - final analysis = await analyzeSlatepack(slatepack); - - String _determineSlatepackType(SlatepackDecodeResult decoded) { - // Fallback analysis based on sender/recipient addresses. - if (decoded.senderAddress != null && decoded.recipientAddress != null) { - return "S2 (Response)"; - } else if (decoded.senderAddress != null) { - return "S1 (Initial)"; - } else { - return "Unknown"; - } - } - - final String slatepackType = switch (analysis.status) { - 'S1' => "S1 (Initial Send)", - 'S2' => "S2 (Response)", - 'S3' => "S3 (Finalized)", - _ => _determineSlatepackType(decoded), // Fallback. - }; - - return (result: decoded, type: slatepackType, raw: slatepack); - } else { - throw Exception(decoded.error ?? "Failed to decode slatepack"); - } - } - /// Decode a slatepack. - Future decodeSlatepack(String slatepack) async { + @override + Future decodeSlatepack(String armored) async { try { - final handle = _walletHandle; - final result = handle != null - ? await libMwc.decodeSlatepackWithWallet( - wallet: handle, - slatepack: slatepack, - ) - : await libMwc.decodeSlatepack(slatepack: slatepack); + final result = _walletHandle == null + ? await _decodeSlatepackWithClosedWallet(armored) + : await libMwc.decodeSlatepackWithWallet( + wallet: _walletHandle!, + slatepack: armored, + ); return SlatepackDecodeResult( success: true, @@ -282,72 +286,116 @@ class MimblewimblecoinWallet extends Bip39Wallet { senderAddress: result.senderAddress, recipientAddress: result.recipientAddress, ); + } on _SlatepackWalletUnavailable catch (e, s) { + Logging.instance.e('Failed to open wallet for slatepack: $e\n$s'); + return SlatepackDecodeResult( + success: false, + failure: SlatepackDecodeFailure.walletUnavailable, + ); } catch (e, s) { Logging.instance.e('Failed to decode slatepack: $e\n$s'); - return SlatepackDecodeResult(success: false, error: e.toString()); + return SlatepackDecodeResult( + success: false, + failure: SlatepackDecodeFailure.invalidInput, + ); } } - /// Receive a slatepack and return response slatepack. - Future receiveSlatepack(String slatepack) async { + Future< + ({ + String? recipientAddress, + String? senderAddress, + String slateJson, + bool wasEncrypted, + }) + > + _decodeSlatepackWithClosedWallet(String slatepack) async { try { - final handle = await _ensureWalletOpen(); - - // Decode to get slate JSON and sender address. - final decoded = await libMwc.decodeSlatepackWithWallet( + // Preserve the existing no-wallet path for unencrypted slatepacks. + return await libMwc.decodeSlatepack(slatepack: slatepack); + } catch (_) { + // Encrypted slatepacks need this wallet's keys. + final String handle; + try { + handle = await _ensureWalletOpen(); + } catch (e) { + throw _SlatepackWalletUnavailable(e); + } + return libMwc.decodeSlatepackWithWallet( wallet: handle, slatepack: slatepack, ); + } + } + + @override + void checkSlatepackFormat(String armored) { + if (!isSlatepack(armored)) { + throw Exception("Invalid slatepack format"); + } + } + + /// Receive a slatepack and return response slatepack. + @override + Future receiveSlatepack( + String slatepack, { + required SlateInspection inspection, + }) async { + try { + final handle = await _ensureWalletOpen(); // Receive and get updated slate JSON. final received = await libMwc.txReceiveDetailed( wallet: handle, - slateJson: decoded.slateJson, + slateJson: inspection.slateJson!, ); // Encode response back to sender if address available. final encoded = await libMwc.encodeSlatepack( slateJson: received.slateJson, - recipientAddress: decoded.senderAddress, - encrypt: decoded.senderAddress != null, + recipientAddress: inspection.senderAddress, + encrypt: inspection.senderAddress != null, wallet: handle, ); - return ReceiveResult( + final responseInspection = inspectSlateJsonString(received.slateJson); + return SlatepackResult( success: true, + slatepack: encoded.slatepack, + slateJson: received.slateJson, slateId: received.slateId, - commitId: received.commitId, - responseSlatepack: encoded.slatepack, wasEncrypted: encoded.wasEncrypted, - recipientAddress: decoded.senderAddress, + recipientAddress: inspection.senderAddress, + state: SlateState.s2, + amount: responseInspection?.amount ?? inspection.amount, + fee: responseInspection?.fee ?? inspection.fee, ); } catch (e, s) { Logging.instance.e('Failed to receive slatepack: $e\n$s'); - return ReceiveResult(success: false, error: e.toString()); + return SlatepackResult(success: false, error: e.toString()); } } /// Finalize a slatepack (sender step 3). - Future finalizeSlatepack(String slatepack) async { + @override + Future finalizeSlatepack( + String slatepack, { + required SlateInspection inspection, + }) async { try { final handle = await _ensureWalletOpen(); - // Decode to get slate JSON. - final decoded = await libMwc.decodeSlatepackWithWallet( - wallet: handle, - slatepack: slatepack, - ); - // Finalize transaction. final finalized = await libMwc.txFinalize( wallet: handle, - slateJson: decoded.slateJson, + slateJson: inspection.slateJson!, ); return FinalizeResult( success: true, slateId: finalized.slateId, commitId: finalized.commitId, + posted: finalized.posted, ); } catch (e, s) { Logging.instance.e('Failed to finalize slatepack: $e\n$s'); diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart new file mode 100644 index 0000000000..795140ade7 --- /dev/null +++ b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart @@ -0,0 +1,375 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:isar_community/isar.dart'; + +import '../../../models/isar/models/blockchain_data/transaction.dart'; +import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import '../../../models/slatepack_models.dart'; +import '../../../utilities/amount/amount.dart'; +import '../../../utilities/enums/slatepack_method.dart'; +import '../../../utilities/slatepack_terms.dart'; +import '../../../utilities/logger.dart'; +import '../../crypto_currency/crypto_currency.dart'; +import '../wallet.dart'; + +/// Slatepack exchange shared by the Mimblewimble coins. The slatepack +/// screens talk to this instead of a concrete wallet type. +/// +mixin SlatepackInterface on Wallet { + final Map< + String, + ({Amount amount, Amount fee, bool isSend, bool isCancelled}) + > + _pendingSlateTransactions = {}; + + /// Methods the send and receive screens offer. The first is the default. + List get supportedMethods; + + /// Whether a send can carry a message that ends up on chain. + bool get supportsOnChainNote; + + /// Whether this wallet can encrypt slatepacks to another wallet's address. + bool get supportsSlatepackEncryption => false; + + /// Whether send/receive should offer a method selector. + bool get hasSlatepackMethodToggle => + supportedMethods.any((method) => method != SlatepackMethod.slatepack); + + /// "slate" or "slatepack" wording for this coin. + SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; + + /// Durable per-slate metadata owned by the concrete wallet. Existing relay + /// address/commit data and the manual-send ownership marker share this map. + @protected + Map get slatepackTransactionMetadata => const {}; + + /// Persists [metadata] without requiring a native history refresh. + @protected + Future updateSlatepackTransactionMetadata( + Map metadata, + ) async {} + + /// The address another wallet encrypts a slatepack to. + Future slatepackAddress() async => + (await getCurrentReceivingAddress())?.value ?? ""; + + /// Decode [armored] without changing wallet state. + Future decodeSlatepack(String armored); + + /// Reject text that is clearly not this coin's slate format before doing + /// native work. Epic's JSON slates need no additional framing check. + @protected + void checkSlatepackFormat(String armored) {} + + /// Decode [armored] and work out its state without changing the wallet. + /// Throws when the text cannot be decoded at all. + Future inspectSlatepack(String armored) async { + final text = armored.trim(); + if (text.isEmpty) { + throw Exception("No ${slatepackTerms.noun} entered"); + } + + checkSlatepackFormat(text); + final decoded = await decodeSlatepack(text); + if (!decoded.success || decoded.slateJson == null) { + if (decoded.failure == SlatepackDecodeFailure.walletUnavailable) { + throw Exception( + "This ${slatepackTerms.noun} could not be read because the wallet " + "could not be opened. Try again.", + ); + } + final encryptionCause = supportsSlatepackEncryption + ? ", incomplete, or encrypted for another wallet" + : " or incomplete"; + throw Exception( + "This ${slatepackTerms.noun} could not be decoded. It may be damaged" + "$encryptionCause.", + ); + } + + final dynamic json = jsonDecode(decoded.slateJson!); + if (json is! Map) { + throw Exception("Not a ${slatepackTerms.noun}"); + } + + final inspection = inspectSlateJson( + json, + fractionDigits: cryptoCurrency.fractionDigits, + slateJson: decoded.slateJson, + isEncrypted: decoded.wasEncrypted ?? false, + senderAddress: decoded.senderAddress, + recipientAddress: decoded.recipientAddress, + ); + Logging.instance.d("Inspected ${slatepackTerms.noun}: $inspection"); + return inspection; + } + + /// Amount, fee and status of this wallet's transaction for [slateId], or + /// null when the wallet has none. `isSend` is true for a send this wallet + /// started, which is the only kind it can finalize. A cancelled send must + /// not be finalized. + Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> + localTxForSlate(String slateId) async { + if (slateId.isEmpty) return null; + + // A slate created in this process is authoritative and immediately + // available, even while Isar is shutting down or before native history is + // refreshed. + final inMemory = _pendingSlateTransactions[slateId]; + if (inMemory != null) return inMemory; + + final tx = localSlateTransaction( + await mainDB.isar.transactionV2s + .where() + .walletIdEqualTo(walletId) + .filter() + .otherDataContains(slateId) + .findAll(), + slateId, + ); + final pending = pendingSlateSendMatching( + slatepackTransactionMetadata, + slateId, + fractionDigits: cryptoCurrency.fractionDigits, + ); + if (tx == null) return pending; + + final digits = cryptoCurrency.fractionDigits; + final isSend = tx.type == TransactionType.outgoing; + return ( + amount: isSend + ? tx.getAmountSentFromThisWallet( + fractionDigits: digits, + subtractFee: true, + ) + : tx.getAmountReceivedInThisWallet(fractionDigits: digits), + fee: tx.getFee(fractionDigits: digits), + isSend: isSend, + isCancelled: tx.isCancelled || (isSend && pending?.isCancelled == true), + ); + } + + /// Persists ownership as soon as an S1 is created, before a refresh can + /// copy the native transaction into Isar. + @protected + Future rememberPendingSlateSend(SlatepackResult result) async { + final slateId = result.slateId; + final amount = result.amount; + final fee = result.fee; + if (slateId == null || slateId.isEmpty || amount == null || fee == null) { + return; + } + + _pendingSlateTransactions[slateId] = ( + amount: amount, + fee: fee, + isSend: true, + isCancelled: false, + ); + + final metadata = Map.from(slatepackTransactionMetadata); + final existing = metadata[slateId]; + final entry = existing is Map + ? Map.from(existing) + : {}; + entry.addAll({ + 'amount': amount.raw.toString(), + 'fee': fee.raw.toString(), + 'isSend': true, + 'isCancelled': false, + }); + metadata[slateId] = entry; + try { + await updateSlatepackTransactionMetadata(metadata); + } catch (e, s) { + Logging.instance.w( + "Could not persist ownership for slate $slateId", + error: e, + stackTrace: s, + ); + } + } + + @protected + Future rememberPendingSlateCancelled(String slateId) async { + final metadata = Map.from(slatepackTransactionMetadata); + final raw = metadata[slateId]; + final pending = + _pendingSlateTransactions[slateId] ?? + pendingSlateSendMatching( + metadata, + slateId, + fractionDigits: cryptoCurrency.fractionDigits, + ); + if (pending == null) return; + + _pendingSlateTransactions[slateId] = ( + amount: pending.amount, + fee: pending.fee, + isSend: true, + isCancelled: true, + ); + + final entry = raw is Map + ? Map.from(raw) + : { + 'amount': pending.amount.raw.toString(), + 'fee': pending.fee.raw.toString(), + 'isSend': true, + }; + entry['isCancelled'] = true; + metadata[slateId] = entry; + try { + await updateSlatepackTransactionMetadata(metadata); + } catch (e, s) { + Logging.instance.w( + "Could not persist cancellation for slate $slateId", + error: e, + stackTrace: s, + ); + } + } + + /// State, id, amount and fee for a native slate JSON result. + @protected + SlateInspection? inspectSlateJsonString(String? slateJson) { + if (slateJson == null) return null; + try { + final dynamic json = jsonDecode(slateJson); + if (json is! Map) return null; + return inspectSlateJson( + json, + fractionDigits: cryptoCurrency.fractionDigits, + slateJson: slateJson, + ); + } catch (_) { + return null; + } + } + + /// Start a send (S1). [message] is dropped when [supportsOnChainNote] is + /// false. [recipientAddress] encrypts the slatepack to that address where + /// the coin supports it. + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + String? message, + }); + + /// Answer an S1 with an S2. + Future receiveSlatepack( + String s1, { + required SlateInspection inspection, + }); + + /// Finalize an S2 from the recipient and post it. + Future finalizeSlatepack( + String s2, { + required SlateInspection inspection, + }); + + /// Returns an empty String on success, error message on failure. + Future cancelPendingTransactionAndPost(String slateId); +} + +/// Reads the small durable record written when a wallet creates an S1. +@visibleForTesting +({Amount amount, Amount fee, bool isSend, bool isCancelled})? +pendingSlateSendMatching( + Map metadata, + String slateId, { + required int fractionDigits, +}) { + final raw = metadata[slateId]; + if (raw is! Map || raw['isSend'] != true) return null; + + final amount = BigInt.tryParse(raw['amount']?.toString() ?? ''); + final fee = BigInt.tryParse(raw['fee']?.toString() ?? ''); + if (amount == null || fee == null) return null; + + return ( + amount: Amount(rawValue: amount, fractionDigits: fractionDigits), + fee: Amount(rawValue: fee, fractionDigits: fractionDigits), + isSend: true, + isCancelled: raw['isCancelled'] == true, + ); +} + +/// Inspect Epic/MWC slate JSON without invoking either native wallet. +@visibleForTesting +SlateInspection inspectSlateJson( + Map json, { + required int fractionDigits, + String? slateJson, + bool isEncrypted = false, + String? senderAddress, + String? recipientAddress, +}) { + var state = SlateState.fromCode(json['sta']?.toString()); + final dynamic participants = json['participant_data']; + if (state == SlateState.unknown && + participants is List && + participants.isNotEmpty) { + var signed = 0; + for (final dynamic participant in participants) { + if (participant is Map && participant['part_sig'] != null) signed++; + } + if (signed == 0) { + state = SlateState.s1; + } else if (signed == 1) { + state = SlateState.s2; + } else if (signed >= participants.length) { + state = SlateState.s3; + } + } + + if (state == SlateState.unknown) { + if (senderAddress != null && recipientAddress != null) { + state = SlateState.s2; + } else if (senderAddress != null) { + state = SlateState.s1; + } + } + + Amount? parseAmount(dynamic raw) { + final value = BigInt.tryParse(raw?.toString() ?? ""); + final isResponse = state == SlateState.s2 || state == SlateState.i2; + if (isResponse && value == BigInt.zero) return null; + return value == null + ? null + : Amount(rawValue: value, fractionDigits: fractionDigits); + } + + return SlateInspection( + state: state, + slateId: (json['id'] ?? '').toString(), + slateJson: slateJson, + amount: parseAmount(json['amount'] ?? json['amt']), + fee: parseAmount(json['fee']), + senderAddress: senderAddress, + recipientAddress: recipientAddress, + isEncrypted: isEncrypted, + ttlCutoffHeight: int.tryParse( + (json['ttl_cutoff_height'] ?? json['ttl'] ?? '').toString(), + ), + ); +} + +/// Exact local transaction for [slateId]. Sends win for self-transfers; a +/// live receive wins over a cancelled duplicate receive. +@visibleForTesting +TransactionV2? localSlateTransaction( + Iterable candidates, + String slateId, +) { + TransactionV2? match; + for (final tx in candidates) { + if (tx.slateId != slateId) continue; + if (tx.type == TransactionType.outgoing) return tx; + if (match == null || (match.isCancelled && !tx.isCancelled)) { + match = tx; + } + } + return match; +} diff --git a/lib/widgets/epic_txs_method_toggle.dart b/lib/widgets/epic_txs_method_toggle.dart deleted file mode 100644 index f08f086f16..0000000000 --- a/lib/widgets/epic_txs_method_toggle.dart +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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 2026-01-12 - * - */ - -import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../providers/ui/preview_tx_button_state_provider.dart'; -import '../themes/stack_colors.dart'; -import '../utilities/assets.dart'; -import '../utilities/constants.dart'; -import '../utilities/enums/epic_transaction_method.dart'; -import '../utilities/util.dart'; -import 'toggle.dart'; - -class EpicTxsMethodToggle extends ConsumerWidget { - const EpicTxsMethodToggle({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - debugPrint("BUILD: $runtimeType"); - final isDesktop = Util.isDesktop; - - return Toggle( - onValueChanged: (value) { - ref.read(pSelectedEpicTransactionMethod.notifier).state = - value - ? EpicTransactionMethod.epicbox - : EpicTransactionMethod.slatepack; - }, - isOn: - ref.watch(pSelectedEpicTransactionMethod) == - EpicTransactionMethod.epicbox, - onColor: - isDesktop - ? Theme.of( - context, - ).extension()!.rateTypeToggleDesktopColorOn - : Theme.of( - context, - ).extension()!.rateTypeToggleColorOn, - offColor: - isDesktop - ? Theme.of( - context, - ).extension()!.rateTypeToggleDesktopColorOff - : Theme.of( - context, - ).extension()!.rateTypeToggleColorOff, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - ), - onIcon: Assets.svg.gear, - onText: "Slatepack", - offIcon: Assets.svg.radioSyncing, - offText: "Automatic", - ); - } -} diff --git a/lib/widgets/mwc_txs_method_toggle.dart b/lib/widgets/mwc_txs_method_toggle.dart deleted file mode 100644 index 4381d6e236..0000000000 --- a/lib/widgets/mwc_txs_method_toggle.dart +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../providers/ui/preview_tx_button_state_provider.dart'; -import '../themes/stack_colors.dart'; -import '../utilities/assets.dart'; -import '../utilities/constants.dart'; -import '../utilities/enums/mwc_transaction_method.dart'; -import '../utilities/util.dart'; -import 'toggle.dart'; - -class MwcTxsMethodToggle extends ConsumerWidget { - const MwcTxsMethodToggle({super.key}); - - @override - Widget build(BuildContext context, WidgetRef ref) { - debugPrint("BUILD: $runtimeType"); - final isDesktop = Util.isDesktop; - - return Toggle( - onValueChanged: (value) { - ref.read(pSelectedMwcTransactionMethod.notifier).state = - value - ? MwcTransactionMethod.mwcmqs - : MwcTransactionMethod.slatepack; - }, - isOn: - ref.watch(pSelectedMwcTransactionMethod) == - MwcTransactionMethod.mwcmqs, - onColor: - isDesktop - ? Theme.of( - context, - ).extension()!.rateTypeToggleDesktopColorOn - : Theme.of( - context, - ).extension()!.rateTypeToggleColorOn, - offColor: - isDesktop - ? Theme.of( - context, - ).extension()!.rateTypeToggleDesktopColorOff - : Theme.of( - context, - ).extension()!.rateTypeToggleColorOff, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular( - Constants.size.circularBorderRadius, - ), - ), - onIcon: Assets.svg.gear, - onText: "Slatepack", - offIcon: Assets.svg.radioSyncing, - offText: "Automatic", - ); - } -} diff --git a/lib/widgets/slatepack_method_toggle.dart b/lib/widgets/slatepack_method_toggle.dart new file mode 100644 index 0000000000..90c8b9a223 --- /dev/null +++ b/lib/widgets/slatepack_method_toggle.dart @@ -0,0 +1,71 @@ +/* + * 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/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../providers/global/wallets_provider.dart'; +import '../providers/ui/preview_tx_button_state_provider.dart'; +import '../themes/stack_colors.dart'; +import '../utilities/assets.dart'; +import '../utilities/constants.dart'; +import '../utilities/enums/slatepack_method.dart'; +import '../utilities/util.dart'; +import '../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import 'toggle.dart'; + +/// Switches a slatepack wallet between manual slatepacks (left) and its +/// other method (right): the relay for Epic Cash and MWC. +class SlatepackMethodToggle extends ConsumerWidget { + const SlatepackMethodToggle({super.key, required this.walletId}); + + final String walletId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + debugPrint("BUILD: $runtimeType"); + final bool isDesktop = Util.isDesktop; + final wallet = + ref.watch(pWallets).getWallet(walletId) as SlatepackInterface; + final otherMethods = wallet.supportedMethods.where( + (method) => method != SlatepackMethod.slatepack, + ); + if (otherMethods.isEmpty) return const SizedBox.shrink(); + final SlatepackMethod other = otherMethods.first; + + return Toggle( + onValueChanged: (bool value) { + ref.read(pSelectedSlatepackMethod(walletId).notifier).state = value + ? other + : SlatepackMethod.slatepack; + }, + isOn: ref.watch(pSelectedSlatepackMethod(walletId)) == other, + onColor: isDesktop + ? Theme.of(context) + .extension()! + .rateTypeToggleDesktopColorOn + : Theme.of(context).extension()!.rateTypeToggleColorOn, + offColor: isDesktop + ? Theme.of(context) + .extension()! + .rateTypeToggleDesktopColorOff + : Theme.of(context).extension()!.rateTypeToggleColorOff, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular( + Constants.size.circularBorderRadius, + ), + ), + onIcon: Assets.svg.gear, + onText: wallet.slatepackTerms.title, + offIcon: Assets.svg.radioSyncing, + offText: other.label, + ); + } +} diff --git a/lib/wl_gen/interfaces/libepiccash_interface.dart b/lib/wl_gen/interfaces/libepiccash_interface.dart index d6ab18565f..04e671ccbd 100644 --- a/lib/wl_gen/interfaces/libepiccash_interface.dart +++ b/lib/wl_gen/interfaces/libepiccash_interface.dart @@ -58,10 +58,8 @@ abstract class LibEpicCashInterface { required String slateJson, }); - Future<({String slateId, String commitId, String slateJson})> txFinalize({ - required DynamicObject wallet, - required String slateJson, - }); + Future<({String slateId, String commitId, String slateJson, bool? posted})> + txFinalize({required DynamicObject wallet, required String slateJson}); Future cancelTransaction({ required DynamicObject wallet, diff --git a/lib/wl_gen/interfaces/libmwc_interface.dart b/lib/wl_gen/interfaces/libmwc_interface.dart index 52608da9b9..450fd5a835 100644 --- a/lib/wl_gen/interfaces/libmwc_interface.dart +++ b/lib/wl_gen/interfaces/libmwc_interface.dart @@ -93,7 +93,7 @@ abstract class LibMwcInterface { Future<({String commitId, String slateId, String slateJson})> txReceiveDetailed({required String wallet, required String slateJson}); - Future<({String commitId, String slateId})> txFinalize({ + Future<({String commitId, String slateId, bool? posted})> txFinalize({ required String wallet, required String slateJson, }); diff --git a/test/pages/send_view/send_views_test.dart b/test/pages/send_view/send_views_test.dart index b21c93a0e7..eecb3bf632 100644 --- a/test/pages/send_view/send_views_test.dart +++ b/test/pages/send_view/send_views_test.dart @@ -6,14 +6,19 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stackwallet/models/balance.dart'; import 'package:stackwallet/pages/send_view/frost_ms/recipient.dart'; +import 'package:stackwallet/pages/send_view/confirm_transaction_view.dart'; import 'package:stackwallet/pages/send_view/send_view.dart'; import 'package:stackwallet/pages/send_view/sub_widgets/transaction_fee_selection_sheet.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_dialog.dart'; +import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_auth_send.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/event_bus/events/global/wallet_sync_status_changed_event.dart'; import 'package:stackwallet/services/event_bus/global_event_bus.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; import 'package:stackwallet/utilities/stack_file_system.dart'; import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/wallets/wallet/wallet.dart'; @@ -901,6 +906,50 @@ void main() { }); group("the send view", () { + for (final (name, walletFactory) in <(String, FakeWallet Function())>[ + ("Epic Cash", FakeEpiccashWallet.new), + ("MWC", FakeMimblewimblecoinWallet.new), + ]) { + for (final view in coinCases) { + testWithoutAnimation( + "creates a manual slate directly without estimating or confirming ($view $name)", + (tester) async { + final wallet = walletFactory(); + final slateCreates = () => wallet is FakeEpiccashWallet + ? wallet.slateCreates + : (wallet as FakeMimblewimblecoinWallet).slateCreates; + await view.pump( + tester, + wallet: wallet as Wallet, + balance: testBalance("10", 8), + overrides: [ + pSelectedSlatepackMethod(wallet.walletId).overrideWithProvider( + StateProvider( + (_) => SlatepackMethod.slatepack, + ), + ), + ], + ); + await enterAmount(tester, view, "1"); + + final createLabel = name == "Epic Cash" + ? "Create slate" + : "Create slatepack"; + expect(find.text(createLabel), findsOneWidget); + + await view.preview(tester, label: createLabel); + + expect(slateCreates(), 1); + expect(wallet.prepared, isNull); + expect(wallet.feeEstimates, 0); + expect(find.byType(ConfirmTransactionView), findsNothing); + expect(find.byType(DesktopAuthSend), findsNothing); + expect(find.byType(SlatepackDialog), findsOneWidget); + }, + ); + } + } + for (final (coin, wallet) in <(String, Wallet Function())>[ ("Epic Cash", FakeEpiccashWallet.new), ("Xelis", FakeXelisWallet.new), diff --git a/test/pages/send_view/support/fake_wallets.dart b/test/pages/send_view/support/fake_wallets.dart index b8adce7142..00afa64b4a 100644 --- a/test/pages/send_view/support/fake_wallets.dart +++ b/test/pages/send_view/support/fake_wallets.dart @@ -4,7 +4,10 @@ import 'package:stackwallet/models/balance.dart'; import 'package:stackwallet/models/isar/models/ethereum/eth_contract.dart'; import 'package:stackwallet/models/isar/models/solana/sol_contract.dart'; import 'package:stackwallet/models/paymint/fee_object_model.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; +import 'package:stackwallet/utilities/slatepack_terms.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/crypto_currency/intermediate/cryptonote_currency.dart'; import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; @@ -15,6 +18,7 @@ import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/ethereum_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/firo_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/monero_wallet.dart'; +import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/solana_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/stellar_wallet.dart'; import 'package:stackwallet/wallets/wallet/impl/sub_wallets/eth_token_wallet.dart'; @@ -280,6 +284,88 @@ class FakeFiroWallet extends FakeWallet implements FiroWallet { class FakeEpiccashWallet extends FakeWallet implements EpiccashWallet { FakeEpiccashWallet() : super(Epiccash(CryptoCurrencyNetwork.main), testFees); + + int slateCreates = 0; + + @override + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + String? message, + }) async { + slateCreates++; + return SlatepackResult( + success: true, + slatepack: '{"id":"test-slate","amount":"${amount.raw}"}', + slateJson: '{"id":"test-slate","amount":"${amount.raw}"}', + slateId: 'test-slate', + state: SlateState.s1, + amount: amount, + fee: Amount(rawValue: BigInt.one, fractionDigits: amount.fractionDigits), + ); + } + + @override + List get supportedMethods => const [ + SlatepackMethod.relay, + SlatepackMethod.slatepack, + ]; + + @override + bool get hasSlatepackMethodToggle => true; + + @override + bool get supportsSlatepackEncryption => false; + + @override + bool get supportsOnChainNote => true; + + @override + SlatepackTerms get slatepackTerms => SlatepackTerms.slate; +} + +class FakeMimblewimblecoinWallet extends FakeWallet + implements MimblewimblecoinWallet { + FakeMimblewimblecoinWallet() + : super(Mimblewimblecoin(CryptoCurrencyNetwork.main), testFees); + + int slateCreates = 0; + + @override + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + String? message, + }) async { + slateCreates++; + return SlatepackResult( + success: true, + slatepack: 'BEGINSLATEPACK. test. ENDSLATEPACK.', + slateJson: '{"id":"test-slate","amount":"${amount.raw}"}', + slateId: 'test-slate', + state: SlateState.s1, + amount: amount, + fee: Amount(rawValue: BigInt.one, fractionDigits: amount.fractionDigits), + ); + } + + @override + List get supportedMethods => const [ + SlatepackMethod.slatepack, + SlatepackMethod.relay, + ]; + + @override + bool get hasSlatepackMethodToggle => true; + + @override + bool get supportsSlatepackEncryption => true; + + @override + bool get supportsOnChainNote => true; + + @override + SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; } /// Monero checking only an address prefix, as tests lack its native library. diff --git a/test/pages/send_view/support/send_view_cases.dart b/test/pages/send_view/support/send_view_cases.dart index 1e191ed6b1..877995e973 100644 --- a/test/pages/send_view/support/send_view_cases.dart +++ b/test/pages/send_view/support/send_view_cases.dart @@ -61,8 +61,8 @@ class SendViewCase { ); } - Future preview(WidgetTester tester) async { - await tester.tap(find.text(previewLabel)); + Future preview(WidgetTester tester, {String? label}) async { + await tester.tap(find.text(label ?? previewLabel)); // The views keep the building dialog up for at least 2.5 s. await tester.pump(const Duration(seconds: 3)); await tester.pumpAndSettle(); diff --git a/test/pages/slatepack/desktop_receive_slatepack_test.dart b/test/pages/slatepack/desktop_receive_slatepack_test.dart new file mode 100644 index 0000000000..609be70abe --- /dev/null +++ b/test/pages/slatepack/desktop_receive_slatepack_test.dart @@ -0,0 +1,103 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart'; +import 'package:stackwallet/services/wallets.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; +import 'package:stackwallet/widgets/qr.dart'; + +import '../../sample_data/theme_json.dart'; + +const _walletId = 'desktop-slatepack-wallet'; +const _address = 'esZrAddressThatMustNotAppearInSlatepackMode'; + +class _Wallet extends EpiccashWallet { + _Wallet(this._info) : super(CryptoCurrencyNetwork.main); + + final WalletInfo _info; + + @override + String get walletId => _info.walletId; + + @override + WalletInfo get info => _info; +} + +class _Wallets extends Fake implements Wallets { + _Wallets(this.wallet); + + final Wallet wallet; + + @override + Wallet getWallet(String walletId) => wallet; +} + +void main() { + testWidgets('slatepack mode replaces the desktop address and QR', ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + + final info = WalletInfo.createNew( + coin: Epiccash(CryptoCurrencyNetwork.main), + name: 'Epic Cash', + walletIdOverride: _walletId, + ).copyWith(cachedReceivingAddress: _address); + final wallet = _Wallet(info); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(_Wallets(wallet)), + pWalletInfo(_walletId).overrideWithValue(info), + pWalletReceivingAddress(_walletId).overrideWithValue(_address), + pSelectedSlatepackMethod(_walletId).overrideWithProvider( + StateProvider((ref) => SlatepackMethod.slatepack), + ), + themeProvider.overrideWithProvider( + StateProvider((ref) => theme), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SizedBox( + width: 520, + child: DesktopReceive(walletId: _walletId), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Import Slate'), findsNWidgets(2)); + expect(find.text('Enter Slate JSON'), findsOneWidget); + expect(find.text(_address), findsNothing); + expect(find.text('Create new QR code'), findsNothing); + expect(find.byType(QR), findsNothing); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/pages/slatepack/slatepack_cancel_transaction_dialog_test.dart b/test/pages/slatepack/slatepack_cancel_transaction_dialog_test.dart new file mode 100644 index 0000000000..046630c226 --- /dev/null +++ b/test/pages/slatepack/slatepack_cancel_transaction_dialog_test.dart @@ -0,0 +1,154 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_cancel_transaction_dialog.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/util.dart'; + +import '../../sample_data/theme_json.dart'; + +void main() { + group('canCancelSlateTransaction', () { + test('allows every pending slate state the wallet can cancel', () { + expect( + canCancelSlateTransaction( + slateId: 'outgoing-s1', + isCancelled: false, + confirmations: 0, + ), + isTrue, + ); + expect( + canCancelSlateTransaction( + slateId: 'incoming-s2', + isCancelled: false, + confirmations: 0, + ), + isTrue, + reason: 'a receiver must be able to unlock an abandoned receive', + ); + expect( + canCancelSlateTransaction( + slateId: 'finalized-but-not-broadcast', + isCancelled: false, + confirmations: 0, + ), + isTrue, + reason: 'an unbroadcast finalized send must not leave funds stuck', + ); + }); + + test('rejects records that are not pending cancellable slates', () { + expect( + canCancelSlateTransaction( + slateId: null, + isCancelled: false, + confirmations: 0, + ), + isFalse, + ); + expect( + canCancelSlateTransaction( + slateId: '', + isCancelled: false, + confirmations: 0, + ), + isFalse, + ); + expect( + canCancelSlateTransaction( + slateId: 'cancelled', + isCancelled: true, + confirmations: 0, + ), + isFalse, + ); + expect( + canCancelSlateTransaction( + slateId: 'confirmed', + isCancelled: false, + confirmations: 1, + ), + isFalse, + ); + }); + }); + + for (final width in [320.0, 375.0, 412.0]) { + testWidgets('cancel confirmation fits at ${width.toInt()} dp', ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android'); + addTearDown(() => Util.layoutPlatform = previousPlatform); + tester.view.physicalSize = Size(width, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousWidth = Util.screenWidth; + Util.screenWidth = width; + addTearDown(() => Util.screenWidth = previousWidth); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context) + .copyWith(textScaler: const TextScaler.linear(1.15)), + child: child!, + ), + home: const SlatepackCancelTransactionDialog(), + ), + ); + + expect(find.text('Go back'), findsOneWidget); + expect(find.text('Cancel it'), findsOneWidget); + expect(find.text('Cancel transaction'), findsNothing); + expect( + find.textContaining('may not prevent another party'), + findsOneWidget, + ); + expect(find.textContaining('can no longer complete'), findsNothing); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('cancel confirmation returns the selected action', ( + tester, + ) async { + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + bool? result; + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(extensions: [StackColors.fromStackColorTheme(theme)]), + home: Builder( + builder: (context) => TextButton( + onPressed: () async { + result = await showDialog( + context: context, + builder: (_) => const SlatepackCancelTransactionDialog(), + ); + }, + child: const Text('Show'), + ), + ), + ), + ); + + await tester.tap(find.text('Show')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Go back')); + await tester.pumpAndSettle(); + expect(result, isFalse); + + await tester.tap(find.text('Show')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel it')); + await tester.pumpAndSettle(); + expect(result, isTrue); + }); +} diff --git a/test/pages/slatepack/slatepack_dialog_test.dart b/test/pages/slatepack/slatepack_dialog_test.dart new file mode 100644 index 0000000000..c094e78ec7 --- /dev/null +++ b/test/pages/slatepack/slatepack_dialog_test.dart @@ -0,0 +1,310 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_dialog.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_popup.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/slatepack_terms.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/widgets/stack_dialog.dart'; + +import '../../sample_data/theme_json.dart'; + +void main() { + void useAndroidLayout() { + final previousPlatform = Util.layoutPlatform; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android'); + addTearDown(() => Util.layoutPlatform = previousPlatform); + } + + test('slatepack text uses a platform-native monospace family', () { + expect(slatepackMonospaceFontFamily(TargetPlatform.iOS), 'Menlo'); + expect(slatepackMonospaceFontFamily(TargetPlatform.macOS), 'Menlo'); + expect(slatepackMonospaceFontFamily(TargetPlatform.windows), 'Consolas'); + expect(slatepackMonospaceFontFamily(TargetPlatform.android), 'monospace'); + expect(slatepackMonospaceFontFamily(TargetPlatform.fuchsia), 'monospace'); + expect(slatepackMonospaceFontFamily(TargetPlatform.linux), 'monospace'); + }); + + test("uses a coin-specific file name", () { + const slate = SlatepackDialog( + terms: SlatepackTerms.slate, + slatepack: '{}', + state: SlateState.s1, + slateId: "epic-id", + ); + const slatepack = SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: "BEGINSLATEPACK. test. ENDSLATEPACK.", + state: SlateState.s2, + slateId: "mwc-id", + ); + const unnamedSlate = SlatepackDialog( + terms: SlatepackTerms.slate, + slatepack: '{}', + state: SlateState.unknown, + ); + + expect(slate.fileName, "epic-id.S1.slate"); + expect(slatepack.fileName, "mwc-id.S2.slatepack"); + expect(unnamedSlate.fileName, "slate.slate"); + }); + + test("uses coin-specific screen wording", () { + const slate = SlatepackDialog( + terms: SlatepackTerms.slate, + slatepack: '{}', + state: SlateState.s1, + ); + const slatepack = SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: "BEGINSLATEPACK. test. ENDSLATEPACK.", + state: SlateState.s1, + ); + + expect(slate.instructions, contains("on the Slate screen")); + expect(slate.instructions, isNot(contains("Slatepack screen"))); + expect(slatepack.instructions, contains("on the Slatepack screen")); + }); + + testWidgets("Share anchors the share sheet to the Share button", ( + tester, + ) async { + useAndroidLayout(); + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetViewInsets); + // Share is only offered on the phone layout. + final previousWidth = Util.screenWidth; + Util.screenWidth = 400; + addTearDown(() => Util.screenWidth = previousWidth); + + const channel = MethodChannel("dev.fluttercommunity.plus/share"); + final calls = []; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return ""; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SlatepackDialog( + terms: SlatepackTerms.slate, + slatepack: '{"slate": true}', + state: SlateState.s1, + slateId: "test-slate", + ), + ), + ), + ), + ); + + await tester.tap(find.text("Share")); + await tester.pump(); + + expect(calls, hasLength(1)); + final args = calls.single.arguments as Map; + expect(args["text"], '{"slate": true}'); + final origin = Rect.fromLTWH( + args["originX"] as double, + args["originY"] as double, + args["originWidth"] as double, + args["originHeight"] as double, + ); + expect(origin.isEmpty, isFalse); + expect(origin.contains(tester.getCenter(find.text("Share"))), isTrue); + expect( + (Offset.zero & tester.view.physicalSize).contains(origin.topLeft), + isTrue, + ); + }); + + testWidgets('actions fit at 360 dp with 115 percent text', (tester) async { + useAndroidLayout(); + tester.view.physicalSize = const Size(360, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousWidth = Util.screenWidth; + Util.screenWidth = 360; + addTearDown(() => Util.screenWidth = previousWidth); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context) + .copyWith(textScaler: const TextScaler.linear(1.15)), + child: child!, + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showSlatepackPopup( + context: context, + barrierDismissible: false, + child: const SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: 'BEGINSLATEPACK. test. ENDSLATEPACK.', + state: SlateState.s1, + slateId: 'test-slate', + ), + ), + child: const Text('Show'), + ), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Show')); + await tester.pumpAndSettle(); + + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect(find.text('Save'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.byType(SlatepackDialog), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('mobile popup stays above the keyboard', (tester) async { + useAndroidLayout(); + tester.view.physicalSize = const Size(400, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetViewInsets); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showSlatepackPopup( + context: context, + child: const TextField(key: Key('slate-input')), + ), + child: const Text('Show'), + ), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Show')); + await tester.pumpAndSettle(); + final before = tester.getBottomRight(find.byKey(const Key('slate-input'))); + + tester.view.viewInsets = const FakeViewPadding(bottom: 300); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byType(StackDialogBase)) + .keyboardPaddingAmount, + 300, + ); + final after = tester.getBottomRight(find.byKey(const Key('slate-input'))); + + expect(after.dy, lessThanOrEqualTo(500)); + expect(after.dy, lessThan(before.dy - 250)); + expect(tester.takeException(), isNull); + }); + + testWidgets('mobile receive entry stays above the keyboard', (tester) async { + useAndroidLayout(); + tester.view.physicalSize = const Size(400, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetViewInsets); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showSlatepackEntryDialog( + context: context, + terms: SlatepackTerms.slatepack, + ), + child: const Text('Import'), + ), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Import')); + await tester.pumpAndSettle(); + tester.view.viewInsets = const FakeViewPadding(bottom: 300); + await tester.pumpAndSettle(); + + expect(find.byType(SlatepackEntryDialog), findsOneWidget); + expect( + tester + .widget(find.byType(StackDialogBase)) + .keyboardPaddingAmount, + 300, + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('Epic slates omit encryption status', (tester) async { + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SlatepackDialog( + terms: SlatepackTerms.slate, + slatepack: '{}', + state: SlateState.s1, + showEncryptionStatus: false, + ), + ), + ), + ), + ); + + expect(find.text('Not encrypted'), findsNothing); + expect(find.textContaining('Encrypted to'), findsNothing); + }); +} diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart new file mode 100644 index 0000000000..6aa58c649f --- /dev/null +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -0,0 +1,843 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_dialog.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_import_flow.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/slatepack_text.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import 'package:stackwallet/widgets/custom_loading_overlay.dart'; +import 'package:stackwallet/widgets/rounded_container.dart'; + +import '../../sample_data/theme_json.dart'; + +/// Epic Cash wallet whose inspection is canned, so run() can be driven +/// without a native wallet. +class _InspectOnlyWallet extends EpiccashWallet { + _InspectOnlyWallet( + this.state, { + this.localIsSend, + this.localIsCancelled = false, + this.localGate, + this.receiveGate, + this.receiveError, + this.senderAddress, + this.finalizeResult, + }) : super(CryptoCurrencyNetwork.main); + + /// When set, receiving waits for it and then succeeds, or throws + /// [receiveError] if that is set. + final Completer? receiveGate; + final Exception? receiveError; + final String? senderAddress; + final FinalizeResult? finalizeResult; + + final SlateState state; + + /// Direction of the wallet's own transaction for the slate. Null when the + /// wallet has none. + final bool? localIsSend; + final bool localIsCancelled; + + /// When set, the local-history lookup waits for it. + final Completer? localGate; + int receiveCalls = 0; + int finalizeCalls = 0; + int refreshCalls = 0; + SlateInspection? actionInspection; + + /// What the flow handed to the wallet. + final seen = []; + + @override + Future inspectSlatepack(String armored) async { + seen.add(armored); + return SlateInspection( + state: state, + slateId: "test-slate", + slateJson: '{"id":"test-slate"}', + amount: Amount(rawValue: BigInt.from(100), fractionDigits: 8), + fee: Amount(rawValue: BigInt.one, fractionDigits: 8), + senderAddress: senderAddress, + ); + } + + @override + Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> + localTxForSlate(String slateId) async { + await localGate?.future; + return localIsSend == null + ? null + : ( + amount: Amount(rawValue: BigInt.from(100), fractionDigits: 8), + fee: Amount(rawValue: BigInt.one, fractionDigits: 8), + isSend: localIsSend!, + isCancelled: localIsCancelled, + ); + } + + @override + Future receiveSlatepack( + String slatepack, { + required SlateInspection inspection, + }) async { + receiveCalls++; + actionInspection = inspection; + if (receiveGate == null) { + return SlatepackResult(success: false, error: "not in tests"); + } + await receiveGate!.future; + if (receiveError != null) throw receiveError!; + return SlatepackResult( + success: true, + slatepack: '{"response": true}', + slateId: "test-slate", + state: SlateState.s2, + ); + } + + @override + Future refresh({bool doScan = true}) async { + refreshCalls++; + } + + @override + Future finalizeSlatepack( + String slatepack, { + required SlateInspection inspection, + }) async { + actionInspection = inspection; + finalizeCalls++; + return finalizeResult ?? + FinalizeResult(success: false, error: "not in tests"); + } +} + +class _SynchronousMwcWallet extends MimblewimblecoinWallet { + _SynchronousMwcWallet({ + required this.onInspect, + this.state = SlateState.s3, + this.localGate, + }) : super(CryptoCurrencyNetwork.main); + + final VoidCallback onInspect; + final SlateState state; + final Completer? localGate; + + @override + Future inspectSlatepack(String armored) { + onInspect(); + return Future.value(SlateInspection(state: state, slateId: 'mwc-slate')); + } + + @override + Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> + localTxForSlate(String slateId) async { + await localGate?.future; + return null; + } +} + +void main() { + group("routeFor", () { + test("standard send states", () { + expect( + SlatepackImportFlow.routeFor(SlateState.s1), + SlatepackRoute.receive, + ); + expect( + SlatepackImportFlow.routeFor(SlateState.s2), + SlatepackRoute.finalizeSend, + ); + expect( + SlatepackImportFlow.routeFor(SlateState.s3), + SlatepackRoute.alreadyFinalized, + ); + expect( + SlatepackImportFlow.routeFor(SlateState.i3), + SlatepackRoute.alreadyFinalized, + ); + expect( + SlatepackImportFlow.routeFor(SlateState.unknown), + SlatepackRoute.unsupported, + ); + }); + + test("invoice states are unsupported", () { + expect( + SlatepackImportFlow.routeFor(SlateState.i1), + SlatepackRoute.invoicesUnsupported, + ); + expect( + SlatepackImportFlow.routeFor(SlateState.i2), + SlatepackRoute.invoicesUnsupported, + ); + }); + }); + + test("SlateState.fromCode", () { + expect(SlateState.fromCode("S1"), SlateState.s1); + expect(SlateState.fromCode("i2"), SlateState.i2); + expect(SlateState.fromCode(" S3 "), SlateState.s3); + expect(SlateState.fromCode("X9"), SlateState.unknown); + expect(SlateState.fromCode(null), SlateState.unknown); + }); + + group("normalize", () { + const armored = + "BEGINSLATEPACK. 4H1qx1wHe668tFW yC2gfL8PPd8kSgv. " + "ENDSLATEPACK."; + + test("trims whitespace", () { + expect(SlatepackImportFlow.normalize(" \n$armored\r\n "), armored); + expect(SlatepackImportFlow.normalize(armored), armored); + }); + + test("drops text around the armored frame", () { + expect( + SlatepackImportFlow.normalize( + "Here is the slatepack:\n\n$armored\n\nSend it back soon.", + ), + armored, + ); + expect(SlatepackImportFlow.normalize("> $armored <"), armored); + }); + + test("keeps line breaks inside the frame", () { + const wrapped = + "BEGINSLATEPACK. 4H1qx1wHe668tFW\nyC2gfL8PPd8kSgv. ENDSLATEPACK."; + expect(SlatepackImportFlow.normalize("Hi\n$wrapped\nBye"), wrapped); + }); + + test("accepts the binary markers and a missing final period", () { + const binary = "BEGINSLATE_BIN. 4H1qx1wHe668tFW. ENDSLATE_BIN."; + expect(SlatepackImportFlow.normalize("x $binary y"), binary); + expect( + SlatepackImportFlow.normalize( + "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK", + ), + "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK", + ); + }); + + test("shares the same armored-frame recognition as the wallets", () { + expect(SlatepackText.isArmored(armored), isTrue); + expect(SlatepackText.isArmored("\n$armored\n"), isTrue); + expect(SlatepackText.isArmored("prefix $armored"), isFalse); + expect(SlatepackText.isArmored('{"id":"abc"}'), isFalse); + }); + + test("takes the first of two slatepacks", () { + expect(SlatepackImportFlow.normalize("$armored\n$armored"), armored); + }); + + test("leaves JSON slates alone apart from trimming", () { + const json = '{"id": "abc", "note": "BEGINSLATEPACK. x. ENDSLATEPACK."}'; + expect(SlatepackImportFlow.normalize(" $json\n"), json); + }); + + test("leaves other text alone apart from trimming", () { + expect( + SlatepackImportFlow.normalize(" not a slatepack "), + "not a slatepack", + ); + expect( + SlatepackImportFlow.normalize("BEGINSLATEPACK. cut off"), + "BEGINSLATEPACK. cut off", + ); + expect(SlatepackImportFlow.normalize(" "), ""); + }); + }); + + group("run", () { + Future runFlow( + WidgetTester tester, + SlatepackInterface wallet, { + String text = "{}", + ValueNotifier? shown, + void Function(bool)? onDone, + }) async { + bool? outcome; + shown ??= ValueNotifier(true); + final coin = wallet.cryptoCurrency; + // The loading overlay reads its indicator from the theme. + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory("test/sample_data").absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: "en_US", + coin: coin, + maxDecimals: coin.fractionDigits, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: ValueListenableBuilder( + valueListenable: shown, + builder: (context, isShown, _) => !isShown + ? const SizedBox() + : Builder( + builder: (context) => TextButton( + onPressed: () async { + outcome = await SlatepackImportFlow.run( + context: context, + wallet: wallet, + text: text, + ); + onDone?.call(outcome!); + }, + child: const Text("go"), + ), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text("go")); + // Loading overlay delay, then the inspection. + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + return outcome; + } + + Future closeDialog(WidgetTester tester) async { + await tester.tap(find.text("OK")); + await tester.pump(const Duration(milliseconds: 400)); + } + + testWidgets('MWC inspection starts after the loading route is visible', ( + tester, + ) async { + double? routeOpacity; + final wallet = _SynchronousMwcWallet( + onInspect: () { + final overlay = tester.element(find.byType(CustomLoadingOverlay)); + routeOpacity = ModalRoute.of(overlay)!.animation!.value; + }, + ); + + await runFlow(tester, wallet); + + expect(routeOpacity, 1); + expect(find.text('Already finalized'), findsOneWidget); + await closeDialog(tester); + }); + + testWidgets('MWC response with no local send does not show zero values', ( + tester, + ) async { + final wallet = _SynchronousMwcWallet( + state: SlateState.s2, + onInspect: () {}, + ); + + await runFlow(tester, wallet); + + expect(find.text('Finalize slatepack'), findsOneWidget); + expect(find.text('Encrypted'), findsOneWidget); + expect( + find.textContaining('amount and fee are unavailable'), + findsOneWidget, + ); + expect(find.textContaining('No matching send was found'), findsOneWidget); + expect(find.textContaining('could not be checked'), findsNothing); + expect(find.textContaining('0.000000000 MWC'), findsNothing); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + }); + + testWidgets("finalized slate shows a message", (tester) async { + final wallet = _InspectOnlyWallet(SlateState.s3); + await runFlow(tester, wallet); + expect(find.text("Already finalized"), findsOneWidget); + await closeDialog(tester); + expect(wallet.receiveCalls + wallet.finalizeCalls, 0); + }); + + testWidgets("unknown slate is unsupported", (tester) async { + final wallet = _InspectOnlyWallet(SlateState.unknown); + await runFlow(tester, wallet); + expect(find.text("Unsupported slate"), findsOneWidget); + await closeDialog(tester); + }); + + testWidgets("invoice without invoice support", (tester) async { + final wallet = _InspectOnlyWallet(SlateState.i1); + await runFlow(tester, wallet); + expect(find.text("Invoices not supported"), findsOneWidget); + await closeDialog(tester); + }); + + testWidgets("response to a send this wallet did not start", (tester) async { + final wallet = _InspectOnlyWallet(SlateState.s2); + await runFlow(tester, wallet); + expect(find.text("Finalize slate"), findsOneWidget); + expect(find.textContaining("No matching send was found"), findsOneWidget); + expect(find.textContaining("could not be checked"), findsNothing); + expect(find.textContaining('other party'), findsOneWidget); + expect(find.textContaining('with the sender'), findsNothing); + final warning = find.byKey(const Key("slatepackHistoryWarning")); + expect(warning, findsOneWidget); + expect(tester.widget(warning), isA()); + final warningContainer = tester.widget(warning); + final warningColors = Theme.of(tester.element(warning)) + .extension()!; + expect(warningContainer.color, warningColors.warningBackground); + expect(warningContainer.borderColor, isNull); + expect( + find.descendant(of: warning, matching: find.byType(Icon)), + findsNothing, + ); + final warningText = tester.widget( + find.textContaining("No matching send was found"), + ); + expect(warningText.style?.color, warningColors.warningForeground); + expect(find.text("0.00000100 EPIC"), findsOneWidget); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.text("Cancel")); + await tester.tap(find.text("Cancel")); + await tester.pumpAndSettle(); + expect(wallet.finalizeCalls, 0); + }); + + testWidgets("this wallet cannot receive its own initial slate", ( + tester, + ) async { + final wallet = _InspectOnlyWallet(SlateState.s1, localIsSend: true); + + await runFlow(tester, wallet); + + expect(find.text("Cannot receive this slate"), findsOneWidget); + expect(find.textContaining("This wallet created"), findsOneWidget); + expect(find.text("Receive"), findsNothing); + expect(wallet.receiveCalls, 0); + await closeDialog(tester); + }); + + testWidgets('a stalled local-history lookup falls back to the summary', ( + tester, + ) async { + final wallet = _SynchronousMwcWallet( + state: SlateState.s2, + onInspect: () {}, + localGate: Completer(), + ); + + await runFlow(tester, wallet); + expect(find.byType(CustomLoadingOverlay), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + expect(find.byType(CustomLoadingOverlay), findsOneWidget); + await tester.pump(const Duration(seconds: 1)); + await tester.pump(const Duration(milliseconds: 400)); + + expect(find.text('Finalize slatepack'), findsOneWidget); + expect(find.byKey(const Key('slatepackHistoryWarning')), findsOneWidget); + expect( + find.textContaining( + "history could not be checked because the wallet " + "is busy", + ), + findsOneWidget, + ); + expect( + find.textContaining('amount and fee are unavailable'), + findsOneWidget, + ); + expect(find.textContaining('No matching send was found'), findsNothing); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + }); + + testWidgets('a stalled lookup with slate values says they are unchecked', ( + tester, + ) async { + final wallet = _InspectOnlyWallet( + SlateState.s2, + localGate: Completer(), + ); + + await runFlow(tester, wallet); + await tester.pump(const Duration(seconds: 2)); + expect(find.byType(CustomLoadingOverlay), findsOneWidget); + await tester.pump(const Duration(seconds: 1)); + await tester.pump(const Duration(milliseconds: 400)); + + expect(find.text('Finalize slate'), findsOneWidget); + expect(find.byKey(const Key('slatepackHistoryWarning')), findsOneWidget); + expect(find.textContaining('could not be checked'), findsOneWidget); + expect( + find.textContaining('come from the imported slate'), + findsOneWidget, + ); + expect(find.textContaining('No matching send was found'), findsNothing); + await tester.ensureVisible(find.text('Cancel')); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(wallet.finalizeCalls, 0); + }); + + testWidgets('a slow receive lookup still offers the summary', ( + tester, + ) async { + final gate = Completer(); + final wallet = _InspectOnlyWallet(SlateState.s1, localGate: gate); + + await runFlow(tester, wallet); + await tester.pump(const Duration(seconds: 2)); + expect(find.byType(CustomLoadingOverlay), findsOneWidget); + expect(find.text('Could not check wallet history'), findsNothing); + + gate.complete(); + await tester.pumpAndSettle(); + + expect(find.text('Receive slate'), findsOneWidget); + expect(find.text('Receive'), findsOneWidget); + expect(find.textContaining('busy'), findsNothing); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(wallet.receiveCalls, 0); + }); + + testWidgets('a receive lookup that never finishes is refused', ( + tester, + ) async { + final wallet = _InspectOnlyWallet( + SlateState.s1, + localGate: Completer(), + ); + + await runFlow(tester, wallet); + await tester.pump(const Duration(seconds: 2)); + expect(find.byType(CustomLoadingOverlay), findsOneWidget); + expect(find.text('Could not check wallet history'), findsNothing); + + await tester.pump(const Duration(seconds: 1)); + await tester.pump(); + + expect(find.text('Could not check wallet history'), findsOneWidget); + expect(find.textContaining('The wallet is busy'), findsOneWidget); + expect(find.text('Receive'), findsNothing); + await closeDialog(tester); + expect(wallet.receiveCalls, 0); + }); + + testWidgets('a slate already received is refused', (tester) async { + final wallet = _InspectOnlyWallet(SlateState.s1, localIsSend: false); + + await runFlow(tester, wallet); + + expect(find.text('Cannot receive this slate'), findsOneWidget); + expect( + find.textContaining("already in this wallet's history"), + findsOneWidget, + ); + expect(find.text('Receive'), findsNothing); + await closeDialog(tester); + expect(wallet.receiveCalls, 0); + }); + + testWidgets('a slate whose receive was cancelled is refused consistently', ( + tester, + ) async { + final wallet = _InspectOnlyWallet( + SlateState.s1, + localIsSend: false, + localIsCancelled: true, + ); + + await runFlow(tester, wallet); + + expect(find.text('Cannot receive this slate'), findsOneWidget); + expect(find.textContaining('receive was cancelled'), findsOneWidget); + expect(find.text('Receive'), findsNothing); + await closeDialog(tester); + expect(wallet.receiveCalls, 0); + }); + + testWidgets("this wallet's cancelled send cannot be received", ( + tester, + ) async { + final wallet = _InspectOnlyWallet( + SlateState.s1, + localIsSend: true, + localIsCancelled: true, + ); + + await runFlow(tester, wallet); + + expect(find.text('Cannot receive this slate'), findsOneWidget); + expect( + find.textContaining('This transaction was cancelled'), + findsOneWidget, + ); + expect(find.textContaining('This wallet created'), findsNothing); + expect(find.text('Receive'), findsNothing); + await closeDialog(tester); + expect(wallet.receiveCalls, 0); + }); + + testWidgets('a hexadecimal slatepack sender is labelled as a key', ( + tester, + ) async { + final senderKey = List.filled(32, 'ab').join(); + final wallet = _InspectOnlyWallet( + SlateState.s1, + senderAddress: senderKey, + ); + + await runFlow(tester, wallet); + + expect(find.text('Sender key'), findsOneWidget); + expect(find.text('From'), findsNothing); + expect(find.text(senderKey), findsOneWidget); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + }); + + testWidgets('Epic summaries omit an inapplicable encryption row', ( + tester, + ) async { + final wallet = _InspectOnlyWallet(SlateState.s1); + + await runFlow(tester, wallet); + + expect(find.text('Receive slate'), findsOneWidget); + expect(find.text('Encrypted'), findsNothing); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + }); + + testWidgets("response to a transaction this wallet received", ( + tester, + ) async { + final wallet = _InspectOnlyWallet(SlateState.s2, localIsSend: false); + await runFlow(tester, wallet); + expect(find.text("Cannot finalize this slate"), findsOneWidget); + expect( + find.textContaining("a transaction this wallet received"), + findsOneWidget, + ); + expect(find.text("Finalize"), findsNothing); + await closeDialog(tester); + expect(wallet.finalizeCalls, 0); + }); + + testWidgets("response to this wallet's cancelled send is refused", ( + tester, + ) async { + final wallet = _InspectOnlyWallet( + SlateState.s2, + localIsSend: true, + localIsCancelled: true, + ); + await runFlow(tester, wallet); + expect(find.text("Cannot finalize this slate"), findsOneWidget); + expect(find.textContaining("was cancelled"), findsOneWidget); + expect(find.text("Finalize"), findsNothing); + await closeDialog(tester); + expect(wallet.finalizeCalls, 0); + }); + + testWidgets("response to this wallet's own send can be finalized", ( + tester, + ) async { + final wallet = _InspectOnlyWallet(SlateState.s2, localIsSend: true); + await runFlow(tester, wallet); + expect(find.text("Cannot finalize this slate"), findsNothing); + expect(find.text("Finalize slate"), findsOneWidget); + expect(find.byKey(const Key("slatepackHistoryWarning")), findsNothing); + expect(find.text("0.00000100 EPIC"), findsOneWidget); + await tester.tap(find.text("Finalize")); + // Loading overlay delay, then the canned failure and its dialog. + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.finalizeCalls, 1); + expect(wallet.refreshCalls, 0); + await closeDialog(tester); + }); + + testWidgets('a finalized transaction reports a rejected broadcast', ( + tester, + ) async { + final wallet = _InspectOnlyWallet( + SlateState.s2, + localIsSend: true, + finalizeResult: FinalizeResult( + success: true, + slateId: 'test-slate', + posted: false, + ), + ); + await runFlow(tester, wallet); + await tester.tap(find.text('Finalize')); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + + expect(find.text('Finalized, not broadcast'), findsOneWidget); + expect(wallet.refreshCalls, 0); + expect(find.textContaining('node did not accept it'), findsOneWidget); + expect(find.textContaining('transaction details'), findsNothing); + await closeDialog(tester); + }); + + testWidgets('an older plugin does not claim an unknown broadcast result', ( + tester, + ) async { + final wallet = _InspectOnlyWallet( + SlateState.s2, + localIsSend: true, + finalizeResult: FinalizeResult( + success: true, + slateId: 'test-slate', + posted: null, + ), + ); + await runFlow(tester, wallet); + await tester.tap(find.text('Finalize')); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + + expect(find.text('Transaction finalized'), findsOneWidget); + expect( + find.textContaining('broadcast result is unavailable'), + findsOneWidget, + ); + expect(find.textContaining('finalized and broadcast'), findsNothing); + expect(find.textContaining('node did not accept'), findsNothing); + await closeDialog(tester); + }); + + testWidgets("the wallet only sees the slatepack itself", (tester) async { + const armored = "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK."; + final wallet = _InspectOnlyWallet(SlateState.s2, localIsSend: true); + await runFlow(tester, wallet, text: "Here you go:\n$armored\nThanks\n"); + await tester.tap(find.text("Finalize")); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.seen, [armored]); + expect(wallet.actionInspection?.slateJson, '{"id":"test-slate"}'); + await closeDialog(tester); + }); + + testWidgets("the response is shown even if the importing screen closed " + "while the slate was received", (tester) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gate = Completer(); + final wallet = _InspectOnlyWallet(SlateState.s1, receiveGate: gate); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + bool? done; + await runFlow(tester, wallet, shown: shown, onDone: (v) => done = v); + expect(find.text("Receive slate"), findsOneWidget); + await tester.tap(find.text("Receive")); + // Summary closes, loading overlay delay, then the wallet is asked. + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.receiveCalls, 1); + expect(find.byType(SlatepackDialog), findsNothing); + expect(find.byType(CustomLoadingOverlay), findsOneWidget); + + shown.value = false; + await tester.pump(); + expect(find.text("go"), findsNothing); + + gate.complete(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.byType(SlatepackDialog), findsOneWidget); + expect(find.text('{"response": true}'), findsOneWidget); + expect(find.text('Not encrypted'), findsNothing); + + await tester.tap(find.text("Done")); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(done, isTrue); + // Nothing is left over the app once the response is closed. + expect( + find.byType(CustomLoadingOverlay, skipOffstage: false), + findsNothing, + ); + expect(find.byType(ModalBarrier), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets("an error is shown even if the importing screen closed " + "while the slate was received", (tester) async { + final gate = Completer(); + final wallet = _InspectOnlyWallet( + SlateState.s1, + receiveGate: gate, + receiveError: Exception("the slate was refused"), + ); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + bool? done; + await runFlow(tester, wallet, shown: shown, onDone: (v) => done = v); + await tester.tap(find.text("Receive")); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.receiveCalls, 1); + + shown.value = false; + await tester.pump(); + gate.complete(); + for ( + var i = 0; + i < 10 && find.text("the slate was refused").evaluate().isEmpty; + i++ + ) { + await tester.pump(); + } + expect(find.text("the slate was refused"), findsOneWidget); + expect( + find.byType(CustomLoadingOverlay, skipOffstage: false), + findsOneWidget, + reason: 'the outgoing and incoming dialog fades should overlap', + ); + await tester.pump(const Duration(milliseconds: 400)); + expect( + find.byType(CustomLoadingOverlay, skipOffstage: false), + findsNothing, + ); + + await closeDialog(tester); + await tester.pump(const Duration(milliseconds: 400)); + expect(done, isFalse); + expect(tester.takeException(), isNull); + }); + }); +} diff --git a/test/pages/slatepack/slatepack_input_field_test.dart b/test/pages/slatepack/slatepack_input_field_test.dart new file mode 100644 index 0000000000..2c92d66462 --- /dev/null +++ b/test/pages/slatepack/slatepack_input_field_test.dart @@ -0,0 +1,122 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_input_field.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/clipboard_interface.dart'; +import 'package:stackwallet/utilities/slatepack_terms.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/utilities/util.dart'; + +import '../../sample_data/theme_json.dart'; + +class _Clipboard extends Fake implements ClipboardInterface { + final response = Completer(); + + @override + Future getData(String format) => response.future; +} + +void main() { + testWidgets('mobile label fits beside the input actions at 360 dp', ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android'); + Util.screenWidth = 360; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + tester.view.physicalSize = const Size(360, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final controller = TextEditingController(); + addTearDown(controller.dispose); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: Center( + child: SizedBox( + width: 328, + child: SlatepackInputField( + controller: controller, + hint: 'Enter Slatepack Message', + terms: SlatepackTerms.slatepack, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final label = find.text('Slatepack'); + final paste = find.byKey(const Key('slatepackPasteButton')); + expect(label, findsOneWidget); + expect(paste, findsOneWidget); + expect( + tester.getRect(label).right, + lessThanOrEqualTo(tester.getRect(paste).left), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('paste completes after the input closes', (tester) async { + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final controller = TextEditingController(); + final clipboard = _Clipboard(); + final changes = []; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: SlatepackInputField( + controller: controller, + hint: 'Slatepack', + terms: SlatepackTerms.slatepack, + clipboard: clipboard, + onChanged: changes.add, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('slatepackPasteButton'))); + await tester.pumpWidget(const SizedBox.shrink()); + controller.dispose(); + clipboard.response.complete(const ClipboardData(text: 'slatepack')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(changes, isEmpty); + }); +} diff --git a/test/pages/slatepack/slatepack_qr_test.dart b/test/pages/slatepack/slatepack_qr_test.dart new file mode 100644 index 0000000000..443efefd53 --- /dev/null +++ b/test/pages/slatepack/slatepack_qr_test.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_qr.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/widgets/qr.dart'; + +import '../../sample_data/theme_json.dart'; + +Widget _app(Widget child) => MaterialApp( + theme: ThemeData( + extensions: [ + StackColors.fromStackColorTheme( + StackTheme.fromJson(json: lightThemeJsonMap), + ), + ], + ), + home: Scaffold(body: SingleChildScrollView(child: child)), +); + +void main() { + test("length guard", () { + expect(slatepackFitsQr("a" * kSlatepackQrMaxBytes), isTrue); + expect(slatepackFitsQr("a" * (kSlatepackQrMaxBytes + 1)), isFalse); + // Bytes count, not characters. + expect(slatepackFitsQr("é" * (kSlatepackQrMaxBytes ~/ 2)), isTrue); + expect(slatepackFitsQr("é" * (kSlatepackQrMaxBytes ~/ 2 + 1)), isFalse); + }); + + testWidgets("the longest slatepack that fits is drawn", (tester) async { + await tester.pumpWidget( + _app(SlatepackQr(data: "a" * kSlatepackQrMaxBytes, noun: "slate")), + ); + await tester.pump(); + expect(find.byKey(const Key("slatepackQrCode")), findsOneWidget); + expect(find.byKey(const Key("slatepackQrTooLong")), findsNothing); + expect(find.text("Too much data to show as a QR code"), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets("a slate of a few thousand characters is drawn", (tester) async { + await tester.pumpWidget( + _app(SlatepackQr(data: '{"slate": "${"a" * 2400}"}', noun: "slate")), + ); + await tester.pump(); + expect(find.byKey(const Key("slatepackQrCode")), findsOneWidget); + expect(find.text("Too much data to show as a QR code"), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets("short slatepack shows a QR code", (tester) async { + await tester.pumpWidget( + _app( + const SlatepackQr( + data: "BEGINSLATEPACK. abc. ENDSLATEPACK.", + noun: "slatepack", + ), + ), + ); + expect(find.byKey(const Key("slatepackQrCode")), findsOneWidget); + expect(find.byType(QR), findsOneWidget); + expect(find.byKey(const Key("slatepackQrTooLong")), findsNothing); + }); + + testWidgets("tap enlarges the QR code", (tester) async { + await tester.pumpWidget( + _app(const SlatepackQr(data: "short", noun: "slatepack")), + ); + await tester.tap(find.byKey(const Key("slatepackQrCode"))); + await tester.pumpAndSettle(); + expect(find.byType(QR), findsNWidgets(2)); + }); + + testWidgets("long slatepack falls back to a note", (tester) async { + await tester.pumpWidget( + _app(SlatepackQr(data: "a" * (kSlatepackQrMaxBytes + 1), noun: "slate")), + ); + expect(find.byType(QR), findsNothing); + expect(find.byKey(const Key("slatepackQrTooLong")), findsOneWidget); + expect(find.textContaining("too long for a QR code"), findsOneWidget); + expect(find.textContaining("Copy or save it instead"), findsOneWidget); + expect(find.textContaining("share"), findsNothing); + }); +} diff --git a/test/pages/slatepack/slatepack_send_flow_test.dart b/test/pages/slatepack/slatepack_send_flow_test.dart new file mode 100644 index 0000000000..b5bbbb2a23 --- /dev/null +++ b/test/pages/slatepack/slatepack_send_flow_test.dart @@ -0,0 +1,358 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/transaction_note.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_dialog.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_send_flow.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; +import 'package:stackwallet/widgets/custom_loading_overlay.dart'; + +import '../../sample_data/theme_json.dart'; + +class _Info extends Fake implements WalletInfo { + _Info(this.coin); + + @override + final CryptoCurrency coin; +} + +class _Wallet extends EpiccashWallet { + _Wallet({ + this.createdAmount, + this.createdFee, + this.createError, + this.cancelResult = '', + this.gate, + }) : super(CryptoCurrencyNetwork.main); + + final int? createdAmount; + final int? createdFee; + final String? createError; + final String cancelResult; + final Completer? gate; + + int created = 0; + int refreshed = 0; + final cancelled = []; + + @override + String get walletId => 'wallet-1'; + + @override + WalletInfo get info => _Info(cryptoCurrency); + + @override + Future refresh({bool doScan = true}) async { + refreshed++; + } + + @override + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + String? message, + }) async { + created++; + await gate?.future; + if (createError != null) { + return SlatepackResult(success: false, error: createError); + } + return SlatepackResult( + success: true, + slatepack: '{}', + slateId: 'slate-1', + state: SlateState.s1, + amount: createdAmount == null ? null : _amount(createdAmount!), + fee: createdFee == null ? null : _amount(createdFee!), + ); + } + + @override + Future cancelPendingTransactionAndPost(String txSlateId) async { + cancelled.add(txSlateId); + return cancelResult; + } +} + +class _SynchronousMwcWallet extends MimblewimblecoinWallet { + _SynchronousMwcWallet({required this.onCreate, required this.gate}) + : super(CryptoCurrencyNetwork.main); + + final VoidCallback onCreate; + final Completer gate; + + @override + String get walletId => 'wallet-1'; + + @override + WalletInfo get info => _Info(cryptoCurrency); + + @override + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + String? message, + }) async { + onCreate(); + await gate.future; + return SlatepackResult( + success: true, + slatepack: 'BEGINSLATEPACK. test. ENDSLATEPACK.', + slateId: 'mwc-slate-1', + state: SlateState.s1, + amount: amount, + fee: _amount(1), + ); + } +} + +class _Notes extends Fake implements MainDB { + _Notes({this.fail = false}); + + final bool fail; + final notes = []; + + @override + Future putTransactionNote(TransactionNote note) async { + if (fail) throw StateError('note unavailable'); + notes.add(note); + } +} + +Amount _amount(int raw) => + Amount(rawValue: BigInt.from(raw), fractionDigits: 8); + +AmountFormatter _formatter(CryptoCurrency coin) => AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: coin, + maxDecimals: coin.fractionDigits, +); + +Future> _pumpSend( + WidgetTester tester, + SlatepackInterface wallet, { + MainDB? db, +}) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + + final succeeded = ValueNotifier(false); + addTearDown(succeeded.dispose); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final format = _formatter(wallet.cryptoCurrency).format; + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((_) => theme)), + ], + child: MaterialApp( + theme: ThemeData(extensions: [StackColors.fromStackColorTheme(theme)]), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + key: const Key('createSlate'), + onPressed: () { + unawaited( + SlatepackSendFlow.run( + context: context, + wallet: wallet, + amount: _amount(100), + message: 'on-chain note', + localNote: 'local note', + db: db ?? _Notes(), + format: format, + ).then((value) => succeeded.value = value), + ); + }, + child: const Text('Create'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.byKey(const Key('createSlate'))); + await tester.pump(); + return succeeded; +} + +void main() { + testWidgets('native creation starts after the progress route is visible', ( + tester, + ) async { + double? routeOpacity; + final gate = Completer(); + late final _SynchronousMwcWallet wallet; + wallet = _SynchronousMwcWallet( + gate: gate, + onCreate: () { + final overlays = find.byType(CustomLoadingOverlay).evaluate(); + routeOpacity = overlays.isEmpty + ? -1 + : ModalRoute.of(overlays.single)!.animation!.value; + }, + ); + + await _pumpSend(tester, wallet); + for (var i = 0; i < 10 && routeOpacity == null; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + expect(routeOpacity, 1); + expect(find.text('Building slatepack...'), findsOneWidget); + + gate.complete(); + await tester.pumpAndSettle(); + expect(find.byType(SlatepackDialog), findsOneWidget); + }); + + testWidgets( + 'the result shows the actual fee, saves its note and never refreshes', + (tester) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 3); + final notes = _Notes(); + final succeeded = await _pumpSend(tester, wallet, db: notes); + await tester.pumpAndSettle(); + + final format = _formatter(wallet.cryptoCurrency).format; + final dialog = find.byType(SlatepackDialog); + expect(dialog, findsOneWidget); + expect( + find.descendant(of: dialog, matching: find.text(format(_amount(3)))), + findsOneWidget, + ); + expect(notes.notes.single.txid, 'slate-1'); + expect(notes.notes.single.value, 'local note'); + expect(wallet.refreshed, 0); + + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + expect(succeeded.value, isTrue); + }, + ); + + testWidgets('a local-note failure does not hide the created slate', ( + tester, + ) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 3); + await _pumpSend(tester, wallet, db: _Notes(fail: true)); + await tester.pumpAndSettle(); + + expect(find.byType(SlatepackDialog), findsOneWidget); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + expect( + find.text( + 'The transaction was created successfully, but its local ' + 'note could not be saved.', + ), + findsOneWidget, + ); + }); + + testWidgets('a slate for another amount is cancelled and not shown', ( + tester, + ) async { + final wallet = _Wallet(createdAmount: 90, createdFee: 1); + final succeeded = await _pumpSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, ['slate-1']); + expect(find.byType(SlatepackDialog), findsNothing); + expect(find.text('Could not create the slate'), findsOneWidget); + expect(find.textContaining('instead of the requested'), findsOneWidget); + expect(succeeded.value, isFalse); + }); + + testWidgets('a failed cancellation is reported after an amount mismatch', ( + tester, + ) async { + final wallet = _Wallet( + createdAmount: 90, + createdFee: 1, + cancelResult: 'wallet busy', + ); + await _pumpSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, ['slate-1']); + expect(find.textContaining('wallet busy'), findsOneWidget); + expect(find.textContaining('Cancel it from its details'), findsOneWidget); + }); + + testWidgets('an incomplete native result is cancelled and not shown', ( + tester, + ) async { + final wallet = _Wallet(); + final succeeded = await _pumpSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, ['slate-1']); + expect(find.byType(SlatepackDialog), findsNothing); + expect(find.text('Could not create the slate'), findsOneWidget); + expect(find.textContaining('complete amount'), findsOneWidget); + expect(succeeded.value, isFalse); + }); + + testWidgets('a native error is shown without an exception prefix', ( + tester, + ) async { + final wallet = _Wallet(createError: 'Exception: wallet is locked'); + await _pumpSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(find.text('wallet is locked'), findsOneWidget); + expect(find.textContaining('Exception:'), findsNothing); + expect(wallet.cancelled, isEmpty); + }); + + testWidgets('a completed slate waits below an intervening lock route', ( + tester, + ) async { + final gate = Completer(); + final wallet = _Wallet(gate: gate, createdAmount: 100, createdFee: 1); + await _pumpSend(tester, wallet); + await tester.pump(const Duration(milliseconds: 500)); + + final root = Navigator.of( + tester.element(find.byType(CustomLoadingOverlay)), + rootNavigator: true, + ); + unawaited( + root.push( + MaterialPageRoute(builder: (_) => const Text('lock route')), + ), + ); + await tester.pumpAndSettle(); + + gate.complete(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('lock route'), findsOneWidget); + expect(find.byType(SlatepackDialog), findsNothing); + + root.pop(); + await tester.pumpAndSettle(); + expect(find.byType(SlatepackDialog), findsOneWidget); + }); +} diff --git a/test/pages/slatepack/slatepack_view_test.dart b/test/pages/slatepack/slatepack_view_test.dart new file mode 100644 index 0000000000..65b509e003 --- /dev/null +++ b/test/pages/slatepack/slatepack_view_test.dart @@ -0,0 +1,116 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:platform/platform.dart' as platform; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_view.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/widgets/desktop/primary_button.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +/// Epic Cash wallet whose inspection waits for [gate] and then reports a +/// finalized slate, which the import flow answers with a plain message. +class _SlowWallet extends EpiccashWallet { + _SlowWallet() : super(CryptoCurrencyNetwork.main); + + final gate = Completer(); + int inspections = 0; + + @override + Future inspectSlatepack(String armored) async { + inspections++; + await gate.future; + return const SlateInspection(state: SlateState.s3, slateId: "test-slate"); + } +} + +void main() { + testWidgets("Continue starts one import however often it is pressed", ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android'); + addTearDown(() => Util.layoutPlatform = previousPlatform); + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + // The phone layout closes the keyboard and waits a moment before it + // starts the import, which is when a second press can get in. + final previousWidth = Util.screenWidth; + Util.screenWidth = 400; + addTearDown(() => Util.screenWidth = previousWidth); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory("test/sample_data").absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final wallet = _SlowWallet(); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold(body: SlatepackView(walletId: "wallet-1")), + ), + ), + ); + await tester.pumpAndSettle(); + + expect( + find.descendant(of: find.byType(AppBar), matching: find.text("Slate")), + findsOneWidget, + ); + + PrimaryButton button() => + tester.widget(find.byType(PrimaryButton)); + + expect(button().enabled, isFalse); + await tester.enterText(find.byType(TextField), "{}"); + await tester.pump(); + expect(button().enabled, isTrue); + + // The second press lands before a frame has disabled the button, the + // third while the keyboard is still closing. + await tester.tap(find.text("Continue")); + await tester.tap(find.text("Continue"), warnIfMissed: false); + await tester.pump(const Duration(milliseconds: 20)); + expect(button().enabled, isFalse); + await tester.tap(find.text("Continue"), warnIfMissed: false); + + // Keyboard delay, loading overlay delay, then the inspection. + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.inspections, 1); + + wallet.gate.complete(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text("Already finalized"), findsOneWidget); + await tester.tap(find.text("OK")); + await tester.pump(const Duration(milliseconds: 400)); + + expect(wallet.inspections, 1); + // Nothing was acted on, so the text stays and Continue works again. + expect(find.text("{}"), findsOneWidget); + expect(button().enabled, isTrue); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/utilities/route_presentation_test.dart b/test/utilities/route_presentation_test.dart new file mode 100644 index 0000000000..7f06789d12 --- /dev/null +++ b/test/utilities/route_presentation_test.dart @@ -0,0 +1,89 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/utilities/route_presentation.dart'; + +void main() { + testWidgets('route presentation completes when the route is dismissed', ( + tester, + ) async { + late BuildContext context; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (builderContext) { + context = builderContext; + return const SizedBox(); + }, + ), + ), + ); + + final route = DialogRoute( + context: context, + builder: (_) => const Text('Progress'), + ); + final navigator = Navigator.of(context); + unawaited(navigator.push(route)); + await tester.pump(); + + final presented = waitForRoutePresentation(route); + navigator.removeRoute(route); + await tester.pumpAndSettle(); + + await expectLater(presented.timeout(const Duration(seconds: 1)), completes); + }); + + testWidgets('current-aware dismissal waits below a newer lock route', ( + tester, + ) async { + late BuildContext context; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (builderContext) { + context = builderContext; + return const Text('Home'); + }, + ), + ), + ); + + final navigator = Navigator.of(context); + final progress = CurrentAwareDialogRoute( + context: context, + barrierDismissible: false, + builder: (_) => const Text('Cancelling'), + ); + unawaited(navigator.push(progress)); + await tester.pumpAndSettle(); + unawaited( + navigator.push( + MaterialPageRoute(builder: (_) => const Text('Locked')), + ), + ); + await tester.pumpAndSettle(); + + var completed = false; + final dismissal = + dismissCurrentAwareDialogRoute( + navigator: navigator, + route: progress, + ).then((value) { + completed = true; + return value; + }); + await tester.pump(); + + expect(completed, isFalse); + expect(find.text('Locked'), findsOneWidget); + + navigator.pop(); + await tester.pumpAndSettle(); + + expect(await dismissal, isTrue); + expect(find.text('Cancelling'), findsNothing); + expect(find.text('Home'), findsOneWidget); + }); +} diff --git a/test/wallets/mimblewimble_slate_inspection_test.dart b/test/wallets/mimblewimble_slate_inspection_test.dart new file mode 100644 index 0000000000..e10418c0e0 --- /dev/null +++ b/test/wallets/mimblewimble_slate_inspection_test.dart @@ -0,0 +1,395 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; +import 'package:stackwallet/utilities/slatepack_terms.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; + +import '../support/isar_test_utils.dart'; + +Map _slate({required int signatures, int participants = 2}) { + return { + "id": "0436430c-2b02-624c-2032-570501212b00", + "amount": "150000000", + "fee": "8000000", + "ttl_cutoff_height": "123456", + "participant_data": [ + for (int i = 0; i < participants; i++) + {"id": "$i", "part_sig": i < signatures ? "sig$i" : null}, + ], + }; +} + +TransactionV2 _tx( + int n, + TransactionType type, + String slateId, { + bool isCancelled = false, + int? numberOfMessages, + String? onChainNote, +}) => TransactionV2( + walletId: "wallet", + blockHash: null, + hash: "hash$n", + txid: "txid$n", + timestamp: 0, + height: null, + inputs: const [], + outputs: const [], + version: 0, + type: type, + subType: TransactionSubType.none, + otherData: jsonEncode({ + "slateId": slateId, + if (numberOfMessages != null) "numberOfMessages": numberOfMessages, + if (onChainNote != null) "onChainNote": onChainNote, + TxV2OdKeys.overrideFee: Amount.zeroWith(fractionDigits: 9).toJsonString(), + if (isCancelled) TxV2OdKeys.isCancelled: true, + }), +); + +class _DecodeFailureWallet extends MimblewimblecoinWallet { + _DecodeFailureWallet(this.failure) : super(CryptoCurrencyNetwork.main); + + final SlatepackDecodeFailure failure; + + @override + Future decodeSlatepack(String slatepack) async => + SlatepackDecodeResult(success: false, failure: failure); +} + +class _LocalLookupWallet extends MimblewimblecoinWallet { + _LocalLookupWallet() : super(CryptoCurrencyNetwork.main) { + mainDB = MainDB.instance; + } + + @override + String get walletId => 'wallet'; +} + +class _PendingLookupWallet extends _LocalLookupWallet { + _PendingLookupWallet({this.failPersistence = false}); + + final bool failPersistence; + Map metadata = {}; + + @override + Map get slatepackTransactionMetadata => metadata; + + @override + Future updateSlatepackTransactionMetadata( + Map metadata, + ) async { + if (failPersistence) throw StateError('persistence unavailable'); + this.metadata = metadata; + } + + Future remember(SlatepackResult result) => + rememberPendingSlateSend(result); + + Future rememberCancelled(String slateId) => + rememberPendingSlateCancelled(slateId); +} + +void main() { + setUpAll(initializeTestIsar); + + test("local transaction for a slate", () { + const id = "0436430c-2b02-624c-2032-570501212b00"; + final received = _tx(1, TransactionType.incoming, id); + final sent = _tx(2, TransactionType.outgoing, id); + // Contains the id without being the transaction for it. + final other = _tx(3, TransactionType.outgoing, "$id-other"); + + expect(localSlateTransaction([other], id), isNull); + expect(localSlateTransaction([other, received], id), received); + // A send to self holds both sides, and the send is what gets finalized. + expect(localSlateTransaction([received, sent], id), sent); + expect(localSlateTransaction([sent, received], id), sent); + + final cancelled = _tx(4, TransactionType.outgoing, id, isCancelled: true); + expect(cancelled.isCancelled, isTrue); + expect(localSlateTransaction([received, cancelled], id), cancelled); + + // Received again after a cancelled receive: the live record wins + // whichever order the two come in. + final cancelledReceive = _tx( + 5, + TransactionType.incoming, + id, + isCancelled: true, + ); + expect(localSlateTransaction([cancelledReceive, received], id), received); + expect(localSlateTransaction([received, cancelledReceive], id), received); + expect(localSlateTransaction([cancelledReceive], id), cancelledReceive); + }); + + SlateInspection inspect( + Map json, { + String? sender, + String? recipient, + }) => inspectSlateJson( + json, + fractionDigits: 8, + senderAddress: sender, + recipientAddress: recipient, + ); + + test("state from partial signatures", () { + expect(inspect(_slate(signatures: 0)).state, SlateState.s1); + expect(inspect(_slate(signatures: 1)).state, SlateState.s2); + expect(inspect(_slate(signatures: 2)).state, SlateState.s3); + }); + + test("falls back to sta, then to addresses", () { + expect(inspect({"id": "a", "sta": "I1"}).state, SlateState.i1); + expect( + inspect({"id": "a"}, sender: "s", recipient: "r").state, + SlateState.s2, + ); + expect(inspect({"id": "a"}, sender: "s").state, SlateState.s1); + expect(inspect({"id": "a"}).state, SlateState.unknown); + }); + + test("explicit invoice state overrides standard-send signatures", () { + final invoice = _slate(signatures: 0)..["sta"] = "I1"; + + expect(inspect(invoice).state, SlateState.i1); + }); + + test("id, amount, fee and ttl", () { + final i = inspect(_slate(signatures: 0)); + expect(i.slateId, "0436430c-2b02-624c-2032-570501212b00"); + expect(i.amount!.raw, BigInt.from(150000000)); + expect(i.fee!.raw, BigInt.from(8000000)); + expect(i.ttlCutoffHeight, 123456); + expect(inspect({"id": "a", "amt": 5}).amount!.raw, BigInt.from(5)); + expect(inspect({"id": "a"}).amount, isNull); + }); + + test("zero amount and fee on a response slate are unknown", () { + final json = _slate(signatures: 1) + ..["amount"] = "0" + ..["fee"] = "0"; + + final response = inspect(json); + + expect(response.state, SlateState.s2); + expect(response.amount, isNull); + expect(response.fee, isNull); + }); + + test('decode failures explain likely slatepack problems', () async { + final wallet = _DecodeFailureWallet(SlatepackDecodeFailure.invalidInput); + + await expectLater( + wallet.inspectSlatepack('BEGINSLATEPACK. broken. ENDSLATEPACK.'), + throwsA( + isA() + .having( + (error) => error.toString(), + 'message', + contains('damaged, incomplete, or encrypted for another wallet'), + ) + .having( + (error) => error.toString(), + 'native error hidden', + isNot(contains('FormatException')), + ), + ), + ); + }); + + test('wallet-open failures are not blamed on the slatepack', () async { + final wallet = _DecodeFailureWallet( + SlatepackDecodeFailure.walletUnavailable, + ); + + await expectLater( + wallet.inspectSlatepack('BEGINSLATEPACK. valid. ENDSLATEPACK.'), + throwsA( + isA() + .having( + (error) => error.toString(), + 'wallet error', + contains('wallet could not be opened. Try again.'), + ) + .having( + (error) => error.toString(), + 'does not blame input', + isNot(contains('damaged')), + ) + .having( + (error) => error.toString(), + 'does not suggest a nonexistent unlock action', + isNot(contains('Unlock')), + ), + ), + ); + }); + + test('Epic decode errors do not mention unsupported encryption', () async { + final wallet = EpiccashWallet(CryptoCurrencyNetwork.main); + + await expectLater( + wallet.inspectSlatepack('not json'), + throwsA( + isA() + .having( + (error) => error.toString(), + 'input explanation', + contains('damaged or incomplete'), + ) + .having( + (error) => error.toString(), + 'encryption omitted', + isNot(contains('encrypted')), + ), + ), + ); + }); + + test('a cache miss never waits for native wallet history', () async { + final directory = await Directory.systemTemp.createTemp( + 'mimblewimble-local-history-', + ); + final isar = await Isar.open( + [TransactionV2Schema, WalletInfoSchema], + directory: directory.path, + name: 'mimblewimble-local-history', + inspector: false, + ); + addTearDown(() async { + await isar.close(); + await directory.delete(recursive: true); + }); + await MainDB.instance.initMainDB(mock: isar); + await MainDB.instance.putWalletInfo( + WalletInfo( + walletId: 'wallet', + name: 'fixture', + mainAddressType: AddressType.mimbleWimble, + coinName: 'mimblewimblecoin', + ), + ); + + final wallet = _PendingLookupWallet(); + final result = await wallet.localTxForSlate('slate'); + + expect(result, isNull); + expect( + await MainDB.instance.isar.transactionV2s.count(), + 0, + reason: 'reading an incoming S1 must not trigger a native history load', + ); + + await wallet.remember( + SlatepackResult( + success: true, + slatepack: 'slate', + slateId: 'slate', + state: SlateState.s1, + amount: Amount(rawValue: BigInt.from(123), fractionDigits: 8), + fee: Amount(rawValue: BigInt.from(4), fractionDigits: 8), + ), + ); + final pending = await wallet.localTxForSlate('slate'); + expect(pending?.isSend, isTrue); + expect(pending?.amount.raw, BigInt.from(123)); + expect(pending?.fee.raw, BigInt.from(4)); + expect(pending?.isCancelled, isFalse); + + await wallet.rememberCancelled('slate'); + expect((await wallet.localTxForSlate('slate'))?.isCancelled, isTrue); + }); + + test("Epic and MWC capabilities", () { + final epic = EpiccashWallet(CryptoCurrencyNetwork.main); + final mwc = MimblewimblecoinWallet(CryptoCurrencyNetwork.main); + + expect(epic.supportedMethods.first, SlatepackMethod.relay); + expect(mwc.supportedMethods.first, SlatepackMethod.slatepack); + for (final SlatepackInterface w in [epic, mwc]) { + expect(w.supportedMethods, contains(SlatepackMethod.slatepack)); + expect(w.supportsOnChainNote, isTrue); + } + expect(epic.slatepackTerms, SlatepackTerms.slate); + expect(mwc.slatepackTerms, SlatepackTerms.slatepack); + expect(epic.supportsSlatepackEncryption, isFalse); + expect(mwc.supportsSlatepackEncryption, isTrue); + expect(epic.hasSlatepackMethodToggle, isTrue); + expect(mwc.hasSlatepackMethodToggle, isTrue); + }); + + test('pending send metadata is immediately usable for ownership checks', () { + final pending = pendingSlateSendMatching( + { + 'slate': { + 'amount': '123', + 'fee': '4', + 'isSend': true, + 'isCancelled': false, + }, + }, + 'slate', + fractionDigits: 8, + ); + + expect(pending?.amount.raw, BigInt.from(123)); + expect(pending?.fee.raw, BigInt.from(4)); + expect(pending?.isSend, isTrue); + expect(pending?.isCancelled, isFalse); + expect( + pendingSlateSendMatching( + { + 'legacy': {'commitId': 'commit'}, + }, + 'legacy', + fractionDigits: 8, + ), + isNull, + ); + }); + + test('Epic treats a successful legacy finalize as broadcast', () { + expect(epicFinalizeBroadcastResult(null), isTrue); + expect(epicFinalizeBroadcastResult(true), isTrue); + expect(epicFinalizeBroadcastResult(false), isFalse); + }); + + test( + 'ownership remains local when durable metadata cannot be written', + () async { + final wallet = _PendingLookupWallet(failPersistence: true); + await wallet.remember( + SlatepackResult( + success: true, + slatepack: 'slate', + slateId: 'volatile-slate', + state: SlateState.s1, + amount: Amount(rawValue: BigInt.from(123), fractionDigits: 8), + fee: Amount(rawValue: BigInt.from(4), fractionDigits: 8), + ), + ); + + expect((await wallet.localTxForSlate('volatile-slate'))?.isSend, isTrue); + await wallet.rememberCancelled('volatile-slate'); + expect( + (await wallet.localTxForSlate('volatile-slate'))?.isCancelled, + isTrue, + ); + }, + ); +} diff --git a/test/widgets/slatepack_method_toggle_test.dart b/test/widgets/slatepack_method_toggle_test.dart new file mode 100644 index 0000000000..efb77d5d62 --- /dev/null +++ b/test/widgets/slatepack_method_toggle_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart'; +import 'package:stackwallet/widgets/slatepack_method_toggle.dart'; +import 'package:stackwallet/widgets/toggle.dart'; + +import '../sample_data/theme_json.dart'; +import '../wallets/support/xelis_test_fakes.dart'; + +class _SlatepackOnlyWallet extends MimblewimblecoinWallet { + _SlatepackOnlyWallet() : super(CryptoCurrencyNetwork.main); + + @override + List get supportedMethods => const [ + SlatepackMethod.slatepack, + ]; +} + +void main() { + test('a slatepack-only wallet reports no method toggle', () { + expect(_SlatepackOnlyWallet().hasSlatepackMethodToggle, isFalse); + }); + + testWidgets('a slatepack-only wallet has no method toggle', (tester) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue( + ConfirmationWallets(_SlatepackOnlyWallet()), + ), + ], + child: const MaterialApp( + home: SlatepackMethodToggle(walletId: 'wallet'), + ), + ), + ); + + expect(find.byType(Toggle), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('Epic labels its manual method Slate', (tester) async { + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue( + ConfirmationWallets(EpiccashWallet(CryptoCurrencyNetwork.main)), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const SlatepackMethodToggle(walletId: 'wallet'), + ), + ), + ); + + expect(find.text('Slate'), findsOneWidget); + expect(find.text('Slatepack'), findsNothing); + }); +} diff --git a/test/widgets/wallet_navigation_bar_item_test.dart b/test/widgets/wallet_navigation_bar_item_test.dart new file mode 100644 index 0000000000..f65497d301 --- /dev/null +++ b/test/widgets/wallet_navigation_bar_item_test.dart @@ -0,0 +1,54 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/widgets/wallet_navigation_bar/components/wallet_navigation_bar_item.dart'; + +import '../sample_data/theme_json.dart'; + +void main() { + testWidgets('a Slatepack label fits a 57.6 dp navigation item', ( + tester, + ) async { + tester.view.physicalSize = const Size(360, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: Align( + alignment: Alignment.bottomCenter, + child: SizedBox( + width: 57.6, + height: 61, + child: WalletNavigationBarItem( + data: WalletNavigationBarItemData( + icon: const Icon(Icons.description, size: 20), + label: 'Slatepack', + overrideText: const FittedBox( + fit: BoxFit.scaleDown, + child: Text('Slatepack', maxLines: 1, softWrap: false), + ), + onTap: () {}, + ), + disableDuration: Duration.zero, + ), + ), + ), + ), + ), + ), + ); + + expect(find.text('Slatepack'), findsOneWidget); + expect(tester.takeException(), isNull); + }); +} diff --git a/tool/wl_templates/EPIC_libepiccash_interface_impl.template.dart b/tool/wl_templates/EPIC_libepiccash_interface_impl.template.dart index 415c447976..f7705af11e 100644 --- a/tool/wl_templates/EPIC_libepiccash_interface_impl.template.dart +++ b/tool/wl_templates/EPIC_libepiccash_interface_impl.template.dart @@ -39,12 +39,23 @@ final class _LibEpicCashInterfaceImpl extends LibEpicCashInterface { } @override - Future<({String slateId, String commitId, String slateJson})> txFinalize({ - required DynamicObject wallet, - required String slateJson, - }) async { - return (await wallet.get().txFinalize(slateJson: slateJson)) - .toRecord(); + Future<({String slateId, String commitId, String slateJson, bool? posted})> + txFinalize({required DynamicObject wallet, required String slateJson}) async { + final dynamic finalized = await wallet.get().txFinalize( + slateJson: slateJson, + ); + bool? posted; + try { + posted = finalized.posted as bool?; + } on NoSuchMethodError { + // Older plugin revisions do not report whether the node accepted it. + } + return ( + slateId: finalized.slateId as String, + commitId: finalized.commitId as String, + slateJson: finalized.slateJson as String, + posted: posted, + ); } @override diff --git a/tool/wl_templates/MWC_libmwc_interface_impl.template.dart b/tool/wl_templates/MWC_libmwc_interface_impl.template.dart index 01dc5c123a..2ba7a6655f 100644 --- a/tool/wl_templates/MWC_libmwc_interface_impl.template.dart +++ b/tool/wl_templates/MWC_libmwc_interface_impl.template.dart @@ -273,14 +273,25 @@ final class _LibMwcInterfaceImpl extends LibMwcInterface { } @override - Future<({String commitId, String slateId})> txFinalize({ + Future<({String commitId, String slateId, bool? posted})> txFinalize({ required String wallet, required String slateJson, - }) { - return mimblewimblecoin.Libmwc.txFinalize( + }) async { + final dynamic finalized = await mimblewimblecoin.Libmwc.txFinalize( wallet: wallet, slateJson: slateJson, ); + bool? posted; + try { + posted = finalized.posted as bool?; + } on NoSuchMethodError { + // Older plugin revisions do not report whether the node accepted it. + } + return ( + commitId: finalized.commitId as String, + slateId: finalized.slateId as String, + posted: posted, + ); } @override From 791288f0dcd35348bea14f4e029c94cf112b2ad2 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Mon, 30 Nov 2026 10:10:19 -0600 Subject: [PATCH 2/3] fix(slatepack): address PR #1507 adversarial review findings --- lib/models/slatepack_models.dart | 22 +- lib/pages/receive_view/receive_view.dart | 31 +- .../sub_widgets/slatepack_entry_dialog.dart | 44 ++- lib/pages/send_view/send_view.dart | 84 +++-- .../slatepack_cancel_transaction_dialog.dart | 13 +- lib/pages/slatepack/slatepack_dialog.dart | 149 +++++--- .../slatepack/slatepack_import_flow.dart | 338 +++++++++-------- .../slatepack/slatepack_input_field.dart | 80 +++- lib/pages/slatepack/slatepack_popup.dart | 92 ++++- lib/pages/slatepack/slatepack_qr.dart | 21 +- lib/pages/slatepack/slatepack_send_flow.dart | 222 ++++++----- .../slatepack/slatepack_summary_dialog.dart | 30 +- lib/pages/slatepack/slatepack_view.dart | 168 ++++++--- .../transaction_details_view.dart | 155 ++++---- .../tx_v2/transaction_v2_details_view.dart | 146 +++---- lib/pages/wallet_view/wallet_view.dart | 29 +- .../sub_widgets/desktop_receive.dart | 74 +--- .../wallet_view/sub_widgets/desktop_send.dart | 56 +-- .../ui/preview_tx_button_state_provider.dart | 17 +- lib/route_generator.dart | 2 +- lib/utilities/enums/slatepack_method.dart | 12 +- lib/utilities/route_presentation.dart | 131 ++++++- lib/utilities/slatepack_text.dart | 12 +- .../crypto_currency/coins/epiccash.dart | 5 +- lib/wallets/wallet/impl/epiccash_wallet.dart | 39 +- .../wallet/impl/mimblewimblecoin_wallet.dart | 157 +++++--- .../slatepack_interface.dart | 357 ++++++++++++------ lib/widgets/slatepack_method_toggle.dart | 14 +- .../interfaces/libepiccash_interface.dart | 6 +- lib/wl_gen/interfaces/libmwc_interface.dart | 2 +- test/pages/send_view/send_views_test.dart | 5 +- .../slatepack/slatepack_dialog_test.dart | 303 ++++++++++++++- .../slatepack/slatepack_import_flow_test.dart | 186 ++++++--- .../slatepack/slatepack_input_field_test.dart | 124 ++++++ .../slatepack/slatepack_send_flow_test.dart | 127 ++++++- test/pages/slatepack/slatepack_view_test.dart | 110 +++++- test/utilities/route_presentation_test.dart | 257 +++++++++++++ .../mimblewimble_slate_inspection_test.dart | 246 ++++++++++-- .../widgets/slatepack_method_toggle_test.dart | 77 ++++ .../wallet_navigation_bar_item_test.dart | 21 +- ...C_libepiccash_interface_impl.template.dart | 23 +- .../MWC_libmwc_interface_impl.template.dart | 17 +- 42 files changed, 2931 insertions(+), 1073 deletions(-) diff --git a/lib/models/slatepack_models.dart b/lib/models/slatepack_models.dart index c326908bba..a0f42dd685 100644 --- a/lib/models/slatepack_models.dart +++ b/lib/models/slatepack_models.dart @@ -15,8 +15,6 @@ enum SlateState { /// "S1", "I2" and so on, as libwallet names them. final String code; - bool get isInvoice => this == i1 || this == i2 || this == i3; - static SlateState fromCode(String? code) { final upper = code?.trim().toUpperCase(); return values.firstWhere((e) => e.code == upper, orElse: () => unknown); @@ -28,7 +26,7 @@ class SlateInspection { const SlateInspection({ required this.state, required this.slateId, - this.slateJson, + required this.slateJson, this.amount, this.fee, this.senderAddress, @@ -42,10 +40,10 @@ class SlateInspection { /// Decoded slate passed to receive/finalize so an armored Slatepack is not /// decoded over FFI a second time. - final String? slateJson; + final String slateJson; - /// Null when the slate does not carry it. Grin's S2 and I2 decode with 0; - /// look the amount up with localTxForSlate instead. + /// Null when the slate does not carry it. MWC compact S2 slates decode with + /// 0; look the amount up with localTxForSlate instead. final Amount? amount; final Amount? fee; final String? senderAddress; @@ -148,20 +146,17 @@ class FinalizeResult { final String? slateId; final String? commitId; - /// Whether the finalized transaction reached the node. Null means the - /// installed native plugin predates explicit broadcast status reporting. + /// Whether the finalized transaction reached the node. True when broadcast + /// is confirmed (Epic); null when the native plugin does not reliably report + /// broadcast status (MWC). final bool? posted; - /// Null for Epic Cash and MWC. - final String? kernelExcess; - FinalizeResult({ required this.success, this.error, this.slateId, this.commitId, this.posted, - this.kernelExcess, }); @override @@ -171,8 +166,7 @@ class FinalizeResult { "error: $error, " "slateId: $slateId, " "commitId: $commitId, " - "posted: $posted, " - "kernelExcess: $kernelExcess" + "posted: $posted" ")"; } } diff --git a/lib/pages/receive_view/receive_view.dart b/lib/pages/receive_view/receive_view.dart index 51875505eb..40835684a3 100644 --- a/lib/pages/receive_view/receive_view.dart +++ b/lib/pages/receive_view/receive_view.dart @@ -82,6 +82,7 @@ class _ReceiveViewState extends ConsumerState { late final bool _showMultiType; late bool supportsMweb; SlatepackTerms? _slatepackTerms; + bool _importingSlatepack = false; int _currentIndex = 0; @@ -90,16 +91,28 @@ class _ReceiveViewState extends ConsumerState { final Map> _addressSubMap = {}; Future _importSlatepack() async { - final wallet = ref.read(pWallets).getWallet(walletId) as SlatepackInterface; - - final text = await showSlatepackEntryDialog( - context: context, - terms: wallet.slatepackTerms, - clipboard: widget.clipboard, - ); - if (text == null || text.trim().isEmpty || !mounted) return; + if (_importingSlatepack) return; + _importingSlatepack = true; + try { + final wallet = + ref.read(pWallets).getWallet(walletId) as SlatepackInterface; + + final text = await showSlatepackEntryDialog( + context: context, + terms: wallet.slatepackTerms, + clipboard: widget.clipboard, + ); + if (text == null || text.trim().isEmpty || !mounted) return; + FocusScope.of(context).unfocus(); - await SlatepackImportFlow.run(context: context, wallet: wallet, text: text); + await SlatepackImportFlow.run( + context: context, + wallet: wallet, + text: text, + ); + } finally { + _importingSlatepack = false; + } } Future generateNewAddress() async { diff --git a/lib/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart b/lib/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart index e4eb92809b..46a79ea9f9 100644 --- a/lib/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart +++ b/lib/pages/receive_view/sub_widgets/slatepack_entry_dialog.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; -import '../../../themes/stack_colors.dart'; import '../../../utilities/clipboard_interface.dart'; import '../../../utilities/slatepack_terms.dart'; import '../../../utilities/text_styles.dart'; @@ -35,12 +34,35 @@ class SlatepackEntryDialog extends StatefulWidget { class _SlatepackEntryDialogState extends State { final _controller = TextEditingController(); + final _focusNode = FocusNode(); + bool _submitting = false; bool get _hasText => _controller.text.trim().isNotEmpty; + Future _submit() async { + if (_submitting) return; + setState(() => _submitting = true); + var popped = false; + try { + if (_focusNode.hasFocus) { + _focusNode.unfocus(); + await Future.delayed(const Duration(milliseconds: 75)); + } + if (mounted && (ModalRoute.of(context)?.isCurrent ?? false)) { + popped = true; + Navigator.of(context).pop(_controller.text.trim()); + } + } finally { + if (!popped && mounted) { + setState(() => _submitting = false); + } + } + } + @override void dispose() { _controller.dispose(); + _focusNode.dispose(); super.dispose(); } @@ -48,19 +70,17 @@ class _SlatepackEntryDialogState extends State { Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( "Import ${widget.terms.title}", - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of(context) - .extension()! - .textFieldActiveSearchIconRight, - ), + style: STextStyles.pageTitleH2(context), textAlign: TextAlign.left, ), const SizedBox(height: 12), SlatepackInputField( controller: _controller, + focusNode: _focusNode, hint: "Enter ${widget.terms.payload}", terms: widget.terms, clipboard: widget.clipboard, @@ -69,13 +89,15 @@ class _SlatepackEntryDialogState extends State { const SizedBox(height: 16), PrimaryButton( label: "Import", - enabled: _hasText, - onPressed: _hasText - ? () => Navigator.of(context).pop(_controller.text.trim()) - : null, + enabled: _hasText && !_submitting, + onPressed: _hasText && !_submitting ? _submit : null, ), const SizedBox(height: 16), - SecondaryButton(label: "Cancel", onPressed: Navigator.of(context).pop), + SecondaryButton( + label: "Cancel", + enabled: !_submitting, + onPressed: _submitting ? null : Navigator.of(context).pop, + ), ], ); } diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index 3c40737955..ffdc96a349 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -136,6 +136,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { late final bool isFiro; late final bool isEth; SlatepackInterface? _slatepackWallet; + bool _creatingSlatepack = false; Amount? _cachedAmountToSend; String? _addressValue; @@ -749,18 +750,51 @@ class _SendViewState extends ConsumerState with SendFeeForm { } Future _previewTransaction() async { - // wait for keyboard to disappear - FocusScope.of(context).unfocus(); - await Future.delayed(const Duration(milliseconds: 100)); - if (!mounted) return; + if (_creatingSlatepack) return; + var lockedSlatepack = false; + final earlyWallet = ref.read(pWallets).getWallet(walletId); + final earlySlatepack = + earlyWallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); + if (earlySlatepack) { + _creatingSlatepack = true; + lockedSlatepack = true; + } + try { + // wait for keyboard to disappear + FocusScope.of(context).unfocus(); + await Future.delayed(const Duration(milliseconds: 100)); + if (!mounted) return; + final wallet = ref.read(pWallets).getWallet(walletId); + final isSlatepackSend = + wallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); + if (isSlatepackSend) { + if (ModalRoute.of(context)?.isCurrent != true) return; + if (!lockedSlatepack && _creatingSlatepack) return; + _creatingSlatepack = true; + lockedSlatepack = true; + final Amount? amount = ref.read(pSendAmount); + if (amount == null || amount <= Amount.zero) return; + final created = await SlatepackSendFlow.run( + context: context, + wallet: wallet, + amount: amount, + message: onChainNoteController.text, + localNote: noteController.text, + db: ref.read(mainDBProvider), + format: ref.read(pAmountFormatter(wallet.cryptoCurrency)).format, + ); + if (created && mounted) clearSendForm(); + return; + } + } finally { + if (lockedSlatepack) _creatingSlatepack = false; + } + final wallet = ref.read(pWallets).getWallet(walletId); - final isSlatepackSend = - wallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); String? openAlias; String? resolvedAddress; final application = coin.openAliasApplication; if (application != null && - !isSlatepackSend && !coin.validateAddress(_address ?? "") && isOpenAlias(_address ?? "")) { var resolved = _openAlias; @@ -777,20 +811,6 @@ class _SendViewState extends ConsumerState with SendFeeForm { late final recipientAddress = resolvedAddress ?? _address!; final Amount amount = ref.read(pSendAmount)!; - if (isSlatepackSend) { - final created = await SlatepackSendFlow.run( - context: context, - wallet: wallet, - amount: amount, - message: onChainNoteController.text, - localNote: noteController.text, - db: ref.read(mainDBProvider), - format: ref.read(pAmountFormatter(wallet.cryptoCurrency)).format, - ); - if (created && mounted) clearSendForm(); - return; - } - final Amount availableBalance; if (isFiro || ref.read(pWalletInfo(walletId)).isMwebEnabled) { switch (ref.read(publicPrivateBalanceStateProvider.state).state) { @@ -1265,9 +1285,6 @@ class _SendViewState extends ConsumerState with SendFeeForm { onChainNoteController = TextEditingController(); feeController = TextEditingController(); memoController = TextEditingController(); - if (coin is Epiccash) { - sendToController.addListener(_formatEpicCashAddress); - } onCryptoAmountChanged = _cryptoAmountChanged; cryptoAmountController.addListener(onCryptoAmountChanged); @@ -1298,6 +1315,10 @@ class _SendViewState extends ConsumerState with SendFeeForm { }); } + if (coin is Epiccash) { + sendToController.addListener(_formatEpicCashAddress); + } + if (isPaynymSend) { sendToController.text = widget.accountLite!.nymName; noteController.text = "PayNym send"; @@ -1419,10 +1440,8 @@ class _SendViewState extends ConsumerState with SendFeeForm { ); } - final isSlatepackMode = ref.watch(pIsSlatepack(widget.walletId)); - final wallet = ref.watch( - pWallets.select((value) => value.getWallet(walletId)), - ); + final isSlatepackMode = + _slatepackWallet != null && ref.watch(pIsSlatepack(widget.walletId)); // Preserve the existing mobile UI: Epic exposes its on-chain note field; // MWC only exposed that field on desktop before this refactor. final showOnChainNote = coin is Epiccash; @@ -1715,9 +1734,7 @@ class _SendViewState extends ConsumerState with SendFeeForm { style: STextStyles.field(context), decoration: standardInputDecoration( - isSlatepackMode - ? "Enter ${coin.ticker} address (optional)" - : "Enter ${coin.ticker} address", + "Enter ${coin.ticker} address", _addressFocusNode, context, ).copyWith( @@ -2651,9 +2668,8 @@ class _SendViewState extends ConsumerState with SendFeeForm { context, ), child: Text( - isSlatepackMode && - wallet is SlatepackInterface - ? "Create ${wallet.slatepackTerms.noun}" + isSlatepackMode && _slatepackWallet != null + ? "Create ${_slatepackWallet!.slatepackTerms.noun}" : "Preview", style: STextStyles.button(context), ), diff --git a/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart index ef8a62ccaa..849d7c8b9a 100644 --- a/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart +++ b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart @@ -11,23 +11,26 @@ bool canCancelSlateTransaction({ required String? slateId, required bool isCancelled, required int confirmations, -}) => slateId?.isNotEmpty == true && !isCancelled && confirmations < 1; +}) => + (slateId?.trim().isNotEmpty ?? false) && !isCancelled && confirmations < 1; class SlatepackCancelTransactionDialog extends StatelessWidget { const SlatepackCancelTransactionDialog({super.key}); @override Widget build(BuildContext context) { + final isDesktop = Util.isDesktop; + return StackDialogBase( - width: Util.isDesktop ? 400 : null, - padding: EdgeInsets.all(Util.isDesktop ? 24 : 16), + width: isDesktop ? 400 : null, + padding: EdgeInsets.all(isDesktop ? 24 : 16), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( "Cancel this transaction?", - style: Util.isDesktop + style: isDesktop ? STextStyles.desktopH3(context) : STextStyles.pageTitleH2(context), ), @@ -42,11 +45,13 @@ class SlatepackCancelTransactionDialog extends StatelessWidget { const SizedBox(height: 20), SecondaryButton( label: "Go back", + buttonHeight: isDesktop ? ButtonHeight.l : null, onPressed: () => Navigator.of(context).pop(false), ), const SizedBox(height: 8), PrimaryButton( label: "Cancel it", + buttonHeight: isDesktop ? ButtonHeight.l : null, onPressed: () => Navigator.of(context).pop(true), ), ], diff --git a/lib/pages/slatepack/slatepack_dialog.dart b/lib/pages/slatepack/slatepack_dialog.dart index fc74f91a6f..9a836e0d22 100644 --- a/lib/pages/slatepack/slatepack_dialog.dart +++ b/lib/pages/slatepack/slatepack_dialog.dart @@ -11,10 +11,12 @@ import '../../notifications/show_flush_bar.dart'; import '../../themes/stack_colors.dart'; import '../../utilities/assets.dart'; import '../../utilities/clipboard_interface.dart'; +import '../../utilities/exception_message.dart'; import '../../utilities/logger.dart'; import '../../utilities/slatepack_terms.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; +import '../../widgets/conditional_parent.dart'; import '../../widgets/desktop/primary_button.dart'; import '../../widgets/desktop/secondary_button.dart'; import '../../widgets/detail_item.dart'; @@ -40,10 +42,12 @@ Future showSlatepackDialog({ required bool supportsEncryption, String? formattedAmount, String? formattedFee, + bool waitForDismissalAnimation = false, }) { return showSlatepackPopup( context: context, barrierDismissible: false, + waitForDismissalAnimation: waitForDismissalAnimation, child: SlatepackDialog.fromResult( terms: terms, result: result, @@ -54,9 +58,9 @@ Future showSlatepackDialog({ ); } -/// One dialog for every slatepack the wallet hands out (S1, S2, I1, I2): +/// One dialog for every slatepack the wallet hands out (S1, S2): /// copy, share, save to file, and a QR code when the text is short enough. -class SlatepackDialog extends StatelessWidget { +class SlatepackDialog extends StatefulWidget { const SlatepackDialog({ super.key, required this.terms, @@ -78,18 +82,24 @@ class SlatepackDialog extends StatelessWidget { bool showEncryptionStatus = true, String? formattedAmount, String? formattedFee, - }) => SlatepackDialog( - key: key, - terms: terms, - slatepack: result.slatepack!, - state: result.state, - slateId: result.slateId, - isEncrypted: result.wasEncrypted ?? false, - showEncryptionStatus: showEncryptionStatus, - formattedAmount: formattedAmount, - formattedFee: formattedFee, - clipboard: clipboard, - ); + }) { + final slatepack = ArgumentError.checkNotNull( + result.slatepack, + 'result.slatepack', + ); + return SlatepackDialog( + key: key, + terms: terms, + slatepack: slatepack, + state: result.state, + slateId: result.slateId, + isEncrypted: result.wasEncrypted ?? false, + showEncryptionStatus: showEncryptionStatus, + formattedAmount: formattedAmount, + formattedFee: formattedFee, + clipboard: clipboard, + ); + } final SlatepackTerms terms; final String slatepack; @@ -104,8 +114,6 @@ class SlatepackDialog extends StatelessWidget { String get title => switch (state) { SlateState.s1 => "Send ${terms.title}", SlateState.s2 => "Response ${terms.title}", - SlateState.i1 => "Invoice ${terms.title}", - SlateState.i2 => "Payment ${terms.title}", _ => terms.title, }; @@ -121,13 +129,6 @@ class SlatepackDialog extends StatelessWidget { SlateState.s2 => "Return this ${terms.noun} to the sender. They finalize and broadcast " "the transaction.", - SlateState.i1 => - "1. Share this invoice with the payer\n" - "2. Wait for them to return the payment ${terms.noun}\n" - "3. Import it on the ${terms.title} screen to finalize the payment", - SlateState.i2 => - "Return this ${terms.noun} to the payee. They finalize and broadcast " - "the payment. The funds stay locked until then.", _ => "Pass this ${terms.noun} to the other party.", }; @@ -138,12 +139,19 @@ class SlatepackDialog extends StatelessWidget { return "$id$suffix.${terms.fileExtension}"; } + @override + State createState() => _SlatepackDialogState(); +} + +class _SlatepackDialogState extends State { + bool _busy = false; + Future _copy(BuildContext context) async { - await clipboard.setData(ClipboardData(text: slatepack)); + await widget.clipboard.setData(ClipboardData(text: widget.slatepack)); if (context.mounted) { await showFloatingFlushBar( type: FlushBarType.info, - message: "${terms.title} copied to clipboard", + message: "${widget.terms.title} copied to clipboard", iconAsset: Assets.svg.copy, context: context, ); @@ -153,6 +161,8 @@ class SlatepackDialog extends StatelessWidget { /// [context] is the Share button's. An iPad anchors the share sheet to the /// button's rect and will not open it without one. Future _share(BuildContext context) async { + if (_busy) return; + _busy = true; final box = context.findRenderObject(); final origin = box is RenderBox && box.hasSize ? box.localToGlobal(Offset.zero) & box.size @@ -160,26 +170,39 @@ class SlatepackDialog extends StatelessWidget { try { await SharePlus.instance.share( ShareParams( - text: slatepack, - subject: title, + text: widget.slatepack, + subject: widget.title, sharePositionOrigin: origin, ), ); } catch (e, s) { Logging.instance.e( - "Sharing ${terms.noun} failed", + "Sharing ${widget.terms.noun} failed", error: e, stackTrace: s, ); + if (context.mounted) { + await showFloatingFlushBar( + type: FlushBarType.warning, + message: + "Could not share the ${widget.terms.noun}: " + "${stripExceptionPrefixes(e)}", + context: context, + ); + } + } finally { + _busy = false; } } Future _save(BuildContext context) async { + if (_busy) return; + _busy = true; try { final path = await FilePicker.platform.saveFile( - dialogTitle: "Save ${terms.noun}", - fileName: fileName, - bytes: Uint8List.fromList(utf8.encode(slatepack)), + dialogTitle: "Save ${widget.terms.noun}", + fileName: widget.fileName, + bytes: Uint8List.fromList(utf8.encode(widget.slatepack)), lockParentWindow: true, ); if (path != null && context.mounted) { @@ -191,17 +214,21 @@ class SlatepackDialog extends StatelessWidget { } } catch (e, s) { Logging.instance.e( - "Saving ${terms.noun} failed", + "Saving ${widget.terms.noun} failed", error: e, stackTrace: s, ); if (context.mounted) { await showFloatingFlushBar( type: FlushBarType.warning, - message: "Could not save the ${terms.noun}: $e", + message: + "Could not save the ${widget.terms.noun}: " + "${stripExceptionPrefixes(e)}", context: context, ); } + } finally { + _busy = false; } } @@ -221,21 +248,24 @@ class SlatepackDialog extends StatelessWidget { final isDesktop = Util.isDesktop; return SlatepackPopupLayout( - title: title, + title: widget.title, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ RoundedContainer( color: colors.textFieldDefaultBG, - child: Text(instructions, style: STextStyles.w400_14(context)), + child: Text( + widget.instructions, + style: STextStyles.w400_14(context), + ), ), const SizedBox(height: 12), - if (showEncryptionStatus) ...[ + if (widget.showEncryptionStatus) ...[ Row( children: [ SvgPicture.asset( - isEncrypted ? Assets.svg.lock : Assets.svg.lockOpen, + widget.isEncrypted ? Assets.svg.lock : Assets.svg.lockOpen, width: 14, height: 14, colorFilter: ColorFilter.mode( @@ -246,7 +276,7 @@ class SlatepackDialog extends StatelessWidget { const SizedBox(width: 8), Flexible( child: Text( - isEncrypted + widget.isEncrypted ? "Encrypted to the other party's address" : "Not encrypted", style: STextStyles.label(context), @@ -256,26 +286,35 @@ class SlatepackDialog extends StatelessWidget { ), const SizedBox(height: 12), ], - if (formattedAmount != null || formattedFee != null) ...[ - RoundedWhiteContainer( - borderColor: isDesktop ? colors.backgroundAppBar : null, - padding: EdgeInsets.zero, + if (widget.formattedAmount != null || + widget.formattedFee != null) ...[ + ConditionalParent( + condition: isDesktop, + builder: (child) => RoundedWhiteContainer( + borderColor: colors.backgroundAppBar, + padding: EdgeInsets.zero, + child: child, + ), child: Column( mainAxisSize: MainAxisSize.min, children: [ - if (formattedAmount != null) - DetailItem(title: "Amount", detail: formattedAmount!), - if (formattedAmount != null && formattedFee != null) + if (widget.formattedAmount != null) + DetailItem( + title: "Amount", + detail: widget.formattedAmount!, + ), + if (widget.formattedAmount != null && + widget.formattedFee != null) const DetailDivider(), - if (formattedFee != null) - DetailItem(title: "Fee", detail: formattedFee!), + if (widget.formattedFee != null) + DetailItem(title: "Fee", detail: widget.formattedFee!), ], ), ), const SizedBox(height: 12), ], Center( - child: SlatepackQr(data: slatepack, noun: terms.noun), + child: SlatepackQr(data: widget.slatepack, noun: widget.terms.noun), ), const SizedBox(height: 12), RoundedWhiteContainer( @@ -283,13 +322,16 @@ class SlatepackDialog extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Text(terms.title, style: STextStyles.itemSubtitle(context)), + Text( + widget.terms.title, + style: STextStyles.itemSubtitle(context), + ), const SizedBox(height: 8), ConstrainedBox( constraints: const BoxConstraints(maxHeight: 200), child: SingleChildScrollView( child: SelectableText( - slatepack, + widget.slatepack, style: STextStyles.w400_14(context).copyWith( fontFamily: slatepackMonospaceFontFamily( Theme.of(context).platform, @@ -304,9 +346,11 @@ class SlatepackDialog extends StatelessWidget { const SizedBox(height: 16), LayoutBuilder( builder: (context, constraints) { + final canShare = + Util.layoutPlatform.isAndroid || Util.layoutPlatform.isIOS; final scaledText = MediaQuery.textScalerOf(context).scale(14); final useTwoRows = - !isDesktop && (constraints.maxWidth < 300 || scaledText > 14); + canShare && (constraints.maxWidth < 300 || scaledText > 14); final copy = SecondaryButton( label: "Copy", @@ -317,6 +361,7 @@ class SlatepackDialog extends StatelessWidget { final share = Builder( builder: (context) => SecondaryButton( label: "Share", + buttonHeight: isDesktop ? ButtonHeight.l : null, icon: _icon(context, Assets.svg.share), onPressed: () => _share(context), ), @@ -348,7 +393,7 @@ class SlatepackDialog extends StatelessWidget { return Row( children: [ Expanded(child: copy), - if (!isDesktop) ...[ + if (canShare) ...[ const SizedBox(width: 12), Expanded(child: share), ], diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart index 26d1935ada..af52e9fad9 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -4,16 +4,14 @@ import 'package:flutter/material.dart'; import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; +import '../../themes/stack_colors.dart'; import '../../utilities/amount/amount.dart'; import '../../utilities/exception_message.dart'; -import '../../themes/stack_colors.dart'; import '../../utilities/logger.dart'; import '../../utilities/route_presentation.dart'; import '../../utilities/slatepack_text.dart'; -import '../../utilities/util.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../widgets/custom_loading_overlay.dart'; -import '../../widgets/stack_dialog.dart'; import 'slatepack_dialog.dart'; import 'slatepack_popup.dart'; import 'slatepack_summary_dialog.dart'; @@ -41,8 +39,7 @@ enum SlatepackRoute { abstract final class SlatepackImportFlow { // This lookup is local-only. A short defensive bound prevents a damaged // database or application shutdown from holding an import screen forever. - static const _receiveHistoryLookupTimeout = Duration(seconds: 3); - static const _finalizeHistoryLookupTimeout = Duration(seconds: 3); + static const _historyLookupTimeout = Duration(seconds: 3); static SlatepackRoute routeFor(SlateState state) => switch (state) { SlateState.s1 => SlatepackRoute.receive, @@ -52,13 +49,6 @@ abstract final class SlatepackImportFlow { SlateState.unknown => SlatepackRoute.unsupported, }; - /// The slatepack in [text] without what came along with it. A pasted or - /// scanned message often has a greeting, a quote or blank lines around the - /// armored slatepack, so only the part from its begin marker to its end - /// marker is kept. Text without such a frame, like a JSON slate, is only - /// trimmed. - static String normalize(String text) => SlatepackText.normalize(text); - /// Returns true once the slatepack has been acted on, so the caller can /// clear its input. static Future run({ @@ -67,57 +57,76 @@ abstract final class SlatepackImportFlow { required String text, }) async { final terms = wallet.slatepackTerms; - final slatepack = normalize(text); + final slatepack = SlatepackText.normalize(text); - final read = await _withLoading( + final readLoaded = await _withLoading( context, "Reading ${terms.noun}...", () async { final inspection = await wallet.inspectSlatepack(slatepack); final route = routeFor(inspection.state); - var historyLookupTimedOut = false; + var historyLookupFailed = false; final needsLocalHistory = route == SlatepackRoute.receive || route == SlatepackRoute.finalizeSend; - final local = needsLocalHistory - ? await wallet - .localTxForSlate(inspection.slateId) - .timeout( - route == SlatepackRoute.receive - ? _receiveHistoryLookupTimeout - : _finalizeHistoryLookupTimeout, - onTimeout: () { - historyLookupTimedOut = true; - Logging.instance.w( - "Timed out looking up local transaction for slate " - "${inspection.slateId}", - ); - return null; - }, - ) - : null; + + Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> + lookupLocal() async { + try { + return await wallet + .localTxForSlate(inspection.slateId) + .timeout( + _historyLookupTimeout, + onTimeout: () { + historyLookupFailed = true; + Logging.instance.w( + "Timed out looking up local transaction for slate " + "${inspection.slateId}", + ); + return null; + }, + ); + } catch (e, s) { + historyLookupFailed = true; + Logging.instance.w( + "Could not look up local transaction for slate " + "${inspection.slateId}", + error: e, + stackTrace: s, + ); + return null; + } + } + + final local = needsLocalHistory ? await lookupLocal() : null; return ( inspection: inspection, route: route, // Only the wallet that started a send can finalize it. local: local, - historyLookupTimedOut: historyLookupTimedOut, + historyLookupFailed: historyLookupFailed, ); }, errorTitle: "Could not read ${terms.noun}", ); - if (read == null || !context.mounted) return false; + if (readLoaded == null || + !readLoaded.canPresentResult || + !context.mounted) { + return false; + } + final read = readLoaded.value; final inspection = read.inspection; final route = read.route; switch (route) { case SlatepackRoute.receive: - if (read.historyLookupTimedOut) { - await _message( - context, - "Could not check wallet history", - "The wallet is busy. Try importing this ${terms.noun} again.", + if (read.historyLookupFailed) { + await showSlatepackOkDialog( + context: context, + title: "Could not check wallet history", + message: + "The wallet is busy. Try importing this ${terms.noun} again.", ); return false; } @@ -128,45 +137,52 @@ abstract final class SlatepackImportFlow { "received or finalized." : "This transaction's earlier receive was cancelled. Ask the " "sender to create a new transaction."; - await _message(context, "Cannot receive this ${terms.noun}", reason); + await showSlatepackOkDialog( + context: context, + title: "Cannot receive this ${terms.noun}", + message: reason, + ); return false; } if (local?.isSend == true) { - await _message( - context, - "Cannot receive this ${terms.noun}", - "This wallet created the transaction. Share this ${terms.noun} " + await showSlatepackOkDialog( + context: context, + title: "Cannot receive this ${terms.noun}", + message: + "This wallet created the transaction. Share this ${terms.noun} " "with the other party, then import their response instead.", ); return false; } if (local != null) { - await _message( - context, - "Cannot receive this ${terms.noun}", - "This transaction is already in this wallet's history.", + await showSlatepackOkDialog( + context: context, + title: "Cannot receive this ${terms.noun}", + message: "This transaction is already in this wallet's history.", ); return false; } - return _receive(context, wallet, slatepack, inspection); + return _receive(context, wallet, inspection); case SlatepackRoute.finalizeSend: final local = read.local; if (local != null && !local.isSend) { - await _message( - context, - "Cannot finalize this ${terms.noun}", - "This ${terms.noun} belongs to a transaction this wallet " + await showSlatepackOkDialog( + context: context, + title: "Cannot finalize this ${terms.noun}", + message: + "This ${terms.noun} belongs to a transaction this wallet " "received, not one it started. Only the wallet that " "started a send can finalize it.", ); return false; } if (local?.isCancelled == true) { - await _message( - context, - "Cannot finalize this ${terms.noun}", - "This transaction was cancelled. A cancelled send cannot be " + await showSlatepackOkDialog( + context: context, + title: "Cannot finalize this ${terms.noun}", + message: + "This transaction was cancelled. A cancelled send cannot be " "finalized.", ); return false; @@ -174,38 +190,40 @@ abstract final class SlatepackImportFlow { return _finalize( context, wallet, - slatepack, inspection, amount: local?.amount ?? inspection.amount, fee: local?.fee ?? inspection.fee, historyWarning: local == null, - historyLookupTimedOut: read.historyLookupTimedOut, + historyLookupTimedOut: read.historyLookupFailed, ); case SlatepackRoute.invoicesUnsupported: - await _message( - context, - "Invoices not supported", - "This ${terms.noun} is part of an invoice. " + await showSlatepackOkDialog( + context: context, + title: "Invoices not supported", + message: + "This ${terms.noun} is part of an invoice. " "${wallet.cryptoCurrency.prettyName} wallets do not support " "invoices.", ); return false; case SlatepackRoute.alreadyFinalized: - await _message( - context, - "Already finalized", - "This ${terms.noun} is already finalized. There is nothing left " + await showSlatepackOkDialog( + context: context, + title: "Already finalized", + message: + "This ${terms.noun} is already finalized. There is nothing left " "to do with it.", ); return false; case SlatepackRoute.unsupported: - await _message( - context, - "Unsupported ${terms.noun}", - "Could not tell which step of a transaction this ${terms.noun} " + await showSlatepackOkDialog( + context: context, + title: "Unsupported ${terms.noun}", + message: + "Could not tell which step of a transaction this ${terms.noun} " "belongs to.", ); return false; @@ -215,7 +233,6 @@ abstract final class SlatepackImportFlow { static Future _receive( BuildContext context, SlatepackInterface wallet, - String text, SlateInspection inspection, ) async { final terms = wallet.slatepackTerms; @@ -228,7 +245,8 @@ abstract final class SlatepackImportFlow { actionLabel: "Receive", amount: inspection.amount, details: [ - if (inspection.senderAddress != null) + if (inspection.senderAddress != null && + inspection.senderAddress!.trim().isNotEmpty) ( RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(inspection.senderAddress!) ? "Sender key" @@ -249,19 +267,28 @@ abstract final class SlatepackImportFlow { // shown if the screen that started the import is gone by then. final root = Navigator.of(context, rootNavigator: true); - final result = await _withLoading( + final loaded = await _withLoading( context, "Processing ${terms.noun}...", () async { - final r = await wallet.receiveSlatepack(text, inspection: inspection); - if (!r.success || r.slatepack == null) { + final r = await wallet.receiveSlatepack(inspection); + if (!r.success || (r.slatepack?.trim().isEmpty ?? true)) { throw Exception(r.error ?? "Failed to receive ${terms.noun}"); } return r; }, errorTitle: "${terms.title} receive error", ); - if (result == null) return false; + if (loaded == null) return false; + final result = loaded.value; + + if (!loaded.canPresentResult) { + Logging.instance.w( + "Received ${terms.noun} ${result.slateId} after overlay route " + "closed; skipping response presentation.", + ); + return true; + } // The transaction is received now and the sender cannot finalize it // without the response, so the response is shown wherever it still can @@ -297,7 +324,6 @@ abstract final class SlatepackImportFlow { static Future _finalize( BuildContext context, SlatepackInterface wallet, - String text, SlateInspection inspection, { required Amount? amount, required Amount? fee, @@ -350,11 +376,13 @@ abstract final class SlatepackImportFlow { ); if (confirmed != true || !context.mounted) return false; - final result = await _withLoading( + final root = Navigator.of(context, rootNavigator: true); + + final loaded = await _withLoading( context, "Finalizing ${terms.noun}...", () async { - final r = await wallet.finalizeSlatepack(text, inspection: inspection); + final r = await wallet.finalizeSlatepack(inspection); if (!r.success) { throw Exception(r.error ?? "Finalize failed"); } @@ -362,37 +390,64 @@ abstract final class SlatepackImportFlow { }, errorTitle: "${terms.title} finalize error", ); - if (result == null) return false; + if (loaded == null) return false; + final result = loaded.value; - if (!context.mounted) { + if (!loaded.canPresentResult) { Logging.instance.w( - "Finalized ${terms.noun} ${inspection.slateId} after the screen that " - "imported it had closed. Broadcast: ${result.posted}.", + "Finalized ${terms.noun} ${inspection.slateId} after overlay route " + "closed. Broadcast: ${result.posted}.", ); return true; } if (result.posted == true) { - unawaited( - showFloatingFlushBar( - type: FlushBarType.success, - message: "Transaction finalized and broadcast", - context: context, - ), + final flushContext = context.mounted + ? context + : (root.mounted ? root.context : null); + if (flushContext != null && flushContext.mounted) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.success, + message: "Transaction finalized and broadcast", + context: flushContext, + ), + ); + } else { + Logging.instance.w( + "Finalized ${terms.noun} ${inspection.slateId} after the screen " + "that imported it had closed. Broadcast: ${result.posted}.", + ); + } + return true; + } + + final dialogContext = context.mounted + ? context + : (root.mounted ? root.context : null); + if (dialogContext == null || !dialogContext.mounted) { + Logging.instance.w( + "Finalized ${terms.noun} ${inspection.slateId} with no context to " + "show broadcast warning. Broadcast: ${result.posted}.", ); - } else if (result.posted == false) { - await _message( - context, - "Finalized, not broadcast", - "The transaction is finalized but the node did not accept it yet. " + return true; + } + + if (result.posted == false) { + await showSlatepackOkDialog( + context: dialogContext, + title: "Finalized, not broadcast", + message: + "The transaction is finalized but the node did not accept it yet. " "Check the node connection and transaction history before " "creating a replacement.", ); } else { - await _message( - context, - "Transaction finalized", - "The native wallet finalized the transaction, but its broadcast " + await showSlatepackOkDialog( + context: dialogContext, + title: "Transaction finalized", + message: + "The native wallet finalized the transaction, but its broadcast " "result is unavailable. Check transaction history and the node " "connection before creating a replacement.", ); @@ -402,24 +457,21 @@ abstract final class SlatepackImportFlow { /// Runs [action] under a loading overlay. Shows the error and returns null /// when it throws. - static Future _withLoading( + static Future<({T value, bool canPresentResult})?> _withLoading( BuildContext context, String message, Future Function() action, { required String errorTitle, }) async { - // The overlay is this flow's own route on the root navigator, so it can - // be taken down again even if the screen that started the import is gone - // by the time the wallet answers. final root = Navigator.of(context, rootNavigator: true); final overlayColor = Theme.of(context) .extension()! .overlay .withValues(alpha: 0.6); - final overlay = CurrentAwareDialogRoute( + + final outcome = await runWithCurrentAwareOverlay( context: context, - barrierDismissible: false, - themes: InheritedTheme.capture(from: context, to: root.context), + useSafeArea: false, builder: (_) => PopScope( canPop: false, child: Container( @@ -427,60 +479,36 @@ abstract final class SlatepackImportFlow { child: CustomLoadingOverlay(message: message, eventBus: null), ), ), + action: action, ); - unawaited(root.push(overlay)); - - T? result; - Object? error; - try { - // MWC's native calls can block synchronously, so wait until the route is - // fully visible rather than merely built at zero transition opacity. - await waitForRoutePresentation(overlay); - result = await action(); - } catch (e, s) { - Logging.instance.w(errorTitle, error: e, stackTrace: s); - error = e; - } + if (outcome.aborted) return null; - if (root.mounted && overlay.isActive) { - await overlay.waitUntilCurrent(); - } - if (root.mounted && overlay.isActive) { - if (overlay.isCurrent) { - root.pop(); - } else { - root.removeRoute(overlay); - } - } - - if (error != null || result == null) { - // An error is worth showing even after the importing screen closed. - final text = error == null - ? "Unexpected result without an error" - : stripExceptionPrefixes(error); - if (context.mounted) { - await _message(context, errorTitle, text); - } else if (root.mounted) { - await _message(root.context, errorTitle, text); + if (outcome.error != null || outcome.value == null) { + Logging.instance.w( + errorTitle, + error: outcome.error, + stackTrace: outcome.stackTrace, + ); + if (outcome.canPresentResult) { + final text = outcome.error == null + ? "Unexpected result without an error" + : stripExceptionPrefixes(outcome.error!); + final errorContext = context.mounted + ? context + : (root.mounted ? root.context : null); + if (errorContext != null && errorContext.mounted) { + await showSlatepackOkDialog( + context: errorContext, + title: errorTitle, + message: text, + ); + } } return null; } - return result; - } - - static Future _message( - BuildContext context, - String title, - String message, - ) { - return showDialog( - context: context, - builder: (_) => StackOkDialog( - title: title, - message: message, - desktopPopRootNavigator: Util.isDesktop, - maxWidth: Util.isDesktop ? 400 : null, - ), + return ( + value: outcome.value as T, + canPresentResult: outcome.canPresentResult, ); } } diff --git a/lib/pages/slatepack/slatepack_input_field.dart b/lib/pages/slatepack/slatepack_input_field.dart index 9f3880288a..a17e6dd022 100644 --- a/lib/pages/slatepack/slatepack_input_field.dart +++ b/lib/pages/slatepack/slatepack_input_field.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:io'; +import 'dart:typed_data'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; @@ -54,15 +55,28 @@ class SlatepackInputField extends ConsumerStatefulWidget { } class _SlatepackInputFieldState extends ConsumerState { - late final FocusNode _focusNode; + late FocusNode _focusNode; + late bool _ownsFocusNode; + late bool _wasEmpty; + bool _busy = false; bool get _isEmpty => widget.controller.text.isEmpty; + void _onControllerChanged() { + final empty = _isEmpty; + if (empty != _wasEmpty) { + _wasEmpty = empty; + if (mounted) setState(() {}); + } + } + void _set(String text) { if (!mounted) return; widget.controller.text = text; widget.onChanged?.call(text); - setState(() {}); + setState(() { + _wasEmpty = _isEmpty; + }); } Future _paste() async { @@ -76,8 +90,10 @@ class _SlatepackInputFieldState extends ConsumerState { } Future _scan() async { + if (_busy) return; + _busy = true; try { - if (Platform.isAndroid || Platform.isIOS) { + if (Util.layoutPlatform.isAndroid || Util.layoutPlatform.isIOS) { if (_focusNode.hasFocus) { _focusNode.unfocus(); await Future.delayed(const Duration(milliseconds: 75)); @@ -118,10 +134,21 @@ class _SlatepackInputFieldState extends ConsumerState { stackTrace: s, ); } + } catch (e, s) { + Logging.instance.w( + "Scanning ${widget.terms.noun} QR failed", + error: e, + stackTrace: s, + ); + _showError(stripExceptionPrefixes(e)); + } finally { + _busy = false; } } Future _openFile() async { + if (_busy) return; + _busy = true; try { final result = await FilePicker.platform.pickFiles( dialogTitle: "Open ${widget.terms.noun} file", @@ -138,10 +165,23 @@ class _SlatepackInputFieldState extends ConsumerState { ); } - final List bytes = - picked.bytes ?? await File(picked.path!).readAsBytes(); - if (bytes.length > kSlatepackFileMaxBytes) { - throw Exception("File is too large to be a ${widget.terms.noun}."); + final List bytes; + if (picked.bytes != null) { + bytes = picked.bytes!; + if (bytes.length > kSlatepackFileMaxBytes) { + throw Exception("File is too large to be a ${widget.terms.noun}."); + } + } else if (picked.path != null) { + final builder = BytesBuilder(copy: false); + await for (final chunk in File(picked.path!).openRead()) { + builder.add(chunk); + if (builder.length > kSlatepackFileMaxBytes) { + throw Exception("File is too large to be a ${widget.terms.noun}."); + } + } + bytes = builder.takeBytes(); + } else { + throw Exception("Could not read the selected file."); } final text = utf8.decode(bytes).trim(); @@ -158,6 +198,8 @@ class _SlatepackInputFieldState extends ConsumerState { stackTrace: s, ); _showError(stripExceptionPrefixes(e)); + } finally { + _busy = false; } } @@ -173,12 +215,33 @@ class _SlatepackInputFieldState extends ConsumerState { @override void initState() { super.initState(); + _ownsFocusNode = widget.focusNode == null; _focusNode = widget.focusNode ?? FocusNode(); + _wasEmpty = _isEmpty; + widget.controller.addListener(_onControllerChanged); + } + + @override + void didUpdateWidget(covariant SlatepackInputField oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + oldWidget.controller.removeListener(_onControllerChanged); + _wasEmpty = _isEmpty; + widget.controller.addListener(_onControllerChanged); + } + if (oldWidget.focusNode != widget.focusNode) { + if (_ownsFocusNode) { + _focusNode.dispose(); + } + _ownsFocusNode = widget.focusNode == null; + _focusNode = widget.focusNode ?? FocusNode(); + } } @override void dispose() { - if (widget.focusNode == null) { + widget.controller.removeListener(_onControllerChanged); + if (_ownsFocusNode) { _focusNode.dispose(); } super.dispose(); @@ -201,7 +264,6 @@ class _SlatepackInputFieldState extends ConsumerState { enableSuggestions: false, onChanged: (value) { widget.onChanged?.call(value); - setState(() {}); }, style: Util.isDesktop ? STextStyles.desktopTextExtraSmall(context) diff --git a/lib/pages/slatepack/slatepack_popup.dart b/lib/pages/slatepack/slatepack_popup.dart index 4bc00185b4..44e91dd08d 100644 --- a/lib/pages/slatepack/slatepack_popup.dart +++ b/lib/pages/slatepack/slatepack_popup.dart @@ -6,33 +6,89 @@ import '../../widgets/desktop/desktop_dialog.dart'; import '../../widgets/desktop/desktop_dialog_close_button.dart'; import '../../widgets/stack_dialog.dart'; +/// Shows an informational dialog on mobile and desktop without popping +/// [DesktopHomeView] off the root navigator. +Future showSlatepackOkDialog({ + required BuildContext context, + required String title, + required String message, + bool waitForDismissalAnimation = false, +}) async { + Widget buildDialog(BuildContext _) => StackOkDialog( + title: title, + message: message, + desktopPopRootNavigator: Util.isDesktop, + maxWidth: Util.isDesktop ? 400 : null, + ); + + if (!waitForDismissalAnimation) { + return showDialog(context: context, builder: buildDialog); + } + + final navigator = Navigator.of(context, rootNavigator: true); + final route = DialogRoute( + context: context, + themes: InheritedTheme.capture(from: context, to: navigator.context), + builder: buildDialog, + ); + await navigator.push(route); + await route.completed; + if (navigator.mounted) { + await WidgetsBinding.instance.endOfFrame; + } +} + /// Shows a slatepack screen as a dialog: a [DesktopDialog] on desktop, a /// bottom sheet style [StackDialogBase] on mobile. Future showSlatepackPopup({ required BuildContext context, required Widget child, bool barrierDismissible = true, -}) { - return showDialog( + bool waitForDismissalAnimation = false, +}) async { + final isDesktop = Util.isDesktop; + + Widget buildPopup(BuildContext dialogContext) { + final mediaInset = MediaQuery.viewInsetsOf(dialogContext).bottom; + // Dialog routes can expose a MediaQuery with consumed insets. Read the + // owning view as well so the mobile popup still follows the IME. + final viewInset = MediaQueryData.fromView(View.of(dialogContext)) + .viewInsets + .bottom; + final keyboardInset = mediaInset > viewInset ? mediaInset : viewInset; + final popup = isDesktop + ? Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: DesktopDialog(maxWidth: 700, maxHeight: null, child: child), + ) + : StackDialogBase(keyboardPaddingAmount: keyboardInset, child: child); + return barrierDismissible ? popup : PopScope(canPop: false, child: popup); + } + + if (!waitForDismissalAnimation) { + return showDialog( + context: context, + barrierDismissible: barrierDismissible, + // Mobile StackDialogBase applies its own safe-area sheet layout. + useSafeArea: isDesktop, + builder: buildPopup, + ); + } + + final navigator = Navigator.of(context, rootNavigator: true); + final route = DialogRoute( context: context, barrierDismissible: barrierDismissible, - // StackDialogBase and DesktopDialog already apply their own safe-area - // layout. - useSafeArea: false, - builder: (context) { - final mediaInset = MediaQuery.viewInsetsOf(context).bottom; - // Dialog routes can expose a MediaQuery with consumed insets. Read the - // owning view as well so the mobile popup still follows the IME. - final viewInset = MediaQueryData.fromView(View.of(context)) - .viewInsets - .bottom; - final keyboardInset = mediaInset > viewInset ? mediaInset : viewInset; - final popup = Util.isDesktop - ? DesktopDialog(maxWidth: 700, maxHeight: null, child: child) - : StackDialogBase(keyboardPaddingAmount: keyboardInset, child: child); - return barrierDismissible ? popup : PopScope(canPop: false, child: popup); - }, + useSafeArea: isDesktop, + themes: InheritedTheme.capture(from: context, to: navigator.context), + builder: buildPopup, ); + final result = await navigator.push(route); + await route.completed; + if (navigator.mounted) { + await WidgetsBinding.instance.endOfFrame; + } + return result; } /// Title and body for a slatepack popup. On desktop the title row carries a diff --git a/lib/pages/slatepack/slatepack_qr.dart b/lib/pages/slatepack/slatepack_qr.dart index 2423c8eff5..f237ea4a17 100644 --- a/lib/pages/slatepack/slatepack_qr.dart +++ b/lib/pages/slatepack/slatepack_qr.dart @@ -33,16 +33,21 @@ class SlatepackQr extends StatelessWidget { final double size; Future _enlarge(BuildContext context) { - final screen = MediaQuery.of(context).size; - final side = math.min(math.min(screen.width, screen.height) - 64, 640.0); return showDialog( context: context, - builder: (dialogContext) => GestureDetector( - onTap: () => Navigator.of(dialogContext).pop(), - child: Center( - child: QR(data: data, size: side), - ), - ), + builder: (dialogContext) { + final screen = MediaQuery.of(dialogContext).size; + final side = (math.min(screen.width, screen.height) - 64).clamp( + 120.0, + 640.0, + ); + return GestureDetector( + onTap: () => Navigator.of(dialogContext).pop(), + child: Center( + child: QR(data: data, size: side), + ), + ); + }, ); } diff --git a/lib/pages/slatepack/slatepack_send_flow.dart b/lib/pages/slatepack/slatepack_send_flow.dart index 2b6fcd6305..7f0a93b994 100644 --- a/lib/pages/slatepack/slatepack_send_flow.dart +++ b/lib/pages/slatepack/slatepack_send_flow.dart @@ -12,8 +12,8 @@ import '../../utilities/logger.dart'; import '../../utilities/route_presentation.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../widgets/custom_loading_overlay.dart'; -import '../../widgets/stack_dialog.dart'; import 'slatepack_dialog.dart'; +import 'slatepack_popup.dart'; /// Creates a manual Epic or MWC slate directly from either send screen. /// @@ -22,6 +22,12 @@ import 'slatepack_dialog.dart'; /// normal fee estimate, confirmation and PIN flow and shows the wallet's /// actual amount and fee after creation. abstract final class SlatepackSendFlow { + static String _cancelOutcomeMessage(String cancelError) => cancelError.isEmpty + ? "The transaction was cancelled." + : "The transaction could not be cancelled " + "(${stripExceptionPrefixes(cancelError)}). " + "Cancel it from its details before trying again."; + static Future run({ required BuildContext context, required SlatepackInterface wallet, @@ -37,10 +43,13 @@ abstract final class SlatepackSendFlow { .extension()! .overlay .withValues(alpha: 0.6); - final overlay = CurrentAwareDialogRoute( + + var noteSaved = localNote.isEmpty; + var shouldRefresh = false; + + final outcome = await runWithCurrentAwareOverlay( context: context, - barrierDismissible: false, - themes: InheritedTheme.capture(from: context, to: root.context), + useSafeArea: false, builder: (_) => PopScope( canPop: false, child: Container( @@ -51,138 +60,127 @@ abstract final class SlatepackSendFlow { ), ), ), - ); - - unawaited(root.push(overlay)); - - SlatepackResult? result; - Object? error; - var noteSaved = localNote.isEmpty; - try { - // Some native MWC calls block synchronously. Do not start one while the - // keyboard or another route is still animating away. - await waitForRoutePresentation(overlay); - result = await wallet.createSlatepack( - amount: amount, - message: wallet.supportsOnChainNote && message.isNotEmpty - ? message - : null, - ); - if (!result.success || (result.slatepack?.trim().isEmpty ?? true)) { - throw Exception( - stripExceptionPrefixes( - result.error ?? "Failed to create ${terms.noun}", - ), + action: () async { + final created = await wallet.createSlatepack( + amount: amount, + message: wallet.supportsOnChainNote && message.isNotEmpty + ? message + : null, ); - } - - final slateId = result.slateId; - final createdAmount = result.amount; - final createdFee = result.fee; - if (slateId == null || - slateId.isEmpty || - createdAmount == null || - createdFee == null) { - final cancelError = slateId == null || slateId.isEmpty - ? "it has no slate id" - : await wallet.cancelPendingTransactionAndPost(slateId); - final outcome = cancelError.isEmpty - ? "The transaction was cancelled." - : "The transaction could not be cancelled ($cancelError). " - "Cancel it from its details before trying again."; - throw Exception( - "The wallet did not return the ${terms.noun}'s complete amount, " - "fee, and identifier. $outcome", - ); - } + if (!created.success || (created.slatepack?.trim().isEmpty ?? true)) { + throw Exception( + stripExceptionPrefixes( + created.error ?? "Failed to create ${terms.noun}", + ), + ); + } - if (createdAmount != amount) { - final cancelError = await wallet.cancelPendingTransactionAndPost( - slateId, - ); - final outcome = cancelError.isEmpty - ? "The transaction was cancelled." - : "The transaction could not be cancelled ($cancelError). " - "Cancel it from its details before trying again."; - throw Exception( - "The ${terms.noun} was created for ${format(createdAmount)} instead " - "of the requested ${format(amount)}. $outcome", - ); - } + final slateId = created.slateId; + final createdAmount = created.amount; + final createdFee = created.fee; + if (slateId == null || + slateId.isEmpty || + createdAmount == null || + createdFee == null) { + final cancelError = slateId == null || slateId.isEmpty + ? "it has no slate id" + : await wallet.cancelPendingTransactionAndPost(slateId); + shouldRefresh = + slateId != null && slateId.isNotEmpty && cancelError.isNotEmpty; + throw Exception( + "The wallet did not return the ${terms.noun}'s complete amount, " + "fee, and identifier. ${_cancelOutcomeMessage(cancelError)}", + ); + } - if (!noteSaved) { - try { - await db.putTransactionNote( - TransactionNote( - walletId: wallet.walletId, - txid: slateId, - value: localNote, - ), + if (createdAmount != amount) { + final cancelError = await wallet.cancelPendingTransactionAndPost( + slateId, ); - noteSaved = true; - } catch (e, s) { - Logging.instance.w( - "Could not save the local note for $slateId", - error: e, - stackTrace: s, + shouldRefresh = cancelError.isNotEmpty; + throw Exception( + "The ${terms.noun} was created for ${format(createdAmount)} " + "instead of the requested ${format(amount)}. " + "${_cancelOutcomeMessage(cancelError)}", ); } - } - } catch (e, s) { - error = e; - Logging.instance.w( - "Could not create the ${terms.noun}", - error: e, - stackTrace: s, - ); - } - if (root.mounted && overlay.isActive) { - await overlay.waitUntilCurrent(); - } - if (root.mounted && overlay.isActive) { - if (overlay.isCurrent) { - root.pop(); - } else { - root.removeRoute(overlay); - } - } + shouldRefresh = true; + if (!noteSaved) { + try { + await db.putTransactionNote( + TransactionNote( + walletId: wallet.walletId, + txid: slateId, + value: localNote, + ), + ); + noteSaved = true; + } catch (e, s) { + Logging.instance.w( + "Could not save the local note for $slateId", + error: e, + stackTrace: s, + ); + } + } + return created; + }, + ); - final resultContext = root.context; - if (!resultContext.mounted) return false; + if (outcome.aborted) return false; - if (error != null || result == null) { - await showDialog( - context: resultContext, - builder: (context) => StackOkDialog( + final result = outcome.value; + if (outcome.error != null || result == null) { + Logging.instance.w( + "Could not create the ${terms.noun}", + error: outcome.error, + stackTrace: outcome.stackTrace, + ); + if (outcome.canPresentResult && root.mounted) { + await showSlatepackOkDialog( + context: root.context, title: "Could not create the ${terms.noun}", message: stripExceptionPrefixes( - error ?? "Failed to create ${terms.noun}", + outcome.error ?? "Failed to create ${terms.noun}", ), - ), - ); + waitForDismissalAnimation: shouldRefresh, + ); + } + if (shouldRefresh) unawaited(wallet.refresh()); return false; } + if (!outcome.canPresentResult || !root.mounted) { + Logging.instance.w( + "Created ${terms.noun} ${result.slateId} after the flow closed.", + ); + if (shouldRefresh) unawaited(wallet.refresh()); + return true; + } + await showSlatepackDialog( - context: resultContext, + context: root.context, terms: terms, result: result, supportsEncryption: wallet.supportsSlatepackEncryption, formattedAmount: format(result.amount!), formattedFee: format(result.fee!), + waitForDismissalAnimation: true, ); - if (!noteSaved && resultContext.mounted) { - await showDialog( - context: resultContext, - builder: (context) => const StackOkDialog( - title: "Local note not saved", - message: - "The transaction was created successfully, but its local " - "note could not be saved.", - ), + if (!noteSaved && + root.mounted && + (!context.mounted || isHostRouteCurrent(context, root))) { + await showSlatepackOkDialog( + context: root.context, + title: "Local note not saved", + message: + "The transaction was created successfully, but its local " + "note could not be saved.", + waitForDismissalAnimation: shouldRefresh, ); } + if (shouldRefresh) unawaited(wallet.refresh()); return true; } } diff --git a/lib/pages/slatepack/slatepack_summary_dialog.dart b/lib/pages/slatepack/slatepack_summary_dialog.dart index ea651c9541..1d6a251ecd 100644 --- a/lib/pages/slatepack/slatepack_summary_dialog.dart +++ b/lib/pages/slatepack/slatepack_summary_dialog.dart @@ -7,6 +7,7 @@ import '../../utilities/amount/amount_formatter.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; import '../../wallets/crypto_currency/crypto_currency.dart'; +import '../../widgets/conditional_parent.dart'; import '../../widgets/desktop/primary_button.dart'; import '../../widgets/desktop/secondary_button.dart'; import '../../widgets/detail_item.dart'; @@ -68,20 +69,25 @@ class SlatepackSummaryDialog extends ConsumerWidget { ), const SizedBox(height: 16), ], - RoundedWhiteContainer( - padding: EdgeInsets.zero, - borderColor: isDesktop ? colors.backgroundAppBar : null, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - for (int i = 0; i < rows.length; i++) ...[ - if (i > 0) const DetailDivider(), - DetailItem(title: rows[i].$1, detail: rows[i].$2), + if (rows.isNotEmpty) + ConditionalParent( + condition: isDesktop, + builder: (child) => RoundedWhiteContainer( + padding: EdgeInsets.zero, + borderColor: colors.backgroundAppBar, + child: child, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (int i = 0; i < rows.length; i++) ...[ + if (i > 0) const DetailDivider(), + DetailItem(title: rows[i].$1, detail: rows[i].$2), + ], ], - ], + ), ), - ), const SizedBox(height: 24), Row( children: [ diff --git a/lib/pages/slatepack/slatepack_view.dart b/lib/pages/slatepack/slatepack_view.dart index 951a3cb205..fdbe55029e 100644 --- a/lib/pages/slatepack/slatepack_view.dart +++ b/lib/pages/slatepack/slatepack_view.dart @@ -25,42 +25,49 @@ import '../../widgets/desktop/primary_button.dart'; import 'slatepack_import_flow.dart'; import 'slatepack_input_field.dart'; -/// The manual slate-exchange screen: takes a slate or slatepack and hands it to -/// [SlatepackImportFlow], which works out whether to receive or finalize. -class SlatepackView extends ConsumerStatefulWidget { - const SlatepackView({ +/// Shared slatepack import form with input field, submit button, and +/// re-entrancy guard. Used by both [SlatepackView] and [DesktopReceive]. +class SlatepackImportForm extends ConsumerStatefulWidget { + const SlatepackImportForm({ super.key, required this.walletId, + required this.buttonLabel, + this.header, + this.expandToFill = true, this.clipboard = const ClipboardWrapper(), }); - static const String routeName = "/slatepackView"; - final String walletId; + final String buttonLabel; + final Widget? header; + final bool expandToFill; final ClipboardInterface clipboard; @override - ConsumerState createState() => _SlatepackViewState(); + ConsumerState createState() => + _SlatepackImportFormState(); } -class _SlatepackViewState extends ConsumerState { +class _SlatepackImportFormState extends ConsumerState { late final TextEditingController _controller; late final FocusNode _focusNode; - late final SlatepackInterface _wallet; + late SlatepackInterface _wallet; - /// True while a slatepack is being imported, so a second press of Continue - /// cannot start the import again. + /// True while a slatepack is being imported, so a second press cannot start + /// the import again. bool _importing = false; bool get _hasText => _controller.text.trim().isNotEmpty; - Future _continuePressed() async { + Future _submitPressed() async { if (_importing) return; setState(() => _importing = true); try { - if (!Util.isDesktop && _focusNode.hasFocus) { + if (_focusNode.hasFocus) { _focusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); + if (Util.layoutPlatform.isAndroid || Util.layoutPlatform.isIOS) { + await Future.delayed(const Duration(milliseconds: 75)); + } } if (!mounted) return; @@ -87,6 +94,15 @@ class _SlatepackViewState extends ConsumerState { ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; } + @override + void didUpdateWidget(covariant SlatepackImportForm oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.walletId != widget.walletId) { + _wallet = + ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; + } + } + @override void dispose() { _controller.dispose(); @@ -94,13 +110,88 @@ class _SlatepackViewState extends ConsumerState { super.dispose(); } + @override + Widget build(BuildContext context) { + final terms = _wallet.slatepackTerms; + final isDesktop = Util.isDesktop; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (widget.header != null) ...[ + widget.header!, + SizedBox(height: widget.expandToFill ? 12 : 8), + ], + SlatepackInputField( + controller: _controller, + focusNode: _focusNode, + hint: "Enter ${terms.payload}", + terms: terms, + clipboard: widget.clipboard, + onChanged: (_) => setState(() {}), + ), + if (widget.expandToFill) + isDesktop ? const SizedBox(height: 24) : const Spacer() + else + const SizedBox(height: 16), + PrimaryButton( + label: widget.buttonLabel, + buttonHeight: isDesktop ? ButtonHeight.l : null, + enabled: _hasText && !_importing, + onPressed: _hasText && !_importing ? _submitPressed : null, + ), + if (widget.expandToFill && !isDesktop) + SizedBox(height: Constants.size.standardPadding), + ], + ); + } +} + +/// The manual slate-exchange screen: takes a slate or slatepack and hands it to +/// [SlatepackImportFlow], which works out whether to receive or finalize. +class SlatepackView extends ConsumerStatefulWidget { + const SlatepackView({ + super.key, + required this.walletId, + this.clipboard = const ClipboardWrapper(), + }); + + static const String routeName = "/slatepackView"; + + final String walletId; + final ClipboardInterface clipboard; + + @override + ConsumerState createState() => _SlatepackViewState(); +} + +class _SlatepackViewState extends ConsumerState { + late SlatepackInterface _wallet; + + @override + void initState() { + super.initState(); + _wallet = + ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; + } + + @override + void didUpdateWidget(covariant SlatepackView oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.walletId != widget.walletId) { + _wallet = + ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; + } + } + @override Widget build(BuildContext context) { debugPrint("BUILD: $runtimeType"); final terms = _wallet.slatepackTerms; + final isDesktop = Util.isDesktop; return ConditionalParent( - condition: !Util.isDesktop, + condition: !isDesktop, builder: (child) => Background( child: Scaffold( backgroundColor: Theme.of(context) @@ -137,38 +228,21 @@ class _SlatepackViewState extends ConsumerState { ), ), ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Text( - "Paste, scan or open a ${terms.noun} you were sent. It is " - "received or finalized depending on what it is.", - style: Util.isDesktop - ? STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of(context) - .extension()! - .textSubtitle1, - ) - : STextStyles.label(context), - ), - const SizedBox(height: 12), - SlatepackInputField( - controller: _controller, - focusNode: _focusNode, - hint: "Enter ${terms.payload}", - terms: terms, - clipboard: widget.clipboard, - onChanged: (_) => setState(() {}), - ), - Util.isDesktop ? const SizedBox(height: 24) : const Spacer(), - PrimaryButton( - label: "Continue", - buttonHeight: Util.isDesktop ? ButtonHeight.l : null, - enabled: _hasText && !_importing, - onPressed: _hasText && !_importing ? _continuePressed : null, - ), - if (!Util.isDesktop) SizedBox(height: Constants.size.standardPadding), - ], + child: SlatepackImportForm( + walletId: widget.walletId, + clipboard: widget.clipboard, + buttonLabel: "Continue", + header: Text( + "Paste, scan or open a ${terms.noun} you were sent. It is " + "received or finalized depending on what it is.", + style: isDesktop + ? STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textSubtitle1, + ) + : STextStyles.label(context), + ), ), ); } 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 d68e5d31b4..9d36a688fc 100644 --- a/lib/pages/wallet_view/transaction_views/transaction_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/transaction_details_view.dart @@ -30,8 +30,10 @@ import '../../../utilities/amount/amount_formatter.dart'; import '../../../utilities/assets.dart'; import '../../../utilities/block_explorers.dart'; import '../../../utilities/constants.dart'; +import '../../../utilities/exception_message.dart'; import '../../../utilities/format.dart'; import '../../../utilities/logger.dart'; +import '../../../utilities/route_presentation.dart'; import '../../../utilities/text_styles.dart'; import '../../../utilities/util.dart'; import '../../../wallets/crypto_currency/crypto_currency.dart'; @@ -51,6 +53,7 @@ import '../../../widgets/icon_widgets/pencil_icon.dart'; import '../../../widgets/rounded_white_container.dart'; import '../../../widgets/stack_dialog.dart'; import '../../receive_view/addresses/address_details_view.dart'; +import '../../slatepack/slatepack_cancel_transaction_dialog.dart'; import '../sub_widgets/tx_icon.dart'; import '../wallet_view.dart'; import 'dialogs/cancelling_transaction_progress_dialog.dart'; @@ -89,8 +92,10 @@ class _TransactionDetailsViewState late final bool isTokenTx; late final EthContract? ethContract; late final int minConfirms; + late final bool isSlatepackWallet; bool showFeePending = false; + bool _cancelling = false; @override void initState() { @@ -101,11 +106,9 @@ class _TransactionDetailsViewState _transaction.subType == TransactionSubType.splToken; walletId = widget.walletId; - minConfirms = ref - .read(pWallets) - .getWallet(widget.walletId) - .cryptoCurrency - .minConfirms; + final wallet = ref.read(pWallets).getWallet(widget.walletId); + isSlatepackWallet = wallet is SlatepackInterface; + minConfirms = wallet.cryptoCurrency.minConfirms; coin = widget.coin; amount = _transaction.realAmount; fee = _transaction.fee.toAmountAsRaw(fractionDigits: coin.fractionDigits); @@ -1674,9 +1677,12 @@ class _TransactionDetailsViewState ), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: - ((coin is Epiccash || coin is Mimblewimblecoin) && - _transaction.getConfirmations(currentHeight) < 1 && - _transaction.isCancelled == false) + (isSlatepackWallet && + canCancelSlateTransaction( + slateId: _transaction.slateId, + isCancelled: _transaction.isCancelled, + confirmations: _transaction.getConfirmations(currentHeight), + )) ? ConditionalParent( condition: isDesktop, builder: (child) => Padding( @@ -1695,78 +1701,91 @@ class _TransactionDetailsViewState ), ), onPressed: () async { - final wallet = ref.read(pWallets).getWallet(walletId); + if (_cancelling) return; + _cancelling = true; + try { + final wallet = ref.read(pWallets).getWallet(walletId); - if (wallet is SlatepackInterface) { - final String? id = _transaction.slateId; - if (id == null) { + if (wallet is SlatepackInterface) { + final String? id = _transaction.slateId; + if (id == null) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: + "Could not find " + "${wallet.cryptoCurrency.ticker} transaction ID", + context: context, + ), + ); + return; + } + + final proceed = await showDialog( + context: context, + builder: (_) => + const SlatepackCancelTransactionDialog(), + ); + if (proceed != true || !context.mounted) return; + + final outcome = + await runWithCurrentAwareOverlay( + context: context, + builder: (_) => + const CancellingTransactionProgressDialog(), + action: () => + wallet.cancelPendingTransactionAndPost(id), + ); + if (outcome.aborted) return; + + final result = outcome.error != null + ? stripExceptionPrefixes(outcome.error!) + : (outcome.value ?? ""); + if (outcome.canPresentResult && context.mounted) { + if (result.isEmpty) { + await showDialog( + context: context, + builder: (_) => StackOkDialog( + title: "Transaction cancelled", + maxWidth: Util.isDesktop ? 400 : null, + onOkPressed: (_) { + Navigator.of(context).popUntil( + ModalRoute.withName(WalletView.routeName), + ); + }, + ), + ); + unawaited(wallet.refresh()); + } else { + await showDialog( + context: context, + builder: (_) => StackOkDialog( + title: "Failed to cancel transaction", + message: result, + maxWidth: Util.isDesktop ? 400 : null, + ), + ); + } + } else if (result.isEmpty) { + unawaited(wallet.refresh()); + } + } else { unawaited( showFloatingFlushBar( type: FlushBarType.warning, message: - "Could not find " - "${wallet.cryptoCurrency.ticker} transaction ID", + "ERROR: This wallet cannot cancel " + "slatepack transactions", context: context, ), ); - return; } - - unawaited( - showDialog( - barrierDismissible: false, - context: context, - builder: (_) => - const CancellingTransactionProgressDialog(), - ), - ); - - final result = await wallet - .cancelPendingTransactionAndPost(id); - - if (context.mounted) { - // pop progress dialog - Navigator.of(context).pop(); - - if (result.isEmpty) { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Transaction cancelled", - maxWidth: Util.isDesktop ? 400 : null, - onOkPressed: (_) { - Navigator.of(context).popUntil( - ModalRoute.withName(WalletView.routeName), - ); - }, - ), - ); - } else { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Failed to cancel transaction", - message: result, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - } - } - } else { - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: - "ERROR: This wallet cannot cancel " - "slatepack transactions", - context: context, - ), - ); - return; + } finally { + _cancelling = false; } }, child: Text( - "Cancel Transaction", + "Cancel transaction", style: STextStyles.button(context), ), ), 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 1ae13a8b07..e920fc71ce 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 @@ -32,6 +32,7 @@ import '../../../../utilities/amount/amount_formatter.dart'; import '../../../../utilities/assets.dart'; import '../../../../utilities/block_explorers.dart'; import '../../../../utilities/constants.dart'; +import '../../../../utilities/exception_message.dart'; import '../../../../utilities/format.dart'; import '../../../../utilities/logger.dart'; import '../../../../utilities/route_presentation.dart'; @@ -109,6 +110,7 @@ class _TransactionV2DetailsViewState late final List<({List addresses, Amount amount})> data; bool showFeePending = false; + bool _cancelling = false; String? _sparkMemo; @@ -1508,87 +1510,87 @@ class _TransactionV2DetailsViewState ), ), onPressed: () async { - final wallet = ref.read(pWallets).getWallet(walletId); + if (_cancelling) return; + _cancelling = true; + try { + final wallet = ref.read(pWallets).getWallet(walletId); + + if (wallet is SlatepackInterface) { + final String? id = _transaction.slateId; + if (id == null) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: + "Could not find " + "${wallet.cryptoCurrency.ticker} transaction ID", + context: context, + ), + ); + return; + } - if (wallet is SlatepackInterface) { - final String? id = _transaction.slateId; - if (id == null) { + final proceed = await showDialog( + context: context, + builder: (_) => + const SlatepackCancelTransactionDialog(), + ); + if (proceed != true || !context.mounted) return; + + final outcome = + await runWithCurrentAwareOverlay( + context: context, + builder: (_) => + const CancellingTransactionProgressDialog(), + action: () => + wallet.cancelPendingTransactionAndPost(id), + ); + if (outcome.aborted) return; + + final result = outcome.error != null + ? stripExceptionPrefixes(outcome.error!) + : (outcome.value ?? ""); + if (outcome.canPresentResult && context.mounted) { + if (result.isEmpty) { + await showDialog( + context: context, + builder: (_) => StackOkDialog( + title: "Transaction cancelled", + onOkPressed: (_) { + Navigator.of(context).popUntil( + ModalRoute.withName(WalletView.routeName), + ); + }, + maxWidth: Util.isDesktop ? 400 : null, + ), + ); + unawaited(wallet.refresh()); + } else { + await showDialog( + context: context, + builder: (_) => StackOkDialog( + title: "Failed to cancel transaction", + message: result, + maxWidth: Util.isDesktop ? 400 : null, + ), + ); + } + } else if (result.isEmpty) { + unawaited(wallet.refresh()); + } + } else { unawaited( showFloatingFlushBar( type: FlushBarType.warning, message: - "Could not find " - "${wallet.cryptoCurrency.ticker} transaction ID", + "ERROR: This wallet cannot cancel " + "slatepack transactions", context: context, ), ); - return; - } - - final proceed = await showDialog( - context: context, - builder: (_) => - const SlatepackCancelTransactionDialog(), - ); - if (proceed != true || !context.mounted) return; - - final navigator = Navigator.of( - context, - rootNavigator: true, - ); - final progressRoute = CurrentAwareDialogRoute( - context: context, - barrierDismissible: false, - builder: (_) => - const CancellingTransactionProgressDialog(), - ); - unawaited(navigator.push(progressRoute)); - await waitForRoutePresentation(progressRoute); - - final result = await wallet - .cancelPendingTransactionAndPost(id); - final canPresentResult = - await dismissCurrentAwareDialogRoute( - navigator: navigator, - route: progressRoute, - ); - if (canPresentResult && context.mounted) { - if (result.isEmpty) { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Transaction cancelled", - onOkPressed: (_) { - Navigator.of(context).popUntil( - ModalRoute.withName(WalletView.routeName), - ); - }, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - unawaited(wallet.refresh()); - } else { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Failed to cancel transaction", - message: result, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - } } - } else { - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: - "ERROR: This wallet cannot cancel " - "slatepack transactions", - context: context, - ), - ); - return; + } finally { + _cancelling = false; } }, child: Text( diff --git a/lib/pages/wallet_view/wallet_view.dart b/lib/pages/wallet_view/wallet_view.dart index ca07cbff62..ac4628be32 100644 --- a/lib/pages/wallet_view/wallet_view.dart +++ b/lib/pages/wallet_view/wallet_view.dart @@ -12,6 +12,7 @@ import 'dart:async'; import 'dart:io'; import 'package:event_bus/event_bus.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/svg.dart'; @@ -1012,18 +1013,9 @@ class _WalletViewState extends ConsumerState { if (wallet is SlatepackInterface) WalletNavigationBarItemData( label: wallet.slatepackTerms.title, - overrideText: FittedBox( - fit: BoxFit.scaleDown, - child: Text( - wallet.slatepackTerms.title, - maxLines: 1, - softWrap: false, - style: STextStyles.buttonSmall(context).copyWith( - color: Theme.of(context) - .extension()! - .bottomNavText, - ), - ), + overrideText: buildSlatepackNavLabel( + context, + wallet.slatepackTerms.title, ), icon: const FinalizeNavIcon(), onTap: () { @@ -1346,3 +1338,16 @@ class _WalletViewState extends ConsumerState { ); } } + +@visibleForTesting +Widget buildSlatepackNavLabel(BuildContext context, String label) => FittedBox( + fit: BoxFit.scaleDown, + child: Text( + label, + maxLines: 1, + softWrap: false, + style: STextStyles.buttonSmall(context).copyWith( + color: Theme.of(context).extension()!.bottomNavText, + ), + ), +); 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 e03703cde9..c8d9cc90f1 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 @@ -22,8 +22,7 @@ import '../../../../models/isar/models/isar_models.dart'; import '../../../../models/keys/view_only_wallet_data.dart'; import '../../../../notifications/show_flush_bar.dart'; import '../../../../pages/receive_view/generate_receiving_uri_qr_code_view.dart'; -import '../../../../pages/slatepack/slatepack_import_flow.dart'; -import '../../../../pages/slatepack/slatepack_input_field.dart'; +import '../../../../pages/slatepack/slatepack_view.dart'; import '../../../../providers/providers.dart'; import '../../../../providers/ui/preview_tx_button_state_provider.dart'; import '../../../../route_generator.dart'; @@ -52,7 +51,6 @@ import '../../../../widgets/conditional_parent.dart'; import '../../../../widgets/custom_buttons/app_bar_icon_button.dart'; import '../../../../widgets/custom_loading_overlay.dart'; import '../../../../widgets/desktop/desktop_dialog.dart'; -import '../../../../widgets/desktop/primary_button.dart'; import '../../../../widgets/desktop/secondary_button.dart'; import '../../../../widgets/slatepack_method_toggle.dart'; import '../../../../widgets/qr.dart'; @@ -81,10 +79,7 @@ class _DesktopReceiveState extends ConsumerState { late final bool supportsSpark; late bool supportsMweb; late final bool showMultiType; - late final bool usesSlatepacks; - late final TextEditingController _receiveSlateController; late final SlatepackTerms _slatepackTerms; - bool _importingSlatepack = false; int _currentIndex = 0; @@ -92,26 +87,6 @@ class _DesktopReceiveState extends ConsumerState { final Map _addressMap = {}; final Map> _addressSubMap = {}; - Future _onImportSlatepackPressed() async { - if (_importingSlatepack) return; - setState(() => _importingSlatepack = true); - try { - final wallet = - ref.read(pWallets).getWallet(walletId) as SlatepackInterface; - final done = await SlatepackImportFlow.run( - context: context, - wallet: wallet, - text: _receiveSlateController.text, - ); - if (done && mounted) { - setState(() => _receiveSlateController.text = ""); - } - } finally { - _importingSlatepack = false; - if (mounted) setState(() {}); - } - } - Future generateNewAddress() async { final wallet = ref.read(pWallets).getWallet(walletId); if (wallet is MultiAddressInterface) { @@ -284,7 +259,6 @@ class _DesktopReceiveState extends ConsumerState { @override void initState() { - _receiveSlateController = TextEditingController(); walletId = widget.walletId; coin = ref.read(pWalletInfo(walletId)).coin; clipboard = widget.clipboard; @@ -295,7 +269,6 @@ class _DesktopReceiveState extends ConsumerState { !wallet.info.isViewOnly && wallet.info.isMwebEnabled; - usesSlatepacks = wallet is SlatepackInterface; _slatepackTerms = wallet is SlatepackInterface ? wallet.slatepackTerms : SlatepackTerms.slatepack; @@ -350,7 +323,6 @@ class _DesktopReceiveState extends ConsumerState { @override void dispose() { - _receiveSlateController.dispose(); for (final subscription in _addressSubMap.values) { subscription.cancel(); } @@ -725,38 +697,22 @@ class _DesktopReceiveState extends ConsumerState { ), ), ], - if (isSlatepackMode) ...[ - Text( - "Import ${_slatepackTerms.title}", - style: STextStyles.desktopTextExtraSmall(context).copyWith( - color: Theme.of(context) - .extension()! - .textFieldActiveSearchIconRight, - ), - textAlign: TextAlign.left, - ), - const SizedBox(height: 8), - SlatepackInputField( - controller: _receiveSlateController, - hint: "Enter ${_slatepackTerms.payload}", - terms: _slatepackTerms, + if (isSlatepackMode) + SlatepackImportForm( + walletId: walletId, clipboard: clipboard, - onChanged: (_) => setState(() {}), - ), - const SizedBox(height: 16), - PrimaryButton( - buttonHeight: ButtonHeight.l, - label: "Import ${_slatepackTerms.title}", - enabled: - _receiveSlateController.text.trim().isNotEmpty && - !_importingSlatepack, - onPressed: - _receiveSlateController.text.trim().isNotEmpty && - !_importingSlatepack - ? _onImportSlatepackPressed - : null, + buttonLabel: "Import ${_slatepackTerms.title}", + expandToFill: false, + header: Text( + "Import ${_slatepackTerms.title}", + style: STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textFieldActiveSearchIconRight, + ), + textAlign: TextAlign.left, + ), ), - ], ], ); } 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 977cee09e4..738dd757ce 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 @@ -125,6 +125,7 @@ class _DesktopSendState extends ConsumerState { late final bool hasOptionalMemo; late final bool usesSlatepacks; + bool _creatingSlatepack = false; void _formatMimblewimbleAddress() { var address = sendToController.text.trim(); @@ -270,11 +271,33 @@ class _DesktopSendState extends ConsumerState { final wallet = ref.read(pWallets).getWallet(walletId); final isSlatepackSend = wallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); + + if (isSlatepackSend) { + final Amount? amount = ref.read(pSendAmount); + if (amount == null || amount <= Amount.zero) return; + if (_creatingSlatepack) return; + _creatingSlatepack = true; + try { + final created = await SlatepackSendFlow.run( + context: context, + wallet: wallet, + amount: amount, + message: _onChainNote ?? "", + localNote: _note ?? "", + db: ref.read(mainDBProvider), + format: ref.read(pAmountFormatter(wallet.cryptoCurrency)).format, + ); + if (created && mounted) clearSendForm(); + } finally { + _creatingSlatepack = false; + } + return; + } + String? openAlias; String? resolvedAddress; final application = coin.openAliasApplication; if (application != null && - !isSlatepackSend && !coin.validateAddress(_address ?? "") && isOpenAlias(_address ?? "")) { var resolved = _openAlias; @@ -291,20 +314,6 @@ class _DesktopSendState extends ConsumerState { late final recipientAddress = resolvedAddress ?? _address!; final Amount amount = ref.read(pSendAmount)!; - if (isSlatepackSend) { - final created = await SlatepackSendFlow.run( - context: context, - wallet: wallet, - amount: amount, - message: _onChainNote ?? "", - localNote: _note ?? "", - db: ref.read(mainDBProvider), - format: ref.read(pAmountFormatter(wallet.cryptoCurrency)).format, - ); - if (created && mounted) clearSendForm(); - return; - } - final Amount availableBalance; if (coin is Firo || ref.read(pWalletInfo(walletId)).isMwebEnabled) { switch (ref.read(publicPrivateBalanceStateProvider.state).state) { @@ -728,6 +737,8 @@ class _DesktopSendState extends ConsumerState { return; } _openAlias = null; + _note = null; + _onChainNote = null; sendToController.text = ""; cryptoAmountController.text = ""; baseAmountController.text = ""; @@ -1336,9 +1347,6 @@ class _DesktopSendState extends ConsumerState { baseAmountController = TextEditingController(); memoController = TextEditingController(); nonceController = TextEditingController(); - if (coin is Epiccash || coin is Mimblewimblecoin) { - sendToController.addListener(_formatMimblewimbleAddress); - } onCryptoAmountChanged = _cryptoAmountChanged; cryptoAmountController.addListener(onCryptoAmountChanged); @@ -1367,6 +1375,10 @@ class _DesktopSendState extends ConsumerState { }); } + if (coin is Epiccash || coin is Mimblewimblecoin) { + sendToController.addListener(_formatMimblewimbleAddress); + } + if (isPaynymSend) { sendToController.text = widget.accountLite!.nymName; WidgetsBinding.instance.addPostFrameCallback( @@ -1909,9 +1921,7 @@ class _DesktopSendState extends ConsumerState { ), decoration: standardInputDecoration( - ref.watch(pIsSlatepack(widget.walletId)) - ? "Enter ${coin.ticker} address (optional)" - : "Enter ${coin.ticker} address", + "Enter ${coin.ticker} address", _addressFocusNode, context, desktopMed: true, @@ -2050,10 +2060,6 @@ class _DesktopSendState extends ConsumerState { } else { if (_data != null && _data.contactLabel == _address) { error = null; - } else if (usesSlatepacks && - ref.watch(pIsSlatepack(widget.walletId))) { - // Slatepack sends have no address to validate. - error = null; } else if (!ref.watch(pValidSendToAddress)) { error = "Invalid address"; } else { diff --git a/lib/providers/ui/preview_tx_button_state_provider.dart b/lib/providers/ui/preview_tx_button_state_provider.dart index 1b5d4540f6..c7c90665f1 100644 --- a/lib/providers/ui/preview_tx_button_state_provider.dart +++ b/lib/providers/ui/preview_tx_button_state_provider.dart @@ -14,6 +14,7 @@ import '../../utilities/amount/amount.dart'; import '../../utilities/enums/slatepack_method.dart'; import '../../wallets/crypto_currency/crypto_currency.dart'; import '../../wallets/isar/providers/wallet_info_provider.dart'; +import '../../wallets/wallet/wallet.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../global/wallets_provider.dart'; import '../wallet/public_private_balance_state_provider.dart'; @@ -30,8 +31,14 @@ final pOpReturnData = StateProvider.autoDispose((_) => null); // Starts at the wallet's default (Epic Cash: epicbox, MWC: slatepack). final pSelectedSlatepackMethod = StateProvider.family( (ref, walletId) { - final wallet = ref.read(pWallets).getWallet(walletId); - return wallet is SlatepackInterface ? wallet.supportedMethods.first : null; + try { + final wallet = ref.read(pWallets).getWallet(walletId); + return wallet is SlatepackInterface + ? wallet.supportedMethods.firstOrNull + : null; + } catch (_) { + return null; + } }, ); @@ -53,7 +60,11 @@ final pPreviewTxButtonEnabled = Provider.autoDispose.family(( } // Slatepack transactions have no address to validate. - if (ref.watch(pIsSlatepack(walletId))) { + Wallet? wallet; + try { + wallet = ref.watch(pWallets.select((w) => w.getWallet(walletId))); + } catch (_) {} + if (wallet is SlatepackInterface && ref.watch(pIsSlatepack(walletId))) { return amount > Amount.zero; } diff --git a/lib/route_generator.dart b/lib/route_generator.dart index ba6ae2ce0f..63803b9c7c 100644 --- a/lib/route_generator.dart +++ b/lib/route_generator.dart @@ -112,9 +112,9 @@ import 'pages/salvium_stake/salvium_create_stake_view.dart'; import 'pages/send_view/confirm_transaction_view.dart'; import 'pages/send_view/frost_ms/frost_send_view.dart'; import 'pages/send_view/send_view.dart'; -import 'pages/slatepack/slatepack_view.dart'; import 'pages/send_view/sol_token_send_view.dart'; import 'pages/send_view/token_send_view.dart'; +import 'pages/slatepack/slatepack_view.dart'; import 'pages/settings_views/global_settings_view/about_view.dart'; import 'pages/settings_views/global_settings_view/advanced_views/advanced_settings_view.dart'; import 'pages/settings_views/global_settings_view/advanced_views/logging_settings_view.dart'; diff --git a/lib/utilities/enums/slatepack_method.dart b/lib/utilities/enums/slatepack_method.dart index a9b3006523..f244136554 100644 --- a/lib/utilities/enums/slatepack_method.dart +++ b/lib/utilities/enums/slatepack_method.dart @@ -4,20 +4,10 @@ enum SlatepackMethod { slatepack("Slatepack"), /// Automatic exchange through the coin's relay server (epicbox, mwcmqs). - relay("Automatic"), - - /// Direct send to the recipient's listener (http(s), Tor). - http("Address"); + relay("Automatic"); const SlatepackMethod(this.label); /// Label on the method toggle. final String label; - - static SlatepackMethod? fromName(String? name) { - for (final m in values) { - if (m.name == name) return m; - } - return null; - } } diff --git a/lib/utilities/route_presentation.dart b/lib/utilities/route_presentation.dart index 10eb33b5e9..25214fcee8 100644 --- a/lib/utilities/route_presentation.dart +++ b/lib/utilities/route_presentation.dart @@ -22,11 +22,15 @@ class CurrentAwareDialogRoute extends DialogRoute { } Future waitUntilCurrent() async { - if (!isActive || isCurrent) return; - final waiter = Completer(); - _currentWaiters.add(waiter); - await Future.any([waiter.future, popped]); - _currentWaiters.remove(waiter); + while (isActive && !isCurrent) { + final waiter = Completer(); + _currentWaiters.add(waiter); + try { + await Future.any([waiter.future, popped]); + } finally { + _currentWaiters.remove(waiter); + } + } } @override @@ -65,22 +69,26 @@ Future dismissCurrentAwareDialogRoute({ return true; } -/// Completes after [route] has finished appearing. +/// Completes with true after [route] has finished appearing, or false if the +/// route was popped/disposed before finishing its entrance transition. /// /// Some native wallet calls do synchronous work before returning their /// Future. Waiting for the first frame is not enough for a transition route: /// its contents can be built while the route opacity is still zero. -Future waitForRoutePresentation(TransitionRoute route) async { +Future waitForRoutePresentation(TransitionRoute route) async { + if (!route.isActive) return false; + await WidgetsBinding.instance.endOfFrame; + if (!route.isActive) return false; final animation = route.animation; if (animation == null) { - return; + return route.isActive; } if (animation.status == AnimationStatus.completed) { await WidgetsBinding.instance.endOfFrame; - return; + return route.isActive; } final completer = Completer(); @@ -97,12 +105,115 @@ Future waitForRoutePresentation(TransitionRoute route) async { final appeared = await Future.any([ completer.future.then((_) => true), route.popped.then((_) => false), + route.completed.then((_) => false), ]); - if (appeared && animation.status == AnimationStatus.completed) { + if (appeared && + route.isActive && + animation.status == AnimationStatus.completed) { // Animation completion precedes the paint of its final frame. await WidgetsBinding.instance.endOfFrame; } } finally { animation.removeStatusListener(listener); } + return route.isActive && animation.status == AnimationStatus.completed; +} + +bool isHostRouteCurrent(BuildContext context, NavigatorState root) { + if (ModalRoute.of(context)?.isCurrent == false) return false; + var nav = Navigator.maybeOf(context); + while (nav != null && nav != root) { + final hostRoute = ModalRoute.of(nav.context); + if (hostRoute != null && !hostRoute.isCurrent) return false; + nav = Navigator.maybeOf(nav.context); + } + return true; +} + +/// Pushes a non-dismissible [CurrentAwareDialogRoute], waits for it to finish +/// appearing, runs [action], and guarantees cleanup even if [action] throws. +Future< + ({ + T? value, + Object? error, + StackTrace? stackTrace, + bool canPresentResult, + bool aborted, + }) +> +runWithCurrentAwareOverlay({ + required BuildContext context, + required WidgetBuilder builder, + required Future Function() action, + bool useSafeArea = true, +}) async { + if (!context.mounted) { + return ( + value: null, + error: null, + stackTrace: null, + canPresentResult: false, + aborted: true, + ); + } + + final root = Navigator.of(context, rootNavigator: true); + if (!isHostRouteCurrent(context, root)) { + return ( + value: null, + error: null, + stackTrace: null, + canPresentResult: false, + aborted: true, + ); + } + + final overlay = CurrentAwareDialogRoute( + context: context, + barrierDismissible: false, + useSafeArea: useSafeArea, + themes: InheritedTheme.capture(from: context, to: root.context), + builder: builder, + ); + unawaited(root.push(overlay)); + + final presented = await waitForRoutePresentation(overlay); + if (!presented || !overlay.isCurrent) { + if (root.mounted && overlay.isActive) { + await dismissCurrentAwareDialogRoute(navigator: root, route: overlay); + } + return ( + value: null, + error: null, + stackTrace: null, + canPresentResult: false, + aborted: true, + ); + } + + T? value; + Object? error; + StackTrace? stackTrace; + var canPresentResult = false; + try { + value = await action(); + } catch (e, s) { + error = e; + stackTrace = s; + } finally { + if (root.mounted && overlay.isActive) { + canPresentResult = await dismissCurrentAwareDialogRoute( + navigator: root, + route: overlay, + ); + } + } + + return ( + value: value, + error: error, + stackTrace: stackTrace, + canPresentResult: canPresentResult, + aborted: false, + ); } diff --git a/lib/utilities/slatepack_text.dart b/lib/utilities/slatepack_text.dart index b9ab3e897e..cf7e6b4f38 100644 --- a/lib/utilities/slatepack_text.dart +++ b/lib/utilities/slatepack_text.dart @@ -12,10 +12,16 @@ abstract final class SlatepackText { /// Removes surrounding prose from an armored Slatepack. /// - /// Plain slate JSON and unrecognized text are only trimmed. + /// Plain slate JSON and unrecognized text (including multiple concatenated + /// frames) are only trimmed so ambiguous inputs fail validation instead of + /// silently taking the first frame. static String normalize(String text) { final trimmed = text.trim(); - if (trimmed.startsWith("{")) return trimmed; - return _armoredFrame.firstMatch(trimmed)?.group(0) ?? trimmed; + if (trimmed.startsWith("{") && trimmed.endsWith("}")) return trimmed; + final matches = _armoredFrame.allMatches(trimmed).toList(); + if (matches.length == 1) { + return matches.single.group(0)!; + } + return trimmed; } } diff --git a/lib/wallets/crypto_currency/coins/epiccash.dart b/lib/wallets/crypto_currency/coins/epiccash.dart index 9dc848c362..665c0ec7b8 100644 --- a/lib/wallets/crypto_currency/coins/epiccash.dart +++ b/lib/wallets/crypto_currency/coins/epiccash.dart @@ -159,9 +159,8 @@ class Epiccash extends Bip39Currency { SlatepackMethod getTransactionMethod(String addressOrData) { if (isSlateJson(addressOrData)) { return SlatepackMethod.slatepack; - } else if (isHttpAddress(addressOrData)) { - return SlatepackMethod.http; - } else if (isEpicboxAddress(addressOrData)) { + } else if (isEpicboxAddress(addressOrData) || + isHttpAddress(addressOrData)) { return SlatepackMethod.relay; } else { throw Exception("Unknown SlatepackMethod found!"); diff --git a/lib/wallets/wallet/impl/epiccash_wallet.dart b/lib/wallets/wallet/impl/epiccash_wallet.dart index d6f3a8117b..64823583d4 100644 --- a/lib/wallets/wallet/impl/epiccash_wallet.dart +++ b/lib/wallets/wallet/impl/epiccash_wallet.dart @@ -46,11 +46,6 @@ import '../supporting/epiccash_wallet_info_extension.dart'; import '../supporting/restore_progress.dart'; import '../wallet_mixin_interfaces/slatepack_interface.dart'; -/// Epic's pinned native API broadcasts inside finalize and throws when that -/// broadcast fails. Older result objects omit the redundant `posted` field. -@visibleForTesting -bool epicFinalizeBroadcastResult(bool? posted) => posted ?? true; - // // refactor of https://github.com/cypherstack/stack_wallet/blob/1d9fb4cd069f22492ece690ac788e05b8f8b1209/lib/services/coins/epiccash/epiccash_wallet.dart // @@ -78,8 +73,14 @@ class EpiccashWallet extends Bip39Wallet with SlatepackInterface { SlatepackTerms get slatepackTerms => SlatepackTerms.slate; @override - Map get slatepackTransactionMetadata => - info.epicData?.slatesToCommits ?? const {}; + Map get slatepackTransactionMetadata { + try { + if (!mainDB.isar.isOpen) return const {}; + return info.epicData?.slatesToCommits ?? const {}; + } catch (_) { + return const {}; + } + } @override Future updateSlatepackTransactionMetadata( @@ -258,7 +259,7 @@ class EpiccashWallet extends Bip39Wallet with SlatepackInterface { slatepack: result.slateJson, slateJson: result.slateJson, wasEncrypted: false, - recipientAddress: recipientAddress, + recipientAddress: null, state: SlateState.s1, slateId: result.slateId, amount: inspection?.amount, @@ -298,10 +299,7 @@ class EpiccashWallet extends Bip39Wallet with SlatepackInterface { /// Receive a slatepack and return response slate JSON. @override - Future receiveSlatepack( - String slateJson, { - required SlateInspection inspection, - }) async { + Future receiveSlatepack(SlateInspection inspection) async { try { _hackedCheckTorNodePrefs(); if (_wallet == null) { @@ -311,11 +309,11 @@ class EpiccashWallet extends Bip39Wallet with SlatepackInterface { // Receive and get updated slate JSON. final received = await libEpic.txReceive( wallet: _wallet!, - slateJson: inspection.slateJson ?? slateJson, + slateJson: inspection.slateJson, ); final responseInspection = inspectSlateJsonString(received.slateJson); - return SlatepackResult( + final response = SlatepackResult( success: true, slatepack: received.slateJson, slateJson: received.slateJson, @@ -326,6 +324,8 @@ class EpiccashWallet extends Bip39Wallet with SlatepackInterface { amount: responseInspection?.amount ?? inspection.amount, fee: responseInspection?.fee ?? inspection.fee, ); + rememberPendingSlateReceive(response); + return response; } catch (e, s) { Logging.instance.e('Failed to receive slatepack: $e\n$s'); return SlatepackResult(success: false, error: e.toString()); @@ -334,10 +334,7 @@ class EpiccashWallet extends Bip39Wallet with SlatepackInterface { /// Finalize a slatepack (sender step 3). @override - Future finalizeSlatepack( - String slateJson, { - required SlateInspection inspection, - }) async { + Future finalizeSlatepack(SlateInspection inspection) async { try { _hackedCheckTorNodePrefs(); if (_wallet == null) { @@ -347,14 +344,16 @@ class EpiccashWallet extends Bip39Wallet with SlatepackInterface { // Finalize transaction. final finalized = await libEpic.txFinalize( wallet: _wallet!, - slateJson: inspection.slateJson ?? slateJson, + slateJson: inspection.slateJson, ); return FinalizeResult( success: true, slateId: finalized.slateId, commitId: finalized.commitId, - posted: epicFinalizeBroadcastResult(finalized.posted), + // Pinned flutter_libepiccash calls owner_api.post_tx(..., true)? + // inside tx_finalize and throws if broadcast fails. + posted: true, ); } catch (e, s) { Logging.instance.e('Failed to finalize slatepack: $e\n$s'); diff --git a/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart b/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart index 0fc40ae1fc..f8fa5ce614 100644 --- a/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart +++ b/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart @@ -30,6 +30,7 @@ import '../../../utilities/enums/slatepack_method.dart'; import '../../../utilities/flutter_secure_storage_interface.dart'; import '../../../utilities/logger.dart'; import '../../../utilities/slatepack_terms.dart'; +import '../../../utilities/slatepack_text.dart'; import '../../../utilities/stack_file_system.dart'; import '../../../utilities/test_mwcmqs_connection.dart'; import '../../../wl_gen/interfaces/libmwc_interface.dart'; @@ -81,8 +82,14 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; @override - Map get slatepackTransactionMetadata => - info.mimblewimblecoinData?.slatesToCommits ?? const {}; + Map get slatepackTransactionMetadata { + try { + if (!mainDB.isar.isOpen) return const {}; + return info.mimblewimblecoinData?.slatesToCommits ?? const {}; + } catch (_) { + return const {}; + } + } @override Future updateSlatepackTransactionMetadata( @@ -228,11 +235,12 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { String? recipientAddress, String? message, }) async { + String? s1Json; try { final handle = await _ensureWalletOpen(); // Generate S1 slate JSON. - final s1Json = await libMwc.txInit( + s1Json = await libMwc.txInit( wallet: handle, amount: amount.raw.toInt(), minimumConfirmations: cryptoCurrency.minConfirms, @@ -240,11 +248,14 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { message: message ?? '', ); + final recipient = recipientAddress?.trim(); + final encrypt = recipient != null && recipient.isNotEmpty; + // Encode to slatepack. final encoded = await libMwc.encodeSlatepack( slateJson: s1Json, - recipientAddress: recipientAddress, - encrypt: recipientAddress != null, + recipientAddress: encrypt ? recipient : null, + encrypt: encrypt, wallet: handle, ); @@ -263,8 +274,32 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { await rememberPendingSlateSend(slatepack); return slatepack; } catch (e, s) { + var errorMessage = e.toString(); + if (s1Json != null) { + final slateId = inspectSlateJsonString(s1Json)?.slateId; + if (slateId != null && slateId.isNotEmpty) { + final cancelError = await cancelPendingTransactionAndPost(slateId); + if (cancelError.isNotEmpty) { + Logging.instance.w( + 'Failed to roll back pending slate $slateId after encode ' + 'failure: $cancelError', + ); + errorMessage = + '$errorMessage (Note: failed to cancel pending transaction: ' + '$cancelError)'; + } + } + } Logging.instance.e('Failed to create slatepack: $e\n$s'); - return SlatepackResult(success: false, error: e.toString()); + return SlatepackResult(success: false, error: errorMessage); + } + } + + bool _isValidSlateJson(String json) { + try { + return jsonDecode(json) is Map; + } catch (_) { + return false; } } @@ -272,12 +307,44 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { @override Future decodeSlatepack(String armored) async { try { - final result = _walletHandle == null - ? await _decodeSlatepackWithClosedWallet(armored) - : await libMwc.decodeSlatepackWithWallet( - wallet: _walletHandle!, - slatepack: armored, - ); + // Ensure the wallet handle / Rust GLOBAL_CHAIN_TYPE is initialized before + // calling mwc_rust_decode_slatepack (which panics on BEGINSLATE_BIN. if + // unset), then try unencrypted decode first to avoid taking wallet.lock. + final cachedHandle = _walletHandle; + final String handle; + if (cachedHandle != null && cachedHandle.isNotEmpty) { + handle = cachedHandle; + } else { + try { + handle = await _ensureWalletOpen(); + } catch (e) { + throw _SlatepackWalletUnavailable(e); + } + } + + try { + final plain = await libMwc.decodeSlatepack(slatepack: armored); + if (_isValidSlateJson(plain.slateJson)) { + return SlatepackDecodeResult( + success: true, + slateJson: plain.slateJson, + wasEncrypted: plain.wasEncrypted, + senderAddress: plain.senderAddress, + recipientAddress: plain.recipientAddress, + ); + } + } catch (_) {} + + final result = await libMwc.decodeSlatepackWithWallet( + wallet: handle, + slatepack: armored, + ); + if (!_isValidSlateJson(result.slateJson)) { + return SlatepackDecodeResult( + success: false, + failure: SlatepackDecodeFailure.invalidInput, + ); + } return SlatepackDecodeResult( success: true, @@ -301,33 +368,6 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { } } - Future< - ({ - String? recipientAddress, - String? senderAddress, - String slateJson, - bool wasEncrypted, - }) - > - _decodeSlatepackWithClosedWallet(String slatepack) async { - try { - // Preserve the existing no-wallet path for unencrypted slatepacks. - return await libMwc.decodeSlatepack(slatepack: slatepack); - } catch (_) { - // Encrypted slatepacks need this wallet's keys. - final String handle; - try { - handle = await _ensureWalletOpen(); - } catch (e) { - throw _SlatepackWalletUnavailable(e); - } - return libMwc.decodeSlatepackWithWallet( - wallet: handle, - slatepack: slatepack, - ); - } - } - @override void checkSlatepackFormat(String armored) { if (!isSlatepack(armored)) { @@ -337,39 +377,41 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { /// Receive a slatepack and return response slatepack. @override - Future receiveSlatepack( - String slatepack, { - required SlateInspection inspection, - }) async { + Future receiveSlatepack(SlateInspection inspection) async { try { final handle = await _ensureWalletOpen(); // Receive and get updated slate JSON. final received = await libMwc.txReceiveDetailed( wallet: handle, - slateJson: inspection.slateJson!, + slateJson: inspection.slateJson, ); + final recipient = inspection.senderAddress?.trim(); + final encrypt = recipient != null && recipient.isNotEmpty; + // Encode response back to sender if address available. final encoded = await libMwc.encodeSlatepack( slateJson: received.slateJson, - recipientAddress: inspection.senderAddress, - encrypt: inspection.senderAddress != null, + recipientAddress: encrypt ? recipient : null, + encrypt: encrypt, wallet: handle, ); final responseInspection = inspectSlateJsonString(received.slateJson); - return SlatepackResult( + final response = SlatepackResult( success: true, slatepack: encoded.slatepack, slateJson: received.slateJson, slateId: received.slateId, wasEncrypted: encoded.wasEncrypted, - recipientAddress: inspection.senderAddress, + recipientAddress: encrypt ? recipient : null, state: SlateState.s2, amount: responseInspection?.amount ?? inspection.amount, fee: responseInspection?.fee ?? inspection.fee, ); + rememberPendingSlateReceive(response); + return response; } catch (e, s) { Logging.instance.e('Failed to receive slatepack: $e\n$s'); return SlatepackResult(success: false, error: e.toString()); @@ -378,24 +420,23 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { /// Finalize a slatepack (sender step 3). @override - Future finalizeSlatepack( - String slatepack, { - required SlateInspection inspection, - }) async { + Future finalizeSlatepack(SlateInspection inspection) async { try { final handle = await _ensureWalletOpen(); // Finalize transaction. final finalized = await libMwc.txFinalize( wallet: handle, - slateJson: inspection.slateJson!, + slateJson: inspection.slateJson, ); return FinalizeResult( success: true, slateId: finalized.slateId, commitId: finalized.commitId, - posted: finalized.posted, + // Pinned flutter_libmwc logs and swallows post_tx errors inside + // _tx_finalize_core, so broadcast status is unavailable. + posted: null, ); } catch (e, s) { Logging.instance.e('Failed to finalize slatepack: $e\n$s'); @@ -433,13 +474,7 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { } /// Detect if an address is a slatepack. - bool isSlatepack(String data) { - return data.trim().startsWith('BEGINSLATE') && - (data.trim().endsWith('ENDSLATEPACK') || - data.trim().endsWith('ENDSLATEPACK.') || - data.trim().endsWith('ENDSLATE_BIN') || - data.trim().endsWith('ENDSLATE_BIN.')); - } + bool isSlatepack(String data) => SlatepackText.isArmored(data); /// Detect if an address is MWCMQS format. bool isMwcmqsAddress(String address) { diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart index 795140ade7..43837b7f89 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart @@ -15,18 +15,20 @@ import '../wallet.dart'; /// Slatepack exchange shared by the Mimblewimble coins. The slatepack /// screens talk to this instead of a concrete wallet type. -/// mixin SlatepackInterface on Wallet { final Map< String, ({Amount amount, Amount fee, bool isSend, bool isCancelled}) > _pendingSlateTransactions = {}; + final Set _cancelledSlateIds = {}; + + String _normalizeSlateId(String slateId) => slateId.trim().toLowerCase(); /// Methods the send and receive screens offer. The first is the default. List get supportedMethods; - /// Whether a send can carry a message that ends up on chain. + /// Whether a slate send can carry a participant message. bool get supportsOnChainNote; /// Whether this wallet can encrypt slatepacks to another wallet's address. @@ -34,7 +36,8 @@ mixin SlatepackInterface on Wallet { /// Whether send/receive should offer a method selector. bool get hasSlatepackMethodToggle => - supportedMethods.any((method) => method != SlatepackMethod.slatepack); + supportedMethods.length > 1 && + supportedMethods.contains(SlatepackMethod.slatepack); /// "slate" or "slatepack" wording for this coin. SlatepackTerms get slatepackTerms => SlatepackTerms.slatepack; @@ -50,10 +53,6 @@ mixin SlatepackInterface on Wallet { Map metadata, ) async {} - /// The address another wallet encrypts a slatepack to. - Future slatepackAddress() async => - (await getCurrentReceivingAddress())?.value ?? ""; - /// Decode [armored] without changing wallet state. Future decodeSlatepack(String armored); @@ -88,7 +87,18 @@ mixin SlatepackInterface on Wallet { ); } - final dynamic json = jsonDecode(decoded.slateJson!); + final dynamic json; + try { + json = jsonDecode(decoded.slateJson!); + } on FormatException { + final encryptionCause = supportsSlatepackEncryption + ? ", incomplete, or encrypted for another wallet" + : " or incomplete"; + throw Exception( + "This ${slatepackTerms.noun} could not be decoded. It may be damaged" + "$encryptionCause.", + ); + } if (json is! Map) { throw Exception("Not a ${slatepackTerms.noun}"); } @@ -96,7 +106,7 @@ mixin SlatepackInterface on Wallet { final inspection = inspectSlateJson( json, fractionDigits: cryptoCurrency.fractionDigits, - slateJson: decoded.slateJson, + slateJson: decoded.slateJson!, isEncrypted: decoded.wasEncrypted ?? false, senderAddress: decoded.senderAddress, recipientAddress: decoded.recipientAddress, @@ -111,116 +121,224 @@ mixin SlatepackInterface on Wallet { /// not be finalized. Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> localTxForSlate(String slateId) async { - if (slateId.isEmpty) return null; - - // A slate created in this process is authoritative and immediately - // available, even while Isar is shutting down or before native history is - // refreshed. - final inMemory = _pendingSlateTransactions[slateId]; - if (inMemory != null) return inMemory; - - final tx = localSlateTransaction( - await mainDB.isar.transactionV2s - .where() - .walletIdEqualTo(walletId) - .filter() - .otherDataContains(slateId) - .findAll(), - slateId, - ); - final pending = pendingSlateSendMatching( - slatepackTransactionMetadata, - slateId, - fractionDigits: cryptoCurrency.fractionDigits, - ); - if (tx == null) return pending; + final id = _normalizeSlateId(slateId); + if (id.isEmpty) return null; + + final inMemory = _pendingSlateTransactions[id]; + ({Amount amount, Amount fee, bool isSend, bool isCancelled})? pending; + try { + pending = pendingSlateSendMatching( + slatepackTransactionMetadata, + id, + fractionDigits: cryptoCurrency.fractionDigits, + ); + } catch (e, s) { + Logging.instance.w( + "Could not read local slate metadata for $slateId", + error: e, + stackTrace: s, + ); + } + + TransactionV2? tx; + try { + if (mainDB.isar.isOpen) { + tx = localSlateTransaction( + await mainDB.isar.transactionV2s + .where() + .walletIdEqualTo(walletId) + .filter() + .otherDataContains(id, caseSensitive: false) + .findAll(), + id, + ); + } + } catch (e, s) { + Logging.instance.w( + "Could not query local transactions for slate $slateId", + error: e, + stackTrace: s, + ); + } + + if (tx == null) { + final fallback = inMemory ?? pending; + if (fallback == null) return null; + return ( + amount: fallback.amount, + fee: fallback.fee, + isSend: fallback.isSend, + isCancelled: fallback.isCancelled || _cancelledSlateIds.contains(id), + ); + } final digits = cryptoCurrency.fractionDigits; - final isSend = tx.type == TransactionType.outgoing; - return ( - amount: isSend + final isSend = + tx.type == TransactionType.outgoing || + tx.type == TransactionType.sentToSelf; + final Amount amount; + if (tx.type == TransactionType.sentToSelf) { + final sentAmount = tx.getAmountSentFromThisWallet( + fractionDigits: digits, + subtractFee: true, + ); + amount = + inMemory?.amount ?? + pending?.amount ?? + (sentAmount.raw > BigInt.zero + ? sentAmount + : tx.getAmountReceivedInThisWallet(fractionDigits: digits)); + } else { + amount = isSend ? tx.getAmountSentFromThisWallet( fractionDigits: digits, subtractFee: true, ) - : tx.getAmountReceivedInThisWallet(fractionDigits: digits), + : tx.getAmountReceivedInThisWallet(fractionDigits: digits); + } + return ( + amount: amount, fee: tx.getFee(fractionDigits: digits), isSend: isSend, - isCancelled: tx.isCancelled || (isSend && pending?.isCancelled == true), + isCancelled: + tx.isCancelled || + _cancelledSlateIds.contains(id) || + (isSend && + (inMemory?.isCancelled == true || pending?.isCancelled == true)), ); } + ({String key, Map? entry}) _findMetadataEntry( + Map metadata, + String rawSlateId, + String normalizedId, + ) { + for (final entry in metadata.entries) { + if (entry.key?.toString().trim().toLowerCase() == normalizedId && + entry.value is Map) { + return ( + key: entry.key.toString(), + entry: entry.value as Map, + ); + } + } + return (key: rawSlateId.trim(), entry: null); + } + /// Persists ownership as soon as an S1 is created, before a refresh can /// copy the native transaction into Isar. @protected Future rememberPendingSlateSend(SlatepackResult result) async { - final slateId = result.slateId; + final rawSlateId = result.slateId; final amount = result.amount; final fee = result.fee; - if (slateId == null || slateId.isEmpty || amount == null || fee == null) { + if (rawSlateId == null || amount == null || fee == null) { return; } + final id = _normalizeSlateId(rawSlateId); + if (id.isEmpty) return; - _pendingSlateTransactions[slateId] = ( + _pendingSlateTransactions[id] = ( amount: amount, fee: fee, isSend: true, isCancelled: false, ); - final metadata = Map.from(slatepackTransactionMetadata); - final existing = metadata[slateId]; - final entry = existing is Map - ? Map.from(existing) - : {}; - entry.addAll({ - 'amount': amount.raw.toString(), - 'fee': fee.raw.toString(), - 'isSend': true, - 'isCancelled': false, - }); - metadata[slateId] = entry; try { + final metadata = Map.from(slatepackTransactionMetadata); + final match = _findMetadataEntry(metadata, rawSlateId, id); + final entry = match.entry != null + ? Map.from(match.entry!) + : {}; + entry.addAll({ + 'amount': amount.raw.toString(), + 'fee': fee.raw.toString(), + 'isSend': true, + 'isCancelled': false, + }); + metadata[match.key] = entry; await updateSlatepackTransactionMetadata(metadata); } catch (e, s) { Logging.instance.w( - "Could not persist ownership for slate $slateId", + "Could not persist ownership for slate $rawSlateId", error: e, stackTrace: s, ); } } + /// Records a pending S1 receive immediately in memory so re-importing the S1 + /// or importing our own S2 is blocked before the next wallet refresh. @protected - Future rememberPendingSlateCancelled(String slateId) async { - final metadata = Map.from(slatepackTransactionMetadata); - final raw = metadata[slateId]; - final pending = - _pendingSlateTransactions[slateId] ?? - pendingSlateSendMatching( - metadata, - slateId, - fractionDigits: cryptoCurrency.fractionDigits, - ); - if (pending == null) return; - - _pendingSlateTransactions[slateId] = ( - amount: pending.amount, - fee: pending.fee, - isSend: true, - isCancelled: true, + void rememberPendingSlateReceive(SlatepackResult result) { + final rawSlateId = result.slateId; + if (rawSlateId == null) return; + final id = _normalizeSlateId(rawSlateId); + if (id.isEmpty) return; + + _pendingSlateTransactions[id] = ( + amount: + result.amount ?? + Amount.zeroWith(fractionDigits: cryptoCurrency.fractionDigits), + fee: + result.fee ?? + Amount.zeroWith(fractionDigits: cryptoCurrency.fractionDigits), + isSend: false, + isCancelled: false, ); + } + + @protected + Future rememberPendingSlateCancelled(String slateId) async { + final id = _normalizeSlateId(slateId); + if (id.isEmpty) return; + + _cancelledSlateIds.add(id); + + final inMemory = _pendingSlateTransactions[id]; + if (inMemory != null) { + _pendingSlateTransactions[id] = ( + amount: inMemory.amount, + fee: inMemory.fee, + isSend: inMemory.isSend, + isCancelled: true, + ); + } - final entry = raw is Map - ? Map.from(raw) - : { - 'amount': pending.amount.raw.toString(), - 'fee': pending.fee.raw.toString(), - 'isSend': true, - }; - entry['isCancelled'] = true; - metadata[slateId] = entry; try { + final metadata = Map.from(slatepackTransactionMetadata); + final match = _findMetadataEntry(metadata, slateId, id); + final pending = + inMemory ?? + pendingSlateSendMatching( + metadata, + id, + fractionDigits: cryptoCurrency.fractionDigits, + ); + if (pending == null) return; + + _pendingSlateTransactions[id] = ( + amount: pending.amount, + fee: pending.fee, + isSend: pending.isSend, + isCancelled: true, + ); + + // Only persist sends (or updates to existing entries); + // pendingSlateSendMatching reads send metadata, while receives persist in + // Isar. + if (!pending.isSend && match.entry == null) return; + + final entry = match.entry != null + ? Map.from(match.entry!) + : { + 'amount': pending.amount.raw.toString(), + 'fee': pending.fee.raw.toString(), + 'isSend': pending.isSend, + }; + entry['isCancelled'] = true; + metadata[match.key] = entry; await updateSlatepackTransactionMetadata(metadata); } catch (e, s) { Logging.instance.w( @@ -258,16 +376,10 @@ mixin SlatepackInterface on Wallet { }); /// Answer an S1 with an S2. - Future receiveSlatepack( - String s1, { - required SlateInspection inspection, - }); + Future receiveSlatepack(SlateInspection inspection); /// Finalize an S2 from the recipient and post it. - Future finalizeSlatepack( - String s2, { - required SlateInspection inspection, - }); + Future finalizeSlatepack(SlateInspection inspection); /// Returns an empty String on success, error message on failure. Future cancelPendingTransactionAndPost(String slateId); @@ -281,8 +393,18 @@ pendingSlateSendMatching( String slateId, { required int fractionDigits, }) { - final raw = metadata[slateId]; - if (raw is! Map || raw['isSend'] != true) return null; + final target = slateId.trim().toLowerCase(); + if (target.isEmpty) return null; + + Map? raw; + for (final entry in metadata.entries) { + if (entry.key?.toString().trim().toLowerCase() == target && + entry.value is Map) { + raw = entry.value as Map; + break; + } + } + if (raw == null || raw['isSend'] != true) return null; final amount = BigInt.tryParse(raw['amount']?.toString() ?? ''); final fee = BigInt.tryParse(raw['fee']?.toString() ?? ''); @@ -301,11 +423,12 @@ pendingSlateSendMatching( SlateInspection inspectSlateJson( Map json, { required int fractionDigits, - String? slateJson, + String slateJson = '', bool isEncrypted = false, String? senderAddress, String? recipientAddress, }) { + final slateId = (json['id'] ?? '').toString().trim(); var state = SlateState.fromCode(json['sta']?.toString()); final dynamic participants = json['participant_data']; if (state == SlateState.unknown && @@ -313,7 +436,10 @@ SlateInspection inspectSlateJson( participants.isNotEmpty) { var signed = 0; for (final dynamic participant in participants) { - if (participant is Map && participant['part_sig'] != null) signed++; + if (participant is Map) { + final dynamic sig = participant['part_sig']; + if (sig is String && sig.isNotEmpty) signed++; + } } if (signed == 0) { state = SlateState.s1; @@ -323,53 +449,60 @@ SlateInspection inspectSlateJson( state = SlateState.s3; } } - - if (state == SlateState.unknown) { - if (senderAddress != null && recipientAddress != null) { - state = SlateState.s2; - } else if (senderAddress != null) { - state = SlateState.s1; - } + if (slateId.isEmpty) { + state = SlateState.unknown; } Amount? parseAmount(dynamic raw) { final value = BigInt.tryParse(raw?.toString() ?? ""); + if (value == null || value < BigInt.zero) return null; final isResponse = state == SlateState.s2 || state == SlateState.i2; if (isResponse && value == BigInt.zero) return null; - return value == null - ? null - : Amount(rawValue: value, fractionDigits: fractionDigits); + return Amount(rawValue: value, fractionDigits: fractionDigits); } + final parsedTtl = int.tryParse( + (json['ttl_cutoff_height'] ?? json['ttl'] ?? '').toString(), + ); + return SlateInspection( state: state, - slateId: (json['id'] ?? '').toString(), + slateId: slateId, slateJson: slateJson, amount: parseAmount(json['amount'] ?? json['amt']), fee: parseAmount(json['fee']), senderAddress: senderAddress, recipientAddress: recipientAddress, isEncrypted: isEncrypted, - ttlCutoffHeight: int.tryParse( - (json['ttl_cutoff_height'] ?? json['ttl'] ?? '').toString(), - ), + ttlCutoffHeight: parsedTtl != null && parsedTtl > 0 ? parsedTtl : null, ); } /// Exact local transaction for [slateId]. Sends win for self-transfers; a -/// live receive wins over a cancelled duplicate receive. +/// live record wins over a cancelled duplicate. @visibleForTesting TransactionV2? localSlateTransaction( Iterable candidates, String slateId, ) { - TransactionV2? match; + final target = slateId.trim().toLowerCase(); + if (target.isEmpty) return null; + + TransactionV2? sendMatch; + TransactionV2? receiveMatch; for (final tx in candidates) { - if (tx.slateId != slateId) continue; - if (tx.type == TransactionType.outgoing) return tx; - if (match == null || (match.isCancelled && !tx.isCancelled)) { - match = tx; + if (tx.slateId?.trim().toLowerCase() != target) continue; + final isSend = + tx.type == TransactionType.outgoing || + tx.type == TransactionType.sentToSelf; + if (isSend) { + if (sendMatch == null || (sendMatch.isCancelled && !tx.isCancelled)) { + sendMatch = tx; + } + } else if (receiveMatch == null || + (receiveMatch.isCancelled && !tx.isCancelled)) { + receiveMatch = tx; } } - return match; + return sendMatch ?? receiveMatch; } diff --git a/lib/widgets/slatepack_method_toggle.dart b/lib/widgets/slatepack_method_toggle.dart index 90c8b9a223..8f03a2be94 100644 --- a/lib/widgets/slatepack_method_toggle.dart +++ b/lib/widgets/slatepack_method_toggle.dart @@ -18,6 +18,7 @@ import '../utilities/assets.dart'; import '../utilities/constants.dart'; import '../utilities/enums/slatepack_method.dart'; import '../utilities/util.dart'; +import '../wallets/wallet/wallet.dart'; import '../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import 'toggle.dart'; @@ -32,8 +33,16 @@ class SlatepackMethodToggle extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { debugPrint("BUILD: $runtimeType"); final bool isDesktop = Util.isDesktop; - final wallet = - ref.watch(pWallets).getWallet(walletId) as SlatepackInterface; + final Wallet? wallet; + try { + wallet = ref.watch(pWallets.select((w) => w.getWallet(walletId))); + } catch (_) { + return const SizedBox.shrink(); + } + if (wallet is! SlatepackInterface) return const SizedBox.shrink(); + if (!wallet.supportedMethods.contains(SlatepackMethod.slatepack)) { + return const SizedBox.shrink(); + } final otherMethods = wallet.supportedMethods.where( (method) => method != SlatepackMethod.slatepack, ); @@ -41,6 +50,7 @@ class SlatepackMethodToggle extends ConsumerWidget { final SlatepackMethod other = otherMethods.first; return Toggle( + key: ValueKey(walletId), onValueChanged: (bool value) { ref.read(pSelectedSlatepackMethod(walletId).notifier).state = value ? other diff --git a/lib/wl_gen/interfaces/libepiccash_interface.dart b/lib/wl_gen/interfaces/libepiccash_interface.dart index 04e671ccbd..d6ab18565f 100644 --- a/lib/wl_gen/interfaces/libepiccash_interface.dart +++ b/lib/wl_gen/interfaces/libepiccash_interface.dart @@ -58,8 +58,10 @@ abstract class LibEpicCashInterface { required String slateJson, }); - Future<({String slateId, String commitId, String slateJson, bool? posted})> - txFinalize({required DynamicObject wallet, required String slateJson}); + Future<({String slateId, String commitId, String slateJson})> txFinalize({ + required DynamicObject wallet, + required String slateJson, + }); Future cancelTransaction({ required DynamicObject wallet, diff --git a/lib/wl_gen/interfaces/libmwc_interface.dart b/lib/wl_gen/interfaces/libmwc_interface.dart index 450fd5a835..52608da9b9 100644 --- a/lib/wl_gen/interfaces/libmwc_interface.dart +++ b/lib/wl_gen/interfaces/libmwc_interface.dart @@ -93,7 +93,7 @@ abstract class LibMwcInterface { Future<({String commitId, String slateId, String slateJson})> txReceiveDetailed({required String wallet, required String slateJson}); - Future<({String commitId, String slateId, bool? posted})> txFinalize({ + Future<({String commitId, String slateId})> txFinalize({ required String wallet, required String slateJson, }); diff --git a/test/pages/send_view/send_views_test.dart b/test/pages/send_view/send_views_test.dart index eecb3bf632..6ab213e1e7 100644 --- a/test/pages/send_view/send_views_test.dart +++ b/test/pages/send_view/send_views_test.dart @@ -921,7 +921,10 @@ void main() { await view.pump( tester, wallet: wallet as Wallet, - balance: testBalance("10", 8), + balance: testBalance( + "10", + (wallet as Wallet).cryptoCurrency.fractionDigits, + ), overrides: [ pSelectedSlatepackMethod(wallet.walletId).overrideWithProvider( StateProvider( diff --git a/test/pages/slatepack/slatepack_dialog_test.dart b/test/pages/slatepack/slatepack_dialog_test.dart index c094e78ec7..f7f6fe525f 100644 --- a/test/pages/slatepack/slatepack_dialog_test.dart +++ b/test/pages/slatepack/slatepack_dialog_test.dart @@ -9,6 +9,7 @@ import 'package:stackwallet/pages/receive_view/sub_widgets/slatepack_entry_dialo import 'package:stackwallet/pages/slatepack/slatepack_dialog.dart'; import 'package:stackwallet/pages/slatepack/slatepack_popup.dart'; import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/clipboard_interface.dart'; import 'package:stackwallet/utilities/slatepack_terms.dart'; import 'package:stackwallet/utilities/util.dart'; import 'package:stackwallet/widgets/stack_dialog.dart'; @@ -80,8 +81,6 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); - addTearDown(tester.view.resetViewInsets); - // Share is only offered on the phone layout. final previousWidth = Util.screenWidth; Util.screenWidth = 400; addTearDown(() => Util.screenWidth = previousWidth); @@ -307,4 +306,304 @@ void main() { expect(find.text('Not encrypted'), findsNothing); expect(find.textContaining('Encrypted to'), findsNothing); }); + + testWidgets('Copy writes the slatepack to clipboard', (tester) async { + useAndroidLayout(); + tester.view.physicalSize = const Size(400, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final copied = []; + final clipboard = _RecordingClipboard(copied); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: SingleChildScrollView( + child: SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: 'BEGINSLATEPACK. copied. ENDSLATEPACK.', + state: SlateState.s1, + clipboard: clipboard, + ), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Copy')); + await tester.pump(); + expect(copied, ['BEGINSLATEPACK. copied. ENDSLATEPACK.']); + + // Let the floating copy confirmation flushbar timer finish. + await tester.pump(const Duration(seconds: 4)); + expect(tester.takeException(), isNull); + }); + + testWidgets('iPad layout keeps Share visible', (tester) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + final previousIpad = Util.isIpad; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'ios'); + Util.screenWidth = 1024; + Util.isIpad = true; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + Util.isIpad = previousIpad; + }); + tester.view.physicalSize = const Size(1024, 1366); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SingleChildScrollView( + child: SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: 'BEGINSLATEPACK. ipad. ENDSLATEPACK.', + state: SlateState.s1, + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect(find.text('Save'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('desktop layout hides Share and shows amount and fee', ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + final previousIpad = Util.isIpad; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + Util.isIpad = false; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + Util.isIpad = previousIpad; + }); + tester.view.physicalSize = const Size(1400, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: Center( + child: SizedBox( + width: 600, + child: SingleChildScrollView( + child: SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: 'BEGINSLATEPACK. desktop. ENDSLATEPACK.', + state: SlateState.s2, + slateId: 'slate-desktop-1', + formattedAmount: '1.25 MWC', + formattedFee: '0.008 MWC', + ), + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Share'), findsNothing); + expect(find.text('Save'), findsOneWidget); + expect(find.text('Amount'), findsOneWidget); + expect(find.text('1.25 MWC'), findsOneWidget); + expect(find.text('Fee'), findsOneWidget); + expect(find.text('0.008 MWC'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('iPad Slide Over wraps Copy, Share, Save into two rows', ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + final previousIpad = Util.isIpad; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'ios'); + Util.screenWidth = 1024; + Util.isIpad = true; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + Util.isIpad = previousIpad; + }); + tester.view.physicalSize = const Size(320, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SingleChildScrollView( + child: SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: 'BEGINSLATEPACK. slideover. ENDSLATEPACK.', + state: SlateState.s1, + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect(find.text('Save'), findsOneWidget); + expect( + tester.getTopLeft(find.text('Save')).dy, + greaterThan(tester.getBottomLeft(find.text('Copy')).dy), + ); + expect(tester.takeException(), isNull); + }); + + group('SlatepackEntryDialog', () { + Future pumpEntryHost( + WidgetTester tester, + void Function(String?) onResult, + ) async { + useAndroidLayout(); + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + final result = await showSlatepackEntryDialog( + context: context, + terms: SlatepackTerms.slatepack, + ); + onResult(result); + }, + child: const Text('OpenEntry'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('OpenEntry')); + await tester.pumpAndSettle(); + } + + testWidgets('submits trimmed text and Cancel returns null', (tester) async { + String? submitted = 'unset'; + await pumpEntryHost(tester, (v) => submitted = v); + + await tester.enterText(find.byType(TextField), ' slate-payload '); + await tester.pump(); + await tester.tap(find.text('Import')); + await tester.pumpAndSettle(); + expect(submitted, 'slate-payload'); + expect(find.text('OpenEntry'), findsOneWidget); + + await tester.tap(find.text('OpenEntry')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(submitted, isNull); + expect(find.text('OpenEntry'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'double-tap Import or dismiss during unfocus delay never pops host', + (tester) async { + String? submitted = 'unset'; + await pumpEntryHost(tester, (v) => submitted = v); + + await tester.tap(find.byType(TextField)); + await tester.enterText(find.byType(TextField), 'payload'); + await tester.pump(); + + // Tap Import while focused, then tap Import & Cancel again inside 75ms. + await tester.tap(find.text('Import')); + await tester.pump(const Duration(milliseconds: 10)); + await tester.tap(find.text('Import'), warnIfMissed: false); + await tester.tap(find.text('Cancel'), warnIfMissed: false); + await tester.pumpAndSettle(); + + expect(submitted, 'payload'); + expect(find.text('OpenEntry'), findsOneWidget); + + // Now pop via Navigator before the 75ms unfocus delay completes. + submitted = 'unset'; + await tester.tap(find.text('OpenEntry')); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextField)); + await tester.enterText(find.byType(TextField), 'payload2'); + await tester.pump(); + + await tester.tap(find.text('Import')); + await tester.pump(const Duration(milliseconds: 10)); + Navigator.of(tester.element(find.byType(SlatepackEntryDialog))).pop(); + await tester.pumpAndSettle(); + + expect(submitted, isNull); + expect(find.text('OpenEntry'), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + }); +} + +class _RecordingClipboard extends Fake implements ClipboardInterface { + _RecordingClipboard(this.copied); + + final List copied; + + @override + Future setData(ClipboardData data) async { + if (data.text != null) copied.add(data.text!); + } } diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart index 6aa58c649f..c0e5cb2266 100644 --- a/test/pages/slatepack/slatepack_import_flow_test.dart +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -90,10 +90,7 @@ class _InspectOnlyWallet extends EpiccashWallet { } @override - Future receiveSlatepack( - String slatepack, { - required SlateInspection inspection, - }) async { + Future receiveSlatepack(SlateInspection inspection) async { receiveCalls++; actionInspection = inspection; if (receiveGate == null) { @@ -115,10 +112,7 @@ class _InspectOnlyWallet extends EpiccashWallet { } @override - Future finalizeSlatepack( - String slatepack, { - required SlateInspection inspection, - }) async { + Future finalizeSlatepack(SlateInspection inspection) async { actionInspection = inspection; finalizeCalls++; return finalizeResult ?? @@ -140,7 +134,9 @@ class _SynchronousMwcWallet extends MimblewimblecoinWallet { @override Future inspectSlatepack(String armored) { onInspect(); - return Future.value(SlateInspection(state: state, slateId: 'mwc-slate')); + return Future.value( + SlateInspection(state: state, slateId: 'mwc-slate', slateJson: '{}'), + ); } @override @@ -202,31 +198,35 @@ void main() { "ENDSLATEPACK."; test("trims whitespace", () { - expect(SlatepackImportFlow.normalize(" \n$armored\r\n "), armored); - expect(SlatepackImportFlow.normalize(armored), armored); + expect(SlatepackText.normalize(" \n$armored\r\n "), armored); + expect(SlatepackText.normalize(armored), armored); }); test("drops text around the armored frame", () { expect( - SlatepackImportFlow.normalize( + SlatepackText.normalize( "Here is the slatepack:\n\n$armored\n\nSend it back soon.", ), armored, ); - expect(SlatepackImportFlow.normalize("> $armored <"), armored); + expect(SlatepackText.normalize("> $armored <"), armored); + }); + + test("unwraps a single armored frame when prose starts with {", () { + expect(SlatepackText.normalize("{note} $armored"), armored); }); test("keeps line breaks inside the frame", () { const wrapped = "BEGINSLATEPACK. 4H1qx1wHe668tFW\nyC2gfL8PPd8kSgv. ENDSLATEPACK."; - expect(SlatepackImportFlow.normalize("Hi\n$wrapped\nBye"), wrapped); + expect(SlatepackText.normalize("Hi\n$wrapped\nBye"), wrapped); }); test("accepts the binary markers and a missing final period", () { const binary = "BEGINSLATE_BIN. 4H1qx1wHe668tFW. ENDSLATE_BIN."; - expect(SlatepackImportFlow.normalize("x $binary y"), binary); + expect(SlatepackText.normalize("x $binary y"), binary); expect( - SlatepackImportFlow.normalize( + SlatepackText.normalize( "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK", ), "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK", @@ -240,25 +240,24 @@ void main() { expect(SlatepackText.isArmored('{"id":"abc"}'), isFalse); }); - test("takes the first of two slatepacks", () { - expect(SlatepackImportFlow.normalize("$armored\n$armored"), armored); + test("leaves concatenated frames untouched so validation fails", () { + const two = "$armored\n$armored"; + expect(SlatepackText.normalize(two), two); + expect(SlatepackText.isArmored(SlatepackText.normalize(two)), isFalse); }); test("leaves JSON slates alone apart from trimming", () { const json = '{"id": "abc", "note": "BEGINSLATEPACK. x. ENDSLATEPACK."}'; - expect(SlatepackImportFlow.normalize(" $json\n"), json); + expect(SlatepackText.normalize(" $json\n"), json); }); test("leaves other text alone apart from trimming", () { + expect(SlatepackText.normalize(" not a slatepack "), "not a slatepack"); expect( - SlatepackImportFlow.normalize(" not a slatepack "), - "not a slatepack", - ); - expect( - SlatepackImportFlow.normalize("BEGINSLATEPACK. cut off"), + SlatepackText.normalize("BEGINSLATEPACK. cut off"), "BEGINSLATEPACK. cut off", ); - expect(SlatepackImportFlow.normalize(" "), ""); + expect(SlatepackText.normalize(" "), ""); }); }); @@ -271,7 +270,8 @@ void main() { void Function(bool)? onDone, }) async { bool? outcome; - shown ??= ValueNotifier(true); + final effectiveShown = shown ?? ValueNotifier(true); + if (shown == null) addTearDown(effectiveShown.dispose); final coin = wallet.cryptoCurrency; // The loading overlay reads its indicator from the theme. final previousThemes = StackFileSystem.themesDir; @@ -297,7 +297,7 @@ void main() { ), home: Scaffold( body: ValueListenableBuilder( - valueListenable: shown, + valueListenable: effectiveShown, builder: (context, isShown, _) => !isShown ? const SizedBox() : Builder( @@ -709,33 +709,34 @@ void main() { await closeDialog(tester); }); - testWidgets('an older plugin does not claim an unknown broadcast result', ( - tester, - ) async { - final wallet = _InspectOnlyWallet( - SlateState.s2, - localIsSend: true, - finalizeResult: FinalizeResult( - success: true, - slateId: 'test-slate', - posted: null, - ), - ); - await runFlow(tester, wallet); - await tester.tap(find.text('Finalize')); - await tester.pump(const Duration(milliseconds: 400)); - await tester.pump(const Duration(milliseconds: 400)); - await tester.pump(const Duration(milliseconds: 400)); - - expect(find.text('Transaction finalized'), findsOneWidget); - expect( - find.textContaining('broadcast result is unavailable'), - findsOneWidget, - ); - expect(find.textContaining('finalized and broadcast'), findsNothing); - expect(find.textContaining('node did not accept'), findsNothing); - await closeDialog(tester); - }); + testWidgets( + 'a finalize with unknown broadcast status reports it honestly', + (tester) async { + final wallet = _InspectOnlyWallet( + SlateState.s2, + localIsSend: true, + finalizeResult: FinalizeResult( + success: true, + slateId: 'test-slate', + posted: null, + ), + ); + await runFlow(tester, wallet); + await tester.tap(find.text('Finalize')); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + + expect(find.text('Transaction finalized'), findsOneWidget); + expect( + find.textContaining('broadcast result is unavailable'), + findsOneWidget, + ); + expect(find.textContaining('finalized and broadcast'), findsNothing); + expect(find.textContaining('node did not accept'), findsNothing); + await closeDialog(tester); + }, + ); testWidgets("the wallet only sees the slatepack itself", (tester) async { const armored = "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK."; @@ -839,5 +840,82 @@ void main() { expect(done, isFalse); expect(tester.takeException(), isNull); }); + + testWidgets( + "a finalized and broadcast transaction shows the success flushbar", + (tester) async { + final wallet = _InspectOnlyWallet( + SlateState.s2, + localIsSend: true, + finalizeResult: FinalizeResult( + success: true, + slateId: "test-slate", + posted: true, + ), + ); + bool? done; + await runFlow(tester, wallet, onDone: (v) => done = v); + await tester.tap(find.text("Finalize")); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + + expect(done, isTrue); + expect( + find.text("Transaction finalized and broadcast"), + findsOneWidget, + ); + expect(find.text("Finalized, not broadcast"), findsNothing); + expect(find.text("Transaction finalized"), findsNothing); + + // Let the floating flushbar timer finish and remove its overlay entry. + await tester.pump(const Duration(seconds: 4)); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets("aborts without inspecting when covered by a lock screen", ( + tester, + ) async { + var inspectCalls = 0; + final wallet = _SynchronousMwcWallet(onInspect: () => inspectCalls++); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + late BuildContext hostContext; + + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Builder( + builder: (context) { + hostContext = context; + return const Scaffold(body: Text("Host")); + }, + ), + ), + ), + ); + + unawaited( + Navigator.of(hostContext).push( + MaterialPageRoute(builder: (_) => const Text("lock route")), + ), + ); + await tester.pumpAndSettle(); + + final result = await SlatepackImportFlow.run( + context: hostContext, + wallet: wallet, + text: "{}", + ); + expect(result, isFalse); + expect(inspectCalls, 0); + expect(tester.takeException(), isNull); + }); }); } diff --git a/test/pages/slatepack/slatepack_input_field_test.dart b/test/pages/slatepack/slatepack_input_field_test.dart index 2c92d66462..61c71fcf54 100644 --- a/test/pages/slatepack/slatepack_input_field_test.dart +++ b/test/pages/slatepack/slatepack_input_field_test.dart @@ -119,4 +119,128 @@ void main() { expect(tester.takeException(), isNull); expect(changes, isEmpty); }); + + testWidgets('paste inserts trimmed clipboard text and swaps suffix icon', ( + tester, + ) async { + final controller = TextEditingController(); + addTearDown(controller.dispose); + final clipboard = _Clipboard(); + final changes = []; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: SlatepackInputField( + controller: controller, + hint: 'Slatepack', + terms: SlatepackTerms.slatepack, + clipboard: clipboard, + onChanged: changes.add, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const Key('slatepackPasteButton'))); + clipboard.response.complete( + const ClipboardData(text: ' BEGINSLATEPACK. pasted. ENDSLATEPACK. '), + ); + await tester.pumpAndSettle(); + + expect(controller.text, 'BEGINSLATEPACK. pasted. ENDSLATEPACK.'); + expect(changes, ['BEGINSLATEPACK. pasted. ENDSLATEPACK.']); + expect(find.byKey(const Key('slatepackClearButton')), findsOneWidget); + expect(find.byKey(const Key('slatepackPasteButton')), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('clear button clears text and restores paste action', ( + tester, + ) async { + final controller = TextEditingController(text: 'abc'); + addTearDown(controller.dispose); + final changes = []; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: SlatepackInputField( + controller: controller, + hint: 'Slatepack', + terms: SlatepackTerms.slatepack, + onChanged: changes.add, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('slatepackClearButton')), findsOneWidget); + expect(find.byKey(const Key('slatepackPasteButton')), findsNothing); + + await tester.tap(find.byKey(const Key('slatepackClearButton'))); + await tester.pumpAndSettle(); + + expect(controller.text, isEmpty); + expect(changes, ['']); + expect(find.byKey(const Key('slatepackPasteButton')), findsOneWidget); + expect(find.byKey(const Key('slatepackClearButton')), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('external controller.clear() updates suffix icon', ( + tester, + ) async { + final controller = TextEditingController(text: 'abc'); + addTearDown(controller.dispose); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Scaffold( + body: SlatepackInputField( + controller: controller, + hint: 'Slatepack', + terms: SlatepackTerms.slatepack, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('slatepackClearButton')), findsOneWidget); + expect(find.byKey(const Key('slatepackPasteButton')), findsNothing); + + controller.clear(); + await tester.pump(); + + expect(find.byKey(const Key('slatepackPasteButton')), findsOneWidget); + expect(find.byKey(const Key('slatepackClearButton')), findsNothing); + expect(tester.takeException(), isNull); + }); } diff --git a/test/pages/slatepack/slatepack_send_flow_test.dart b/test/pages/slatepack/slatepack_send_flow_test.dart index b5bbbb2a23..015ba91511 100644 --- a/test/pages/slatepack/slatepack_send_flow_test.dart +++ b/test/pages/slatepack/slatepack_send_flow_test.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:platform/platform.dart' as platform; import 'package:stackwallet/db/isar/main_db.dart'; import 'package:stackwallet/models/isar/models/transaction_note.dart'; import 'package:stackwallet/models/isar/stack_theme.dart'; @@ -16,6 +17,7 @@ import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/amount/amount_formatter.dart'; import 'package:stackwallet/utilities/amount/amount_unit.dart'; import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/utilities/util.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; @@ -228,7 +230,7 @@ void main() { }); testWidgets( - 'the result shows the actual fee, saves its note and never refreshes', + 'the result shows actual fee, saves note, and refreshes on close', (tester) async { final wallet = _Wallet(createdAmount: 100, createdFee: 3); final notes = _Notes(); @@ -249,6 +251,7 @@ void main() { await tester.tap(find.text('Done')); await tester.pumpAndSettle(); expect(succeeded.value, isTrue); + expect(wallet.refreshed, 1); }, ); @@ -355,4 +358,126 @@ void main() { await tester.pumpAndSettle(); expect(find.byType(SlatepackDialog), findsOneWidget); }); + + testWidgets('desktop OK on create error keeps Home on root navigator', ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + + final wallet = _Wallet(createError: 'Exception: wallet is locked'); + await _pumpSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(find.text('Could not create the slate'), findsOneWidget); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('createSlate')), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('desktop OK on note failure keeps Home on root navigator', ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + + final wallet = _Wallet(createdAmount: 100, createdFee: 3); + final succeeded = await _pumpSend(tester, wallet, db: _Notes(fail: true)); + await tester.pumpAndSettle(); + + expect(find.byType(SlatepackDialog), findsOneWidget); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + + expect(find.text('Local note not saved'), findsOneWidget); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('createSlate')), findsOneWidget); + expect(succeeded.value, isTrue); + expect(wallet.refreshed, 1); + expect(tester.takeException(), isNull); + }); + + testWidgets('aborts without creating when covered by a lock screen', ( + tester, + ) async { + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final wallet = _Wallet(createdAmount: 100, createdFee: 1); + late BuildContext hostContext; + + await tester.pumpWidget( + ProviderScope( + overrides: [ + themeProvider.overrideWithProvider(StateProvider((_) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Builder( + builder: (context) { + hostContext = context; + return const Scaffold(body: Text('Host')); + }, + ), + ), + ), + ); + + unawaited( + Navigator.of( + hostContext, + ).push(MaterialPageRoute(builder: (_) => const Text('lock route'))), + ); + await tester.pumpAndSettle(); + + final created = await SlatepackSendFlow.run( + context: hostContext, + wallet: wallet, + amount: _amount(100), + message: '', + localNote: '', + db: _Notes(), + format: _formatter(wallet.cryptoCurrency).format, + ); + expect(created, isFalse); + expect(wallet.created, 0); + expect(tester.takeException(), isNull); + }); + + testWidgets('aborts without creating if overlay closes before presentation', ( + tester, + ) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 1); + final succeeded = await _pumpSend(tester, wallet); + await tester.pump(); + + Navigator.of( + tester.element(find.byType(CustomLoadingOverlay)), + rootNavigator: true, + ).pop(); + await tester.pumpAndSettle(); + + expect(wallet.created, 0); + expect(succeeded.value, isFalse); + expect(tester.takeException(), isNull); + }); } diff --git a/test/pages/slatepack/slatepack_view_test.dart b/test/pages/slatepack/slatepack_view_test.dart index 65b509e003..83127597f6 100644 --- a/test/pages/slatepack/slatepack_view_test.dart +++ b/test/pages/slatepack/slatepack_view_test.dart @@ -11,10 +11,14 @@ import 'package:stackwallet/pages/slatepack/slatepack_view.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; import 'package:stackwallet/utilities/stack_file_system.dart'; import 'package:stackwallet/utilities/util.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/widgets/background.dart'; import 'package:stackwallet/widgets/desktop/primary_button.dart'; import '../../sample_data/theme_json.dart'; @@ -23,8 +27,11 @@ import '../../wallets/support/xelis_test_fakes.dart'; /// Epic Cash wallet whose inspection waits for [gate] and then reports a /// finalized slate, which the import flow answers with a plain message. class _SlowWallet extends EpiccashWallet { - _SlowWallet() : super(CryptoCurrencyNetwork.main); + _SlowWallet({this.state = SlateState.s3, this.receiveResponse}) + : super(CryptoCurrencyNetwork.main); + final SlateState state; + final SlatepackResult? receiveResponse; final gate = Completer(); int inspections = 0; @@ -32,8 +39,22 @@ class _SlowWallet extends EpiccashWallet { Future inspectSlatepack(String armored) async { inspections++; await gate.future; - return const SlateInspection(state: SlateState.s3, slateId: "test-slate"); + return SlateInspection( + state: state, + slateId: "test-slate", + slateJson: "{}", + amount: Amount(rawValue: BigInt.from(100), fractionDigits: 8), + fee: Amount(rawValue: BigInt.one, fractionDigits: 8), + ); } + + @override + Future<({Amount amount, Amount fee, bool isSend, bool isCancelled})?> + localTxForSlate(String slateId) async => null; + + @override + Future receiveSlatepack(SlateInspection inspection) async => + receiveResponse ?? SlatepackResult(success: false, error: "unused"); } void main() { @@ -113,4 +134,89 @@ void main() { expect(button().enabled, isTrue); expect(tester.takeException(), isNull); }); + + testWidgets("desktop layout omits Scaffold and clears input when done", ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + tester.view.physicalSize = const Size(1400, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory("test/sample_data").absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + + final wallet = _SlowWallet( + state: SlateState.s1, + receiveResponse: SlatepackResult( + success: true, + slatepack: '{"response": true}', + slateId: "test-slate", + state: SlateState.s2, + ), + )..gate.complete(); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final coin = wallet.cryptoCurrency; + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: "en_US", + coin: coin, + maxDecimals: coin.fractionDigits, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SizedBox( + width: 600, + height: 600, + child: SlatepackView(walletId: "wallet-1"), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(Background), findsNothing); + expect(find.byType(AppBar), findsNothing); + + await tester.enterText(find.byType(TextField), "{}"); + await tester.pump(); + await tester.tap(find.text("Continue")); + await tester.pumpAndSettle(); + + expect(find.text("Receive slate"), findsOneWidget); + await tester.tap(find.text("Receive")); + await tester.pumpAndSettle(); + expect(find.text("Response Slate"), findsOneWidget); + await tester.tap(find.text("Done")); + await tester.pumpAndSettle(); + + // Acting on the slate cleared the input and disabled Continue. + expect(find.text("{}"), findsNothing); + expect( + tester.widget(find.byType(PrimaryButton)).enabled, + isFalse, + ); + expect(tester.takeException(), isNull); + }); } diff --git a/test/utilities/route_presentation_test.dart b/test/utilities/route_presentation_test.dart index 7f06789d12..7e2635c290 100644 --- a/test/utilities/route_presentation_test.dart +++ b/test/utilities/route_presentation_test.dart @@ -86,4 +86,261 @@ void main() { expect(find.text('Cancelling'), findsNothing); expect(find.text('Home'), findsOneWidget); }); + + testWidgets('waitUntilCurrent waits across chained covering routes', ( + tester, + ) async { + late BuildContext context; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (builderContext) { + context = builderContext; + return const Text('Home'); + }, + ), + ), + ); + + final navigator = Navigator.of(context); + final progress = CurrentAwareDialogRoute( + context: context, + barrierDismissible: false, + builder: (_) => const Text('Progress'), + ); + unawaited(navigator.push(progress)); + await tester.pumpAndSettle(); + unawaited( + navigator.push( + MaterialPageRoute(builder: (_) => const Text('Cover1')), + ), + ); + await tester.pumpAndSettle(); + + var completed = false; + final waitFuture = progress.waitUntilCurrent().then((_) { + completed = true; + }); + + // Replace Cover1 with Cover2 in the same frame so Cover2 is now covering + // before waitUntilCurrent wakes up cleanly. + navigator.pop(); + unawaited( + navigator.push( + MaterialPageRoute(builder: (_) => const Text('Cover2')), + ), + ); + await tester.pumpAndSettle(); + + expect(completed, isFalse); + expect(find.text('Cover2'), findsOneWidget); + + navigator.pop(); + await tester.pumpAndSettle(); + await waitFuture; + expect(completed, isTrue); + expect(find.text('Progress'), findsOneWidget); + }); + + testWidgets( + 'waitForRoutePresentation returns false if Navigator is disposed early', + (tester) async { + late BuildContext context; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (builderContext) { + context = builderContext; + return const SizedBox(); + }, + ), + ), + ); + + final route = DialogRoute( + context: context, + builder: (_) => const Text('Progress'), + ); + unawaited(Navigator.of(context).push(route)); + await tester.pump(); + + final presentedFuture = waitForRoutePresentation(route); + await tester.pumpWidget(const SizedBox.shrink()); + + final presented = await presentedFuture.timeout( + const Duration(seconds: 1), + ); + expect(presented, isFalse); + }, + ); + + testWidgets('runWithCurrentAwareOverlay cleans up when action throws', ( + tester, + ) async { + ({bool aborted, bool canPresentResult, Object? error})? captured; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + final outcome = await runWithCurrentAwareOverlay( + context: context, + builder: (_) => const Text('Overlay'), + action: () async => throw StateError('boom'), + ); + captured = ( + aborted: outcome.aborted, + canPresentResult: outcome.canPresentResult, + error: outcome.error, + ); + }, + child: const Text('Run'), + ), + ), + ), + ), + ); + + await tester.tap(find.text('Run')); + await tester.pumpAndSettle(); + + expect(captured?.aborted, isFalse); + expect(captured?.canPresentResult, isTrue); + expect(captured?.error, isA()); + expect(find.text('Overlay'), findsNothing); + expect(find.text('Run'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'runWithCurrentAwareOverlay aborts for covered nested navigator', + (tester) async { + late BuildContext nestedContext; + late BuildContext rootContext; + + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (ctx) { + rootContext = ctx; + return Navigator( + onGenerateRoute: (_) => MaterialPageRoute( + builder: (innerCtx) { + nestedContext = innerCtx; + return const Text('Nested'); + }, + ), + ); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + unawaited( + Navigator.of( + rootContext, + rootNavigator: true, + ).push(MaterialPageRoute(builder: (_) => const Text('Locked'))), + ); + await tester.pumpAndSettle(); + + var actionCalls = 0; + final outcome = await runWithCurrentAwareOverlay( + context: nestedContext, + builder: (_) => const Text('Overlay'), + action: () async => actionCalls++, + ); + + expect(outcome.aborted, isTrue); + expect(actionCalls, 0); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'runWithCurrentAwareOverlay aborts if covered during entrance animation', + (tester) async { + late BuildContext rootContext; + ({bool aborted, bool canPresentResult})? captured; + var actionCalls = 0; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (ctx) { + rootContext = ctx; + return TextButton( + onPressed: () async { + final outcome = await runWithCurrentAwareOverlay( + context: ctx, + builder: (_) => const Text('Overlay'), + action: () async => actionCalls++, + ); + captured = ( + aborted: outcome.aborted, + canPresentResult: outcome.canPresentResult, + ); + }, + child: const Text('Run'), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.text('Run')); + await tester.pump(const Duration(milliseconds: 50)); + unawaited( + Navigator.of( + rootContext, + rootNavigator: true, + ).push(MaterialPageRoute(builder: (_) => const Text('Locked'))), + ); + await tester.pumpAndSettle(); + + expect(actionCalls, 0); + expect(find.text('Locked'), findsOneWidget); + + Navigator.of(rootContext, rootNavigator: true).pop(); + await tester.pumpAndSettle(); + + expect(captured?.aborted, isTrue); + expect(captured?.canPresentResult, isFalse); + expect(find.text('Overlay'), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'runWithCurrentAwareOverlay returns aborted for unmounted context', + (tester) async { + late BuildContext capturedContext; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (ctx) { + capturedContext = ctx; + return const SizedBox(); + }, + ), + ), + ); + await tester.pumpWidget(const SizedBox.shrink()); + + var actionCalls = 0; + final outcome = await runWithCurrentAwareOverlay( + context: capturedContext, + builder: (_) => const Text('Overlay'), + action: () async => actionCalls++, + ); + + expect(outcome.aborted, isTrue); + expect(actionCalls, 0); + expect(tester.takeException(), isNull); + }, + ); } diff --git a/test/wallets/mimblewimble_slate_inspection_test.dart b/test/wallets/mimblewimble_slate_inspection_test.dart index e10418c0e0..77de943418 100644 --- a/test/wallets/mimblewimble_slate_inspection_test.dart +++ b/test/wallets/mimblewimble_slate_inspection_test.dart @@ -8,9 +8,11 @@ import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_cancel_transaction_dialog.dart'; import 'package:stackwallet/utilities/amount/amount.dart'; import 'package:stackwallet/utilities/enums/slatepack_method.dart'; import 'package:stackwallet/utilities/slatepack_terms.dart'; +import 'package:stackwallet/utilities/slatepack_text.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; @@ -37,8 +39,6 @@ TransactionV2 _tx( TransactionType type, String slateId, { bool isCancelled = false, - int? numberOfMessages, - String? onChainNote, }) => TransactionV2( walletId: "wallet", blockHash: null, @@ -53,8 +53,6 @@ TransactionV2 _tx( subType: TransactionSubType.none, otherData: jsonEncode({ "slateId": slateId, - if (numberOfMessages != null) "numberOfMessages": numberOfMessages, - if (onChainNote != null) "onChainNote": onChainNote, TxV2OdKeys.overrideFee: Amount.zeroWith(fractionDigits: 9).toJsonString(), if (isCancelled) TxV2OdKeys.isCancelled: true, }), @@ -99,10 +97,24 @@ class _PendingLookupWallet extends _LocalLookupWallet { Future remember(SlatepackResult result) => rememberPendingSlateSend(result); + void rememberReceive(SlatepackResult result) => + rememberPendingSlateReceive(result); + Future rememberCancelled(String slateId) => rememberPendingSlateCancelled(slateId); } +class _ThrowingMetadataWallet extends _PendingLookupWallet { + @override + Map get slatepackTransactionMetadata => + throw StateError('db closed'); + + @override + Future updateSlatepackTransactionMetadata( + Map metadata, + ) async => throw StateError('db closed'); +} + void main() { setUpAll(initializeTestIsar); @@ -153,15 +165,18 @@ void main() { expect(inspect(_slate(signatures: 2)).state, SlateState.s3); }); - test("falls back to sta, then to addresses", () { - expect(inspect({"id": "a", "sta": "I1"}).state, SlateState.i1); - expect( - inspect({"id": "a"}, sender: "s", recipient: "r").state, - SlateState.s2, - ); - expect(inspect({"id": "a"}, sender: "s").state, SlateState.s1); - expect(inspect({"id": "a"}).state, SlateState.unknown); - }); + test( + "falls back to sta only, never infers state from transport addresses", + () { + expect(inspect({"id": "a", "sta": "I1"}).state, SlateState.i1); + expect( + inspect({"id": "a"}, sender: "s", recipient: "r").state, + SlateState.unknown, + ); + expect(inspect({"id": "a"}, sender: "s").state, SlateState.unknown); + expect(inspect({"id": "a"}).state, SlateState.unknown); + }, + ); test("explicit invoice state overrides standard-send signatures", () { final invoice = _slate(signatures: 0)..["sta"] = "I1"; @@ -265,16 +280,14 @@ void main() { final directory = await Directory.systemTemp.createTemp( 'mimblewimble-local-history-', ); + addTearDown(() => directory.delete(recursive: true)); final isar = await Isar.open( [TransactionV2Schema, WalletInfoSchema], directory: directory.path, name: 'mimblewimble-local-history', inspector: false, ); - addTearDown(() async { - await isar.close(); - await directory.delete(recursive: true); - }); + addTearDown(isar.close); await MainDB.instance.initMainDB(mock: isar); await MainDB.instance.putWalletInfo( WalletInfo( @@ -363,12 +376,6 @@ void main() { ); }); - test('Epic treats a successful legacy finalize as broadcast', () { - expect(epicFinalizeBroadcastResult(null), isTrue); - expect(epicFinalizeBroadcastResult(true), isTrue); - expect(epicFinalizeBroadcastResult(false), isFalse); - }); - test( 'ownership remains local when durable metadata cannot be written', () async { @@ -392,4 +399,197 @@ void main() { ); }, ); + + test( + 'checkSlatepackFormat rejects mismatched markers and concatenated frames', + () { + final mwc = MimblewimblecoinWallet(CryptoCurrencyNetwork.main); + const valid = 'BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK.'; + const mismatched = 'BEGINSLATEFOO. 4H1qx1wHe668tFW. ENDSLATEPACK.'; + const concatenated = '$valid\n$valid'; + + expect(SlatepackText.isArmored(valid), isTrue); + expect(() => mwc.checkSlatepackFormat(valid), returnsNormally); + + expect(SlatepackText.isArmored(mismatched), isFalse); + expect(() => mwc.checkSlatepackFormat(mismatched), throwsException); + + expect(SlatepackText.isArmored(concatenated), isFalse); + expect(() => mwc.checkSlatepackFormat(concatenated), throwsException); + }, + ); + + test( + 'inspectSlateJson rejects negative numbers, bad ttl, empty sigs/ids', + () { + final negative = inspect({ + 'id': 'a', + 'sta': 'S1', + 'amount': '-5', + 'fee': '-1', + 'ttl_cutoff_height': '0', + }); + expect(negative.amount, isNull); + expect(negative.fee, isNull); + expect(negative.ttlCutoffHeight, isNull); + + final zeroTtl = inspect({ + 'id': 'a', + 'sta': 'S1', + 'ttl_cutoff_height': '-10', + }); + expect(zeroTtl.ttlCutoffHeight, isNull); + + final emptySig = inspect({ + 'id': 'a', + 'participant_data': [ + {'part_sig': ''}, + {'part_sig': null}, + ], + }); + expect(emptySig.state, SlateState.s1); + + final emptyId = inspect({ + 'id': ' ', + 'sta': 'S1', + 'participant_data': [{}], + }); + expect(emptyId.slateId, isEmpty); + expect(emptyId.state, SlateState.unknown); + }, + ); + + test( + 'localTxForSlate handles case, Isar cancel, sentToSelf, and receives', + () async { + final directory = await Directory.systemTemp.createTemp( + 'mimblewimble_slate_lookup_test_', + ); + addTearDown(() => directory.delete(recursive: true)); + final isar = await Isar.open( + [TransactionV2Schema, WalletInfoSchema], + directory: directory.path, + name: 'mimblewimble-local-lookup-edge', + inspector: false, + ); + addTearDown(isar.close); + await MainDB.instance.initMainDB(mock: isar); + await MainDB.instance.putWalletInfo( + WalletInfo( + walletId: 'wallet', + name: 'fixture', + mainAddressType: AddressType.mimbleWimble, + coinName: 'mimblewimblecoin', + ), + ); + + final wallet = _PendingLookupWallet(); + + // Stale non-cancelled in-memory send still yields to Isar isCancelled. + const sendUuidUpper = '0436430C-2B02-624C-2032-570501212B00'; + const sendUuidLower = '0436430c-2b02-624c-2032-570501212b00'; + await wallet.remember( + SlatepackResult( + success: true, + slatepack: 's1', + slateId: sendUuidUpper, + state: SlateState.s1, + amount: Amount(rawValue: BigInt.from(200), fractionDigits: 9), + fee: Amount(rawValue: BigInt.from(5), fractionDigits: 9), + ), + ); + await isar.writeTxn( + () => isar.transactionV2s.putAll([ + _tx(1, TransactionType.outgoing, sendUuidUpper, isCancelled: true), + _tx(2, TransactionType.sentToSelf, 'self-slate'), + _tx(3, TransactionType.outgoing, 'isar-only-slate'), + ]), + ); + + final cancelledFromIsar = await wallet.localTxForSlate(sendUuidLower); + expect(cancelledFromIsar?.isSend, isTrue); + expect(cancelledFromIsar?.isCancelled, isTrue); + + final selfTransfer = await wallet.localTxForSlate('SELF-SLATE'); + expect(selfTransfer?.isSend, isTrue); + expect(selfTransfer?.isCancelled, isFalse); + + wallet.rememberReceive( + SlatepackResult( + success: true, + slatepack: 's2', + slateId: 'receive-slate', + state: SlateState.s2, + amount: Amount(rawValue: BigInt.from(50), fractionDigits: 9), + fee: Amount(rawValue: BigInt.from(1), fractionDigits: 9), + ), + ); + final pendingReceive = await wallet.localTxForSlate('RECEIVE-SLATE'); + expect(pendingReceive?.isSend, isFalse); + expect(pendingReceive?.isCancelled, isFalse); + + // Cancelling an Isar-only slate (no in-memory/metadata entry) must still + // stick in localTxForSlate immediately. + await wallet.rememberCancelled('ISAR-ONLY-SLATE'); + final cancelledIsarOnly = await wallet.localTxForSlate('isar-only-slate'); + expect(cancelledIsarOnly?.isCancelled, isTrue); + }, + ); + + test('throwing metadata getters never break send/cancel/lookup, receives stay out of send metadata, and blank slateId is not cancellable', () async { + final throwingWallet = _ThrowingMetadataWallet(); + await throwingWallet.remember( + SlatepackResult( + success: true, + slatepack: 's1', + slateId: 'throw-slate', + state: SlateState.s1, + amount: Amount(rawValue: BigInt.from(100), fractionDigits: 9), + fee: Amount(rawValue: BigInt.from(2), fractionDigits: 9), + ), + ); + final beforeCancel = await throwingWallet.localTxForSlate('throw-slate'); + expect(beforeCancel?.isSend, isTrue); + expect(beforeCancel?.isCancelled, isFalse); + + await throwingWallet.rememberCancelled('throw-slate'); + final afterCancel = await throwingWallet.localTxForSlate('throw-slate'); + expect(afterCancel?.isSend, isTrue); + expect(afterCancel?.isCancelled, isTrue); + + final pendingWallet = _PendingLookupWallet(); + pendingWallet.rememberReceive( + SlatepackResult( + success: true, + slatepack: 's2', + slateId: 'receive-only', + state: SlateState.s2, + amount: Amount(rawValue: BigInt.from(50), fractionDigits: 9), + fee: Amount(rawValue: BigInt.from(1), fractionDigits: 9), + ), + ); + await pendingWallet.rememberCancelled('receive-only'); + expect(pendingWallet.metadata, isEmpty); + expect( + (await pendingWallet.localTxForSlate('receive-only'))?.isCancelled, + isTrue, + ); + + expect( + canCancelSlateTransaction( + slateId: ' ', + isCancelled: false, + confirmations: 0, + ), + isFalse, + ); + expect( + canCancelSlateTransaction( + slateId: 'abc', + isCancelled: false, + confirmations: 0, + ), + isTrue, + ); + }); } diff --git a/test/widgets/slatepack_method_toggle_test.dart b/test/widgets/slatepack_method_toggle_test.dart index efb77d5d62..9a5868266d 100644 --- a/test/widgets/slatepack_method_toggle_test.dart +++ b/test/widgets/slatepack_method_toggle_test.dart @@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stackwallet/models/isar/stack_theme.dart'; import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/enums/slatepack_method.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; @@ -67,4 +68,80 @@ void main() { expect(find.text('Slate'), findsOneWidget); expect(find.text('Slatepack'), findsNothing); }); + + testWidgets('toggling flips pSelectedSlatepackMethod for Epic and MWC', ( + tester, + ) async { + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + late WidgetRef readRef; + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue( + ConfirmationWallets(EpiccashWallet(CryptoCurrencyNetwork.main)), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Consumer( + builder: (context, ref, _) { + readRef = ref; + return const SlatepackMethodToggle(walletId: 'epic-w'); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect( + readRef.read(pSelectedSlatepackMethod('epic-w')), + SlatepackMethod.relay, + ); + await tester.tap(find.byType(Toggle)); + await tester.pumpAndSettle(); + expect( + readRef.read(pSelectedSlatepackMethod('epic-w')), + SlatepackMethod.slatepack, + ); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue( + ConfirmationWallets( + MimblewimblecoinWallet(CryptoCurrencyNetwork.main), + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Consumer( + builder: (context, ref, _) { + readRef = ref; + return const SlatepackMethodToggle(walletId: 'mwc-w'); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Slatepack'), findsOneWidget); + expect( + readRef.read(pSelectedSlatepackMethod('mwc-w')), + SlatepackMethod.slatepack, + ); + await tester.tap(find.byType(Toggle)); + await tester.pumpAndSettle(); + expect( + readRef.read(pSelectedSlatepackMethod('mwc-w')), + SlatepackMethod.relay, + ); + }); } diff --git a/test/widgets/wallet_navigation_bar_item_test.dart b/test/widgets/wallet_navigation_bar_item_test.dart index f65497d301..53f8ca7819 100644 --- a/test/widgets/wallet_navigation_bar_item_test.dart +++ b/test/widgets/wallet_navigation_bar_item_test.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/wallet_view/wallet_view.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/widgets/wallet_navigation_bar/components/wallet_navigation_bar_item.dart'; @@ -29,17 +30,19 @@ void main() { child: SizedBox( width: 57.6, height: 61, - child: WalletNavigationBarItem( - data: WalletNavigationBarItemData( - icon: const Icon(Icons.description, size: 20), - label: 'Slatepack', - overrideText: const FittedBox( - fit: BoxFit.scaleDown, - child: Text('Slatepack', maxLines: 1, softWrap: false), + child: Builder( + builder: (context) => WalletNavigationBarItem( + data: WalletNavigationBarItemData( + icon: const Icon(Icons.description, size: 20), + label: 'Slatepack', + overrideText: buildSlatepackNavLabel( + context, + 'Slatepack', + ), + onTap: () {}, ), - onTap: () {}, + disableDuration: Duration.zero, ), - disableDuration: Duration.zero, ), ), ), diff --git a/tool/wl_templates/EPIC_libepiccash_interface_impl.template.dart b/tool/wl_templates/EPIC_libepiccash_interface_impl.template.dart index f7705af11e..415c447976 100644 --- a/tool/wl_templates/EPIC_libepiccash_interface_impl.template.dart +++ b/tool/wl_templates/EPIC_libepiccash_interface_impl.template.dart @@ -39,23 +39,12 @@ final class _LibEpicCashInterfaceImpl extends LibEpicCashInterface { } @override - Future<({String slateId, String commitId, String slateJson, bool? posted})> - txFinalize({required DynamicObject wallet, required String slateJson}) async { - final dynamic finalized = await wallet.get().txFinalize( - slateJson: slateJson, - ); - bool? posted; - try { - posted = finalized.posted as bool?; - } on NoSuchMethodError { - // Older plugin revisions do not report whether the node accepted it. - } - return ( - slateId: finalized.slateId as String, - commitId: finalized.commitId as String, - slateJson: finalized.slateJson as String, - posted: posted, - ); + Future<({String slateId, String commitId, String slateJson})> txFinalize({ + required DynamicObject wallet, + required String slateJson, + }) async { + return (await wallet.get().txFinalize(slateJson: slateJson)) + .toRecord(); } @override diff --git a/tool/wl_templates/MWC_libmwc_interface_impl.template.dart b/tool/wl_templates/MWC_libmwc_interface_impl.template.dart index 2ba7a6655f..01dc5c123a 100644 --- a/tool/wl_templates/MWC_libmwc_interface_impl.template.dart +++ b/tool/wl_templates/MWC_libmwc_interface_impl.template.dart @@ -273,25 +273,14 @@ final class _LibMwcInterfaceImpl extends LibMwcInterface { } @override - Future<({String commitId, String slateId, bool? posted})> txFinalize({ + Future<({String commitId, String slateId})> txFinalize({ required String wallet, required String slateJson, - }) async { - final dynamic finalized = await mimblewimblecoin.Libmwc.txFinalize( + }) { + return mimblewimblecoin.Libmwc.txFinalize( wallet: wallet, slateJson: slateJson, ); - bool? posted; - try { - posted = finalized.posted as bool?; - } on NoSuchMethodError { - // Older plugin revisions do not report whether the node accepted it. - } - return ( - commitId: finalized.commitId as String, - slateId: finalized.slateId as String, - posted: posted, - ); } @override From 0850e7d15c30d1612009067a49e54215b2b38179 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Mon, 30 Nov 2026 13:49:40 -0600 Subject: [PATCH 3/3] fix(slatepack): fix nested nav loop, MWC finalize UX, and adversarial review findings --- lib/pages/send_view/send_view.dart | 4 +- .../slatepack_cancel_transaction_dialog.dart | 87 +++++++++++ lib/pages/slatepack/slatepack_dialog.dart | 21 ++- .../slatepack/slatepack_import_flow.dart | 75 ++++------ lib/pages/slatepack/slatepack_popup.dart | 37 +++++ lib/pages/slatepack/slatepack_send_flow.dart | 41 +++-- lib/pages/slatepack/slatepack_view.dart | 40 ++++- .../transaction_details_view.dart | 85 +---------- .../tx_v2/transaction_v2_details_view.dart | 85 +---------- .../sub_widgets/desktop_receive.dart | 6 + lib/utilities/route_presentation.dart | 3 +- lib/utilities/slatepack_text.dart | 10 ++ .../wallet/impl/mimblewimblecoin_wallet.dart | 29 +++- .../slatepack_interface.dart | 63 +++++--- test/pages/send_view/send_views_test.dart | 30 ++++ .../desktop_receive_slatepack_test.dart | 88 +++++++++++ ...tepack_cancel_transaction_dialog_test.dart | 141 ++++++++++++++++++ .../slatepack/slatepack_dialog_test.dart | 122 ++++++++++++--- .../slatepack/slatepack_import_flow_test.dart | 87 ++++++++++- .../slatepack/slatepack_send_flow_test.dart | 128 +++++++++++++--- test/pages/slatepack/slatepack_view_test.dart | 133 +++++++++++++++++ test/utilities/route_presentation_test.dart | 122 +++++++++++++++ .../mimblewimble_slate_inspection_test.dart | 79 +++++++++- 23 files changed, 1200 insertions(+), 316 deletions(-) diff --git a/lib/pages/send_view/send_view.dart b/lib/pages/send_view/send_view.dart index ffdc96a349..5312ca1563 100644 --- a/lib/pages/send_view/send_view.dart +++ b/lib/pages/send_view/send_view.dart @@ -767,11 +767,9 @@ class _SendViewState extends ConsumerState with SendFeeForm { final wallet = ref.read(pWallets).getWallet(walletId); final isSlatepackSend = wallet is SlatepackInterface && ref.read(pIsSlatepack(walletId)); + if (isSlatepackSend != earlySlatepack) return; if (isSlatepackSend) { if (ModalRoute.of(context)?.isCurrent != true) return; - if (!lockedSlatepack && _creatingSlatepack) return; - _creatingSlatepack = true; - lockedSlatepack = true; final Amount? amount = ref.read(pSendAmount); if (amount == null || amount <= Amount.zero) return; final created = await SlatepackSendFlow.run( diff --git a/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart index 849d7c8b9a..86032a9769 100644 --- a/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart +++ b/lib/pages/slatepack/slatepack_cancel_transaction_dialog.dart @@ -1,11 +1,20 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; +import '../../notifications/show_flush_bar.dart'; import '../../themes/stack_colors.dart'; +import '../../utilities/exception_message.dart'; +import '../../utilities/route_presentation.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; +import '../../wallets/wallet/wallet.dart'; +import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; import '../../widgets/desktop/primary_button.dart'; import '../../widgets/desktop/secondary_button.dart'; import '../../widgets/stack_dialog.dart'; +import '../wallet_view/transaction_views/dialogs/cancelling_transaction_progress_dialog.dart'; +import '../wallet_view/wallet_view.dart'; bool canCancelSlateTransaction({ required String? slateId, @@ -14,6 +23,84 @@ bool canCancelSlateTransaction({ }) => (slateId?.trim().isNotEmpty ?? false) && !isCancelled && confirmations < 1; +/// Confirms, executes, and reports cancelling a pending slate transaction. +Future cancelSlatepackTransaction({ + required BuildContext context, + required Wallet wallet, + required String? slateId, +}) async { + if (wallet is! SlatepackInterface) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: "ERROR: This wallet cannot cancel slatepack transactions", + context: context, + ), + ); + return; + } + + final id = slateId?.trim(); + if (id == null || id.isEmpty) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: + "Could not find ${wallet.cryptoCurrency.ticker} transaction ID", + context: context, + ), + ); + return; + } + + final proceed = await showDialog( + context: context, + builder: (_) => const SlatepackCancelTransactionDialog(), + ); + if (proceed != true || !context.mounted) return; + + final outcome = await runWithCurrentAwareOverlay( + context: context, + builder: (_) => const CancellingTransactionProgressDialog(), + action: () => wallet.cancelPendingTransactionAndPost(id), + ); + if (outcome.aborted) return; + + final rawMessage = outcome.error != null + ? stripExceptionPrefixes(outcome.error!) + : (outcome.value ?? ""); + final succeeded = outcome.error == null && rawMessage.isEmpty; + if (outcome.canPresentResult && context.mounted) { + if (succeeded) { + await showDialog( + context: context, + builder: (_) => StackOkDialog( + title: "Transaction cancelled", + maxWidth: Util.isDesktop ? 400 : null, + onOkPressed: (_) { + Navigator.of(context) + .popUntil(ModalRoute.withName(WalletView.routeName)); + }, + ), + ); + unawaited(wallet.refresh()); + } else { + await showDialog( + context: context, + builder: (_) => StackOkDialog( + title: "Failed to cancel transaction", + message: rawMessage.isEmpty + ? "Failed to cancel transaction" + : rawMessage, + maxWidth: Util.isDesktop ? 400 : null, + ), + ); + } + } else if (succeeded) { + unawaited(wallet.refresh()); + } +} + class SlatepackCancelTransactionDialog extends StatelessWidget { const SlatepackCancelTransactionDialog({super.key}); diff --git a/lib/pages/slatepack/slatepack_dialog.dart b/lib/pages/slatepack/slatepack_dialog.dart index 9a836e0d22..e574afc1bc 100644 --- a/lib/pages/slatepack/slatepack_dialog.dart +++ b/lib/pages/slatepack/slatepack_dialog.dart @@ -348,9 +348,13 @@ class _SlatepackDialogState extends State { builder: (context, constraints) { final canShare = Util.layoutPlatform.isAndroid || Util.layoutPlatform.isIOS; - final scaledText = MediaQuery.textScalerOf(context).scale(14); + final scaledText = MediaQuery.textScalerOf(context).scale(16); + final useOneColumn = + canShare && + ((constraints.maxWidth < 260 && scaledText > 16) || + constraints.maxWidth < 200); final useTwoRows = - canShare && (constraints.maxWidth < 300 || scaledText > 14); + canShare && (constraints.maxWidth < 340 || scaledText > 16); final copy = SecondaryButton( label: "Copy", @@ -373,6 +377,19 @@ class _SlatepackDialogState extends State { onPressed: () => _save(context), ); + if (useOneColumn) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + copy, + const SizedBox(height: 12), + share, + const SizedBox(height: 12), + save, + ], + ); + } + if (useTwoRows) { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart index af52e9fad9..6d84338a43 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -4,14 +4,11 @@ import 'package:flutter/material.dart'; import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; -import '../../themes/stack_colors.dart'; import '../../utilities/amount/amount.dart'; import '../../utilities/exception_message.dart'; import '../../utilities/logger.dart'; -import '../../utilities/route_presentation.dart'; import '../../utilities/slatepack_text.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; -import '../../widgets/custom_loading_overlay.dart'; import 'slatepack_dialog.dart'; import 'slatepack_popup.dart'; import 'slatepack_summary_dialog.dart'; @@ -401,39 +398,18 @@ abstract final class SlatepackImportFlow { return true; } - if (result.posted == true) { - final flushContext = context.mounted + if (result.posted == false) { + final dialogContext = context.mounted ? context : (root.mounted ? root.context : null); - if (flushContext != null && flushContext.mounted) { - unawaited( - showFloatingFlushBar( - type: FlushBarType.success, - message: "Transaction finalized and broadcast", - context: flushContext, - ), - ); - } else { + if (dialogContext == null || !dialogContext.mounted) { Logging.instance.w( - "Finalized ${terms.noun} ${inspection.slateId} after the screen " - "that imported it had closed. Broadcast: ${result.posted}.", + "Finalized ${terms.noun} ${inspection.slateId} with no context to " + "show broadcast warning. Broadcast: ${result.posted}.", ); + return true; } - return true; - } - final dialogContext = context.mounted - ? context - : (root.mounted ? root.context : null); - if (dialogContext == null || !dialogContext.mounted) { - Logging.instance.w( - "Finalized ${terms.noun} ${inspection.slateId} with no context to " - "show broadcast warning. Broadcast: ${result.posted}.", - ); - return true; - } - - if (result.posted == false) { await showSlatepackOkDialog( context: dialogContext, title: "Finalized, not broadcast", @@ -442,14 +418,24 @@ abstract final class SlatepackImportFlow { "Check the node connection and transaction history before " "creating a replacement.", ); + return true; + } + + if (context.mounted && + Overlay.maybeOf(context, rootOverlay: true) != null) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.success, + message: result.posted == true + ? "Transaction finalized and broadcast" + : "Transaction finalized", + context: context, + ), + ); } else { - await showSlatepackOkDialog( - context: dialogContext, - title: "Transaction finalized", - message: - "The native wallet finalized the transaction, but its broadcast " - "result is unavailable. Check transaction history and the node " - "connection before creating a replacement.", + Logging.instance.w( + "Finalized ${terms.noun} ${inspection.slateId} after the screen " + "that imported it had closed. Broadcast: ${result.posted}.", ); } return true; @@ -464,21 +450,10 @@ abstract final class SlatepackImportFlow { required String errorTitle, }) async { final root = Navigator.of(context, rootNavigator: true); - final overlayColor = Theme.of(context) - .extension()! - .overlay - .withValues(alpha: 0.6); - final outcome = await runWithCurrentAwareOverlay( + final outcome = await runWithSlatepackLoadingOverlay( context: context, - useSafeArea: false, - builder: (_) => PopScope( - canPop: false, - child: Container( - color: overlayColor, - child: CustomLoadingOverlay(message: message, eventBus: null), - ), - ), + message: message, action: action, ); if (outcome.aborted) return null; diff --git a/lib/pages/slatepack/slatepack_popup.dart b/lib/pages/slatepack/slatepack_popup.dart index 44e91dd08d..2e08630721 100644 --- a/lib/pages/slatepack/slatepack_popup.dart +++ b/lib/pages/slatepack/slatepack_popup.dart @@ -1,11 +1,48 @@ import 'package:flutter/material.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/route_presentation.dart'; import '../../utilities/text_styles.dart'; import '../../utilities/util.dart'; +import '../../widgets/custom_loading_overlay.dart'; import '../../widgets/desktop/desktop_dialog.dart'; import '../../widgets/desktop/desktop_dialog_close_button.dart'; import '../../widgets/stack_dialog.dart'; +/// Pushes a current-aware loading overlay using the shared Slatepack scrim +/// and [CustomLoadingOverlay]. +Future< + ({ + T? value, + Object? error, + StackTrace? stackTrace, + bool canPresentResult, + bool aborted, + }) +> +runWithSlatepackLoadingOverlay({ + required BuildContext context, + required String message, + required Future Function() action, +}) { + final overlayColor = Theme.of(context) + .extension()! + .overlay + .withValues(alpha: 0.6); + return runWithCurrentAwareOverlay( + context: context, + useSafeArea: false, + builder: (_) => PopScope( + canPop: false, + child: Container( + color: overlayColor, + child: CustomLoadingOverlay(message: message, eventBus: null), + ), + ), + action: action, + ); +} + /// Shows an informational dialog on mobile and desktop without popping /// [DesktopHomeView] off the root navigator. Future showSlatepackOkDialog({ diff --git a/lib/pages/slatepack/slatepack_send_flow.dart b/lib/pages/slatepack/slatepack_send_flow.dart index 7f0a93b994..e08b9cc94b 100644 --- a/lib/pages/slatepack/slatepack_send_flow.dart +++ b/lib/pages/slatepack/slatepack_send_flow.dart @@ -5,13 +5,11 @@ import 'package:flutter/material.dart'; import '../../db/isar/main_db.dart'; import '../../models/isar/models/transaction_note.dart'; import '../../models/slatepack_models.dart'; -import '../../themes/stack_colors.dart'; import '../../utilities/amount/amount.dart'; import '../../utilities/exception_message.dart'; import '../../utilities/logger.dart'; import '../../utilities/route_presentation.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; -import '../../widgets/custom_loading_overlay.dart'; import 'slatepack_dialog.dart'; import 'slatepack_popup.dart'; @@ -39,27 +37,13 @@ abstract final class SlatepackSendFlow { }) async { final terms = wallet.slatepackTerms; final root = Navigator.of(context, rootNavigator: true); - final overlayColor = Theme.of(context) - .extension()! - .overlay - .withValues(alpha: 0.6); var noteSaved = localNote.isEmpty; var shouldRefresh = false; - final outcome = await runWithCurrentAwareOverlay( + final outcome = await runWithSlatepackLoadingOverlay( context: context, - useSafeArea: false, - builder: (_) => PopScope( - canPop: false, - child: Container( - color: overlayColor, - child: CustomLoadingOverlay( - message: "Building ${terms.noun}...", - eventBus: null, - ), - ), - ), + message: "Building ${terms.noun}...", action: () async { final created = await wallet.createSlatepack( amount: amount, @@ -67,7 +51,10 @@ abstract final class SlatepackSendFlow { ? message : null, ); - if (!created.success || (created.slatepack?.trim().isEmpty ?? true)) { + if (!created.success) { + if (created.slateId != null && created.slateId!.isNotEmpty) { + shouldRefresh = true; + } throw Exception( stripExceptionPrefixes( created.error ?? "Failed to create ${terms.noun}", @@ -75,18 +62,27 @@ abstract final class SlatepackSendFlow { ); } + final missingPayload = created.slatepack?.trim().isEmpty ?? true; final slateId = created.slateId; final createdAmount = created.amount; final createdFee = created.fee; - if (slateId == null || + final missingFields = + slateId == null || slateId.isEmpty || createdAmount == null || - createdFee == null) { + createdFee == null; + if (missingPayload || missingFields) { final cancelError = slateId == null || slateId.isEmpty ? "it has no slate id" : await wallet.cancelPendingTransactionAndPost(slateId); shouldRefresh = slateId != null && slateId.isNotEmpty && cancelError.isNotEmpty; + if (!missingFields && missingPayload) { + throw Exception( + "The wallet did not return a ${terms.noun}. " + "${_cancelOutcomeMessage(cancelError)}", + ); + } throw Exception( "The wallet did not return the ${terms.noun}'s complete amount, " "fee, and identifier. ${_cancelOutcomeMessage(cancelError)}", @@ -170,7 +166,8 @@ abstract final class SlatepackSendFlow { ); if (!noteSaved && root.mounted && - (!context.mounted || isHostRouteCurrent(context, root))) { + context.mounted && + isHostRouteCurrent(context, root)) { await showSlatepackOkDialog( context: root.context, title: "Local note not saved", diff --git a/lib/pages/slatepack/slatepack_view.dart b/lib/pages/slatepack/slatepack_view.dart index fdbe55029e..62eb6073ee 100644 --- a/lib/pages/slatepack/slatepack_view.dart +++ b/lib/pages/slatepack/slatepack_view.dart @@ -32,6 +32,7 @@ class SlatepackImportForm extends ConsumerStatefulWidget { super.key, required this.walletId, required this.buttonLabel, + this.controller, this.header, this.expandToFill = true, this.clipboard = const ClipboardWrapper(), @@ -39,6 +40,7 @@ class SlatepackImportForm extends ConsumerStatefulWidget { final String walletId; final String buttonLabel; + final TextEditingController? controller; final Widget? header; final bool expandToFill; final ClipboardInterface clipboard; @@ -49,7 +51,9 @@ class SlatepackImportForm extends ConsumerStatefulWidget { } class _SlatepackImportFormState extends ConsumerState { - late final TextEditingController _controller; + late TextEditingController _controller; + late bool _ownsController; + late bool _hadText; late final FocusNode _focusNode; late SlatepackInterface _wallet; @@ -59,6 +63,14 @@ class _SlatepackImportFormState extends ConsumerState { bool get _hasText => _controller.text.trim().isNotEmpty; + void _onControllerChanged() { + final hasText = _hasText; + if (hasText != _hadText) { + _hadText = hasText; + if (mounted) setState(() {}); + } + } + Future _submitPressed() async { if (_importing) return; setState(() => _importing = true); @@ -69,7 +81,7 @@ class _SlatepackImportFormState extends ConsumerState { await Future.delayed(const Duration(milliseconds: 75)); } } - if (!mounted) return; + if (!mounted || !_hasText) return; final done = await SlatepackImportFlow.run( context: context, @@ -77,7 +89,8 @@ class _SlatepackImportFormState extends ConsumerState { text: _controller.text, ); if (done && mounted) { - setState(() => _controller.text = ""); + _controller.text = ""; + setState(() => _hadText = false); } } finally { _importing = false; @@ -88,7 +101,10 @@ class _SlatepackImportFormState extends ConsumerState { @override void initState() { super.initState(); - _controller = TextEditingController(); + _ownsController = widget.controller == null; + _controller = widget.controller ?? TextEditingController(); + _hadText = _hasText; + _controller.addListener(_onControllerChanged); _focusNode = FocusNode(); _wallet = ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; @@ -97,6 +113,16 @@ class _SlatepackImportFormState extends ConsumerState { @override void didUpdateWidget(covariant SlatepackImportForm oldWidget) { super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + _controller.removeListener(_onControllerChanged); + if (_ownsController) { + _controller.dispose(); + } + _ownsController = widget.controller == null; + _controller = widget.controller ?? TextEditingController(); + _hadText = _hasText; + _controller.addListener(_onControllerChanged); + } if (oldWidget.walletId != widget.walletId) { _wallet = ref.read(pWallets).getWallet(widget.walletId) as SlatepackInterface; @@ -105,7 +131,10 @@ class _SlatepackImportFormState extends ConsumerState { @override void dispose() { - _controller.dispose(); + _controller.removeListener(_onControllerChanged); + if (_ownsController) { + _controller.dispose(); + } _focusNode.dispose(); super.dispose(); } @@ -128,7 +157,6 @@ class _SlatepackImportFormState extends ConsumerState { hint: "Enter ${terms.payload}", terms: terms, clipboard: widget.clipboard, - onChanged: (_) => setState(() {}), ), if (widget.expandToFill) isDesktop ? const SizedBox(height: 24) : const Spacer() 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 9d36a688fc..f8b2e2c7bd 100644 --- a/lib/pages/wallet_view/transaction_views/transaction_details_view.dart +++ b/lib/pages/wallet_view/transaction_views/transaction_details_view.dart @@ -30,10 +30,8 @@ import '../../../utilities/amount/amount_formatter.dart'; import '../../../utilities/assets.dart'; import '../../../utilities/block_explorers.dart'; import '../../../utilities/constants.dart'; -import '../../../utilities/exception_message.dart'; import '../../../utilities/format.dart'; import '../../../utilities/logger.dart'; -import '../../../utilities/route_presentation.dart'; import '../../../utilities/text_styles.dart'; import '../../../utilities/util.dart'; import '../../../wallets/crypto_currency/crypto_currency.dart'; @@ -55,8 +53,6 @@ import '../../../widgets/stack_dialog.dart'; import '../../receive_view/addresses/address_details_view.dart'; import '../../slatepack/slatepack_cancel_transaction_dialog.dart'; import '../sub_widgets/tx_icon.dart'; -import '../wallet_view.dart'; -import 'dialogs/cancelling_transaction_progress_dialog.dart'; import 'edit_note_view.dart'; class TransactionDetailsView extends ConsumerStatefulWidget { @@ -1704,82 +1700,11 @@ class _TransactionDetailsViewState if (_cancelling) return; _cancelling = true; try { - final wallet = ref.read(pWallets).getWallet(walletId); - - if (wallet is SlatepackInterface) { - final String? id = _transaction.slateId; - if (id == null) { - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: - "Could not find " - "${wallet.cryptoCurrency.ticker} transaction ID", - context: context, - ), - ); - return; - } - - final proceed = await showDialog( - context: context, - builder: (_) => - const SlatepackCancelTransactionDialog(), - ); - if (proceed != true || !context.mounted) return; - - final outcome = - await runWithCurrentAwareOverlay( - context: context, - builder: (_) => - const CancellingTransactionProgressDialog(), - action: () => - wallet.cancelPendingTransactionAndPost(id), - ); - if (outcome.aborted) return; - - final result = outcome.error != null - ? stripExceptionPrefixes(outcome.error!) - : (outcome.value ?? ""); - if (outcome.canPresentResult && context.mounted) { - if (result.isEmpty) { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Transaction cancelled", - maxWidth: Util.isDesktop ? 400 : null, - onOkPressed: (_) { - Navigator.of(context).popUntil( - ModalRoute.withName(WalletView.routeName), - ); - }, - ), - ); - unawaited(wallet.refresh()); - } else { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Failed to cancel transaction", - message: result, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - } - } else if (result.isEmpty) { - unawaited(wallet.refresh()); - } - } else { - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: - "ERROR: This wallet cannot cancel " - "slatepack transactions", - context: context, - ), - ); - } + await cancelSlatepackTransaction( + context: context, + wallet: ref.read(pWallets).getWallet(walletId), + slateId: _transaction.slateId, + ); } finally { _cancelling = false; } 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 e920fc71ce..9356d38e49 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 @@ -32,10 +32,8 @@ import '../../../../utilities/amount/amount_formatter.dart'; import '../../../../utilities/assets.dart'; import '../../../../utilities/block_explorers.dart'; import '../../../../utilities/constants.dart'; -import '../../../../utilities/exception_message.dart'; import '../../../../utilities/format.dart'; import '../../../../utilities/logger.dart'; -import '../../../../utilities/route_presentation.dart'; import '../../../../utilities/show_loading.dart'; import '../../../../utilities/text_styles.dart'; import '../../../../utilities/util.dart'; @@ -63,8 +61,6 @@ import '../../../../widgets/stack_dialog.dart'; import '../../../../widgets/tx_key_widget.dart'; import '../../../slatepack/slatepack_cancel_transaction_dialog.dart'; import '../../sub_widgets/tx_icon.dart'; -import '../../wallet_view.dart'; -import '../dialogs/cancelling_transaction_progress_dialog.dart'; import '../edit_note_view.dart'; import 'boost_transaction_view.dart'; @@ -1513,82 +1509,11 @@ class _TransactionV2DetailsViewState if (_cancelling) return; _cancelling = true; try { - final wallet = ref.read(pWallets).getWallet(walletId); - - if (wallet is SlatepackInterface) { - final String? id = _transaction.slateId; - if (id == null) { - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: - "Could not find " - "${wallet.cryptoCurrency.ticker} transaction ID", - context: context, - ), - ); - return; - } - - final proceed = await showDialog( - context: context, - builder: (_) => - const SlatepackCancelTransactionDialog(), - ); - if (proceed != true || !context.mounted) return; - - final outcome = - await runWithCurrentAwareOverlay( - context: context, - builder: (_) => - const CancellingTransactionProgressDialog(), - action: () => - wallet.cancelPendingTransactionAndPost(id), - ); - if (outcome.aborted) return; - - final result = outcome.error != null - ? stripExceptionPrefixes(outcome.error!) - : (outcome.value ?? ""); - if (outcome.canPresentResult && context.mounted) { - if (result.isEmpty) { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Transaction cancelled", - onOkPressed: (_) { - Navigator.of(context).popUntil( - ModalRoute.withName(WalletView.routeName), - ); - }, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - unawaited(wallet.refresh()); - } else { - await showDialog( - context: context, - builder: (_) => StackOkDialog( - title: "Failed to cancel transaction", - message: result, - maxWidth: Util.isDesktop ? 400 : null, - ), - ); - } - } else if (result.isEmpty) { - unawaited(wallet.refresh()); - } - } else { - unawaited( - showFloatingFlushBar( - type: FlushBarType.warning, - message: - "ERROR: This wallet cannot cancel " - "slatepack transactions", - context: context, - ), - ); - } + await cancelSlatepackTransaction( + context: context, + wallet: ref.read(pWallets).getWallet(walletId), + slateId: _transaction.slateId, + ); } finally { _cancelling = false; } 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 c8d9cc90f1..9120a27741 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 @@ -80,6 +80,7 @@ class _DesktopReceiveState extends ConsumerState { late bool supportsMweb; late final bool showMultiType; late final SlatepackTerms _slatepackTerms; + late final TextEditingController? _receiveSlateController; int _currentIndex = 0; @@ -272,6 +273,9 @@ class _DesktopReceiveState extends ConsumerState { _slatepackTerms = wallet is SlatepackInterface ? wallet.slatepackTerms : SlatepackTerms.slatepack; + _receiveSlateController = wallet is SlatepackInterface + ? TextEditingController() + : null; if (wallet is ViewOnlyOptionInterface && wallet.isViewOnly) { showMultiType = false; @@ -323,6 +327,7 @@ class _DesktopReceiveState extends ConsumerState { @override void dispose() { + _receiveSlateController?.dispose(); for (final subscription in _addressSubMap.values) { subscription.cancel(); } @@ -700,6 +705,7 @@ class _DesktopReceiveState extends ConsumerState { if (isSlatepackMode) SlatepackImportForm( walletId: walletId, + controller: _receiveSlateController, clipboard: clipboard, buttonLabel: "Import ${_slatepackTerms.title}", expandToFill: false, diff --git a/lib/utilities/route_presentation.dart b/lib/utilities/route_presentation.dart index 25214fcee8..b96ad1656f 100644 --- a/lib/utilities/route_presentation.dart +++ b/lib/utilities/route_presentation.dart @@ -120,12 +120,13 @@ Future waitForRoutePresentation(TransitionRoute route) async { } bool isHostRouteCurrent(BuildContext context, NavigatorState root) { + if (!context.mounted) return false; if (ModalRoute.of(context)?.isCurrent == false) return false; var nav = Navigator.maybeOf(context); while (nav != null && nav != root) { final hostRoute = ModalRoute.of(nav.context); if (hostRoute != null && !hostRoute.isCurrent) return false; - nav = Navigator.maybeOf(nav.context); + nav = nav.context.findAncestorStateOfType(); } return true; } diff --git a/lib/utilities/slatepack_text.dart b/lib/utilities/slatepack_text.dart index cf7e6b4f38..ff66c83b29 100644 --- a/lib/utilities/slatepack_text.dart +++ b/lib/utilities/slatepack_text.dart @@ -10,6 +10,16 @@ abstract final class SlatepackText { return _armoredFrame.firstMatch(trimmed)?.group(0) == trimmed; } + /// Number of armored Slatepack frames found in [text]. + /// + /// Returns 0 for plain JSON objects (`{...}`) so embedded text inside JSON + /// fields is not mistaken for armored frames. + static int armoredFrameCount(String text) { + final trimmed = text.trim(); + if (trimmed.startsWith("{") && trimmed.endsWith("}")) return 0; + return _armoredFrame.allMatches(trimmed).length; + } + /// Removes surrounding prose from an armored Slatepack. /// /// Plain slate JSON and unrecognized text (including multiple concatenated diff --git a/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart b/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart index f8fa5ce614..1ab9839086 100644 --- a/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart +++ b/lib/wallets/wallet/impl/mimblewimblecoin_wallet.dart @@ -275,11 +275,26 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { return slatepack; } catch (e, s) { var errorMessage = e.toString(); + String? failedRollbackSlateId; if (s1Json != null) { - final slateId = inspectSlateJsonString(s1Json)?.slateId; + final failedInspection = inspectSlateJsonString(s1Json); + final slateId = failedInspection?.slateId; if (slateId != null && slateId.isNotEmpty) { final cancelError = await cancelPendingTransactionAndPost(slateId); if (cancelError.isNotEmpty) { + failedRollbackSlateId = slateId; + if (failedInspection?.amount != null && + failedInspection?.fee != null) { + await rememberPendingSlateSend( + SlatepackResult( + success: false, + slateId: slateId, + amount: failedInspection!.amount, + fee: failedInspection.fee, + state: SlateState.s1, + ), + ); + } Logging.instance.w( 'Failed to roll back pending slate $slateId after encode ' 'failure: $cancelError', @@ -291,7 +306,11 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { } } Logging.instance.e('Failed to create slatepack: $e\n$s'); - return SlatepackResult(success: false, error: errorMessage); + return SlatepackResult( + success: false, + slateId: failedRollbackSlateId, + error: errorMessage, + ); } } @@ -370,6 +389,12 @@ class MimblewimblecoinWallet extends Bip39Wallet with SlatepackInterface { @override void checkSlatepackFormat(String armored) { + final frameCount = SlatepackText.armoredFrameCount(armored); + if (frameCount > 1) { + throw Exception( + "Found $frameCount slatepacks. Enter only one slatepack at a time.", + ); + } if (!isSlatepack(armored)) { throw Exception("Invalid slatepack format"); } diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart index 43837b7f89..e0561e7883 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart @@ -13,6 +13,8 @@ import '../../../utilities/logger.dart'; import '../../crypto_currency/crypto_currency.dart'; import '../wallet.dart'; +String _normalizeSlateId(String slateId) => slateId.trim().toLowerCase(); + /// Slatepack exchange shared by the Mimblewimble coins. The slatepack /// screens talk to this instead of a concrete wallet type. mixin SlatepackInterface on Wallet { @@ -23,8 +25,6 @@ mixin SlatepackInterface on Wallet { _pendingSlateTransactions = {}; final Set _cancelledSlateIds = {}; - String _normalizeSlateId(String slateId) => slateId.trim().toLowerCase(); - /// Methods the send and receive screens offer. The first is the default. List get supportedMethods; @@ -141,8 +141,12 @@ mixin SlatepackInterface on Wallet { } TransactionV2? tx; + Object? dbError; + StackTrace? dbStackTrace; try { - if (mainDB.isar.isOpen) { + if (!mainDB.isar.isOpen) { + dbError = StateError('Local transaction database is unavailable'); + } else { tx = localSlateTransaction( await mainDB.isar.transactionV2s .where() @@ -154,6 +158,8 @@ mixin SlatepackInterface on Wallet { ); } } catch (e, s) { + dbError = e; + dbStackTrace = s; Logging.instance.w( "Could not query local transactions for slate $slateId", error: e, @@ -163,13 +169,21 @@ mixin SlatepackInterface on Wallet { if (tx == null) { final fallback = inMemory ?? pending; - if (fallback == null) return null; - return ( - amount: fallback.amount, - fee: fallback.fee, - isSend: fallback.isSend, - isCancelled: fallback.isCancelled || _cancelledSlateIds.contains(id), - ); + if (fallback != null) { + return ( + amount: fallback.amount, + fee: fallback.fee, + isSend: fallback.isSend, + isCancelled: fallback.isCancelled || _cancelledSlateIds.contains(id), + ); + } + if (dbError != null) { + if (dbStackTrace != null) { + Error.throwWithStackTrace(dbError, dbStackTrace); + } + throw dbError; + } + return null; } final digits = cryptoCurrency.fractionDigits; @@ -196,9 +210,14 @@ mixin SlatepackInterface on Wallet { ) : tx.getAmountReceivedInThisWallet(fractionDigits: digits); } + final txFee = tx.getFee(fractionDigits: digits); + final fee = + tx.type == TransactionType.sentToSelf && txFee.raw == BigInt.zero + ? (inMemory?.fee ?? pending?.fee ?? txFee) + : txFee; return ( amount: amount, - fee: tx.getFee(fractionDigits: digits), + fee: fee, isSend: isSend, isCancelled: tx.isCancelled || @@ -214,7 +233,8 @@ mixin SlatepackInterface on Wallet { String normalizedId, ) { for (final entry in metadata.entries) { - if (entry.key?.toString().trim().toLowerCase() == normalizedId && + if (entry.key != null && + _normalizeSlateId(entry.key.toString()) == normalizedId && entry.value is Map) { return ( key: entry.key.toString(), @@ -393,12 +413,13 @@ pendingSlateSendMatching( String slateId, { required int fractionDigits, }) { - final target = slateId.trim().toLowerCase(); + final target = _normalizeSlateId(slateId); if (target.isEmpty) return null; Map? raw; for (final entry in metadata.entries) { - if (entry.key?.toString().trim().toLowerCase() == target && + if (entry.key != null && + _normalizeSlateId(entry.key.toString()) == target && entry.value is Map) { raw = entry.value as Map; break; @@ -485,18 +506,26 @@ TransactionV2? localSlateTransaction( Iterable candidates, String slateId, ) { - final target = slateId.trim().toLowerCase(); + final target = _normalizeSlateId(slateId); if (target.isEmpty) return null; TransactionV2? sendMatch; TransactionV2? receiveMatch; for (final tx in candidates) { - if (tx.slateId?.trim().toLowerCase() != target) continue; + final txSlateId = tx.slateId; + if (txSlateId == null || _normalizeSlateId(txSlateId) != target) continue; final isSend = tx.type == TransactionType.outgoing || tx.type == TransactionType.sentToSelf; if (isSend) { - if (sendMatch == null || (sendMatch.isCancelled && !tx.isCancelled)) { + final upgradeFromSelf = + sendMatch != null && + sendMatch.isCancelled == tx.isCancelled && + sendMatch.type == TransactionType.sentToSelf && + tx.type == TransactionType.outgoing; + final preferLive = + sendMatch != null && sendMatch.isCancelled && !tx.isCancelled; + if (sendMatch == null || preferLive || upgradeFromSelf) { sendMatch = tx; } } else if (receiveMatch == null || diff --git a/test/pages/send_view/send_views_test.dart b/test/pages/send_view/send_views_test.dart index 6ab213e1e7..2dcc6afc74 100644 --- a/test/pages/send_view/send_views_test.dart +++ b/test/pages/send_view/send_views_test.dart @@ -968,5 +968,35 @@ void main() { expect(tester.element(find.byType(SendView)).dirty, isFalse); }); } + + testWithoutAnimation( + "aborts instead of crashing if method switches during unfocus delay", + (tester) async { + final wallet = FakeEpiccashWallet(); + await mobileCoin.pump( + tester, + wallet: wallet, + balance: testBalance("10", wallet.cryptoCurrency.fractionDigits), + overrides: [ + pSelectedSlatepackMethod(wallet.walletId).overrideWithProvider( + StateProvider((_) => SlatepackMethod.slatepack), + ), + ], + ); + await enterAmount(tester, mobileCoin, "1"); + + await tester.tap(find.text("Create slate")); + await tester.pump(const Duration(milliseconds: 20)); + ProviderScope.containerOf(tester.element(find.byType(SendView))) + .read(pSelectedSlatepackMethod(wallet.walletId).notifier) + .state = + SlatepackMethod.relay; + await settle(tester); + + expect(wallet.slateCreates, 0); + expect(wallet.prepared, isNull); + expect(tester.takeException(), isNull); + }, + ); }); } diff --git a/test/pages/slatepack/desktop_receive_slatepack_test.dart b/test/pages/slatepack/desktop_receive_slatepack_test.dart index 609be70abe..0d57c27ffb 100644 --- a/test/pages/slatepack/desktop_receive_slatepack_test.dart +++ b/test/pages/slatepack/desktop_receive_slatepack_test.dart @@ -16,7 +16,9 @@ import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; import 'package:stackwallet/wallets/wallet/wallet.dart'; +import 'package:stackwallet/widgets/desktop/primary_button.dart'; import 'package:stackwallet/widgets/qr.dart'; +import 'package:stackwallet/widgets/slatepack_method_toggle.dart'; import '../../sample_data/theme_json.dart'; @@ -100,4 +102,90 @@ void main() { expect(find.byType(QR), findsNothing); expect(tester.takeException(), isNull); }); + + testWidgets( + 'desktop receive preserves pasted slatepack text across mode switches', + (tester) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + tester.view.physicalSize = const Size(1400, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final info = WalletInfo.createNew( + coin: Epiccash(CryptoCurrencyNetwork.main), + name: 'Epic Cash', + walletIdOverride: _walletId, + ).copyWith(cachedReceivingAddress: _address); + final wallet = _Wallet(info); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(_Wallets(wallet)), + pWalletInfo(_walletId).overrideWithValue(info), + pWalletReceivingAddress(_walletId).overrideWithValue(_address), + pSelectedSlatepackMethod(_walletId).overrideWithProvider( + StateProvider( + (ref) => SlatepackMethod.slatepack, + ), + ), + themeProvider.overrideWithProvider( + StateProvider((ref) => theme), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold( + body: SingleChildScrollView( + child: SizedBox( + width: 520, + child: DesktopReceive(walletId: _walletId), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + const pasted = '{"id":"keep-me"}'; + await tester.enterText( + find.byKey(const Key('slatepackInputField')), + pasted, + ); + await tester.pump(); + expect( + tester.widget(find.byType(PrimaryButton)).enabled, + isTrue, + ); + + // Toggle from Slate -> Automatic, then back to Slate. + await tester.tap(find.byType(SlatepackMethodToggle)); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('slatepackInputField')), findsNothing); + expect(find.text(_address), findsOneWidget); + expect(find.byType(QR), findsOneWidget); + + await tester.tap(find.byType(SlatepackMethodToggle)); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('slatepackInputField')), findsOneWidget); + expect(find.text(pasted), findsOneWidget); + expect( + tester.widget(find.byType(PrimaryButton)).enabled, + isTrue, + ); + expect(tester.takeException(), isNull); + }, + ); } diff --git a/test/pages/slatepack/slatepack_cancel_transaction_dialog_test.dart b/test/pages/slatepack/slatepack_cancel_transaction_dialog_test.dart index 046630c226..a623be16b0 100644 --- a/test/pages/slatepack/slatepack_cancel_transaction_dialog_test.dart +++ b/test/pages/slatepack/slatepack_cancel_transaction_dialog_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:platform/platform.dart' as platform; @@ -5,9 +7,31 @@ import 'package:stackwallet/models/isar/stack_theme.dart'; import 'package:stackwallet/pages/slatepack/slatepack_cancel_transaction_dialog.dart'; import 'package:stackwallet/themes/stack_colors.dart'; import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; import '../../sample_data/theme_json.dart'; +class _CancelWallet extends EpiccashWallet { + _CancelWallet({this.cancelError}) : super(CryptoCurrencyNetwork.main); + + final Exception? cancelError; + int cancelCalls = 0; + int refreshCalls = 0; + + @override + Future cancelPendingTransactionAndPost(String txSlateId) async { + cancelCalls++; + if (cancelError != null) throw cancelError!; + return ''; + } + + @override + Future refresh({bool doScan = true}) async { + refreshCalls++; + } +} + void main() { group('canCancelSlateTransaction', () { test('allows every pending slate state the wallet can cancel', () { @@ -151,4 +175,121 @@ void main() { await tester.pumpAndSettle(); expect(result, isTrue); }); + + testWidgets( + 'cancelSlatepackTransaction treats empty-message exception as failure', + (tester) async { + final wallet = _CancelWallet(cancelError: Exception('')); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Builder( + builder: (context) => TextButton( + onPressed: () { + unawaited( + cancelSlatepackTransaction( + context: context, + wallet: wallet, + slateId: 'slate-1', + ), + ); + }, + child: const Text('Cancel tx'), + ), + ), + ), + ); + + await tester.tap(find.text('Cancel tx')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel it')); + await tester.pumpAndSettle(); + + expect(wallet.cancelCalls, 1); + expect(wallet.refreshCalls, 0); + expect(find.text('Failed to cancel transaction'), findsNWidgets(2)); + expect(find.text('Transaction cancelled'), findsNothing); + + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'cancelSlatepackTransaction succeeds inside an active nested navigator', + (tester) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + tester.view.physicalSize = const Size(1400, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final wallet = _CancelWallet(); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Navigator( + onGenerateRoute: (_) => MaterialPageRoute( + builder: (_) => Builder( + builder: (hostContext) => TextButton( + onPressed: () { + unawaited( + showDialog( + context: hostContext, + builder: (dialogContext) => TextButton( + onPressed: () { + unawaited( + cancelSlatepackTransaction( + context: dialogContext, + wallet: wallet, + slateId: 'slate-1', + ), + ); + }, + child: const Text('Cancel tx'), + ), + ), + ); + }, + child: const Text('Open details'), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Open details')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel tx')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel it')); + await tester.pumpAndSettle(); + + expect(wallet.cancelCalls, 1); + expect(find.text('Transaction cancelled'), findsOneWidget); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + + expect(find.text('Open details'), findsOneWidget); + expect(find.text('Cancel tx'), findsNothing); + expect(wallet.refreshCalls, 1); + expect(tester.takeException(), isNull); + }, + ); } diff --git a/test/pages/slatepack/slatepack_dialog_test.dart b/test/pages/slatepack/slatepack_dialog_test.dart index f7f6fe525f..598ef048eb 100644 --- a/test/pages/slatepack/slatepack_dialog_test.dart +++ b/test/pages/slatepack/slatepack_dialog_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -447,21 +449,91 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('iPad Slide Over wraps Copy, Share, Save into two rows', ( + for (final scale in [1.0, 1.5]) { + testWidgets( + 'iPad Slide Over popup lays out Copy, Share, Save without overflow at ' + '${scale}x text scale', + (tester) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + final previousIpad = Util.isIpad; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'ios'); + Util.screenWidth = 1024; + Util.isIpad = true; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + Util.isIpad = previousIpad; + }); + tester.view.physicalSize = const Size(320, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context) + .copyWith(textScaler: TextScaler.linear(scale)), + child: child!, + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () { + unawaited( + showSlatepackPopup( + context: context, + child: const SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: + 'BEGINSLATEPACK. slideover. ENDSLATEPACK.', + state: SlateState.s1, + ), + ), + ); + }, + child: const Text('Open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Share'), findsOneWidget); + expect(find.text('Save'), findsOneWidget); + expect( + tester.getTopLeft(find.text('Save')).dy, + greaterThan(tester.getBottomLeft(find.text('Copy')).dy), + ); + if (scale > 1.0) { + expect( + tester.getTopLeft(find.text('Share')).dy, + greaterThan(tester.getBottomLeft(find.text('Copy')).dy), + ); + } + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets('380dp phone popup wraps action buttons without overflow', ( tester, ) async { - final previousPlatform = Util.layoutPlatform; + useAndroidLayout(); final previousWidth = Util.screenWidth; - final previousIpad = Util.isIpad; - Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'ios'); - Util.screenWidth = 1024; - Util.isIpad = true; - addTearDown(() { - Util.layoutPlatform = previousPlatform; - Util.screenWidth = previousWidth; - Util.isIpad = previousIpad; - }); - tester.view.physicalSize = const Size(320, 1000); + Util.screenWidth = 380; + addTearDown(() => Util.screenWidth = previousWidth); + tester.view.physicalSize = const Size(380, 900); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); @@ -473,23 +545,31 @@ void main() { theme: ThemeData( extensions: [StackColors.fromStackColorTheme(theme)], ), - home: const Scaffold( - body: SingleChildScrollView( - child: SlatepackDialog( - terms: SlatepackTerms.slatepack, - slatepack: 'BEGINSLATEPACK. slideover. ENDSLATEPACK.', - state: SlateState.s1, + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () { + unawaited( + showSlatepackPopup( + context: context, + child: const SlatepackDialog( + terms: SlatepackTerms.slatepack, + slatepack: 'BEGINSLATEPACK. narrow. ENDSLATEPACK.', + state: SlateState.s1, + ), + ), + ); + }, + child: const Text('Open'), ), ), ), ), ), ); + await tester.tap(find.text('Open')); await tester.pumpAndSettle(); - expect(find.text('Copy'), findsOneWidget); - expect(find.text('Share'), findsOneWidget); - expect(find.text('Save'), findsOneWidget); expect( tester.getTopLeft(find.text('Save')).dy, greaterThan(tester.getBottomLeft(find.text('Copy')).dy), diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart index c0e5cb2266..4ed2c84fdd 100644 --- a/test/pages/slatepack/slatepack_import_flow_test.dart +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -33,6 +33,7 @@ class _InspectOnlyWallet extends EpiccashWallet { this.localIsCancelled = false, this.localGate, this.receiveGate, + this.finalizeGate, this.receiveError, this.senderAddress, this.finalizeResult, @@ -41,6 +42,7 @@ class _InspectOnlyWallet extends EpiccashWallet { /// When set, receiving waits for it and then succeeds, or throws /// [receiveError] if that is set. final Completer? receiveGate; + final Completer? finalizeGate; final Exception? receiveError; final String? senderAddress; final FinalizeResult? finalizeResult; @@ -115,6 +117,7 @@ class _InspectOnlyWallet extends EpiccashWallet { Future finalizeSlatepack(SlateInspection inspection) async { actionInspection = inspection; finalizeCalls++; + await finalizeGate?.future; return finalizeResult ?? FinalizeResult(success: false, error: "not in tests"); } @@ -244,11 +247,20 @@ void main() { const two = "$armored\n$armored"; expect(SlatepackText.normalize(two), two); expect(SlatepackText.isArmored(SlatepackText.normalize(two)), isFalse); + expect(SlatepackText.armoredFrameCount(two), 2); + expect( + SlatepackText.armoredFrameCount("Reply:\n$armored\nOrig:\n$armored"), + 2, + ); + expect(SlatepackText.armoredFrameCount("Hi $armored Bye"), 1); + expect(SlatepackText.armoredFrameCount(armored), 1); + expect(SlatepackText.armoredFrameCount("not a slatepack"), 0); }); test("leaves JSON slates alone apart from trimming", () { const json = '{"id": "abc", "note": "BEGINSLATEPACK. x. ENDSLATEPACK."}'; expect(SlatepackText.normalize(" $json\n"), json); + expect(SlatepackText.armoredFrameCount(" $json\n"), 0); }); test("leaves other text alone apart from trimming", () { @@ -721,20 +733,22 @@ void main() { posted: null, ), ); - await runFlow(tester, wallet); + bool? done; + await runFlow(tester, wallet, onDone: (v) => done = v); await tester.tap(find.text('Finalize')); await tester.pump(const Duration(milliseconds: 400)); await tester.pump(const Duration(milliseconds: 400)); await tester.pump(const Duration(milliseconds: 400)); + expect(done, isTrue); expect(find.text('Transaction finalized'), findsOneWidget); - expect( - find.textContaining('broadcast result is unavailable'), - findsOneWidget, - ); - expect(find.textContaining('finalized and broadcast'), findsNothing); + expect(find.text('OK'), findsNothing); + expect(find.textContaining('broadcast'), findsNothing); expect(find.textContaining('node did not accept'), findsNothing); - await closeDialog(tester); + + // Let the floating flushbar timer finish and remove its overlay entry. + await tester.pump(const Duration(seconds: 4)); + expect(tester.takeException(), isNull); }, ); @@ -874,6 +888,41 @@ void main() { }, ); + for (final posted in [true, null]) { + testWidgets('finalize does not throw when the importing screen closed ' + '(posted: $posted)', (tester) async { + final gate = Completer(); + final wallet = _InspectOnlyWallet( + SlateState.s2, + localIsSend: true, + finalizeGate: gate, + finalizeResult: FinalizeResult( + success: true, + slateId: 'test-slate', + posted: posted, + ), + ); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + bool? done; + await runFlow(tester, wallet, shown: shown, onDone: (v) => done = v); + await tester.tap(find.text('Finalize')); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(wallet.finalizeCalls, 1); + + shown.value = false; + await tester.pump(); + expect(find.text('go'), findsNothing); + + gate.complete(); + await tester.pumpAndSettle(); + + expect(done, isTrue); + expect(tester.takeException(), isNull); + }); + } + testWidgets("aborts without inspecting when covered by a lock screen", ( tester, ) async { @@ -917,5 +966,29 @@ void main() { expect(inspectCalls, 0); expect(tester.takeException(), isNull); }); + + testWidgets("multiple pasted MWC slatepacks explain that two were found", ( + tester, + ) async { + final wallet = MimblewimblecoinWallet(CryptoCurrencyNetwork.main); + const reply = + "Here is my response:\n" + "BEGINSLATEPACK. 4H1qx1wHe668tFW. ENDSLATEPACK.\n\n" + "On Mon you wrote:\n" + "BEGINSLATEPACK. 9B2ry2xIf779uGX. ENDSLATEPACK."; + + bool? done; + await runFlow(tester, wallet, text: reply, onDone: (v) => done = v); + + expect(find.text("Could not read slatepack"), findsOneWidget); + expect( + find.text("Found 2 slatepacks. Enter only one slatepack at a time."), + findsOneWidget, + ); + expect(find.textContaining("Invalid slatepack format"), findsNothing); + await closeDialog(tester); + expect(done, isFalse); + expect(tester.takeException(), isNull); + }); }); } diff --git a/test/pages/slatepack/slatepack_send_flow_test.dart b/test/pages/slatepack/slatepack_send_flow_test.dart index 015ba91511..5710b970c1 100644 --- a/test/pages/slatepack/slatepack_send_flow_test.dart +++ b/test/pages/slatepack/slatepack_send_flow_test.dart @@ -38,14 +38,18 @@ class _Wallet extends EpiccashWallet { _Wallet({ this.createdAmount, this.createdFee, + this.createdSlatepack = '{}', this.createError, + this.failedSlateId, this.cancelResult = '', this.gate, }) : super(CryptoCurrencyNetwork.main); final int? createdAmount; final int? createdFee; + final String? createdSlatepack; final String? createError; + final String? failedSlateId; final String cancelResult; final Completer? gate; @@ -73,11 +77,15 @@ class _Wallet extends EpiccashWallet { created++; await gate?.future; if (createError != null) { - return SlatepackResult(success: false, error: createError); + return SlatepackResult( + success: false, + slateId: failedSlateId, + error: createError, + ); } return SlatepackResult( success: true, - slatepack: '{}', + slatepack: createdSlatepack, slateId: 'slate-1', state: SlateState.s1, amount: createdAmount == null ? null : _amount(createdAmount!), @@ -151,6 +159,7 @@ Future> _pumpSend( WidgetTester tester, SlatepackInterface wallet, { MainDB? db, + bool nestedNavigator = false, }) async { tester.view.physicalSize = const Size(1400, 2400); tester.view.devicePixelRatio = 1; @@ -163,6 +172,27 @@ Future> _pumpSend( addTearDown(succeeded.dispose); final theme = StackTheme.fromJson(json: lightThemeJsonMap); final format = _formatter(wallet.cryptoCurrency).format; + final homeBody = Scaffold( + body: Builder( + builder: (context) => TextButton( + key: const Key('createSlate'), + onPressed: () { + unawaited( + SlatepackSendFlow.run( + context: context, + wallet: wallet, + amount: _amount(100), + message: 'on-chain note', + localNote: 'local note', + db: db ?? _Notes(), + format: format, + ).then((value) => succeeded.value = value), + ); + }, + child: const Text('Create'), + ), + ), + ); await tester.pumpWidget( ProviderScope( overrides: [ @@ -170,27 +200,12 @@ Future> _pumpSend( ], child: MaterialApp( theme: ThemeData(extensions: [StackColors.fromStackColorTheme(theme)]), - home: Scaffold( - body: Builder( - builder: (context) => TextButton( - key: const Key('createSlate'), - onPressed: () { - unawaited( - SlatepackSendFlow.run( - context: context, - wallet: wallet, - amount: _amount(100), - message: 'on-chain note', - localNote: 'local note', - db: db ?? _Notes(), - format: format, - ).then((value) => succeeded.value = value), - ); - }, - child: const Text('Create'), - ), - ), - ), + home: nestedNavigator + ? Navigator( + onGenerateRoute: (_) => + MaterialPageRoute(builder: (_) => homeBody), + ) + : homeBody, ), ), ); @@ -480,4 +495,71 @@ void main() { expect(succeeded.value, isFalse); expect(tester.takeException(), isNull); }); + + testWidgets('blank slatepack payload with slateId rolls back', ( + tester, + ) async { + final wallet = _Wallet( + createdAmount: 100, + createdFee: 1, + createdSlatepack: ' ', + ); + final succeeded = await _pumpSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, ['slate-1']); + expect(find.byType(SlatepackDialog), findsNothing); + expect(find.text('Could not create the slate'), findsOneWidget); + expect(find.textContaining('did not return a slate'), findsOneWidget); + expect(succeeded.value, isFalse); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + expect(wallet.refreshed, 0); + }); + + testWidgets( + 'failed creation returning a locked slateId refreshes after error OK', + (tester) async { + final wallet = _Wallet( + createError: 'encode failed (Note: failed to cancel)', + failedSlateId: 'locked-slate-1', + ); + final succeeded = await _pumpSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(find.text('Could not create the slate'), findsOneWidget); + expect(wallet.refreshed, 0); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + + expect(wallet.refreshed, 1); + expect(succeeded.value, isFalse); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('desktop send flow completes inside a nested navigator', ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + + final wallet = _Wallet(createdAmount: 100, createdFee: 3); + final succeeded = await _pumpSend(tester, wallet, nestedNavigator: true); + await tester.pumpAndSettle(); + + expect(find.byType(SlatepackDialog), findsOneWidget); + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + + expect(succeeded.value, isTrue); + expect(wallet.refreshed, 1); + expect(tester.takeException(), isNull); + }); } diff --git a/test/pages/slatepack/slatepack_view_test.dart b/test/pages/slatepack/slatepack_view_test.dart index 83127597f6..f22aa2089a 100644 --- a/test/pages/slatepack/slatepack_view_test.dart +++ b/test/pages/slatepack/slatepack_view_test.dart @@ -219,4 +219,137 @@ void main() { ); expect(tester.takeException(), isNull); }); + + testWidgets("clearing input during the unfocus delay cancels import", ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android'); + addTearDown(() => Util.layoutPlatform = previousPlatform); + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousWidth = Util.screenWidth; + Util.screenWidth = 400; + addTearDown(() => Util.screenWidth = previousWidth); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory("test/sample_data").absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + + final wallet = _SlowWallet()..gate.complete(); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: const Scaffold(body: SlatepackView(walletId: "wallet-1")), + ), + ), + ); + await tester.pumpAndSettle(); + + final field = find.byKey(const Key("slatepackInputField")); + await tester.tap(field); + await tester.enterText(field, "{}"); + await tester.pump(); + + await tester.tap(find.text("Continue")); + await tester.pump(const Duration(milliseconds: 20)); + await tester.tap(find.byKey(const Key("slatepackClearButton"))); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pumpAndSettle(); + + expect(wallet.inspections, 0); + expect(find.text("Could not read slate"), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets("desktop SlatepackView completes inside a nested navigator", ( + tester, + ) async { + final previousPlatform = Util.layoutPlatform; + final previousWidth = Util.screenWidth; + Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'linux'); + Util.screenWidth = 1400; + addTearDown(() { + Util.layoutPlatform = previousPlatform; + Util.screenWidth = previousWidth; + }); + tester.view.physicalSize = const Size(1400, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory("test/sample_data").absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + + final wallet = _SlowWallet( + state: SlateState.s1, + receiveResponse: SlatepackResult( + success: true, + slatepack: '{"response": true}', + slateId: "test-slate", + state: SlateState.s2, + ), + )..gate.complete(); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final coin = wallet.cryptoCurrency; + + await tester.pumpWidget( + ProviderScope( + overrides: [ + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: "en_US", + coin: coin, + maxDecimals: coin.fractionDigits, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: Navigator( + onGenerateRoute: (_) => MaterialPageRoute( + builder: (_) => const Scaffold( + body: SizedBox( + width: 600, + height: 600, + child: SlatepackView(walletId: "wallet-1"), + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), "{}"); + await tester.pump(); + await tester.tap(find.text("Continue")); + await tester.pumpAndSettle(); + + expect(find.text("Receive slate"), findsOneWidget); + await tester.tap(find.text("Receive")); + await tester.pumpAndSettle(); + expect(find.text("Response Slate"), findsOneWidget); + await tester.tap(find.text("Done")); + await tester.pumpAndSettle(); + + expect(find.text("{}"), findsNothing); + expect(tester.takeException(), isNull); + }); } diff --git a/test/utilities/route_presentation_test.dart b/test/utilities/route_presentation_test.dart index 7e2635c290..70bedafd34 100644 --- a/test/utilities/route_presentation_test.dart +++ b/test/utilities/route_presentation_test.dart @@ -343,4 +343,126 @@ void main() { expect(tester.takeException(), isNull); }, ); + + testWidgets( + 'runWithCurrentAwareOverlay succeeds for active nested navigator', + (tester) async { + late BuildContext nestedContext; + + await tester.pumpWidget( + MaterialApp( + home: Navigator( + onGenerateRoute: (_) => MaterialPageRoute( + builder: (innerCtx) { + nestedContext = innerCtx; + return const Text('Nested'); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + var actionCalls = 0; + final future = runWithCurrentAwareOverlay( + context: nestedContext, + builder: (_) => const Text('Overlay'), + action: () async { + actionCalls++; + return 'ok'; + }, + ); + await tester.pumpAndSettle(); + final outcome = await future; + + expect(outcome.aborted, isFalse); + expect(outcome.canPresentResult, isTrue); + expect(outcome.value, 'ok'); + expect(actionCalls, 1); + expect(find.text('Overlay'), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'runWithCurrentAwareOverlay handles a two-level nested navigator', + (tester) async { + late BuildContext rootContext; + late BuildContext outerContext; + late BuildContext innerContext; + + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (rCtx) { + rootContext = rCtx; + return Navigator( + onGenerateRoute: (_) => MaterialPageRoute( + builder: (oCtx) { + outerContext = oCtx; + return Navigator( + onGenerateRoute: (_) => MaterialPageRoute( + builder: (iCtx) { + innerContext = iCtx; + return const Text('Inner'); + }, + ), + ); + }, + ), + ); + }, + ), + ), + ); + await tester.pumpAndSettle(); + + var actionCalls = 0; + final okFuture = runWithCurrentAwareOverlay( + context: innerContext, + builder: (_) => const Text('Overlay'), + action: () async => actionCalls++, + ); + await tester.pumpAndSettle(); + final okOutcome = await okFuture; + expect(okOutcome.aborted, isFalse); + expect(okOutcome.canPresentResult, isTrue); + expect(actionCalls, 1); + + // Outer nested navigator pushes a covering route. + unawaited( + Navigator.of(outerContext).push( + MaterialPageRoute(builder: (_) => const Text('OuterCover')), + ), + ); + await tester.pumpAndSettle(); + final outerCoveredOutcome = await runWithCurrentAwareOverlay( + context: innerContext, + builder: (_) => const Text('Overlay'), + action: () async => actionCalls++, + ); + expect(outerCoveredOutcome.aborted, isTrue); + expect(actionCalls, 1); + + Navigator.of(outerContext).pop(); + await tester.pumpAndSettle(); + + // Root navigator pushes a lock route. + unawaited( + Navigator.of( + rootContext, + rootNavigator: true, + ).push(MaterialPageRoute(builder: (_) => const Text('Locked'))), + ); + await tester.pumpAndSettle(); + final rootCoveredOutcome = await runWithCurrentAwareOverlay( + context: innerContext, + builder: (_) => const Text('Overlay'), + action: () async => actionCalls++, + ); + expect(rootCoveredOutcome.aborted, isTrue); + expect(actionCalls, 1); + expect(tester.takeException(), isNull); + }, + ); } diff --git a/test/wallets/mimblewimble_slate_inspection_test.dart b/test/wallets/mimblewimble_slate_inspection_test.dart index 77de943418..e768a50239 100644 --- a/test/wallets/mimblewimble_slate_inspection_test.dart +++ b/test/wallets/mimblewimble_slate_inspection_test.dart @@ -412,10 +412,31 @@ void main() { expect(() => mwc.checkSlatepackFormat(valid), returnsNormally); expect(SlatepackText.isArmored(mismatched), isFalse); - expect(() => mwc.checkSlatepackFormat(mismatched), throwsException); + expect( + () => mwc.checkSlatepackFormat(mismatched), + throwsA( + isA().having( + (e) => e.toString(), + 'message', + contains('Invalid slatepack format'), + ), + ), + ); expect(SlatepackText.isArmored(concatenated), isFalse); - expect(() => mwc.checkSlatepackFormat(concatenated), throwsException); + expect( + () => mwc.checkSlatepackFormat(concatenated), + throwsA( + isA().having( + (e) => e.toString(), + 'message', + allOf( + contains('Found 2 slatepacks'), + contains('only one slatepack'), + ), + ), + ), + ); }, ); @@ -592,4 +613,58 @@ void main() { isTrue, ); }); + + test( + 'localSlateTransaction prefers outgoing over sentToSelf, sentToSelf falls ' + 'back to pending fee, and localTxForSlate fails closed when Isar is closed', + () async { + const id = '0436430c-2b02-624c-2032-570501212b00'; + final selfTx = _tx(10, TransactionType.sentToSelf, id); + final outgoingTx = _tx(11, TransactionType.outgoing, id); + expect(localSlateTransaction([selfTx, outgoingTx], id), outgoingTx); + expect(localSlateTransaction([outgoingTx, selfTx], id), outgoingTx); + + final directory = await Directory.systemTemp.createTemp( + 'mimblewimble_slate_fee_fallback_', + ); + addTearDown(() => directory.delete(recursive: true)); + final isar = await Isar.open( + [TransactionV2Schema, WalletInfoSchema], + directory: directory.path, + name: 'mimblewimble-fee-fallback', + inspector: false, + ); + await MainDB.instance.initMainDB(mock: isar); + await MainDB.instance.putWalletInfo( + WalletInfo( + walletId: 'wallet', + name: 'fixture', + mainAddressType: AddressType.mimbleWimble, + coinName: 'mimblewimblecoin', + ), + ); + await isar.writeTxn(() => isar.transactionV2s.put(selfTx)); + + final wallet = _PendingLookupWallet(); + await wallet.remember( + SlatepackResult( + success: true, + slatepack: 's1', + slateId: id, + state: SlateState.s1, + amount: Amount(rawValue: BigInt.from(300), fractionDigits: 9), + fee: Amount(rawValue: BigInt.from(8), fractionDigits: 9), + ), + ); + final record = await wallet.localTxForSlate(id); + expect(record?.isSend, isTrue); + expect(record?.fee.raw, BigInt.from(8)); + + await isar.close(); + await expectLater( + wallet.localTxForSlate('unknown-slate'), + throwsA(isA()), + ); + }, + ); }