From fda3c1cd82493bee011e71f69eef3c5f833798fe Mon Sep 17 00:00:00 2001 From: sneurlax Date: Tue, 10 Nov 2026 14:29:18 -0600 Subject: [PATCH 01/15] Keep local notes when creating a slatepack --- .../send_view/confirm_transaction_view.dart | 28 +++ .../slatepack_confirmation_test.dart | 164 ++++++++++++++++++ 2 files changed, 192 insertions(+) create mode 100644 test/pages/send_view/slatepack_confirmation_test.dart diff --git a/lib/pages/send_view/confirm_transaction_view.dart b/lib/pages/send_view/confirm_transaction_view.dart index 7e1326c909..f274d94224 100644 --- a/lib/pages/send_view/confirm_transaction_view.dart +++ b/lib/pages/send_view/confirm_transaction_view.dart @@ -163,6 +163,8 @@ class _ConfirmTransactionViewState final terms = wallet.slatepackTerms; final recipient = widget.txData.recipients!.first; final note = onChainNoteController.text; + final localNote = noteController.text; + final db = ref.read(mainDBProvider); final result = await wallet.createSlatepack( amount: recipient.amount, @@ -173,10 +175,36 @@ class _ConfirmTransactionViewState throw Exception(result.error ?? "Failed to create ${terms.noun}"); } + var noteSaved = localNote.isEmpty; + if (!noteSaved && result.slateId != null) { + try { + await db.putTransactionNote( + TransactionNote( + walletId: walletId, + txid: result.slateId!, + value: localNote, + ), + ); + noteSaved = true; + } catch (_) { + // The slate already exists and still needs to reach the recipient. + } + } + unawaited(wallet.refresh()); closeSendingDialog(); if (context.mounted) { + if (!noteSaved) { + unawaited( + showFloatingFlushBar( + type: FlushBarType.warning, + message: + "Transaction created, but the local note could not be saved.", + context: context, + ), + ); + } await showSlatepackDialog(context: context, terms: terms, result: result); } diff --git a/test/pages/send_view/slatepack_confirmation_test.dart b/test/pages/send_view/slatepack_confirmation_test.dart new file mode 100644 index 0000000000..7c6bda018a --- /dev/null +++ b/test/pages/send_view/slatepack_confirmation_test.dart @@ -0,0 +1,164 @@ +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/blockchain_data/address.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/send_view/confirm_transaction_view.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/db/main_db_provider.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_providers.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; +import 'package:stackwallet/utilities/enums/slatepack_method.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/isar/providers/wallet_info_provider.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; + +import '../../sample_data/theme_json.dart'; +import '../../wallets/support/xelis_test_fakes.dart'; + +class _Info extends Fake implements WalletInfo { + _Info(this.coin); + @override + final CryptoCurrency coin; +} + +class _Wallet extends EpiccashWallet { + _Wallet() : super(CryptoCurrencyNetwork.main); + int created = 0; + @override + WalletInfo get info => _Info(cryptoCurrency); + @override + Future refresh({bool doScan = true}) async {} + @override + Future createSlatepack({ + required Amount amount, + String? recipientAddress, + String? message, + bool sendAll = false, + }) async { + created++; + return SlatepackResult( + success: true, + slatepack: '{}', + slateId: 'slate-1', + state: SlateState.s1, + ); + } +} + +class _Notes extends Fake implements MainDB { + _Notes({required this.fail}); + final bool fail; + final notes = []; + @override + Future putTransactionNote(TransactionNote note) async { + if (fail) throw StateError('note unavailable'); + notes.add(note); + } +} + +void main() { + for (final failNote in [false, true]) { + testWidgets('slate send keeps its result with note failure=$failNote', ( + tester, + ) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final wallet = _Wallet(); + final coin = wallet.cryptoCurrency; + final notes = _Notes(fail: failNote); + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + var succeeded = false; + await tester.pumpWidget( + ProviderScope( + overrides: [ + mainDBProvider.overrideWithValue(notes), + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletCoin('wallet-1').overrideWithValue(coin), + prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), + 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: ConfirmTransactionView( + walletId: 'wallet-1', + onSuccess: () => succeeded = true, + onSuccessInsteadOfRouteOnSuccess: () {}, + txData: TxData( + note: 'local note', + fee: Amount(rawValue: BigInt.one, fractionDigits: 8), + recipients: [ + TxRecipient( + address: '', + amount: Amount( + rawValue: BigInt.from(100), + fractionDigits: 8, + ), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + otherData: slatepackMethodOtherData( + SlatepackMethod.slatepack, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.text('Send')); + await tester.tap(find.text('Send')); + await tester.pumpAndSettle(); + Navigator.of(tester.element(find.byType(DesktopAuthSend))).pop(true); + await tester.pumpAndSettle(); + expect(wallet.created, 1); + expect(find.byType(SlatepackDialog), findsOneWidget); + if (!failNote) { + expect(notes.notes, hasLength(1)); + expect(notes.notes.single.walletId, 'wallet-1'); + expect(notes.notes.single.txid, 'slate-1'); + expect(notes.notes.single.value, 'local note'); + } else { + expect(notes.notes, isEmpty); + } + await tester.tap(find.text('Done')); + await tester.pumpAndSettle(); + expect(succeeded, isTrue); + await tester.pump(const Duration(seconds: 3)); + expect(tester.takeException(), isNull); + }); + } +} From 763d49999afc086a4a620080f3c5554e34d0223a Mon Sep 17 00:00:00 2001 From: sneurlax Date: Tue, 10 Nov 2026 14:29:18 -0600 Subject: [PATCH 02/15] Ignore slatepack input results after the screen closes --- .../slatepack/slatepack_input_field.dart | 1 + .../slatepack/slatepack_input_field_test.dart | 62 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 test/pages/slatepack/slatepack_input_field_test.dart diff --git a/lib/pages/slatepack/slatepack_input_field.dart b/lib/pages/slatepack/slatepack_input_field.dart index 4afbe7c80e..154061f86a 100644 --- a/lib/pages/slatepack/slatepack_input_field.dart +++ b/lib/pages/slatepack/slatepack_input_field.dart @@ -55,6 +55,7 @@ class _SlatepackInputFieldState extends ConsumerState { bool get _isEmpty => widget.controller.text.isEmpty; void _set(String text) { + if (!mounted) return; widget.controller.text = text; widget.onChanged?.call(text); setState(() {}); 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..5104771e8c --- /dev/null +++ b/test/pages/slatepack/slatepack_input_field_test.dart @@ -0,0 +1,62 @@ +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: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/stack_file_system.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('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', + 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); + }); +} From 041703beec5c005465577357fda34e2166d857c9 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Tue, 10 Nov 2026 17:18:44 -0600 Subject: [PATCH 03/15] Use a readable color for the Slatepack screen's help text desktopTextExtraSmall uses the disabled button text color, which is nearly white on the desktop card, so the explanation above the input was almost invisible. Use the subtitle color like the other slatepack hints. --- lib/pages/slatepack/slatepack_view.dart | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/pages/slatepack/slatepack_view.dart b/lib/pages/slatepack/slatepack_view.dart index ba60a6f691..4cd962c7cb 100644 --- a/lib/pages/slatepack/slatepack_view.dart +++ b/lib/pages/slatepack/slatepack_view.dart @@ -133,7 +133,11 @@ class _SlatepackViewState extends ConsumerState { "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) + ? STextStyles.desktopTextExtraSmall(context).copyWith( + color: Theme.of(context) + .extension()! + .textSubtitle1, + ) : STextStyles.label(context), ), const SizedBox(height: 12), From f014d7cef1e7cc7f6f8e858a4eae5d058afc29dd Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:09:22 -0600 Subject: [PATCH 04/15] Check the created slatepack against the confirmed send Creating a slatepack did not compare the result with what the user had just confirmed, reported failures as "Broadcast transaction failed" although nothing is broadcast, and dropped the result without a trace when the confirmation view had closed in the meantime. A slatepack created for another amount is now cancelled and refused with an error naming both amounts. A different fee is logged and shown as a warning only, because the confirmed fee is an estimate and the wallet may select other inputs when it builds the slate. Failures are titled "Could not create the slate" or "slatepack". The sending dialog is closed through a navigator looked up before the send, so it no longer stays up when the view is gone, and that case is logged. --- .../send_view/confirm_transaction_view.dart | 61 +++- .../slatepack_confirmation_test.dart | 301 ++++++++++++++---- 2 files changed, 292 insertions(+), 70 deletions(-) diff --git a/lib/pages/send_view/confirm_transaction_view.dart b/lib/pages/send_view/confirm_transaction_view.dart index f274d94224..db6483184b 100644 --- a/lib/pages/send_view/confirm_transaction_view.dart +++ b/lib/pages/send_view/confirm_transaction_view.dart @@ -165,6 +165,7 @@ class _ConfirmTransactionViewState final note = onChainNoteController.text; final localNote = noteController.text; final db = ref.read(mainDBProvider); + final format = ref.read(pAmountFormatter(wallet.cryptoCurrency)).format; final result = await wallet.createSlatepack( amount: recipient.amount, @@ -175,6 +176,37 @@ class _ConfirmTransactionViewState throw Exception(result.error ?? "Failed to create ${terms.noun}"); } + // The user confirmed one amount, so a slate for any other amount must not + // be handed over. + final createdAmount = result.amount; + if (createdAmount != null && createdAmount != recipient.amount) { + final slateId = result.slateId; + final cancelError = slateId == null + ? "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 ${terms.noun} was created for ${format(createdAmount)} instead of" + " the confirmed ${format(recipient.amount)}. $outcome", + ); + } + + // The confirmed fee is an estimate and the wallet may pick other inputs + // when it builds the slate, so a different fee is reported, not refused. + final createdFee = result.fee; + final confirmedFee = widget.txData.fee; + final feeChange = + createdFee != null && confirmedFee != null && createdFee != confirmedFee + ? "The ${terms.noun} pays a fee of ${format(createdFee)} instead of" + " the estimated ${format(confirmedFee)}." + : null; + if (feeChange != null) { + Logging.instance.w("$feeChange Slate id: ${result.slateId}"); + } + var noteSaved = localNote.isEmpty; if (!noteSaved && result.slateId != null) { try { @@ -195,17 +227,26 @@ class _ConfirmTransactionViewState closeSendingDialog(); if (context.mounted) { - if (!noteSaved) { + if (!noteSaved || feeChange != null) { unawaited( showFloatingFlushBar( type: FlushBarType.warning, - message: + message: [ + ?feeChange, + if (!noteSaved) "Transaction created, but the local note could not be saved.", + ].join(" "), context: context, ), ); } await showSlatepackDialog(context: context, terms: terms, result: result); + } else { + Logging.instance.w( + "Created ${terms.noun} ${result.slateId} but the confirmation view" + " closed before it could be shown. The pending transaction is in the" + " wallet's history and can be cancelled there.", + ); } widget.onSuccess.call(); @@ -225,11 +266,14 @@ class _ConfirmTransactionViewState final sendProgressController = ProgressAndSuccessController(); var isSendingDialogOpen = true; + // Looked up now so the dialog can still be closed if this view is gone by + // the time the send returns. + final navigator = Navigator.of(context, rootNavigator: true); + void closeSendingDialog() { - if (!context.mounted || !isSendingDialogOpen) { + if (!navigator.mounted || !isSendingDialogOpen) { return; } - final navigator = Navigator.of(context, rootNavigator: true); if (navigator.canPop()) { navigator.pop(); } @@ -376,12 +420,15 @@ class _ConfirmTransactionViewState return; } } catch (e, s) { - const message = "Broadcast transaction failed"; + // Nothing is broadcast when a slatepack is created. + final message = + wallet is SlatepackInterface && widget.txData.isSlatepackSend + ? "Could not create the ${wallet.slatepackTerms.noun}" + : "Broadcast transaction failed"; Logging.instance.e(message, error: e, stackTrace: s); // pop sending dialog + closeSendingDialog(); if (context.mounted) { - closeSendingDialog(); - await showDialog( context: context, useSafeArea: false, diff --git a/test/pages/send_view/slatepack_confirmation_test.dart b/test/pages/send_view/slatepack_confirmation_test.dart index 7c6bda018a..892cfdf7ee 100644 --- a/test/pages/send_view/slatepack_confirmation_test.dart +++ b/test/pages/send_view/slatepack_confirmation_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; @@ -9,6 +10,7 @@ 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/send_view/confirm_transaction_view.dart'; +import 'package:stackwallet/pages/send_view/sub_widgets/sending_transaction_dialog.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/db/main_db_provider.dart'; @@ -38,8 +40,27 @@ class _Info extends Fake implements WalletInfo { } class _Wallet extends EpiccashWallet { - _Wallet() : super(CryptoCurrencyNetwork.main); + _Wallet({ + this.createdAmount, + this.createdFee, + this.createError, + this.cancelResult = '', + this.gate, + }) : super(CryptoCurrencyNetwork.main); + + /// What the created slate reports, in raw units. + final int? createdAmount; + final int? createdFee; + + final String? createError; + final String cancelResult; + + /// When set, creation waits for it. + final Completer? gate; + int created = 0; + final cancelled = []; + @override WalletInfo get info => _Info(cryptoCurrency); @override @@ -52,13 +73,104 @@ class _Wallet extends EpiccashWallet { bool sendAll = false, }) 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; + } +} + +/// Outlasts the minimum time the sending dialog is meant to stay up. +const _sendTimer = Duration(seconds: 3); + +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, +); + +/// Pumps the confirmation of a slate send of 100 with a fee of 1 and presses +/// Send. [shown] takes the view off screen when set to false. +Future _confirmSend( + WidgetTester tester, + _Wallet wallet, { + MainDB? db, + void Function()? onSuccess, + ValueNotifier? shown, +}) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final previousThemes = StackFileSystem.themesDir; + StackFileSystem.themesDir = Directory('test/sample_data').absolute; + addTearDown(() => StackFileSystem.themesDir = previousThemes); + final coin = wallet.cryptoCurrency; + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + final view = ConfirmTransactionView( + walletId: 'wallet-1', + onSuccess: onSuccess ?? () {}, + onSuccessInsteadOfRouteOnSuccess: () {}, + txData: TxData( + note: 'local note', + fee: _amount(1), + recipients: [ + TxRecipient( + address: '', + amount: _amount(100), + isChange: false, + addressType: AddressType.mimbleWimble, + ), + ], + otherData: slatepackMethodOtherData(SlatepackMethod.slatepack), + ), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + mainDBProvider.overrideWithValue(db ?? _Notes(fail: false)), + pWallets.overrideWithValue(ConfirmationWallets(wallet)), + pWalletCoin('wallet-1').overrideWithValue(coin), + prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), + themeProvider.overrideWithProvider(StateProvider((ref) => theme)), + pAmountFormatter(coin).overrideWithValue(_formatter(coin)), + ], + child: MaterialApp( + theme: ThemeData(extensions: [StackColors.fromStackColorTheme(theme)]), + home: Scaffold( + body: shown == null + ? view + : ValueListenableBuilder( + valueListenable: shown, + builder: (_, isShown, _) => isShown ? view : const SizedBox(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.text('Send')); + await tester.tap(find.text('Send')); + await tester.pumpAndSettle(); + Navigator.of(tester.element(find.byType(DesktopAuthSend))).pop(true); } class _Notes extends Fake implements MainDB { @@ -77,73 +189,16 @@ void main() { testWidgets('slate send keeps its result with note failure=$failNote', ( tester, ) async { - tester.view.physicalSize = const Size(1400, 2400); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.resetPhysicalSize); - addTearDown(tester.view.resetDevicePixelRatio); - final previousThemes = StackFileSystem.themesDir; - StackFileSystem.themesDir = Directory('test/sample_data').absolute; - addTearDown(() => StackFileSystem.themesDir = previousThemes); final wallet = _Wallet(); - final coin = wallet.cryptoCurrency; final notes = _Notes(fail: failNote); - final theme = StackTheme.fromJson(json: lightThemeJsonMap); var succeeded = false; - await tester.pumpWidget( - ProviderScope( - overrides: [ - mainDBProvider.overrideWithValue(notes), - pWallets.overrideWithValue(ConfirmationWallets(wallet)), - pWalletCoin('wallet-1').overrideWithValue(coin), - prefsChangeNotifierProvider.overrideWithValue(ConfirmationPrefs()), - 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: ConfirmTransactionView( - walletId: 'wallet-1', - onSuccess: () => succeeded = true, - onSuccessInsteadOfRouteOnSuccess: () {}, - txData: TxData( - note: 'local note', - fee: Amount(rawValue: BigInt.one, fractionDigits: 8), - recipients: [ - TxRecipient( - address: '', - amount: Amount( - rawValue: BigInt.from(100), - fractionDigits: 8, - ), - isChange: false, - addressType: AddressType.mimbleWimble, - ), - ], - otherData: slatepackMethodOtherData( - SlatepackMethod.slatepack, - ), - ), - ), - ), - ), - ), + await _confirmSend( + tester, + wallet, + db: notes, + onSuccess: () => succeeded = true, ); await tester.pumpAndSettle(); - await tester.ensureVisible(find.text('Send')); - await tester.tap(find.text('Send')); - await tester.pumpAndSettle(); - Navigator.of(tester.element(find.byType(DesktopAuthSend))).pop(true); - await tester.pumpAndSettle(); expect(wallet.created, 1); expect(find.byType(SlatepackDialog), findsOneWidget); if (!failNote) { @@ -161,4 +216,124 @@ void main() { expect(tester.takeException(), isNull); }); } + + for (final cancelResult in ['', 'node unreachable']) { + testWidgets('a slate for another amount is cancelled and refused, cancel ' + 'result "$cancelResult"', (tester) async { + final wallet = _Wallet(createdAmount: 90, cancelResult: cancelResult); + final format = _formatter(wallet.cryptoCurrency).format; + final notes = _Notes(fail: false); + var succeeded = false; + await _confirmSend( + tester, + wallet, + db: notes, + onSuccess: () => succeeded = true, + ); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, ['slate-1']); + expect(find.byType(SlatepackDialog), findsNothing); + expect(find.byType(SendingTransactionDialog), findsNothing); + expect(find.text('Could not create the slate'), findsOneWidget); + expect( + find.textContaining( + 'created for ${format(_amount(90))} instead of the confirmed ' + '${format(_amount(100))}', + ), + findsOneWidget, + ); + expect( + find.textContaining( + cancelResult.isEmpty + ? 'The transaction was cancelled.' + : 'could not be cancelled (node unreachable)', + ), + findsOneWidget, + ); + expect(notes.notes, isEmpty); + expect(succeeded, isFalse); + await tester.pump(_sendTimer); + }); + } + + testWidgets('a slate with another fee is shown with a warning', ( + tester, + ) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 3); + final format = _formatter(wallet.cryptoCurrency).format; + await _confirmSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, isEmpty); + expect(find.byType(SlatepackDialog), findsOneWidget); + expect( + find.textContaining( + 'fee of ${format(_amount(3))} instead of the estimated ' + '${format(_amount(1))}', + ), + findsOneWidget, + ); + await tester.pump(const Duration(seconds: 10)); + await tester.pumpAndSettle(); + }); + + testWidgets('a slate matching the confirmation is shown without a warning', ( + tester, + ) async { + final wallet = _Wallet(createdAmount: 100, createdFee: 1); + await _confirmSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(wallet.cancelled, isEmpty); + expect(find.byType(SlatepackDialog), findsOneWidget); + expect(find.textContaining('instead of'), findsNothing); + await tester.pump(_sendTimer); + }); + + testWidgets('a failed creation is not called a broadcast failure', ( + tester, + ) async { + final wallet = _Wallet(createError: 'not enough funds'); + await _confirmSend(tester, wallet); + await tester.pumpAndSettle(); + + expect(find.text('Could not create the slate'), findsOneWidget); + expect(find.text('Broadcast transaction failed'), findsNothing); + expect(find.textContaining('not enough funds'), findsOneWidget); + expect(find.byType(SendingTransactionDialog), findsNothing); + expect(wallet.cancelled, isEmpty); + await tester.pump(_sendTimer); + }); + + testWidgets('the sending dialog closes when the view is gone before the ' + 'slate is created', (tester) async { + final gate = Completer(); + final wallet = _Wallet(gate: gate); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + var succeeded = false; + await _confirmSend( + tester, + wallet, + shown: shown, + onSuccess: () => succeeded = true, + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byType(SendingTransactionDialog), findsOneWidget); + + shown.value = false; + await tester.pump(); + expect(find.byType(ConfirmTransactionView), findsNothing); + + gate.complete(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.byType(SendingTransactionDialog), findsNothing); + expect(find.byType(SlatepackDialog), findsNothing); + expect(succeeded, isTrue); + await tester.pump(_sendTimer); + expect(tester.takeException(), isNull); + }); } From 88b0d47f2ebee0a62a1e2ef903d0cbb24f4b8eb3 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:12:13 -0600 Subject: [PATCH 05/15] Offer Finalize only for a send this wallet started An imported response slatepack was offered for finalizing even when the wallet had no transaction for it, with only a note in the summary, and a transaction the wallet had received counted as a match. The lookup now reports the direction of the local transaction, prefers the send when a wallet holds both sides of a slate, and refreshes the stored history once before giving up, since a send made moments ago may not be in it yet. Without a send of its own the import flow explains that only the wallet that started the transaction can finalize it and no longer shows the Finalize button. --- .../slatepack/slatepack_import_flow.dart | 74 +++++++---- .../intermediate/mimblewimble_wallet.dart | 64 +++++++--- .../slatepack_interface.dart | 9 +- .../slatepack/slatepack_import_flow_test.dart | 115 +++++++++++++++--- .../mimblewimble_slate_inspection_test.dart | 33 +++++ 5 files changed, 236 insertions(+), 59 deletions(-) diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart index b6162bf558..610bd86582 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; +import '../../utilities/amount/amount.dart'; import '../../utilities/show_loading.dart'; import '../../utilities/util.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; @@ -66,25 +67,61 @@ abstract final class SlatepackImportFlow { }) async { final terms = wallet.slatepackTerms; - final inspection = await _withLoading( + final read = await _withLoading( context, "Reading ${terms.noun}...", - () => wallet.inspectSlatepack(text), + () async { + final inspection = await wallet.inspectSlatepack(text); + final route = routeFor( + inspection.state, + supportsInvoices: wallet.supportsInvoices, + ); + return ( + inspection: inspection, + route: route, + // Only the wallet that started a send can finalize it. + local: route == SlatepackRoute.finalizeSend + ? await wallet.localTxForSlate(inspection.slateId) + : null, + ); + }, errorTitle: "Could not read ${terms.noun}", ); - if (inspection == null || !context.mounted) return false; + if (read == null || !context.mounted) return false; - final route = routeFor( - inspection.state, - supportsInvoices: wallet.supportsInvoices, - ); + final inspection = read.inspection; + final route = read.route; switch (route) { case SlatepackRoute.receive: return _receive(context, wallet, text, inspection); case SlatepackRoute.finalizeSend: - return _finalize(context, wallet, text, inspection); + final local = read.local; + if (local == null || !local.isSend) { + await _message( + context, + "Cannot finalize this ${terms.noun}", + local == null + ? "This wallet did not start the transaction this " + "${terms.noun} belongs to. Only the wallet that " + "started a send can finalize it. If the send was made " + "here moments ago, let the wallet finish syncing and " + "try again." + : "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; + } + return _finalize( + context, + wallet, + text, + inspection, + amount: local.amount, + fee: local.fee, + ); case SlatepackRoute.payInvoice: // TODO(S5): PayInvoiceConfirmView. @@ -184,31 +221,26 @@ abstract final class SlatepackImportFlow { BuildContext context, SlatepackInterface wallet, String text, - SlateInspection inspection, - ) async { + SlateInspection inspection, { + required Amount amount, + required Amount fee, + }) async { final terms = wallet.slatepackTerms; - // An S2 may carry amount 0, so the summary comes from our own record of - // the send when there is one. - final local = await wallet.localTxForSlate(inspection.slateId); - if (!context.mounted) return false; - + // 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: local?.amount ?? inspection.amount, - fee: local?.fee ?? inspection.fee, + amount: amount, + fee: fee, details: [ if (inspection.slateId.isNotEmpty) ("Slate ID", inspection.slateId), ("Encrypted", inspection.isEncrypted ? "Yes" : "No"), ], - note: local == null - ? "No matching send was found in this wallet's history. " - "Finalizing only works for a send this wallet started." - : null, ), ); if (confirmed != true || !context.mounted) return false; diff --git a/lib/wallets/wallet/intermediate/mimblewimble_wallet.dart b/lib/wallets/wallet/intermediate/mimblewimble_wallet.dart index de2abe8ce3..e57b9e3bb3 100644 --- a/lib/wallets/wallet/intermediate/mimblewimble_wallet.dart +++ b/lib/wallets/wallet/intermediate/mimblewimble_wallet.dart @@ -233,28 +233,60 @@ abstract class MimblewimbleWallet extends Bip39Wallet with SlatepackInterface { } @override - Future<({Amount amount, Amount fee})?> localTxForSlate(String slateId) async { + Future<({Amount amount, Amount fee, bool isSend})?> localTxForSlate( + String slateId, + ) async { if (slateId.isEmpty) return null; - final List candidates = await mainDB.isar.transactionV2s - .where() - .walletIdEqualTo(walletId) - .filter() - .otherDataContains(slateId) - .findAll(); + Future find() async => localTxMatching( + await mainDB.isar.transactionV2s + .where() + .walletIdEqualTo(walletId) + .filter() + .otherDataContains(slateId) + .findAll(), + slateId, + ); - for (final TransactionV2 tx in candidates) { - if (tx.slateId != slateId) continue; - final int digits = cryptoCurrency.fractionDigits; - final Amount amount = tx.type == TransactionType.incoming - ? tx.getAmountReceivedInThisWallet(fractionDigits: digits) - : tx.getAmountSentFromThisWallet( + TransactionV2? tx = await find(); + if (tx == null) { + // The stored history only changes on a refresh, and a refresh is + // skipped while another one runs, so a send made moments ago may not be + // in it yet. + await updateTransactions(); + tx = await find(); + } + if (tx == null) return null; + + final int digits = cryptoCurrency.fractionDigits; + final bool isSend = tx.type == TransactionType.outgoing; + return ( + amount: isSend + ? tx.getAmountSentFromThisWallet( fractionDigits: digits, subtractFee: true, - ); - return (amount: amount, fee: tx.getFee(fractionDigits: digits)); + ) + : tx.getAmountReceivedInThisWallet(fractionDigits: digits), + fee: tx.getFee(fractionDigits: digits), + isSend: isSend, + ); + } + + /// The transaction for [slateId] among [candidates]. A wallet that sent to + /// itself holds both sides of the slate, and then the send is the one + /// returned. + @visibleForTesting + static TransactionV2? localTxMatching( + Iterable candidates, + String slateId, + ) { + TransactionV2? match; + for (final TransactionV2 tx in candidates) { + if (tx.slateId != slateId) continue; + if (tx.type == TransactionType.outgoing) return tx; + match ??= tx; } - return null; + return match; } // ================= Native wallet hooks ===================================== diff --git a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart index 7b19c01461..5b2b2cbcfe 100644 --- a/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart +++ b/lib/wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart @@ -37,9 +37,12 @@ mixin SlatepackInterface on Wallet { /// Throws when the text cannot be decoded at all. Future inspectSlatepack(String armored); - /// Amount and fee of this wallet's transaction for [slateId], or null when - /// the wallet has none. - Future<({Amount amount, Amount fee})?> localTxForSlate(String slateId); + /// Amount, fee and direction 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. + Future<({Amount amount, Amount fee, bool isSend})?> localTxForSlate( + String slateId, + ); /// Start a send (S1). [message] is dropped when [supportsOnChainNote] is /// false. [recipientAddress] encrypts the slatepack to that address where diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart index 376642d50b..8ee3fb359d 100644 --- a/test/pages/slatepack/slatepack_import_flow_test.dart +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -1,9 +1,13 @@ 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_import_flow.dart'; import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/amount/amount_formatter.dart'; +import 'package:stackwallet/utilities/amount/amount_unit.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; @@ -12,11 +16,15 @@ 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.invoices = false}) + _InspectOnlyWallet(this.state, {this.invoices = false, this.localIsSend}) : super(CryptoCurrencyNetwork.main); final SlateState state; final bool invoices; + + /// Direction of the wallet's own transaction for the slate. Null when the + /// wallet has none. + final bool? localIsSend; int receiveCalls = 0; int finalizeCalls = 0; @@ -27,6 +35,17 @@ class _InspectOnlyWallet extends EpiccashWallet { Future inspectSlatepack(String armored) async => SlateInspection(state: state, slateId: "test-slate"); + @override + Future<({Amount amount, Amount fee, bool isSend})?> localTxForSlate( + String slateId, + ) async => localIsSend == null + ? null + : ( + amount: Amount(rawValue: BigInt.from(100), fractionDigits: 8), + fee: Amount(rawValue: BigInt.one, fractionDigits: 8), + isSend: localIsSend!, + ); + @override Future receiveSlatepack(String slatepack) async { receiveCalls++; @@ -116,26 +135,39 @@ void main() { _InspectOnlyWallet wallet, ) async { bool? outcome; + final coin = wallet.cryptoCurrency; await tester.pumpWidget( - MaterialApp( - theme: ThemeData( - extensions: [ - StackColors.fromStackColorTheme( - StackTheme.fromJson(json: lightThemeJsonMap), + ProviderScope( + overrides: [ + pAmountFormatter(coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: "en_US", + coin: coin, + maxDecimals: coin.fractionDigits, ), - ], - ), - home: Scaffold( - body: Builder( - builder: (context) => TextButton( - onPressed: () async { - outcome = await SlatepackImportFlow.run( - context: context, - wallet: wallet, - text: "{}", - ); - }, - child: const Text("go"), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [ + StackColors.fromStackColorTheme( + StackTheme.fromJson(json: lightThemeJsonMap), + ), + ], + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + outcome = await SlatepackImportFlow.run( + context: context, + wallet: wallet, + text: "{}", + ); + }, + child: const Text("go"), + ), ), ), ), @@ -176,6 +208,51 @@ void main() { 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("Cannot finalize this slate"), findsOneWidget); + expect( + find.textContaining("This wallet did not start the transaction"), + findsOneWidget, + ); + expect(find.text("Finalize"), findsNothing); + await closeDialog(tester); + expect(wallet.finalizeCalls, 0); + }); + + 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 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.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); + await closeDialog(tester); + }); + testWidgets("invoice with invoice support is a placeholder", ( tester, ) async { diff --git a/test/wallets/mimblewimble_slate_inspection_test.dart b/test/wallets/mimblewimble_slate_inspection_test.dart index 77f581e69f..0761fbe497 100644 --- a/test/wallets/mimblewimble_slate_inspection_test.dart +++ b/test/wallets/mimblewimble_slate_inspection_test.dart @@ -1,4 +1,8 @@ +import 'dart:convert'; + import 'package:flutter_test/flutter_test.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/enums/slatepack_method.dart'; import 'package:stackwallet/utilities/slatepack_terms.dart'; @@ -22,7 +26,36 @@ Map _slate({required int signatures, int participants = 2}) { }; } +TransactionV2 _tx(int n, TransactionType type, String slateId) => 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}), +); + void main() { + 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(MimblewimbleWallet.localTxMatching([other], id), isNull); + expect(MimblewimbleWallet.localTxMatching([other, received], id), received); + // A send to self holds both sides, and the send is what gets finalized. + expect(MimblewimbleWallet.localTxMatching([received, sent], id), sent); + expect(MimblewimbleWallet.localTxMatching([sent, received], id), sent); + }); + SlateInspection inspect( Map json, { String? sender, From 0d1bb818a9b50aeb97c5c854ae552b2631b7e01e Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:13:03 -0600 Subject: [PATCH 06/15] Draw a slatepack QR code whenever the data fits in one The slatepack dialog refused to draw a QR code for anything over 1000 characters. Epic Cash slates and MWC slatepacks can be longer than that and were drawn at any length before the shared dialog replaced the per-coin ones, so the longer ones lost their QR code. The limit is now what a QR code can hold at the error correction level the widget draws at, 2953 bytes, counted in bytes instead of characters. Longer data still gets the note to copy, share or save it. --- lib/pages/slatepack/slatepack_qr.dart | 14 ++++----- test/pages/slatepack/slatepack_qr_test.dart | 33 +++++++++++++++++---- 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/lib/pages/slatepack/slatepack_qr.dart b/lib/pages/slatepack/slatepack_qr.dart index bb438c4bab..30442cf8a1 100644 --- a/lib/pages/slatepack/slatepack_qr.dart +++ b/lib/pages/slatepack/slatepack_qr.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:math' as math; import 'package:flutter/material.dart'; @@ -7,14 +8,13 @@ import '../../utilities/text_styles.dart'; import '../../widgets/qr.dart'; import '../../widgets/rounded_container.dart'; -/// Longest slatepack shown as a QR code. Measured armored Grin slatepacks -/// (characters): S1 360 plain, 806-955 encrypted; I1 348 plain, 719-855 -/// encrypted; S2 1837-2185; I2 1881-2068; S3 2683-2871. S1 and I1 fit one -/// QR at any error correction level, S2 and I2 only at L or M, so the cap -/// sits above S1/I1 and below S2/I2, which fall back to copy, share or save. -const kSlatepackQrMaxLength = 1000; +/// 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) => text.length <= kSlatepackQrMaxLength; +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. diff --git a/test/pages/slatepack/slatepack_qr_test.dart b/test/pages/slatepack/slatepack_qr_test.dart index c763ea648b..fde826e7bb 100644 --- a/test/pages/slatepack/slatepack_qr_test.dart +++ b/test/pages/slatepack/slatepack_qr_test.dart @@ -20,11 +20,32 @@ Widget _app(Widget child) => MaterialApp( void main() { test("length guard", () { - expect(slatepackFitsQr("a" * kSlatepackQrMaxLength), isTrue); - expect(slatepackFitsQr("a" * (kSlatepackQrMaxLength + 1)), isFalse); - // Measured Grin lengths: an encrypted S1 fits, an S2 does not. - expect(slatepackFitsQr("a" * 955), isTrue); - expect(slatepackFitsQr("a" * 1837), isFalse); + 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 { @@ -52,7 +73,7 @@ void main() { testWidgets("long slatepack falls back to a note", (tester) async { await tester.pumpWidget( - _app(SlatepackQr(data: "a" * (kSlatepackQrMaxLength + 1), noun: "slate")), + _app(SlatepackQr(data: "a" * (kSlatepackQrMaxBytes + 1), noun: "slate")), ); expect(find.byType(QR), findsNothing); expect(find.byKey(const Key("slatepackQrTooLong")), findsOneWidget); From 5e00116549d0e473f434c606144a009efd539699 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:14:18 -0600 Subject: [PATCH 07/15] Normalise slatepack text once before importing it The import flow passed whatever was pasted, scanned or opened straight to the wallet, so a slatepack with a greeting, a quote marker or other text around it was rejected. The flow now trims the text and, when it holds an armored slatepack, keeps only the part from the begin marker to the end marker. Both the BEGINSLATEPACK and BEGINSLATE_BIN frames are recognised, with or without the final period. JSON slates and anything without a frame are only trimmed. Inspecting, receiving and finalizing all use that text. --- .../slatepack/slatepack_import_flow.dart | 22 ++++- .../slatepack/slatepack_import_flow_test.dart | 89 +++++++++++++++++-- 2 files changed, 103 insertions(+), 8 deletions(-) diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart index 610bd86582..33994b5493 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -58,6 +58,21 @@ abstract final class SlatepackImportFlow { SlateState.unknown => SlatepackRoute.unsupported, }; + static final _armored = RegExp( + r"BEGINSLATE(PACK|_BIN)\.[\s\S]*?ENDSLATE\1\.?", + ); + + /// 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) { + final trimmed = text.trim(); + if (trimmed.startsWith("{")) return trimmed; + return _armored.firstMatch(trimmed)?.group(0) ?? trimmed; + } + /// Returns true once the slatepack has been acted on, so the caller can /// clear its input. static Future run({ @@ -66,12 +81,13 @@ abstract final class SlatepackImportFlow { 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(text); + final inspection = await wallet.inspectSlatepack(slatepack); final route = routeFor( inspection.state, supportsInvoices: wallet.supportsInvoices, @@ -94,7 +110,7 @@ abstract final class SlatepackImportFlow { switch (route) { case SlatepackRoute.receive: - return _receive(context, wallet, text, inspection); + return _receive(context, wallet, slatepack, inspection); case SlatepackRoute.finalizeSend: final local = read.local; @@ -117,7 +133,7 @@ abstract final class SlatepackImportFlow { return _finalize( context, wallet, - text, + slatepack, inspection, amount: local.amount, fee: local.fee, diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart index 8ee3fb359d..7ce063e040 100644 --- a/test/pages/slatepack/slatepack_import_flow_test.dart +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -31,9 +31,14 @@ class _InspectOnlyWallet extends EpiccashWallet { @override bool get supportsInvoices => invoices; + /// What the flow handed to the wallet. + final seen = []; + @override - Future inspectSlatepack(String armored) async => - SlateInspection(state: state, slateId: "test-slate"); + Future inspectSlatepack(String armored) async { + seen.add(armored); + return SlateInspection(state: state, slateId: "test-slate"); + } @override Future<({Amount amount, Amount fee, bool isSend})?> localTxForSlate( @@ -54,6 +59,7 @@ class _InspectOnlyWallet extends EpiccashWallet { @override Future finalizeSlatepack(String slatepack) async { + seen.add(slatepack); finalizeCalls++; return FinalizeResult(success: false, error: "not in tests"); } @@ -129,11 +135,71 @@ void main() { 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("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, - _InspectOnlyWallet wallet, - ) async { + _InspectOnlyWallet wallet, { + String text = "{}", + }) async { bool? outcome; final coin = wallet.cryptoCurrency; await tester.pumpWidget( @@ -163,7 +229,7 @@ void main() { outcome = await SlatepackImportFlow.run( context: context, wallet: wallet, - text: "{}", + text: text, ); }, child: const Text("go"), @@ -253,6 +319,19 @@ void main() { 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)); + // Once for the inspection and once for the finalize. + expect(wallet.seen, [armored, armored]); + await closeDialog(tester); + }); + testWidgets("invoice with invoice support is a placeholder", ( tester, ) async { From 0cc68fc5d51e6d57aa3eebaefa3ac2752dcfd52c Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:16:12 -0600 Subject: [PATCH 08/15] Keep Continue from starting a slatepack import twice On the slatepack screen a second press of Continue could start the import again while the first was still under way. On a phone the screen closes the keyboard and waits briefly before it starts, which leaves room for that, and the slatepack would then be processed twice. The screen now tracks a running import, ignores further presses and disables the button until the import has returned. --- lib/pages/slatepack/slatepack_view.dart | 39 ++++--- test/pages/slatepack/slatepack_view_test.dart | 107 ++++++++++++++++++ 2 files changed, 132 insertions(+), 14 deletions(-) create mode 100644 test/pages/slatepack/slatepack_view_test.dart diff --git a/lib/pages/slatepack/slatepack_view.dart b/lib/pages/slatepack/slatepack_view.dart index 4cd962c7cb..0ba05f7803 100644 --- a/lib/pages/slatepack/slatepack_view.dart +++ b/lib/pages/slatepack/slatepack_view.dart @@ -48,22 +48,33 @@ class _SlatepackViewState extends ConsumerState { 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 (!Util.isDesktop && _focusNode.hasFocus) { - _focusNode.unfocus(); - await Future.delayed(const Duration(milliseconds: 75)); - } - if (!mounted) return; + 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 = ""); + final done = await SlatepackImportFlow.run( + context: context, + wallet: _wallet, + text: _controller.text, + ); + if (done && mounted) { + setState(() => _controller.text = ""); + } + } finally { + _importing = false; + if (mounted) setState(() {}); } } @@ -152,8 +163,8 @@ class _SlatepackViewState extends ConsumerState { PrimaryButton( label: "Continue", buttonHeight: Util.isDesktop ? ButtonHeight.l : null, - enabled: _hasText, - onPressed: _hasText ? _continuePressed : null, + enabled: _hasText && !_importing, + onPressed: _hasText && !_importing ? _continuePressed : null, ), if (!Util.isDesktop) SizedBox(height: Constants.size.standardPadding), ], diff --git a/test/pages/slatepack/slatepack_view_test.dart b/test/pages/slatepack/slatepack_view_test.dart new file mode 100644 index 0000000000..a24652c7c6 --- /dev/null +++ b/test/pages/slatepack/slatepack_view_test.dart @@ -0,0 +1,107 @@ +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_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 { + 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(); + + 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); + }); +} From 3c8b7aea93e29c27c2a76c207d95bf0a7e67723b Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:21:04 -0600 Subject: [PATCH 09/15] Show a received slatepack's response after its screen closes Receiving a slatepack takes a while. If the screen that started the import was gone by the time the wallet had signed it, the response was dropped without a word, even though the wallet had already recorded the transaction and the sender still needs that response. The import flow now keeps hold of the root navigator before it starts and shows the response from there when its own screen has closed. It logs the slate id in that case, and also when a finalize completes after the screen closed. The response text itself is not logged. --- .../slatepack/slatepack_import_flow.dart | 41 ++++++- .../slatepack/slatepack_import_flow_test.dart | 111 +++++++++++++++--- 2 files changed, 130 insertions(+), 22 deletions(-) diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart index 33994b5493..6fb617934d 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; import '../../utilities/amount/amount.dart'; +import '../../utilities/logger.dart'; import '../../utilities/show_loading.dart'; import '../../utilities/util.dart'; import '../../wallets/wallet/wallet_mixin_interfaces/slatepack_interface.dart'; @@ -214,6 +215,10 @@ abstract final class SlatepackImportFlow { ); 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}...", @@ -226,10 +231,32 @@ abstract final class SlatepackImportFlow { }, errorTitle: "${terms.title} receive error", ); - if (result == null || !context.mounted) return false; + if (result == null) return false; unawaited(wallet.refresh()); - await showSlatepackDialog(context: context, terms: terms, result: result); + + // 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); + } 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, + ); + } else { + Logging.instance.e( + "Received ${terms.noun} ${result.slateId} but there was nowhere left " + "to show the response.", + ); + } return true; } @@ -273,10 +300,18 @@ abstract final class SlatepackImportFlow { }, errorTitle: "${terms.title} finalize error", ); - if (result == null || !context.mounted) return false; + if (result == null) return false; unawaited(wallet.refresh()); + 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) { unawaited( showFloatingFlushBar( diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart index 7ce063e040..888d0ed67a 100644 --- a/test/pages/slatepack/slatepack_import_flow_test.dart +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -1,13 +1,19 @@ +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/stack_file_system.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart'; @@ -16,8 +22,15 @@ 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.invoices = false, this.localIsSend}) - : super(CryptoCurrencyNetwork.main); + _InspectOnlyWallet( + this.state, { + this.invoices = false, + this.localIsSend, + this.receiveGate, + }) : super(CryptoCurrencyNetwork.main); + + /// When set, receiving waits for it and then succeeds. + final Completer? receiveGate; final SlateState state; final bool invoices; @@ -54,9 +67,21 @@ class _InspectOnlyWallet extends EpiccashWallet { @override Future receiveSlatepack(String slatepack) async { receiveCalls++; - return SlatepackResult(success: false, error: "not in tests"); + if (receiveGate == null) { + return SlatepackResult(success: false, error: "not in tests"); + } + await receiveGate!.future; + return SlatepackResult( + success: true, + slatepack: '{"response": true}', + slateId: "test-slate", + state: SlateState.s2, + ); } + @override + Future refresh({bool doScan = true}) async {} + @override Future finalizeSlatepack(String slatepack) async { seen.add(slatepack); @@ -199,12 +224,21 @@ void main() { WidgetTester tester, _InspectOnlyWallet 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, @@ -216,24 +250,26 @@ void main() { ], child: MaterialApp( theme: ThemeData( - extensions: [ - StackColors.fromStackColorTheme( - StackTheme.fromJson(json: lightThemeJsonMap), - ), - ], + extensions: [StackColors.fromStackColorTheme(theme)], ), home: Scaffold( - body: Builder( - builder: (context) => TextButton( - onPressed: () async { - outcome = await SlatepackImportFlow.run( - context: context, - wallet: wallet, - text: text, - ); - }, - child: const Text("go"), - ), + 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"), + ), + ), ), ), ), @@ -332,6 +368,43 @@ void main() { 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); + + 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); + + await tester.tap(find.text("Done")); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(done, isTrue); + expect(tester.takeException(), isNull); + }); + testWidgets("invoice with invoice support is a placeholder", ( tester, ) async { From bd0338761340cc5a42642d1331542f701321e162 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:22:11 -0600 Subject: [PATCH 10/15] Anchor the slatepack share sheet to the Share button The slatepack dialog shared its text without a position for the share sheet. An iPad needs one to place the popover and refuses to open the sheet without it, so Share did nothing there apart from logging an error. The dialog now passes the Share button's rect on screen. Other devices ignore it. --- lib/pages/slatepack/slatepack_dialog.dart | 24 ++++-- .../slatepack/slatepack_dialog_test.dart | 75 +++++++++++++++++++ 2 files changed, 93 insertions(+), 6 deletions(-) create mode 100644 test/pages/slatepack/slatepack_dialog_test.dart diff --git a/lib/pages/slatepack/slatepack_dialog.dart b/lib/pages/slatepack/slatepack_dialog.dart index 5a8dc27583..47260064f6 100644 --- a/lib/pages/slatepack/slatepack_dialog.dart +++ b/lib/pages/slatepack/slatepack_dialog.dart @@ -118,10 +118,20 @@ class SlatepackDialog extends StatelessWidget { } } - Future _share() async { + /// [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), + ShareParams( + text: slatepack, + subject: title, + sharePositionOrigin: origin, + ), ); } catch (e, s) { Logging.instance.e( @@ -250,10 +260,12 @@ class SlatepackDialog extends StatelessWidget { if (!isDesktop) ...[ const SizedBox(width: 12), Expanded( - child: SecondaryButton( - label: "Share", - icon: _icon(context, Assets.svg.share), - onPressed: _share, + child: Builder( + builder: (context) => SecondaryButton( + label: "Share", + icon: _icon(context, Assets.svg.share), + onPressed: () => _share(context), + ), ), ), ], diff --git a/test/pages/slatepack/slatepack_dialog_test.dart b/test/pages/slatepack/slatepack_dialog_test.dart new file mode 100644 index 0000000000..74fd356693 --- /dev/null +++ b/test/pages/slatepack/slatepack_dialog_test.dart @@ -0,0 +1,75 @@ +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:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/models/slatepack_models.dart'; +import 'package:stackwallet/pages/slatepack/slatepack_dialog.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/utilities/slatepack_terms.dart'; +import 'package:stackwallet/utilities/util.dart'; + +import '../../sample_data/theme_json.dart'; + +void main() { + testWidgets("Share anchors the share sheet to the Share button", ( + tester, + ) async { + tester.view.physicalSize = const Size(1400, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + // 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, + ); + }); +} From 924778788cdf6a19b5d1cabbac227f4f73594f13 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:45:08 -0600 Subject: [PATCH 11/15] Close the sending dialog by its own route The sending dialog was closed by popping the root navigator. If another route had opened above the dialog by the time the send returned, that route was popped and the dialog stayed up. The dialog's route is now kept and removed directly, so nothing else is closed. A failed HTTP address also closes the dialog when the view is already gone. --- .../send_view/confirm_transaction_view.dart | 42 ++++++++---------- .../slatepack_confirmation_test.dart | 43 +++++++++++++++++++ 2 files changed, 62 insertions(+), 23 deletions(-) diff --git a/lib/pages/send_view/confirm_transaction_view.dart b/lib/pages/send_view/confirm_transaction_view.dart index db6483184b..49f52dd7cc 100644 --- a/lib/pages/send_view/confirm_transaction_view.dart +++ b/lib/pages/send_view/confirm_transaction_view.dart @@ -264,36 +264,33 @@ class _ConfirmTransactionViewState final coin = wallet.info.coin; final sendProgressController = ProgressAndSuccessController(); - var isSendingDialogOpen = true; // Looked up now so the dialog can still be closed if this view is gone by // the time the send returns. final navigator = Navigator.of(context, rootNavigator: true); + // The dialog's own route is kept so that closing it removes that route + // and nothing else, whatever is on top of it by then. + final sendingRoute = DialogRoute( + context: context, + useSafeArea: false, + barrierDismissible: false, + themes: InheritedTheme.capture(from: context, to: navigator.context), + builder: (context) { + return SendingTransactionDialog( + coin: coin, + controller: sendProgressController, + ); + }, + ); + void closeSendingDialog() { - if (!navigator.mounted || !isSendingDialogOpen) { - return; + if (navigator.mounted && sendingRoute.isActive) { + navigator.removeRoute(sendingRoute); } - if (navigator.canPop()) { - navigator.pop(); - } - isSendingDialogOpen = false; } - unawaited( - showDialog( - context: context, - useRootNavigator: true, - useSafeArea: false, - barrierDismissible: false, - builder: (context) { - return SendingTransactionDialog( - coin: coin, - controller: sendProgressController, - ); - }, - ).whenComplete(() => isSendingDialogOpen = false), - ); + unawaited(navigator.push(sendingRoute)); final time = Future.delayed(const Duration(milliseconds: 2500)); @@ -406,9 +403,8 @@ class _ConfirmTransactionViewState } } } on BadHttpAddressException catch (_) { + closeSendingDialog(); if (context.mounted) { - // pop building dialog - closeSendingDialog(); unawaited( showFloatingFlushBar( type: FlushBarType.warning, diff --git a/test/pages/send_view/slatepack_confirmation_test.dart b/test/pages/send_view/slatepack_confirmation_test.dart index 892cfdf7ee..c40dc7db61 100644 --- a/test/pages/send_view/slatepack_confirmation_test.dart +++ b/test/pages/send_view/slatepack_confirmation_test.dart @@ -336,4 +336,47 @@ void main() { await tester.pump(_sendTimer); expect(tester.takeException(), isNull); }); + + testWidgets('closing the sending dialog leaves a route opened above it ' + 'alone', (tester) async { + final gate = Completer(); + final wallet = _Wallet(gate: gate); + final shown = ValueNotifier(true); + addTearDown(shown.dispose); + await _confirmSend(tester, wallet, shown: shown); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byType(SendingTransactionDialog), findsOneWidget); + + final root = Navigator.of( + tester.element(find.byType(SendingTransactionDialog)), + rootNavigator: true, + ); + unawaited( + root.push( + MaterialPageRoute(builder: (_) => const Text('opened above')), + ), + ); + shown.value = false; + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('opened above'), findsOneWidget); + + gate.complete(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('opened above'), findsOneWidget); + expect( + find.byType(SendingTransactionDialog, skipOffstage: false), + findsNothing, + ); + + root.pop(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('opened above'), findsNothing); + expect(find.byType(SendingTransactionDialog), findsNothing); + await tester.pump(_sendTimer); + expect(tester.takeException(), isNull); + }); } From 4b852ea2cc16749e670d801e4277f6968ecaa4c5 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:47:53 -0600 Subject: [PATCH 12/15] Take the slatepack loading overlay down after the screen closes The import flow showed its loading overlay through showLoading, which only removes the overlay while the calling screen is still mounted. If that screen closed while the wallet was working, the overlay stayed over the whole app, under the response that is now shown in that case. The flow keeps its own overlay route on the root navigator and removes it when the wallet answers. An error is shown from the root navigator too when the screen is gone. --- .../slatepack/slatepack_import_flow.dart | 61 +++++++++++++------ .../slatepack/slatepack_import_flow_test.dart | 48 ++++++++++++++- 2 files changed, 91 insertions(+), 18 deletions(-) diff --git a/lib/pages/slatepack/slatepack_import_flow.dart b/lib/pages/slatepack/slatepack_import_flow.dart index 6fb617934d..a8d5927eda 100644 --- a/lib/pages/slatepack/slatepack_import_flow.dart +++ b/lib/pages/slatepack/slatepack_import_flow.dart @@ -5,10 +5,11 @@ import 'package:flutter/material.dart'; import '../../models/slatepack_models.dart'; import '../../notifications/show_flush_bar.dart'; import '../../utilities/amount/amount.dart'; +import '../../themes/stack_colors.dart'; import '../../utilities/logger.dart'; -import '../../utilities/show_loading.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'; @@ -339,26 +340,52 @@ abstract final class SlatepackImportFlow { Future Function() action, { required String errorTitle, }) async { - Exception? ex; - final result = await showLoading( - // Let the overlay open before the work starts, so an early error - // does not pop the wrong route. - whileFuture: Future.delayed(const Duration(milliseconds: 300)) - .then((_) => action()), + // 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 = DialogRoute( context: context, - message: message, - rootNavigator: true, - onException: (e) => ex = e, + 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 { + // Let the overlay paint before the wallet is asked. + await Future.delayed(const Duration(milliseconds: 300)); + result = await action(); + } catch (e, s) { + Logging.instance.w(errorTitle, error: e, stackTrace: s); + error = e; + } - if (ex != null || result == null) { + if (root.mounted && overlay.isActive) { + root.removeRoute(overlay); + } + + if (error != null || result == null) { + // An error is worth showing even after the importing screen closed. + final text = + error?.toString().replaceFirst("Exception: ", "") ?? + "Unexpected result without an error"; if (context.mounted) { - await _message( - context, - errorTitle, - ex?.toString().replaceFirst("Exception: ", "") ?? - "Unexpected result without an error", - ); + await _message(context, errorTitle, text); + } else if (root.mounted) { + await _message(root.context, errorTitle, text); } return null; } diff --git a/test/pages/slatepack/slatepack_import_flow_test.dart b/test/pages/slatepack/slatepack_import_flow_test.dart index 888d0ed67a..8a251cadce 100644 --- a/test/pages/slatepack/slatepack_import_flow_test.dart +++ b/test/pages/slatepack/slatepack_import_flow_test.dart @@ -16,6 +16,7 @@ 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/wallet/impl/epiccash_wallet.dart'; +import 'package:stackwallet/widgets/custom_loading_overlay.dart'; import '../../sample_data/theme_json.dart'; @@ -27,10 +28,13 @@ class _InspectOnlyWallet extends EpiccashWallet { this.invoices = false, this.localIsSend, this.receiveGate, + this.receiveError, }) : super(CryptoCurrencyNetwork.main); - /// When set, receiving waits for it and then succeeds. + /// When set, receiving waits for it and then succeeds, or throws + /// [receiveError] if that is set. final Completer? receiveGate; + final Exception? receiveError; final SlateState state; final bool invoices; @@ -71,6 +75,7 @@ class _InspectOnlyWallet extends EpiccashWallet { return SlatepackResult(success: false, error: "not in tests"); } await receiveGate!.future; + if (receiveError != null) throw receiveError!; return SlatepackResult( success: true, slatepack: '{"response": true}', @@ -387,6 +392,7 @@ void main() { 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(); @@ -402,6 +408,46 @@ void main() { 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(); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.text("the slate was refused"), findsOneWidget); + expect( + find.byType(CustomLoadingOverlay, skipOffstage: false), + findsNothing, + ); + + await closeDialog(tester); + await tester.pump(const Duration(milliseconds: 400)); + expect(done, isFalse); expect(tester.takeException(), isNull); }); From d8e691a80e83b9167e7b886516bac5825e71ef1d Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 11 Nov 2026 17:47:53 -0600 Subject: [PATCH 13/15] Remove the unused note from the slatepack summary dialog --- .../slatepack/slatepack_summary_dialog.dart | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/lib/pages/slatepack/slatepack_summary_dialog.dart b/lib/pages/slatepack/slatepack_summary_dialog.dart index a13456bd5a..9f0435e82b 100644 --- a/lib/pages/slatepack/slatepack_summary_dialog.dart +++ b/lib/pages/slatepack/slatepack_summary_dialog.dart @@ -4,13 +4,11 @@ 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'; @@ -25,7 +23,6 @@ class SlatepackSummaryDialog extends ConsumerWidget { this.amount, this.fee, this.details = const [], - this.note, }); final String title; @@ -37,9 +34,6 @@ class SlatepackSummaryDialog extends ConsumerWidget { /// Extra label and value rows shown under the amount and fee. final List<(String, String)> details; - /// Shown above the buttons, e.g. a warning. - final String? note; - @override Widget build(BuildContext context, WidgetRef ref) { final isDesktop = Util.isDesktop; @@ -72,17 +66,6 @@ class SlatepackSummaryDialog extends ConsumerWidget { ], ), ), - if (note != null) ...[ - const SizedBox(height: 16), - RoundedContainer( - color: colors.warningBackground, - child: Text( - note!, - style: STextStyles.label(context) - .copyWith(color: colors.warningForeground), - ), - ), - ], const SizedBox(height: 24), Row( children: [ From c61a2a7464824dbc143846b65f97e589aff3a7e6 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Sat, 7 Nov 2026 13:05:37 -0600 Subject: [PATCH 14/15] Hide cancel on slatepack wallet rows that have no slate --- .../transaction_views/tx_v2/transaction_v2_details_view.dart | 2 ++ 1 file changed, 2 insertions(+) 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 c629675f93..ad1dba17ab 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 @@ -1468,6 +1468,7 @@ class _TransactionV2DetailsViewState ), ), if (isSlatepackWallet && + _transaction.slateId != null && _transaction.getConfirmations(currentHeight) < 1 && _transaction.isCancelled == false) const SizedBox(height: 40), @@ -1478,6 +1479,7 @@ class _TransactionV2DetailsViewState floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: (isSlatepackWallet && + _transaction.slateId != null && _transaction.getConfirmations(currentHeight) < 1 && _transaction.isCancelled == false) ? ConditionalParent( From d517fc371f6d9ebf92452eff2761644a78fb2682 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Fri, 13 Nov 2026 15:41:49 -0600 Subject: [PATCH 15/15] fix: confirm slatepack cancellation --- .../tx_v2/transaction_v2_details_view.dart | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) 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 ad1dba17ab..c792e140e1 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 @@ -1517,6 +1517,26 @@ class _TransactionV2DetailsViewState return; } + final proceed = await showDialog( + context: context, + builder: (context) => StackDialog( + title: "Cancel this transaction?", + message: + "The other party can no longer complete it, " + "and any funds it locked become spendable " + "again.", + leftButton: SecondaryButton( + label: "Keep", + onPressed: () => Navigator.of(context).pop(false), + ), + rightButton: PrimaryButton( + label: "Cancel transaction", + onPressed: () => Navigator.of(context).pop(true), + ), + ), + ); + if (proceed != true || !context.mounted) return; + unawaited( showDialog( barrierDismissible: false, @@ -1571,7 +1591,7 @@ class _TransactionV2DetailsViewState } }, child: Text( - "Cancel Transaction", + "Cancel transaction", style: STextStyles.button(context), ), ),