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