diff --git a/lib/pages/wallet_view/wallet_view.dart b/lib/pages/wallet_view/wallet_view.dart index 0234a5567..b462e18e2 100644 --- a/lib/pages/wallet_view/wallet_view.dart +++ b/lib/pages/wallet_view/wallet_view.dart @@ -53,6 +53,7 @@ import '../../wallets/wallet/impl/bitcoin_frost_wallet.dart'; import '../../wallets/wallet/impl/firo_wallet.dart'; import '../../wallets/wallet/impl/namecoin_wallet.dart'; import '../../wallets/wallet/impl/salvium_wallet.dart'; +import '../../wallets/wallet/impl/zcash_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'; @@ -109,6 +110,7 @@ import '../settings_views/wallet_settings_view/wallet_settings_view.dart'; import '../signing/signing_view.dart'; import '../spark_names/spark_names_home_view.dart'; import '../token_view/my_tokens_view.dart'; +import '../zcash_migration/zcash_migration_view.dart'; import 'sub_widgets/transactions_list.dart'; import 'sub_widgets/wallet_summary.dart'; import 'transaction_views/all_transactions_view.dart'; @@ -1327,6 +1329,27 @@ class _WalletViewState extends ConsumerState { ); }, ), + if (wallet is ZcashWallet) + WalletNavigationBarItemData( + label: "Migrate", + icon: SvgPicture.asset( + Assets.svg.recycle, + height: 20, + width: 20, + colorFilter: ColorFilter.mode( + Theme.of(context) + .extension()! + .bottomNavIconIcon, + BlendMode.srcIn, + ), + ), + onTap: () { + Navigator.of(context).pushNamed( + ZcashMigrationView.routeName, + arguments: walletId, + ); + }, + ), ], ), ), diff --git a/lib/pages/zcash_migration/zcash_migration_view.dart b/lib/pages/zcash_migration/zcash_migration_view.dart new file mode 100644 index 000000000..21e9b0141 --- /dev/null +++ b/lib/pages/zcash_migration/zcash_migration_view.dart @@ -0,0 +1,273 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../pages_desktop_specific/desktop_home_view.dart'; +import '../../providers/providers.dart'; +import '../../route_generator.dart'; +import '../../themes/stack_colors.dart'; +import '../../utilities/amount/amount.dart'; +import '../../utilities/amount/amount_formatter.dart'; +import '../../utilities/show_loading.dart'; +import '../../utilities/text_styles.dart'; +import '../../utilities/util.dart'; +import '../../wallets/models/tx_data.dart'; +import '../../wallets/wallet/impl/zcash_wallet.dart'; +import '../../wallets/wallet/intermediate/zcash_send.dart'; +import '../../widgets/background.dart'; +import '../../widgets/conditional_parent.dart'; +import '../../widgets/custom_buttons/app_bar_icon_button.dart'; +import '../../widgets/desktop/desktop_app_bar.dart'; +import '../../widgets/desktop/desktop_dialog.dart'; +import '../../widgets/desktop/desktop_scaffold.dart'; +import '../../widgets/desktop/primary_button.dart'; +import '../../widgets/loading_indicator.dart'; +import '../../widgets/rounded_white_container.dart'; +import '../../widgets/stack_dialog.dart'; +import '../send_view/confirm_transaction_view.dart'; + +/// Moves what a Zcash wallet holds in the Sapling pool, and its transparent +/// coins, to Ironwood, the pool a send spends from. +class ZcashMigrationView extends ConsumerStatefulWidget { + const ZcashMigrationView({super.key, required this.walletId}); + + static const routeName = '/zcashMigration'; + + final String walletId; + + @override + ConsumerState createState() => _ZcashMigrationViewState(); +} + +class _ZcashMigrationViewState extends ConsumerState { + late Future> _funds; + bool _preparing = false; + + ZcashWallet get _wallet => + ref.read(pWallets).getWallet(widget.walletId) as ZcashWallet; + + @override + void initState() { + super.initState(); + _funds = _wallet.movableFunds(); + } + + Future _move(ZcashMovablePool pool) async { + if (_preparing) return; + _preparing = true; + try { + Exception? failure; + final prepared = await showLoading( + whileFuture: _wallet.prepareMoveToIronwood(pool), + context: context, + message: 'Preparing transaction', + rootNavigator: Util.isDesktop, + onException: (e) => failure = e, + ); + if (!mounted) return; + if (prepared == null) { + await showDialog( + context: context, + builder: (_) => StackOkDialog( + title: 'The funds were not moved', + message: switch (failure) { + final ZcashMoveException e => e.message, + final ZcashSaplingParametersUnavailableException e => + e.toString(), + _ => + 'The transaction could not be prepared. Check that the ' + 'wallet is synced, then try again.\n\n$failure', + }, + desktopPopRootNavigator: Util.isDesktop, + ), + ); + return; + } + // The mobile confirmation shows the note, which a send's form sets. + final txData = prepared.copyWith(note: ''); + void reload() { + if (mounted) setState(() => _funds = _wallet.movableFunds()); + } + + if (Util.isDesktop) { + await showDialog( + context: context, + builder: (context) => DesktopDialog( + maxHeight: MediaQuery.of(context).size.height - 64, + maxWidth: 580, + child: ConfirmTransactionView( + txData: txData, + walletId: widget.walletId, + onSuccess: reload, + routeOnSuccessName: DesktopHomeView.routeName, + ), + ), + ); + } else { + await Navigator.of(context).push( + RouteGenerator.getRoute( + shouldUseMaterialRoute: RouteGenerator.useMaterialPageRoute, + builder: (_) => ConfirmTransactionView( + txData: txData, + walletId: widget.walletId, + onSuccess: reload, + ), + settings: const RouteSettings( + name: ConfirmTransactionView.routeName, + ), + ), + ); + } + } finally { + _preparing = false; + } + } + + @override + Widget build(BuildContext context) { + final isDesktop = Util.isDesktop; + final formatter = ref.watch(pAmountFormatter(_wallet.cryptoCurrency)); + return ConditionalParent( + condition: !isDesktop, + builder: (child) => Background(child: child), + child: MasterScaffold( + isDesktop: isDesktop, + appBar: isDesktop + ? DesktopAppBar( + isCompactHeight: true, + background: Theme.of(context).extension()!.popupBG, + leading: Row( + children: [ + Padding( + padding: const EdgeInsets.only(left: 24, right: 20), + child: AppBarBackButton( + size: 32, + onPressed: Navigator.of(context).pop, + ), + ), + Text( + 'Migrate funds', + style: STextStyles.desktopH3(context), + ), + ], + ), + ) + : AppBar( + leading: AppBarBackButton(onPressed: Navigator.of(context).pop), + titleSpacing: 0, + title: Text( + 'Migrate funds', + style: STextStyles.navBarTitle(context), + ), + ), + body: ConditionalParent( + condition: !isDesktop, + builder: (child) => SafeArea( + child: Padding(padding: const EdgeInsets.all(16), child: child), + ), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 640), + child: FutureBuilder>( + future: _funds, + builder: (context, snapshot) { + if (snapshot.hasError) { + return Center( + child: Text( + 'The funds of this wallet could not be read.', + textAlign: TextAlign.center, + style: STextStyles.smallMed14(context), + ), + ); + } + final funds = snapshot.data; + if (funds == null) return const LoadingIndicator(); + return ZcashMigrationPanel( + funds: funds, + format: formatter.format, + onMove: (pool) => unawaited(_move(pool)), + ); + }, + ), + ), + ), + ), + ), + ); + } +} + +/// The pools of [funds], each with what it holds and a button that moves it. +class ZcashMigrationPanel extends StatelessWidget { + const ZcashMigrationPanel({ + super.key, + required this.funds, + required this.format, + required this.onMove, + }); + + final Map funds; + final String Function(Amount amount) format; + final ValueChanged onMove; + + static String _title(ZcashMovablePool pool) => switch (pool) { + ZcashMovablePool.sapling => 'Sapling funds', + ZcashMovablePool.transparent => 'Transparent funds', + }; + + static String _detail(ZcashMovablePool pool) => switch (pool) { + ZcashMovablePool.sapling => + 'Funds received on a Sapling address of this wallet. Moving them ' + 'needs the Sapling parameters, which are downloaded first if they ' + 'are not on this device.', + ZcashMovablePool.transparent => + 'Funds received on a transparent address of this wallet. The ' + 'transaction that moves them shows their amount and where they ' + 'came from on the chain.', + }; + + @override + Widget build(BuildContext context) => ListView( + padding: Util.isDesktop ? const EdgeInsets.all(24) : EdgeInsets.zero, + children: [ + Text( + 'A Zcash send spends the funds of the Ironwood pool. Funds this ' + 'wallet holds in another pool count towards its balance and can be ' + 'moved to Ironwood here, in a transaction to the wallet itself that ' + 'you confirm like a send. A transaction moves up to 50 notes or ' + 'coins.', + style: STextStyles.smallMed14(context), + ), + const SizedBox(height: 16), + for (final pool in ZcashMovablePool.values) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: RoundedWhiteContainer( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(_title(pool), style: STextStyles.w600_14(context)), + const SizedBox(height: 4), + Text(_detail(pool), style: STextStyles.smallMed12(context)), + const SizedBox(height: 12), + Text( + format(funds[pool]!), + key: Key('zcash_movable_${pool.name}'), + style: STextStyles.w500_14(context), + ), + const SizedBox(height: 12), + PrimaryButton( + key: Key('zcash_move_${pool.name}'), + buttonHeight: ButtonHeight.l, + label: 'Move to Ironwood', + enabled: funds[pool]!.raw > BigInt.zero, + onPressed: () => onMove(pool), + ), + ], + ), + ), + ), + ], + ); +} diff --git a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart index 936e079e1..a4acd7297 100644 --- a/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart +++ b/lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart @@ -28,6 +28,7 @@ import '../../../../pages/paynym/paynym_home_view.dart'; import '../../../../pages/salvium_stake/salvium_create_stake_view.dart'; import '../../../../pages/signing/signing_view.dart'; import '../../../../pages/spark_names/spark_names_home_view.dart'; +import '../../../../pages/zcash_migration/zcash_migration_view.dart'; import '../../../../providers/desktop/current_desktop_menu_item.dart'; import '../../../../providers/global/paynym_api_provider.dart'; import '../../../../providers/providers.dart'; @@ -45,6 +46,7 @@ import '../../../../wallets/wallet/impl/bitcoin_wallet.dart'; import '../../../../wallets/wallet/impl/firo_wallet.dart'; import '../../../../wallets/wallet/impl/namecoin_wallet.dart'; import '../../../../wallets/wallet/impl/salvium_wallet.dart'; +import '../../../../wallets/wallet/impl/zcash_wallet.dart'; import '../../../../wallets/wallet/intermediate/cryptonote_wallet.dart'; import '../../../../wallets/wallet/intermediate/lib_salvium_wallet.dart'; import '../../../../wallets/wallet/wallet.dart' show Wallet; @@ -95,6 +97,7 @@ enum WalletFeature { salviumStaking("Staking", "Staking"), sign("Sign/Verify", "Sign / Verify messages"), masternodes("Masternodes", "Manage masternodes"), + zcashMigration("Migrate", "Move Sapling and transparent funds to Ironwood"), // special cases clearSparkCache("", ""), @@ -369,6 +372,11 @@ class _DesktopWalletFeaturesState extends ConsumerState { .pushNamed(DesktopChurningView.routeName, arguments: widget.walletId); } + void _onZcashMigrationPressed() { + Navigator.of(context) + .pushNamed(ZcashMigrationView.routeName, arguments: widget.walletId); + } + void _onNamesPressed() { Navigator.of(context) .pushNamed(NamecoinNamesHomeView.routeName, arguments: widget.walletId); @@ -535,6 +543,13 @@ class _DesktopWalletFeaturesState extends ConsumerState { if (!isViewOnly && (wallet is CryptonoteWallet)) (WalletFeature.churn, Assets.svg.churn, _onChurnPressed), + if (wallet is ZcashWallet) + ( + WalletFeature.zcashMigration, + Assets.svg.recycle, + _onZcashMigrationPressed, + ), + if (wallet is NamecoinWallet) (WalletFeature.namecoinName, Assets.svg.robotHead, _onNamesPressed), ]; diff --git a/lib/route_generator.dart b/lib/route_generator.dart index 35ff64546..a3900f8c7 100644 --- a/lib/route_generator.dart +++ b/lib/route_generator.dart @@ -212,6 +212,7 @@ import 'pages/wallet_view/transaction_views/tx_v2/transaction_v2_details_view.da import 'pages/wallet_view/wallet_view.dart'; import 'pages/wallets_view/wallets_overview.dart'; import 'pages/wallets_view/wallets_view.dart'; +import 'pages/zcash_migration/zcash_migration_view.dart'; import 'pages_desktop_specific/address_book_view/desktop_address_book.dart'; import 'pages_desktop_specific/addresses/desktop_wallet_addresses_view.dart'; import 'pages_desktop_specific/cashfusion/desktop_cashfusion_view.dart'; @@ -1037,6 +1038,16 @@ class RouteGenerator { } return _routeError("${settings.name} invalid args: ${args.toString()}"); + case ZcashMigrationView.routeName: + if (args is String) { + return getRoute( + shouldUseMaterialRoute: useMaterialPageRoute, + builder: (_) => ZcashMigrationView(walletId: args), + settings: RouteSettings(name: settings.name), + ); + } + return _routeError("${settings.name} invalid args: ${args.toString()}"); + case ChurningView.routeName: if (args is String) { return getRoute( diff --git a/test/pages/zcash_migration/zcash_migration_view_test.dart b/test/pages/zcash_migration/zcash_migration_view_test.dart new file mode 100644 index 000000000..8071d87ac --- /dev/null +++ b/test/pages/zcash_migration/zcash_migration_view_test.dart @@ -0,0 +1,252 @@ +import 'dart:async'; +import 'dart:typed_data'; + +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/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/stack_theme.dart'; +import 'package:stackwallet/pages/send_view/confirm_transaction_view.dart'; +import 'package:stackwallet/pages/zcash_migration/zcash_migration_view.dart'; +import 'package:stackwallet/providers/global/prefs_provider.dart'; +import 'package:stackwallet/providers/global/wallets_provider.dart'; +import 'package:stackwallet/services/wallets.dart'; +import 'package:stackwallet/themes/stack_colors.dart'; +import 'package:stackwallet/themes/theme_service.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/prefs.dart'; +import 'package:stackwallet/utilities/util.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.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/zcash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_send.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; +import 'package:stackwallet/widgets/desktop/primary_button.dart'; + +import '../../sample_data/theme_json.dart'; + +final _coin = Zcash(CryptoCurrencyNetwork.main); + +Amount _zatoshis(int value) => + Amount(rawValue: BigInt.from(value), fractionDigits: _coin.fractionDigits); + +bool _enabled(WidgetTester tester, ZcashMovablePool pool) => tester + .widget(find.byKey(Key('zcash_move_${pool.name}'))) + .enabled; + +void main() { + late platform.Platform originalPlatform; + + setUp(() => originalPlatform = Util.layoutPlatform); + tearDown(() => Util.layoutPlatform = originalPlatform); + + Future pump(WidgetTester tester, Widget home) async { + final theme = StackTheme.fromJson(json: lightThemeJsonMap); + tester.view.physicalSize = const Size(1200, 2400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + ProviderScope( + overrides: [ + pThemeService.overrideWithValue(_TestThemeService(theme)), + pWallets.overrideWithValue(_Wallets()), + pWalletCoin('zcash').overrideWithValue(_coin), + prefsChangeNotifierProvider.overrideWithValue(_Prefs()), + pAmountFormatter(_coin).overrideWithValue( + AmountFormatter( + unit: AmountUnit.normal, + locale: 'en_US', + coin: _coin, + maxDecimals: _coin.fractionDigits, + ), + ), + ], + child: MaterialApp( + theme: ThemeData( + extensions: [StackColors.fromStackColorTheme(theme)], + ), + home: home, + ), + ), + ); + } + + testWidgets('the panel shows what each pool holds and moves only a pool ' + 'that holds funds', (tester) async { + final moved = []; + await pump( + tester, + Scaffold( + body: ZcashMigrationPanel( + funds: { + ZcashMovablePool.sapling: _zatoshis(250000), + ZcashMovablePool.transparent: _zatoshis(0), + }, + format: (amount) => '${amount.raw} zatoshis', + onMove: moved.add, + ), + ), + ); + + expect( + tester.widget(find.byKey(const Key('zcash_movable_sapling'))).data, + '250000 zatoshis', + ); + expect( + tester + .widget(find.byKey(const Key('zcash_movable_transparent'))) + .data, + '0 zatoshis', + ); + expect(_enabled(tester, ZcashMovablePool.sapling), isTrue); + expect(_enabled(tester, ZcashMovablePool.transparent), isFalse); + + await tester.tap(find.byKey(const Key('zcash_move_transparent'))); + await tester.tap(find.byKey(const Key('zcash_move_sapling'))); + expect(moved, [ZcashMovablePool.sapling]); + }); + + for (final os in ['android', 'linux']) { + testWidgets('$os: the view shows the wallet\'s funds and says why a move ' + 'was refused', (tester) async { + Util.layoutPlatform = platform.FakePlatform(operatingSystem: os); + final wallet = _Wallets.wallet + ..prepared.clear() + ..refusal = const ZcashMoveException( + 'These Sapling funds were received more than 20000 blocks ago.', + ); + await pump(tester, const ZcashMigrationView(walletId: 'zcash')); + await tester.pump(); + + expect(find.textContaining('0.0025'), findsOneWidget); + expect(_enabled(tester, ZcashMovablePool.sapling), isTrue); + expect(_enabled(tester, ZcashMovablePool.transparent), isFalse); + + await tester.tap(find.byKey(const Key('zcash_move_sapling'))); + await tester.pump(); + // The loading dialog is up until the wallet answers. + wallet.answer.complete(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + expect(wallet.prepared, [ZcashMovablePool.sapling]); + expect(find.text('The funds were not moved'), findsOneWidget); + expect( + find.text( + 'These Sapling funds were received more than 20000 blocks ago.', + ), + findsOneWidget, + ); + }); + + testWidgets('$os: a prepared move opens the confirmation, and leaving it ' + 'drops the move', (tester) async { + Util.layoutPlatform = platform.FakePlatform(operatingSystem: os); + final wallet = _Wallets.wallet + ..prepared.clear() + ..cancelled.clear() + ..refusal = null; + await pump(tester, const ZcashMigrationView(walletId: 'zcash')); + await tester.pump(); + + await tester.tap(find.byKey(const Key('zcash_move_sapling'))); + await tester.pump(); + wallet.answer.complete(); + await tester.pumpAndSettle(); + + expect(wallet.prepared, [ZcashMovablePool.sapling]); + final confirmation = tester.widget( + find.byType(ConfirmTransactionView), + ); + expect(confirmation.txData.txid, wallet.txData.txid); + expect(confirmation.txData.vExtraData, wallet.txData.vExtraData); + expect(confirmation.walletId, 'zcash'); + expect(wallet.cancelled, isEmpty); + + Navigator.of( + tester.element(find.byType(ConfirmTransactionView)), + rootNavigator: true, + ).pop(); + await tester.pumpAndSettle(); + + expect(find.byType(ConfirmTransactionView), findsNothing); + expect(find.byType(ZcashMigrationView), findsOneWidget); + expect(wallet.cancelled.single.vExtraData, wallet.txData.vExtraData); + }); + } +} + +class _TestThemeService extends Fake implements ThemeService { + _TestThemeService(this.theme); + + final StackTheme theme; + + @override + StackTheme? getTheme({required String themeId}) => theme; +} + +class _Wallets extends Fake implements Wallets { + static final wallet = _Wallet(); + + @override + Wallet getWallet(String walletId) => wallet; +} + +class _Prefs extends ChangeNotifier implements Prefs { + @override + bool get externalCalls => false; + + @override + String get currency => 'USD'; + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class _Wallet extends Fake implements ZcashWallet { + final prepared = []; + final cancelled = []; + Exception? refusal; + + final txData = TxData( + raw: '00', + txid: '77' * 32, + vExtraData: Uint8List.fromList([1, 2, 3]), + fee: _zatoshis(15000), + recipients: [ + TxRecipient( + address: 'u1own', + amount: _zatoshis(234999), + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + ); + + @override + Future cancelSend({required TxData txData}) async => + cancelled.add(txData); + var answer = Completer(); + + @override + Zcash get cryptoCurrency => _coin; + + @override + Future> movableFunds() async => { + ZcashMovablePool.sapling: _zatoshis(250000), + ZcashMovablePool.transparent: _zatoshis(0), + }; + + @override + Future prepareMoveToIronwood(ZcashMovablePool pool) async { + prepared.add(pool); + answer = Completer(); + await answer.future; + if (refusal != null) throw refusal!; + return txData; + } +}