Merge pull request #1501 from cypherstack/various-patches
What changed, and why it matters
This is a large routine merge of bug fixes and test additions for the Stack Wallet cryptocurrency app. The visible code changes fix UI glitches, make Firo's privacy cache reset more reliable, clean up exchange-rate refresh logic, and add a new suite of wallet-creation integration tests. None of the changes appear to introduce a security vulnerability; several look like defensive hardening against race conditions and stale data.
No immediate security action required. Treat as a normal maintenance merge. Reviewers may want to verify the Firo cache reset logic and exchange refresh controller with the new unit/integration tests before release.
Security signals we found
Firo Spark cache reset now uses epoch/generation tracking and on-disk markers to prevent stale cache reads/writes during resets
Exchange estimate refresh switched from UUID set to a single refresh controller, reducing race-condition surface
Send/token amount fields now use null instead of zero for invalid/empty input, preventing accidental zero-amount transactions
Debug print of recovery-phrase challenge word removed from verify_recovery_phrase_view.dart
Legacy price cache migrated under a single currency key to avoid cross-currency cache confusion
Evidence from the diff
The commit is a broad maintenance merge (89 files, +8,140/-824). Notable non-test changes include: (1) Firo Spark cache reset coordination with epoch/generation tracking, marker files, and worker isolate cancellation to prevent stale reads/writes during cache resets; (2) exchange form refresh controller replacing UUID-based request tracking to avoid stale estimate results and race conditions; (3) send/token views now null out invalid amounts instead of defaulting to zero, and Solana token amount display updates are guarded against re-entrancy; (4) price/legacy price-cache migration and currency-change refresh fixes; (5) removal of a debug print that leaked the recovery-phrase challenge word; (6) addition of widget keys for integration testing. The bulk of the diff is new integration/unit tests and formatting/refactoring.
Changed components
lib/db/sqlite/firo_cache.dartlib/db/sqlite/firo_cache_coordinator.dartlib/db/sqlite/firo_cache_reader.dartlib/db/sqlite/firo_cache_worker.dartlib/pages/exchange_view/exchange_form.dartlib/pages/send_view/send_view.dartlib/pages/send_view/sol_token_send_view.dartlib/pages/send_view/token_send_view.dartlib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dartlib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_sol_token_send.dartlib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dartlib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dartlib/db/hive/db.dartlib/pages/settings_views/global_settings_view/currency_view.dartintegration_test/wallet_creation/*test/*Inspect captured patch +8140 / −824
### .github/workflows/test.yaml
@@ -93,6 +93,10 @@ jobs:
# - name: Analyze
# run: flutter analyze
+ - name: Test build scripts
+ run: dart scripts/tests/build_input_test.dart
+ - name: Test wallet creation launcher
+ run: dart scripts/tests/wallet_creation_runner_test.dart
- name: Test
run: |
bash scripts/ensure_test_app_config.sh
### docs/wallet_creation_integration_tests.md
@@ -0,0 +1,28 @@
+# Wallet creation integration tests
+
+Real UI tests create and reopen 24 mainnet mnemonic wallets, checking recovery
+phrases, derived identities, and persistence. FROST and token subwallets are excluded.
+Configure/build the app and native dependencies first: [building.md](building.md).
+
+```sh
+dart scripts/test_wallet_creation.dart --list
+dart scripts/test_wallet_creation.dart --device macos --coin bitcoin
+dart scripts/test_wallet_creation.dart --device macos --all-coins
+dart scripts/test_wallet_creation.dart --device macos --report /tmp/creation-results.json
+dart scripts/test_wallet_creation.dart --device DEVICE_ID --platform android --disposable-mobile
+dart scripts/tests/wallet_creation_runner_test.dart
+```
+
+Without `--coin` or `--all-coins`, each coin gets a separate fresh create/reopen pair.
+Repeat `--coin` to select several; `--all-coins` shares one installation instead.
+Use `linux` or `windows` on those hosts, or `--platform ios` for a dedicated iPhone.
+Mobile requires clean, disposable app data and secure storage before each fresh case.
+Use `--help` for options. Host runner checks do not launch the app.
+
+Tests use real storage/native libraries and may contact configured nodes.
+Desktop fixtures are removed after exit; mobile installations must be reset.
+Raw app logs can contain recovery data; share only the sanitized JSON report.
+
+Verified on macOS: combined 24-coin create/reopen and independent Bitcoin/Epic Cash pairs.
+Other platforms and the full 24 independent fresh-install pairs remain unverified.
+iOS simulator builds are blocked by the device-only Monero framework.
### integration_test/wallet_creation/all_coins_test.dart
@@ -0,0 +1,3 @@
+import 'harness.dart';
+
+void main() => walletCreationTest(allCoins: true);
### integration_test/wallet_creation/coin_cases.dart
@@ -0,0 +1,24 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/app_config.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import 'coin_matrix.dart';
+
+export 'coin_matrix.dart' show defaultWordCounts;
+
+List<CryptoCurrency> creationCoins() {
+ final mainnet = AppConfig.coins.where(
+ (coin) => coin.network == CryptoCurrencyNetwork.main,
+ );
+ expect(
+ mainnet.map((coin) => coin.identifier).toSet(),
+ {...defaultWordCounts.keys, 'bitcoinFrost'},
+ reason:
+ 'Every configured main coin needs an explicit creation case. '
+ 'Bitcoin FROST requires a separate multisig suite.',
+ );
+ return [
+ for (final id in defaultWordCounts.keys)
+ mainnet.singleWhere((coin) => coin.identifier == id),
+ ];
+}
### integration_test/wallet_creation/coin_matrix.dart
@@ -0,0 +1,27 @@
+/// Shared by the app scenarios and the host runner, without Flutter imports.
+const defaultWordCounts = <String, int>{
+ 'bitcoin': 12,
+ 'banano': 24,
+ 'bitcoincash': 12,
+ 'cardano': 15,
+ 'dash': 12,
+ 'dogecoin': 12,
+ 'eCash': 12,
+ 'epicCash': 24,
+ 'ethereum': 12,
+ 'fact0rn': 12,
+ 'firo': 12,
+ 'litecoin': 12,
+ 'mimblewimblecoin': 12,
+ 'monero': 16,
+ 'namecoin': 12,
+ 'nano': 24,
+ 'particl': 12,
+ 'peercoin': 12,
+ 'salvium': 25,
+ 'solana': 12,
+ 'stellar': 24,
+ 'tezos': 24,
+ 'wownero': 16,
+ 'xelis': 25,
+};
### integration_test/wallet_creation/drivers/desktop_driver.dart
@@ -0,0 +1,120 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/pages/wallets_view/sub_widgets/empty_wallets.dart';
+import 'package:stackwallet/pages_desktop_specific/desktop_home_view.dart';
+import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_summary_table.dart';
+import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart';
+import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_receive.dart';
+import 'package:stackwallet/pages_desktop_specific/password/create_password_view.dart';
+import 'package:stackwallet/pages_desktop_specific/password/desktop_login_view.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/widgets/mwc_txs_method_toggle.dart';
+import 'package:stackwallet/widgets/toggle.dart';
+import 'package:stackwallet/widgets/wallet_card.dart';
+
+import 'platform_driver.dart';
+
+const testPassword = 'wallet-creation-integration-only-4862!';
+
+class DesktopDriver extends PlatformDriver {
+ DesktopDriver(super.ui);
+
+ @override
+ Finder get home => find.byType(DesktopHomeView);
+ @override
+ Finder get walletScreen => find.byType(DesktopWalletView);
+ @override
+ String get verificationButton => 'Verify';
+
+ @override
+ Future<void> createCredentials() async {
+ await ui.waitFor(find.byType(CreatePasswordView));
+ await ui.enter(
+ find.byKey(const Key('createBackupPasswordFieldKey1')),
+ testPassword,
+ );
+ await ui.enter(
+ find.byKey(const Key('createDesktopPasswordFieldKey2')),
+ testPassword,
+ );
+ await ui.tapText('Next');
+ await ui.waitFor(home);
+ }
+
+ @override
+ Future<void> unlock() async {
+ await ui.waitFor(find.byType(DesktopLoginView));
+ await ui.enter(
+ find.byKey(const Key('desktopLoginPasswordFieldKey')),
+ testPassword,
+ );
+ await ui.tapText('Continue');
+ await ui.waitFor(home);
+ }
+
+ @override
+ Future<void> addWallet() async {
+ await ui.waitFor(home);
+ final empty = find.byType(AddWalletButton);
+ if (empty.evaluate().isNotEmpty) {
+ await ui.tap(empty);
+ } else {
+ await ui.tapText('Add new wallet');
+ }
+ }
+
+ @override
+ Future<void> openWallet(Wallet wallet) async {
+ final row = find.byKey(
+ Key('DesktopWalletSummaryRow_key_${wallet.cryptoCurrency.identifier}'),
+ );
+ await ui.revealListRow(row, find.byType(WalletSummaryTable));
+ await ui.tap(row);
+ if (wallet.cryptoCurrency.hasTokenSupport) {
+ final card = find.byWidgetPredicate(
+ (widget) =>
+ widget is SimpleWalletCard &&
+ widget.walletId == wallet.walletId &&
+ widget.contractAddress == null,
+ );
+ await ui.tapText('Open wallet', within: card);
+ }
+ await ui.waitFor(walletScreen);
+ }
+
+ @override
+ Future<void> verifyReceiveAddress(Wallet wallet, String address) async {
+ await ui.tap(
+ find.descendant(
+ of: walletScreen,
+ matching: find.byKey(const ValueKey('customTab_Receive')),
+ ),
+ );
+ final receive = find.byType(DesktopReceive);
+ await ui.waitFor(receive);
+ final mwcMode = find.descendant(
+ of: receive,
+ matching: find.byType(MwcTxsMethodToggle),
+ );
+ if (mwcMode.evaluate().isNotEmpty) {
+ final toggle = ui.tester.widget<Toggle>(
+ find.descendant(of: mwcMode, matching: find.byType(Toggle)),
+ );
+ // MWC defaults to Slatepack, which does not display the MQS address.
+ if (!toggle.isOn) await ui.tap(mwcMode);
+ }
+ await selectPrimaryAddress(wallet, receive);
+ final displayed = find.descendant(
+ of: receive,
+ matching: find.text(address),
+ );
+ await ui.waitFor(displayed, description: 'receiving address in desktop UI');
+ await ui.reveal(displayed);
+ }
+
+ @override
+ Future<void> backToHome() async {
+ await ui.tap(find.byKey(const Key('desktopWalletBackButton')));
+ await ui.waitFor(home);
+ }
+}
### integration_test/wallet_creation/drivers/mobile_driver.dart
@@ -0,0 +1,147 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/pages/home_view/home_view.dart';
+import 'package:stackwallet/pages/pinpad_views/create_pin_view.dart';
+import 'package:stackwallet/pages/pinpad_views/lock_screen_view.dart';
+import 'package:stackwallet/pages/receive_view/receive_view.dart';
+import 'package:stackwallet/pages/wallet_view/wallet_view.dart';
+import 'package:stackwallet/pages/wallets_view/sub_widgets/all_wallets.dart';
+import 'package:stackwallet/pages/wallets_view/sub_widgets/empty_wallets.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/widgets/custom_buttons/app_bar_icon_button.dart';
+import 'package:stackwallet/widgets/custom_pin_put/pin_keyboard.dart';
+import 'package:stackwallet/widgets/master_wallet_card.dart';
+
+import 'platform_driver.dart';
+
+class MobileDriver extends PlatformDriver {
+ MobileDriver(super.ui);
+
+ @override
+ Finder get home => find.byType(HomeView);
+ @override
+ Finder get walletScreen => find.byType(WalletView);
+ @override
+ String get verificationButton => 'Continue';
+
+ Future<void> _enterPin() async {
+ // Use the actual custom keypad. It may be randomized and there can be
+ // offscreen keypads in the PIN PageView, so select only hit-testable keys.
+ for (final digit in '486251'.split('')) {
+ await ui.tap(
+ find
+ .byWidgetPredicate(
+ (widget) => widget is NumberKey && widget.number == digit,
+ )
+ .hitTestable(),
+ );
+ }
+ await ui.tap(find.byType(SubmitKey).hitTestable());
+ }
+
+ @override
+ Future<void> createCredentials() async {
+ await ui.waitFor(find.byType(CreatePinView));
+ await ui.waitFor(find.text('Create a PIN').hitTestable());
+ await _enterPin();
+ await ui.waitFor(find.text('Confirm PIN').hitTestable());
+ await ui.until(() {
+ final pages = ui.tester.widget<PageView>(
+ find.descendant(
+ of: find.byType(CreatePinView),
+ matching: find.byType(PageView),
+ ),
+ );
+ final controller = pages.controller!;
+ return controller.hasClients &&
+ (controller.page! - 1).abs() < 0.001 &&
+ !controller.position.isScrollingNotifier.value;
+ }, 'confirmation PIN page to settle');
+ await _enterPin();
+ // IS_INTEGRATION_TEST uses the app's existing biometric opt-out; PIN
+ // creation and the platform secure-storage plugin are still real.
+ await ui.waitFor(home);
+ }
+
+ @override
+ Future<void> unlock() async {
+ await ui.waitFor(find.byType(LockscreenView));
+ await _enterPin();
+ await ui.waitFor(home);
+ }
+
+ @override
+ Future<void> addWallet() async {
+ await ui.waitFor(home);
+ final empty = find.byType(AddWalletButton);
+ if (empty.evaluate().isNotEmpty) {
+ await ui.tap(empty);
+ } else {
+ await ui.tapText('Add new');
+ }
+ }
+
+ @override
+ Future<void> openWallet(Wallet wallet) async {
+ final row = find.byKey(
+ Key('walletListItemButtonKey_${wallet.cryptoCurrency.identifier}'),
+ );
+ await ui.revealListRow(row, find.byType(AllWallets));
+ await ui.tap(row);
+ // A single ETH wallet opens an overview even without tokens. A base SOL
+ // wallet with no tokens opens directly (WalletListItem's production flow).
+ if (wallet.cryptoCurrency is Ethereum) {
+ // The mobile overview starts with its master card collapsed.
+ final master = find.byWidgetPredicate(
+ (widget) =>
+ widget is MasterWalletCard && widget.walletId == wallet.walletId,
+ );
+ await ui.tap(
+ find
+ .descendant(of: master, matching: find.byType(MaterialButton))
+ .hitTestable(),
+ );
+ await ui.tap(
+ find.byKey(Key('walletsSheetItemButtonKey_${wallet.walletId}')),
+ );
+ }
+ await ui.waitFor(walletScreen);
+ }
+
+ @override
+ Future<void> verifyReceiveAddress(Wallet wallet, String address) async {
+ await ui.tapText('Receive', within: walletScreen);
+ final receive = find.byType(ReceiveView);
+ await ui.waitFor(receive);
+ await selectPrimaryAddress(wallet, receive);
+ final displayed = find.descendant(
+ of: receive,
+ matching: find.text(address),
+ );
+ await ui.waitFor(displayed, description: 'receiving address in mobile UI');
+ await ui.reveal(displayed);
+ await ui.tap(
+ find.descendant(of: receive, matching: find.byType(AppBarBackButton)),
+ );
+ await ui.waitFor(walletScreen);
+ }
+
+ @override
+ Future<void> backToHome() async {
+ await ui.tap(
+ find.descendant(
+ of: walletScreen,
+ matching: find.byType(AppBarBackButton),
+ ),
+ );
+ await ui.until(
+ () => walletScreen.evaluate().isEmpty,
+ 'wallet screen to close',
+ );
+ if (home.evaluate().isEmpty) {
+ await ui.tap(find.byType(AppBarBackButton).hitTestable());
+ }
+ await ui.waitFor(home);
+ }
+}
### integration_test/wallet_creation/drivers/platform_driver.dart
@@ -0,0 +1,42 @@
+import 'package:dropdown_button2/dropdown_button2.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+import '../ui.dart';
+
+abstract class PlatformDriver {
+ PlatformDriver(this.ui);
+
+ final TestUI ui;
+ Finder get home;
+ Finder get walletScreen;
+ String get verificationButton;
+ Future<void> createCredentials();
+ Future<void> unlock();
+ Future<void> addWallet();
+ Future<void> openWallet(Wallet wallet);
+ Future<void> verifyReceiveAddress(Wallet wallet, String address);
+ Future<void> backToHome();
+
+ Future<void> selectPrimaryAddress(Wallet wallet, Finder receive) async {
+ final selector = find.descendant(
+ of: receive,
+ matching: find.byType(DropdownButton2<int>),
+ );
+ if (selector.evaluate().isEmpty) return;
+ // Firo initially shows Spark. Select the address type checked by the wallet
+ // API; the same rule covers Litecoin if MWEB is enabled by default later.
+ final label = wallet.cryptoCurrency is Firo
+ ? 'Transparent address'
+ : '${wallet.info.mainAddressType.readableName} address';
+ final dropdown = ui.tester.widget<DropdownButton2<int>>(selector);
+ final item = dropdown.items!.singleWhere(
+ (item) => item.child is Text && (item.child as Text).data == label,
+ );
+ if (dropdown.value == item.value) return;
+ await ui.tap(selector);
+ await ui.tap(find.text(label).hitTestable());
+ }
+}
### integration_test/wallet_creation/fresh_install_test.dart
@@ -0,0 +1,3 @@
+import 'harness.dart';
+
+void main() => walletCreationTest(allCoins: false);
### integration_test/wallet_creation/harness.dart
@@ -0,0 +1,369 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:crypto/crypto.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/main.dart' as app;
+import 'package:stackwallet/pages/add_wallet_views/add_token_view/edit_wallet_tokens_view.dart';
+import 'package:stackwallet/pages/add_wallet_views/add_wallet_view/add_wallet_view.dart';
+import 'package:stackwallet/pages/add_wallet_views/name_your_wallet_view/name_your_wallet_view.dart';
+import 'package:stackwallet/pages/add_wallet_views/new_wallet_options/new_wallet_options_view.dart';
+import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_view/new_wallet_recovery_phrase_view.dart';
+import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_view/sub_widgets/mnemonic_table_item.dart';
+import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart';
+import 'package:stackwallet/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart';
+import 'package:stackwallet/pages/intro_view.dart';
+import 'package:stackwallet/pages/stack_privacy_calls.dart';
+import 'package:stackwallet/providers/global/secure_store_provider.dart';
+import 'package:stackwallet/services/notifications_api.dart';
+import 'package:stackwallet/services/wallets.dart';
+import 'package:stackwallet/utilities/biometrics.dart';
+import 'package:stackwallet/utilities/util.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/token_wallet_info.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_solana_token_info.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/mnemonic_interface.dart';
+
+import 'coin_cases.dart';
+import 'drivers/desktop_driver.dart';
+import 'drivers/mobile_driver.dart';
+import 'drivers/platform_driver.dart';
+import 'seed_validators.dart';
+import 'storage.dart';
+import 'ui.dart';
+
+String phraseFingerprint(String phrase) =>
+ sha256.convert(utf8.encode(phrase)).toString();
+
+void walletCreationTest({required bool allCoins}) {
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+ const selected = String.fromEnvironment(
+ 'WALLET_TEST_COIN',
+ defaultValue: 'bitcoin',
+ );
+ const phase = String.fromEnvironment(
+ 'WALLET_TEST_PHASE',
+ defaultValue: 'create',
+ );
+ testWidgets(
+ 'wallet creation ${allCoins ? 'all main coins' : selected}: $phase',
+ (tester) async {
+ expect(['create', 'reopen'], contains(phase));
+ expect(
+ const String.fromEnvironment('WALLET_TEST_PLATFORM'),
+ Platform.operatingSystem,
+ reason: 'The requested target must match the native OS',
+ );
+ expect(
+ Biometrics.integrationTestFlag,
+ isTrue,
+ reason:
+ 'Pass --dart-define=IS_INTEGRATION_TEST=true for biometric opt-out',
+ );
+ final coins = creationCoins();
+ if (!allCoins) {
+ expect(
+ defaultWordCounts.containsKey(selected),
+ isTrue,
+ reason: 'Unknown coin; FROST is a separate multisig scenario',
+ );
+ coins.retainWhere((coin) => coin.identifier == selected);
+ }
+ final ui = TestUI(tester);
+ final storage = await TestStorage.prepare(reopen: phase == 'reopen');
+ ui.errorLog = File('${storage.root.path}/failure.txt');
+ final driver = storage.mobile ? MobileDriver(ui) : DesktopDriver(ui);
+ final test = CreationScenario(ui, storage, driver);
+ var succeeded = false;
+ // Keep the real notification plugin but avoid OS permission dialogs,
+ // which Flutter's widget driver cannot dismiss on a fresh mobile install.
+ await NotificationApi.init(requestPermissions: false);
+
+ // Set a usable desktop surface only. Mobile uses the real device viewport
+ // and OS; no layoutPlatform, screenWidth, or isIpad overrides.
+ if (!storage.mobile) {
+ await tester.binding.setSurfaceSize(const Size(1920, 1080));
+ }
+ runZonedGuarded(
+ () => app.main(const []),
+ (error, stack) => ui.errors.add(error),
+ );
+ try {
+ if (phase == 'create') {
+ await test.onboard();
+ for (final coin in coins) {
+ await test.create(coin);
+ }
+ await storage.manifest.writeAsString(
+ jsonEncode(test.snapshots),
+ flush: true,
+ );
+ } else {
+ await driver.unlock();
+ test.checkPlatform();
+ final saved =
+ jsonDecode(await storage.manifest.readAsString()) as List;
+ expect(
+ saved.map((entry) => entry['coin']).toSet(),
+ coins.map((coin) => coin.identifier).toSet(),
+ );
+ test.snapshots.addAll(saved.cast<Map<String, dynamic>>());
+ await test.verifySavedWallets(open: true);
+ }
+ await ui.pump();
+ succeeded = true;
+ } finally {
+ // The runner removes desktop files after Flutter terminates,
+ // when database locks and background services can no longer hold them.
+ for (final wallet in Wallets.sharedInstance.wallets) {
+ wallet.shouldAutoSync = false;
+ await wallet.exit();
+ }
+ if (storage.mobile && succeeded && phase == 'reopen') {
+ await tester.pumpWidget(const SizedBox.shrink());
+ await storage.clearMobileTestKeys();
+ }
+ }
+ },
+ timeout: Timeout(Duration(minutes: allCoins ? 60 : 20)),
+ );
+}
+
+class CreationScenario {
+ CreationScenario(this.ui, this.storage, this.driver);
+ final TestUI ui;
+ final TestStorage storage;
+ final PlatformDriver driver;
+ final snapshots = <Map<String, dynamic>>[];
+
+ MainDB get db => MainDB.instance;
+
+ void checkPlatform() {
+ const expected = String.fromEnvironment('WALLET_TEST_PLATFORM');
+ expect(
+ expected,
+ Platform.operatingSystem,
+ reason: 'Test target must match the actual native OS',
+ );
+ expect(
+ Util.isDesktop,
+ !storage.mobile,
+ reason: 'Use an iPhone for mobile iOS and a desktop for Linux desktop',
+ );
+ }
+
+ Future<void> onboard() async {
+ ui.stage = 'fresh install onboarding';
+ await ui.waitFor(find.byType(IntroView));
+ checkPlatform();
+ expect(await db.isar.walletInfo.count(), 0);
+ await ui.tap(find.byType(GetStartedButton));
+ await ui.waitFor(find.byType(StackPrivacyCalls));
+ await ui.tapText('Incognito');
+ await ui.tapText('Continue');
+ await driver.createCredentials();
+ final container = ProviderScope.containerOf(ui.tester.element(driver.home));
+ final keys = await container.read(secureStoreProvider).keys;
+ expect(keys.where((key) => key.endsWith('_mnemonic')), isEmpty);
+ expect(await db.isar.walletInfo.count(), 0);
+ }
+
+ Future<void> create(CryptoCurrency coin) async {
+ ui.stage = '${coin.identifier}: select and name';
+ await driver.addWallet();
+ await ui.waitFor(find.byType(AddWalletView));
+ await ui.enter(
+ find.descendant(
+ of: find.byType(AddWalletView),
+ matching: find.byType(TextField),
+ ),
+ coin.identifier,
+ );
+ await ui.tap(
+ find.byKey(
+ Key('coinSelectItemButtonKey_${coin.prettyName}${coin.ticker}'),
+ ),
+ );
+ await ui.tapText('Next');
+ await ui.tapText('Create new wallet');
+ await ui.waitFor(find.byType(NameYourWalletView));
+ final name = 'Test ${coin.ticker}';
+ await ui.enter(
+ find.descendant(
+ of: find.byType(NameYourWalletView),
+ matching: find.byType(TextField),
+ ),
+ name,
+ );
+ await ui.tapText('Next');
+ ui.stage = '${coin.identifier}: default options';
+ await ui.until(
+ () =>
+ find.byType(NewWalletOptionsView).evaluate().isNotEmpty ||
+ find.byType(NewWalletRecoveryPhraseWarningView).evaluate().isNotEmpty,
+ 'wallet options or recovery warning',
+ );
+ if (find.byType(NewWalletOptionsView).evaluate().isNotEmpty) {
+ await ui.tapText('Continue', within: find.byType(NewWalletOptionsView));
+ }
+ await ui.waitFor(find.byType(NewWalletRecoveryPhraseWarningView));
+ await ui.tap(find.byType(Checkbox));
+ ui.stage = '${coin.identifier}: generate';
+ await ui.tapText('View recovery phrase');
+ await ui.waitFor(
+ find.byType(NewWalletRecoveryPhraseView),
+ description: 'generated recovery phrase',
+ timeout: const Duration(minutes: 10),
+ );
+ final screen = ui.tester.widget<NewWalletRecoveryPhraseView>(
+ find.byType(NewWalletRecoveryPhraseView),
+ );
+ final wallet = screen.wallet;
+ final words = <String>[];
+ final items =
+ ui.tester
+ .widgetList<MnemonicTableItem>(find.byType(MnemonicTableItem))
+ .toList()
+ ..sort((a, b) => a.number.compareTo(b.number));
+ for (var index = 0; index < items.length; index++) {
+ final item = items[index];
+ expect(item.number, index + 1);
+ final finder = find.byWidget(item);
+ await ui.reveal(finder);
+ final text = find.descendant(of: finder, matching: find.byType(Text));
+ final rendered = ui.tester
+ .widgetList<Text>(text)
+ .map((w) => w.data)
+ .toList();
+ expect(rendered.length, 2);
+ words.add(rendered.last!);
+ }
+ validatePhrase(coin, words);
+ final phrase = words.join(' ');
+ final mnemonicWallet = wallet as MnemonicInterface;
+ expect(
+ await mnemonicWallet.getMnemonic() == phrase,
+ isTrue,
+ reason: '${coin.identifier}: displayed seed differs from secure storage',
+ );
+ expect(
+ await wallet.secureStorageInterface.read(
+ key: Wallet.mnemonicKey(walletId: wallet.walletId),
+ ) ==
+ phrase,
+ isTrue,
+ );
+ expect(await wallet.info.isMnemonicVerified(db.isar), isFalse);
+
+ ui.stage = '${coin.identifier}: confirm recovery phrase';
+ await ui.tapText('I saved my recovery phrase');
+ await ui.waitFor(find.byType(VerifyRecoveryPhraseView));
+ final challenge = ui.tester.widget<Text>(
+ find.byKey(const Key('recoveryPhraseWordIndex')),
+ );
+ final index = int.parse(challenge.data!) - 1;
+ expect(index >= 0 && index < words.length, isTrue);
+ await ui.tap(find.byKey(Key('coinSelectItemButtonKey_${words[index]}')));
+ await ui.tapText(driver.verificationButton);
+ if (coin is Ethereum || coin is Solana) {
+ await ui.waitFor(find.byType(EditWalletTokensView));
+ await ui.tapText('Next', within: find.byType(EditWalletTokensView));
+ }
+ await ui.waitFor(driver.home);
+ expect(await wallet.info.isMnemonicVerified(db.isar), isTrue);
+ expect(wallet.info.name, name);
+ expect(wallet.info.coin, coin);
+ expect(wallet.info.isViewOnly, isFalse);
+ expect(await db.isar.walletInfo.count(), snapshots.length + 1);
+
+ ui.stage = '${coin.identifier}: open created wallet';
+ // CryptoNote wallets populate their first receiving address in open(),
+ // reached by normal wallet-list navigation, after seed confirmation.
+ await driver.openWallet(wallet);
+ final address = await wallet.getCurrentReceivingAddress();
+ expect(address, isNotNull);
+ expect(
+ address!.value.isNotEmpty && coin.validateAddress(address.value),
+ isTrue,
+ );
+ expect(address.value, wallet.info.cachedReceivingAddress);
+ await verifyOpenNativeWallet(wallet, address.value);
+ await driver.verifyReceiveAddress(wallet, address.value);
+ await driver.backToHome();
+ // Opening a wallet may enable background refresh. Do not wait for a scan.
+ wallet.shouldAutoSync = false;
+
+ ui.stage = '${coin.identifier}: recovery identity';
+ await verifyRecoveryIdentity(wallet, phrase, storage.root.path);
+ expect(await db.isar.walletInfo.count(), snapshots.length + 1);
+ final fingerprint = phraseFingerprint(phrase);
+ expect(
+ snapshots.any((saved) => saved['seed'] == fingerprint),
+ isFalse,
+ reason: '${coin.identifier}: a previous wallet seed was reused',
+ );
+ snapshots.add({
+ 'id': wallet.walletId,
+ 'coin': coin.identifier,
+ 'name': name,
+ 'seed': fingerprint,
+ 'address': address.value,
+ });
+ await verifySavedWallets();
+ ui.report(
+ 'OK ${Platform.operatingSystem} '
+ '${coin.identifier} create',
+ );
+ }
+
+ Future<void> verifySavedWallets({bool open = false}) async {
+ expect(await db.isar.walletInfo.count(), snapshots.length);
+ expect(await db.isar.tokenWalletInfo.count(), 0);
+ expect(await db.isar.walletSolanaTokenInfo.count(), 0);
+ for (final saved in snapshots) {
+ ui.stage = '${saved['coin']}: check persisted wallet';
+ await ui.until(
+ () => Wallets.sharedInstance.wallets.any(
+ (w) => w.walletId == saved['id'],
+ ),
+ 'loaded wallet',
+ );
+ final wallet = Wallets.sharedInstance.getWallet(saved['id'] as String);
+ expect(wallet.info.name, saved['name']);
+ expect(wallet.cryptoCurrency.identifier, saved['coin']);
+ expect(wallet.cryptoCurrency.network, CryptoCurrencyNetwork.main);
+ expect(await wallet.info.isMnemonicVerified(db.isar), isTrue);
+ final phrase = await (wallet as MnemonicInterface).getMnemonic();
+ expect(
+ phraseFingerprint(phrase) == saved['seed'],
+ isTrue,
+ reason: '${saved['coin']}: recovery phrase changed',
+ );
+ expect(wallet.info.tokenContractAddresses, isEmpty);
+ expect(wallet.info.solanaTokenMintAddresses, isEmpty);
+ expect(wallet.info.solanaCustomTokenMintAddresses, isEmpty);
+ if (open) await driver.openWallet(wallet);
+ final address = await wallet.getCurrentReceivingAddress();
+ expect(address?.value, saved['address']);
+ expect(wallet.info.cachedReceivingAddress, saved['address']);
+ if (open) {
+ await verifyOpenNativeWallet(wallet, address!.value);
+ await driver.verifyReceiveAddress(wallet, address.value);
+ await verifyRecoveryIdentity(wallet, phrase, storage.root.path);
+ await driver.backToHome();
+ wallet.shouldAutoSync = false;
+ ui.report(
+ 'OK ${Platform.operatingSystem} '
+ '${saved['coin']} reopen',
+ );
+ }
+ }
+ }
+}
### integration_test/wallet_creation/seed_validators.dart
@@ -0,0 +1,180 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:bip39/bip39.dart' as bip39;
+import 'package:flutter_test/flutter_test.dart';
+import 'package:path/path.dart' as p;
+import 'package:stackwallet/services/wallets.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/wallet/impl/epiccash_wallet.dart';
+import 'package:stackwallet/wallets/wallet/impl/mimblewimblecoin_wallet.dart';
+import 'package:stackwallet/wallets/wallet/intermediate/cryptonote_wallet.dart';
+import 'package:stackwallet/wallets/wallet/intermediate/lib_xelis_wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/wl_gen/interfaces/cs_monero_interface.dart';
+import 'package:stackwallet/wl_gen/interfaces/cs_salvium_interface.dart';
+import 'package:stackwallet/wl_gen/interfaces/cs_wownero_interface.dart';
+
+import 'coin_cases.dart';
+
+/// The original native wallet must answer too: a cached database address and
+/// a working recovery probe alone would miss a failed native-file reopen.
+Future<void> verifyOpenNativeWallet(Wallet wallet, String expected) async {
+ final String actual;
+ if (wallet is CryptonoteWallet) {
+ actual = await wallet.internalGetAddress(accountIndex: 0, addressIndex: 0);
+ } else if (wallet is EpiccashWallet) {
+ actual = await wallet.getNativeReceivingAddress();
+ } else if (wallet is MimblewimblecoinWallet) {
+ actual = (await wallet.thisWalletAddress(
+ 0,
+ await wallet.getMwcMqsConfig(),
+ )).value;
+ } else if (wallet is LibXelisWallet) {
+ wallet.checkInitialized();
+ actual = wallet.xelis.getAddress(wallet.wallet!);
+ } else {
+ return;
+ }
+ expect(
+ actual == expected,
+ isTrue,
+ reason:
+ '${wallet.cryptoCurrency.identifier}: native wallet identity differs',
+ );
+}
+
+void validatePhrase(CryptoCurrency coin, List<String> words) {
+ expect(
+ words.length,
+ defaultWordCounts[coin.identifier],
+ reason: '${coin.identifier}: wrong default recovery phrase length',
+ );
+ expect(
+ words.every((word) => word.isNotEmpty && word == word.trim()),
+ isTrue,
+ reason: '${coin.identifier}: empty or malformed recovery word',
+ );
+ expect(coin.defaultSeedPhraseLength, defaultWordCounts[coin.identifier]);
+ if (coin is! Monero &&
+ coin is! Wownero &&
+ coin is! Salvium &&
+ coin is! Xelis) {
+ expect(
+ bip39.validateMnemonic(words.join(' ')),
+ isTrue,
+ reason: '${coin.identifier}: invalid BIP39 wordlist or checksum',
+ );
+ }
+ // Native seed formats are decoded by the recovery roundtrip below. Merely
+ // checking their lengths or accepting the restore screen is insufficient.
+}
+
+/// Recover identity from the displayed words without copying cached addresses
+/// or native files. This does not scan the blockchain or fund an account.
+Future<void> verifyRecoveryIdentity(
+ Wallet original,
+ String phrase,
+ String root,
+) async {
+ final coin = original.cryptoCurrency;
+ final expected = (await original.getCurrentReceivingAddress())!.value;
+ if (coin is Monero || coin is Wownero || coin is Salvium) {
+ final directory = await Directory(p.join(root, 'recovery'))
+ .createTemp('${coin.identifier}_');
+ final file = p.join(directory.path, 'wallet');
+ const password = 'disposable-recovery-probe';
+ WrappedWallet? probe;
+ try {
+ final String address;
+ if (coin is Monero) {
+ probe = await csMonero.getRestoredWallet(
+ walletId: 'creation-probe',
+ path: file,
+ password: password,
+ mnemonic: phrase,
+ seedOffset: '',
+ );
+ address = await csMonero.getAddress(probe);
+ } else if (coin is Wownero) {
+ probe = await csWownero.getRestoredWallet(
+ walletId: 'creation-probe',
+ path: file,
+ password: password,
+ mnemonic: phrase,
+ seedOffset: '',
+ );
+ address = csWownero.getAddress(probe);
+ } else {
+ probe = await csSalvium.getRestoredWallet(
+ walletId: 'creation-probe',
+ path: file,
+ password: password,
+ mnemonic: phrase,
+ seedOffset: '',
+ );
+ address = csSalvium.getAddress(probe);
+ }
+ expect(
+ address == expected,
+ isTrue,
+ reason: '${coin.identifier}: displayed seed recovers another address',
+ );
+ } finally {
+ if (probe != null) {
+ if (coin is Monero) {
+ await csMonero.close(probe);
+ } else if (coin is Wownero) {
+ await csWownero.close(probe);
+ } else {
+ await csSalvium.close(probe);
+ }
+ }
+ await directory.delete(recursive: true);
+ }
+ return;
+ }
+
+ // A new ID ensures init() cannot reuse the original wallet's database rows,
+ // secure-storage keys, or native files. Use the real factory and libraries.
+ final info = WalletInfo.createNew(
+ coin: coin,
+ name: 'Recovery probe ${coin.identifier}',
+ otherDataJsonString: coin is Tezos
+ ? jsonEncode({
+ WalletInfoKeys.tezosDerivationPath:
+ Tezos.standardDerivationPath.value,
+ })
+ : null,
+ );
+ Wallet? probe;
+ try {
+ probe = await Wallet.create(
+ walletInfo: info,
+ mainDB: original.mainDB,
+ secureStorageInterface: original.secureStorageInterface,
+ nodeService: original.nodeService,
+ prefs: original.prefs,
+ mnemonic: phrase,
+ mnemonicPassphrase: '',
+ );
+ // Register solely so the production deletion service also cleans up Epic's
+ // native wallet. The probe is never marked as a verified user wallet.
+ Wallets.sharedInstance.addWallet(probe);
+ await probe.init();
+ final address = await probe.getCurrentReceivingAddress();
+ expect(
+ address != null && address.value == expected,
+ isTrue,
+ reason: '${coin.identifier}: displayed seed recovers another address',
+ );
+ } finally {
+ if (probe != null) {
+ await Wallets.sharedInstance.deleteWallet(
+ info,
+ original.secureStorageInterface,
+ );
+ }
+ }
+}
### integration_test/wallet_creation/storage.dart
@@ -0,0 +1,127 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:flutter_secure_storage/flutter_secure_storage.dart';
+import 'package:path/path.dart' as p;
+import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
+import 'package:stackwallet/utilities/stack_file_system.dart';
+
+const mobileStore = FlutterSecureStorage(
+ aOptions: AndroidOptions(resetOnError: false, migrateWithBackup: true),
+);
+
+class TestStorage {
+ TestStorage(this.root, this.mobile);
+
+ final Directory root;
+ final bool mobile;
+ File get manifest => File(p.join(root.path, 'wallets.json'));
+ File get marker => File(p.join(root.path, '.wallet-creation-test'));
+
+ Future<void> clearMobileTestKeys() async {
+ if (!mobile) return;
+ // prepare() required an empty store and an explicitly disposable mobile
+ // install before onboarding. Only a successful create/reopen pair reaches
+ // this cleanup. Failed mobile runs require an explicit reset by the caller.
+ expect(await marker.readAsString(), 'wallet-creation-test-v1');
+ expect(await manifest.exists(), isTrue);
+ for (final key in (await mobileStore.readAll()).keys) {
+ await mobileStore.delete(key: key);
+ }
+ expect((await mobileStore.readAll()).isEmpty, isTrue);
+ }
+
+ static Future<TestStorage> prepare({required bool reopen}) async {
+ final mobile = Platform.isAndroid || Platform.isIOS;
+ final String path;
+ if (mobile) {
+ expect(
+ const bool.fromEnvironment('WALLET_TEST_DISPOSABLE_DEVICE'),
+ isTrue,
+ reason: 'Mobile runs require a dedicated disposable device/app install',
+ );
+ const runId = String.fromEnvironment('WALLET_TEST_RUN_ID');
+ expect(
+ RegExp(r'^[a-zA-Z0-9_-]+$').hasMatch(runId),
+ isTrue,
+ reason: 'A safe, nonempty WALLET_TEST_RUN_ID is required on mobile',
+ );
+ final support = await PathProviderPlatform.instance
+ .getApplicationSupportPath();
+ expect(support, isNotNull);
+ path = p.join(support!, 'wallet_creation_tests', runId);
+ // Fail before writing any app state if this install already has keys.
+ // In particular, an iOS reinstall may retain Keychain items.
+ if (!reopen) {
+ expect(
+ (await mobileStore.readAll()).isEmpty,
+ isTrue,
+ reason:
+ 'Mobile secure storage is not empty; use a clean test install',
+ );
+ }
+ } else {
+ path = const String.fromEnvironment('WALLET_TEST_ROOT');
+ expect(
+ path.isNotEmpty && p.isAbsolute(path),
+ isTrue,
+ reason: 'Pass an absolute disposable WALLET_TEST_ROOT (use the runner)',
+ );
+ }
+
+ final root = Directory(path);
+ final storage = TestStorage(root, mobile);
+ if (reopen) {
+ expect(
+ await storage.marker.exists(),
+ isTrue,
+ reason: 'Refusing to reopen storage not owned by this test',
+ );
+ expect(await storage.marker.readAsString(), 'wallet-creation-test-v1');
+ expect(
+ await storage.manifest.exists(),
+ isTrue,
+ reason: 'No successful creation manifest exists',
+ );
+ } else {
+ expect(
+ !await root.exists() || await root.list().isEmpty,
+ isTrue,
+ reason: 'Fresh install requires an empty test directory',
+ );
+ await root.create(recursive: true);
+ await storage.marker.writeAsString(
+ 'wallet-creation-test-v1',
+ flush: true,
+ );
+ }
+
+ PathProviderPlatform.instance = _TestPaths(root.path);
+ if (!mobile) {
+ StackFileSystem.setDesktopOverrideDir(p.join(root.path, 'data'));
+ }
+ await Directory(p.join(root.path, 'recovery')).create(recursive: true);
+ return storage;
+ }
+}
+
+class _TestPaths extends PathProviderPlatform {
+ _TestPaths(this.root);
+ final String root;
+
+ Future<String> _directory(String name) async =>
+ (await Directory(p.join(root, name)).create(recursive: true)).path;
+
+ @override
+ Future<String?> getTemporaryPath() => _directory('temp');
+ @override
+ Future<String?> getApplicationSupportPath() => _directory('support');
+ @override
+ Future<String?> getLibraryPath() => _directory('library');
+ @override
+ Future<String?> getApplicationDocumentsPath() => _directory('documents');
+ @override
+ Future<String?> getApplicationCachePath() => _directory('cache');
+ @override
+ Future<String?> getDownloadsPath() => _directory('downloads');
+}
### integration_test/wallet_creation/ui.dart
@@ -0,0 +1,131 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+/// Bounded real-app pumping. Never print finders containing recovery words.
+class TestUI {
+ TestUI(this.tester);
+
+ final WidgetTester tester;
+ final errors = <Object>[];
+ File? errorLog;
+ String _stage = 'startup';
+ String get stage => _stage;
+ set stage(String value) {
+ _stage = value;
+ report('STAGE $value');
+ }
+
+ void report(String message) =>
+ debugPrintSynchronously('WALLET_CREATION_$message');
+
+ Future<void> pump() async {
+ await tester
+ .pump(const Duration(milliseconds: 100))
+ .timeout(
+ const Duration(seconds: 20),
+ onTimeout: () =>
+ fail('$stage: no frame received from the native app'),
+ );
+ final Object? exception = tester.takeException();
+ if (exception != null) errors.add(exception);
+ if (errors.isNotEmpty) {
+ // Only the disposable test root gets full diagnostics. The runner deletes
+ // this with the native logs; public output cannot expose recovery data.
+ await errorLog?.writeAsString(errors.first.toString(), flush: true);
+ fail(
+ '$stage: app raised ${errors.first.runtimeType} '
+ '(exception text omitted to protect recovery data)',
+ );
+ }
+ if (find.text('Create Wallet Error').evaluate().isNotEmpty) {
+ fail('$stage: app displayed a wallet creation error');
+ }
+ }
+
+ Future<void> until(
+ FutureOr<bool> Function() condition,
+ String description, {
+ Duration timeout = const Duration(minutes: 2),
+ }) async {
+ final deadline = DateTime.now().add(timeout);
+ while (true) {
+ await pump();
+ if (await condition()) return;
+ if (DateTime.now().isAfter(deadline)) {
+ fail('$stage: timed out waiting for $description');
+ }
+ }
+ }
+
+ Future<void> waitFor(
+ Finder finder, {
+ String description = 'screen',
+ Duration timeout = const Duration(minutes: 2),
+ }) =>
+ until(() => finder.evaluate().isNotEmpty, description, timeout: timeout);
+
+ Future<void> reveal(Finder finder) async {
+ await waitFor(finder, description: 'control');
+ expect(finder.evaluate().length, 1, reason: '$stage: ambiguous control');
+ if (finder.hitTestable().evaluate().isNotEmpty) return;
+ await tester.ensureVisible(finder);
+ await tester
+ .pump(const Duration(milliseconds: 350))
+ .timeout(
+ const Duration(seconds: 20),
+ onTimeout: () => fail('$stage: native app stopped producing frames'),
+ );
+ }
+
+ Future<void> tap(Finder finder) async {
+ await reveal(finder);
+ await until(
+ () => finder.hitTestable().evaluate().length == 1,
+ 'tappable control',
+ );
+ await tester.tap(finder.hitTestable());
+ await pump();
+ }
+
+ Future<void> tapText(String text, {Finder? within}) => tap(
+ within == null
+ ? find.text(text, findRichText: true)
+ : find.descendant(
+ of: within,
+ matching: find.text(text, findRichText: true),
+ ),
+ );
+
+ Future<void> enter(Finder finder, String value) async {
+ await reveal(finder);
+ await tester.enterText(finder, value);
+ await pump();
+ }
+
+ /// Scroll a lazy wallet list until its requested row is built.
+ Future<void> revealListRow(Finder finder, Finder list) async {
+ await waitFor(list);
+ if (finder.evaluate().isEmpty) {
+ final scrollable = find
+ .descendant(of: list, matching: find.byType(Scrollable))
+ .first;
+ await waitFor(scrollable.hitTestable(), description: 'wallet list');
+ // Coin sorting can put a new row above the previously opened wallet.
+ // Reset the viewport before searching the lazily built list downward.
+ final position = tester.state<ScrollableState>(scrollable).position;
+ position.jumpTo(position.minScrollExtent);
+ await pump();
+ await tester.scrollUntilVisible(
+ finder,
+ 250,
+ scrollable: scrollable,
+ maxScrolls: 50,
+ );
+ }
+ await reveal(finder);
+ }
+}
### lib/db/hive/db.dart
@@ -177,6 +177,26 @@ class DB {
hive.openBox<dynamic>(boxNamePriceCache),
_loadWalletBoxes(),
]);
+ // Claim old prices before the UI can change the saved currency preference.
+ await migrateLegacyPriceCache();
+ }
+
+ Future<void> migrateLegacyPriceCache() async {
+ final cache = hive.box<dynamic>(boxNamePriceCache);
+ if (cache.get('cache') is! Map) return;
+ await mutex.protect(() async {
+ final legacy = cache.get('cache');
+ if (legacy is! Map) return;
+ // Old snapshots have no currency metadata. Preserve them only under the
+ // saved preference (USD was the default), never every requested currency.
+ final currency =
+ get<dynamic>(boxName: boxNamePrefs, key: 'currency') as String? ??
+ 'USD';
+ final key = 'cache_${currency.toLowerCase()}';
+ if (!cache.containsKey(key)) await cache.put(key, legacy);
+ // Write first so an interrupted migration can safely be repeated.
+ await cache.delete('cache');
+ });
}
Future<void> _loadWalletBoxes() async {
### lib/db/sqlite/firo_cache.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:io';
import 'dart:isolate';
+import 'package:meta/meta.dart';
import 'package:mutex/mutex.dart';
import 'package:sqlite3/sqlite3.dart';
import 'package:uuid/uuid.dart';
@@ -37,6 +38,9 @@ abstract class _FiroCache {
? "spark_tags_v$_tagsCacheVersion.sqlite3"
: "spark_tags_v${_tagsCacheVersion}_${network.name}.sqlite3";
+ static String resetMarkerName(CryptoCurrencyNetwork network) =>
+ 'spark_reset_${network.name}.pending';
+
static final Map<CryptoCurrencyNetwork, Database> _setCacheDB = {};
static final Map<CryptoCurrencyNetwork, Database> _usedTagsCacheDB = {};
static Database setCacheDB(CryptoCurrencyNetwork network) {
@@ -73,6 +77,16 @@ abstract class _FiroCache {
"${sqliteDir.path}/${sparkUsedTagsCacheFileName(network)}",
);
+ // A reset acknowledged on disk must survive termination before its
+ // worker finishes. Recover it before any reader or writer opens the DBs.
+ final marker = File('${sqliteDir.path}/${resetMarkerName(network)}');
+ if (await marker.exists()) {
+ final sets = (await marker.readAsString()).trim() != 'tags-v1';
+ if (sets) await _recreateSetFile(sparkSetCacheFile.path);
+ await _recreateTagsFile(sparkUsedTagsCacheFile.path);
+ await marker.delete();
+ }
+
if (!(await sparkSetCacheFile.exists())) {
await _createSparkSetCacheDb(sparkSetCacheFile.path);
}
@@ -91,36 +105,23 @@ abstract class _FiroCache {
}
}
- static Future<void> _deleteAllCache(CryptoCurrencyNetwork network) async {
- final start = DateTime.now();
- setCacheDB(network).execute("""
- DELETE FROM SparkSet;
- DELETE FROM SparkCoin;
- DELETE FROM SparkSetCoins;
- VACUUM;
- """);
- await _deleteUsedTagsCache(network);
-
- Logging.instance.d(
- "_deleteAllCache() "
- "duration = ${DateTime.now().difference(start)}",
- );
+ // Called only after both the reader and worker have closed these files.
+ // Recreating avoids an unbounded foreground VACUUM of a large cache.
+ static Future<void> _removeDatabaseFiles(String path) async {
+ for (final suffix in ['', '-wal', '-shm', '-journal']) {
+ final file = File('$path$suffix');
+ if (await file.exists()) await file.delete();
+ }
}
- static Future<void> _deleteUsedTagsCache(
- CryptoCurrencyNetwork network,
- ) async {
- final start = DateTime.now();
-
- usedTagsCacheDB(network).execute("""
- DELETE FROM SparkUsedCoinTags;
- VACUUM;
- """);
+ static Future<void> _recreateSetFile(String path) async {
+ await _removeDatabaseFiles(path);
+ await _createSparkSetCacheDb(path);
+ }
- Logging.instance.d(
- "_deleteUsedTagsCache() "
- "duration = ${DateTime.now().difference(start)}",
- );
+ static Future<void> _recreateTagsFile(String path) async {
+ await _removeDatabaseFiles(path);
+ await _createSparkUsedTagsCacheDb(path);
}
static Future<void> _createSparkSetCacheDb(String file) async {
@@ -154,7 +155,7 @@ abstract class _FiroCache {
);
""");
- db.dispose();
+ db.close();
}
static Future<void> _createSparkUsedTagsCacheDb(String file) async {
@@ -168,6 +169,6 @@ abstract class _FiroCache {
);
""");
- db.dispose();
+ db.close();
}
}
### lib/db/sqlite/firo_cache_coordinator.dart
@@ -2,29 +2,98 @@ part of 'firo_cache.dart';
typedef LTagPair = ({String tag, String txid});
-/// Wrapper class for [_FiroCache] as [_FiroCache] should eventually be handled in a
-/// background isolate and [FiroCacheCoordinator] should manage that isolate
+/// The cache was reset while this refresh was running. Its caller must stop
+/// the old batch, rather than start the next sector against the new cache.
+class FiroCacheResetException implements Exception {
+ const FiroCacheResetException();
+ @override
+ String toString() => 'Firo cache update invalidated by reset';
+}
+
+class _CacheEpoch {
+ _CacheEpoch(this.number);
+ final int number;
+ bool _cancelled = false;
+ final _cancellation = StreamController<void>.broadcast(sync: true);
+
+ void check() {
+ if (_cancelled) throw const FiroCacheResetException();
+ }
+
+ void invalidate() {
+ _cancelled = true;
+ _cancellation.add(null);
+ unawaited(_cancellation.close());
+ }
+
+ Future<T> wait<T>(Future<T> pending) async {
+ final result = Completer<T>();
+ void cancel() {
+ if (!result.isCompleted) {
+ result.completeError(const FiroCacheResetException());
+ }
+ }
+
+ final subscription = _cancellation.stream.listen((_) => cancel());
+ unawaited(
+ pending.then(
+ (value) {
+ if (!result.isCompleted) result.complete(value);
+ },
+ onError: (Object error, StackTrace stack) {
+ if (!result.isCompleted) result.completeError(error, stack);
+ },
+ ),
+ );
+ if (_cancelled) cancel();
+ try {
+ return await result.future;
+ } finally {
+ await subscription.cancel();
+ }
+ }
+}
+
+/// Coordinates network fetches and serialized cache writes per Firo network.
abstract class FiroCacheCoordinator {
static final Map<CryptoCurrencyNetwork, _FiroCacheWorker> _workers = {};
static final Map<CryptoCurrencyNetwork, Mutex> _tagLocks = {};
static final Map<CryptoCurrencyNetwork, Mutex> _setLocks = {};
-
- static bool _init = false;
- static Future<void> init() async {
- if (_init) {
- return;
- }
- _init = true;
+ static final Map<CryptoCurrencyNetwork, Mutex> _resetLocks = {};
+ static final Map<CryptoCurrencyNetwork, _CacheEpoch> _setEpochs = {};
+ static final Map<CryptoCurrencyNetwork, _CacheEpoch> _tagEpochs = {};
+ static final Map<CryptoCurrencyNetwork, Future<void>> _resets = {};
+ static final Map<CryptoCurrencyNetwork, Object> _resetErrors = {};
+ static final Set<CryptoCurrencyNetwork> _pendingFullResets = {};
+ static bool _closing = false;
+
+ static Future<void>? _initFuture;
+ static Future<void> init() => _initFuture ??= _initialize();
+
+ static Future<void> _initialize() async {
await _FiroCache.init();
for (final network in _FiroCache.networks) {
_tagLocks[network] = Mutex();
_setLocks[network] = Mutex();
+ _resetLocks[network] = Mutex();
+ _setEpochs[network] = _CacheEpoch(0);
+ _tagEpochs[network] = _CacheEpoch(0);
_workers[network] = await _FiroCacheWorker.spawn(network);
}
}
/// Terminal shutdown for a desktop reset, followed by process exit.
static Future<void> close() async {
+ _closing = true;
+ for (final epochs in [_setEpochs, _tagEpochs]) {
+ for (final network in epochs.keys.toList()) {
+ _invalidate(epochs, network);
+ }
+ }
+ // Reset work is local only. Even if a reset failed, close every handle.
+ await Future.wait(
+ _resets.values.toList().map((reset) => reset.catchError((Object _) {})),
+ );
await Future.wait(_workers.values.map((worker) => worker.close()));
for (final db in [
..._FiroCache._setCacheDB.values,
@@ -34,17 +103,101 @@ abstract class FiroCacheCoordinator {
}
}
+ @visibleForTesting
+ static String usedTagsCacheFileName(CryptoCurrencyNetwork network) =>
+ _FiroCache.sparkUsedTagsCacheFileName(network);
+
static Future<void> clearSharedCache(
CryptoCurrencyNetwork network, {
bool clearOnlyUsedTagsCache = false,
}) async {
- if (clearOnlyUsedTagsCache) {
- return await _FiroCache._deleteUsedTagsCache(network);
+ if (_closing) throw StateError('Firo cache is closing');
+ if (!_workers.containsKey(network)) {
+ throw StateError('Firo cache is not initialized for $network');
}
- return await _FiroCache._deleteAllCache(network);
+ _invalidate(_tagEpochs, network);
+ if (!clearOnlyUsedTagsCache) _invalidate(_setEpochs, network);
+ final reset = _resetLocks[network]!.protect(() async {
+ try {
+ await _reset(network, clearSets: !clearOnlyUsedTagsCache);
+ } catch (error) {
+ _resetErrors[network] = error;
+ rethrow;
+ }
+ });
+ late final Future<void> finished;
+ finished = reset.whenComplete(() {
+ if (identical(_resets[network], finished)) _resets.remove(network);
+ });
+ _resets[network] = finished;
+ return finished;
+ }
+
+ static void _invalidate(
+ Map<CryptoCurrencyNetwork, _CacheEpoch> epochs,
+ CryptoCurrencyNetwork network,
+ ) {
+ final previous = epochs[network]!;
+ previous.invalidate();
+ epochs[network] = _CacheEpoch(previous.number + 1);
+ }
+
+ static Future<void> _ready(CryptoCurrencyNetwork network) async {
+ while (_resets[network] != null) {
+ await _resets[network];
+ }
+ if (_closing) throw StateError('Firo cache is closing');
+ if (_resetErrors[network] != null) {
+ // Retry the failed local reset before serving reads, so one filesystem
+ // error does not disable the cache for the rest of the session.
+ await clearSharedCache(network, clearOnlyUsedTagsCache: true);
+ }
+ }
+
+ static Future<void> _reset(
+ CryptoCurrencyNetwork network, {
+ required bool clearSets,
+ }) async {
+ // Record intent inside the reset lock before filesystem access can fail.
+ if (clearSets) _pendingFullResets.add(network);
+ final dir = await StackFileSystem.applicationFiroCacheSQLiteDirectory();
+ final marker = File('${dir.path}/${_FiroCache.resetMarkerName(network)}');
+ // Preserve an earlier interrupted full reset when retrying a tags reset.
+ final resetSets =
+ _pendingFullResets.contains(network) ||
+ (await marker.exists() &&
+ (await marker.readAsString()).trim() != 'tags-v1');
+ if (resetSets && !clearSets) _invalidate(_setEpochs, network);
+ await marker.writeAsString(resetSets ? 'all-v1' : 'tags-v1', flush: true);
+ if (resetSets) _FiroCache._setCacheDB.remove(network)?.close();
+ _FiroCache._usedTagsCacheDB.remove(network)?.close();
+ await _workers[network]!.runTask(
+ FCTask(
+ func: FCFuncName._reset,
+ data: (
+ resetSets,
+ _setEpochs[network]!.number,
+ _tagEpochs[network]!.number,
+ ),
+ ),
+ );
+ if (resetSets) {
+ _FiroCache._setCacheDB[network] = sqlite3.open(
+ '${dir.path}/${_FiroCache.sparkSetCacheFileName(network)}',
+ mode: OpenMode.readWrite,
+ );
+ }
+ _FiroCache._usedTagsCacheDB[network] = sqlite3.open(
+ '${dir.path}/${_FiroCache.sparkUsedTagsCacheFileName(network)}',
+ mode: OpenMode.readWrite,
+ );
+ await marker.delete();
+ _pendingFullResets.remove(network);
+ _resetErrors.remove(network);
}
static Future<String> getSparkCacheSize(CryptoCurrencyNetwork network) async {
+ await _ready(network);
final dir = await StackFileSystem.applicationFiroCacheSQLiteDirectory();
final setCacheFile = File(
"${dir.path}/${_FiroCache.sparkSetCacheFileName(network)}",
@@ -83,14 +236,24 @@ abstract class FiroCacheCoordinator {
ElectrumXClient client,
CryptoCurrencyNetwork network,
) async {
+ final epoch = _tagEpochs[network]!;
await _tagLocks[network]!.protect(() async {
+ epoch.check();
final count = await FiroCacheCoordinator.getUsedCoinTagsCount(network);
- final unhashedTags = await client
- .getSparkUnhashedUsedCoinsTagsWithTxHashes(startNumber: count);
+ epoch.check();
+ final unhashedTags = await epoch.wait(
+ client.getSparkUnhashedUsedCoinsTagsWithTxHashes(startNumber: count),
+ );
+ epoch.check();
if (unhashedTags.isNotEmpty) {
await _workers[network]!.runTask(
- FCTask(func: FCFuncName._updateSparkUsedTagsWith, data: unhashedTags),
+ FCTask(
+ func: FCFuncName._updateSparkUsedTagsWith,
+ data: unhashedTags,
+ generation: epoch.number,
+ ),
);
+ epoch.check();
}
});
}
@@ -101,16 +264,23 @@ abstract class FiroCacheCoordinator {
CryptoCurrencyNetwork network,
void Function(int countFetched, int totalCount)? progressUpdated,
) async {
+ final epoch = _setEpochs[network]!;
await _setLocks[network]!.protect(() async {
+ epoch.check();
const sectorSize = 1500; // chosen as a somewhat decent value. Could be changed in the future if wanted/needed
final prevMeta = await FiroCacheCoordinator.getLatestSetInfoForGroupId(
groupId,
network,
);
+ epoch.check();
+
final prevSize = prevMeta?.size ?? 0;
- final meta = await client.getSparkAnonymitySetMeta(coinGroupId: groupId);
+ final meta = await epoch.wait(
+ client.getSparkAnonymitySetMeta(coinGroupId: groupId),
+ );
+ epoch.check();
progressUpdated?.call(prevSize, meta.size);
@@ -128,24 +298,30 @@ abstract class FiroCacheCoordinator {
for (int i = 0; i < fullSectorCount; i++) {
final start = (i * sectorSize);
- final data = await client.getSparkAnonymitySetBySector(
- coinGroupId: groupId,
- latestBlock: meta.blockHash,
- startIndex: start,
- endIndex: start + sectorSize,
+ final data = await epoch.wait(
+ client.getSparkAnonymitySetBySector(
+ coinGroupId: groupId,
+ latestBlock: meta.blockHash,
+ startIndex: start,
+ endIndex: start + sectorSize,
+ ),
);
+ epoch.check();
progressUpdated?.call(start + sectorSize, numberOfCoinsToFetch);
coins.addAll(data);
}
if (remainder > 0) {
- final data = await client.getSparkAnonymitySetBySector(
- coinGroupId: groupId,
- latestBlock: meta.blockHash,
- startIndex: numberOfCoinsToFetch - remainder,
- endIndex: numberOfCoinsToFetch,
+ final data = await epoch.wait(
+ client.getSparkAnonymitySetBySector(
+ coinGroupId: groupId,
+ latestBlock: meta.blockHash,
+ startIndex: numberOfCoinsToFetch - remainder,
+ endIndex: numberOfCoinsToFetch,
+ ),
);
+ epoch.check();
progressUpdated?.call(numberOfCoinsToFetch, numberOfCoinsToFetch);
coins.addAll(data);
@@ -159,8 +335,10 @@ abstract class FiroCacheCoordinator {
FCTask(
func: FCFuncName._updateSparkAnonSetCoinsWith,
data: (meta, result),
+ generation: epoch.number,
),
);
+ epoch.check();
});
}
@@ -170,6 +348,7 @@ abstract class FiroCacheCoordinator {
int startNumber,
CryptoCurrencyNetwork network,
) async {
+ await _ready(network);
final result = await _Reader._getSparkUsedCoinTags(
startNumber,
db: _FiroCache.usedTagsCacheDB(network),
@@ -178,6 +357,7 @@ abstract class FiroCacheCoordinator {
}
static Future<int> getUsedCoinTagsCount(CryptoCurrencyNetwork network) async {
+ await _ready(network);
final result = await _Reader._getUsedCoinTagsCount(
db: _FiroCache.usedTagsCacheDB(network),
);
@@ -191,6 +371,7 @@ abstract class FiroCacheCoordinator {
required List<String> tags,
required CryptoCurrencyNetwork network,
}) async {
+ await _ready(network);
if (tags.isEmpty) {
return [];
}
@@ -211,6 +392,7 @@ abstract class FiroCacheCoordinator {
required String txid,
required CryptoCurrencyNetwork network,
}) async {
+ await _ready(network);
final result = await _Reader._getUsedCoinTagsFor(
txid,
db: _FiroCache.usedTagsCacheDB(network),
@@ -222,6 +404,7 @@ abstract class FiroCacheCoordinator {
String tag,
CryptoCurrencyNetwork network,
) async {
+ await _ready(network);
return await _Reader._checkTagIsUsed(
tag,
db: _FiroCache.usedTagsCacheDB(network),
@@ -233,6 +416,7 @@ abstract class FiroCacheCoordinator {
String? afterBlockHash,
required CryptoCurrencyNetwork network,
}) async {
+ await _ready(network);
final resultSet = afterBlockHash == null
? await _Reader._getSetCoinsForGroupId(
groupId,
@@ -262,6 +446,7 @@ abstract class FiroCacheCoordinator {
int groupId,
CryptoCurrencyNetwork network,
) async {
+ await _ready(network);
final result = await _Reader._getLatestSetInfoForGroupId(
groupId,
db: _FiroCache.setCacheDB(network),
@@ -283,6 +468,7 @@ abstract class FiroCacheCoordinator {
int groupId,
CryptoCurrencyNetwork network,
) async {
+ await _ready(network);
return await _Reader._checkSetInfoForGroupIdExists(
groupId,
db: _FiroCache.setCacheDB(network),
### lib/db/sqlite/firo_cache_reader.dart
@@ -9,7 +9,8 @@ abstract class _Reader {
int groupId, {
required Database db,
}) async {
- final query = """
+ final query =
+ """
SELECT sc.serialized, sc.txHash, sc.context, sc.groupId
FROM SparkSet AS ss
JOIN SparkSetCoins AS ssc ON ss.id = ssc.setId
@@ -24,7 +25,8 @@ abstract class _Reader {
int groupId, {
required Database db,
}) async {
- final query = """
+ final query =
+ """
SELECT ss.blockHash, ss.setHash, ss.size
FROM SparkSet ss
WHERE ss.groupId = $groupId
@@ -40,16 +42,19 @@ abstract class _Reader {
String blockHash, {
required Database db,
}) async {
+ // A full reset rebuilds SparkSet, so a wallet's checkpoint hash may no
+ // longer exist. The wallet advances its checkpoint after this read, so an
+ // unknown hash must return the whole set rather than nothing.
const query = """
WITH TargetBlock AS (
SELECT id
FROM SparkSet
- WHERE blockHash = ?
+ WHERE blockHash = ? AND groupId = ?
),
TargetSets AS (
SELECT id AS setId
FROM SparkSet
- WHERE groupId = ? AND id > (SELECT id FROM TargetBlock)
+ WHERE groupId = ? AND id > COALESCE((SELECT id FROM TargetBlock), 0)
)
SELECT
SparkCoin.serialized,
@@ -61,14 +66,15 @@ abstract class _Reader {
WHERE SparkSetCoins.setId IN (SELECT setId FROM TargetSets);
""";
- return db.select("$query;", [blockHash, groupId]);
+ return db.select("$query;", [blockHash, groupId, groupId]);
}
static Future<bool> _checkSetInfoForGroupIdExists(
int groupId, {
required Database db,
}) async {
- final query = """
+ final query =
+ """
SELECT EXISTS (
SELECT 1
FROM SparkSet
@@ -98,9 +104,7 @@ abstract class _Reader {
return db.select("$query;");
}
- static Future<ResultSet> _getUsedCoinTagsCount({
- required Database db,
- }) async {
+ static Future<ResultSet> _getUsedCoinTagsCount({required Database db}) async {
const query = """
SELECT COUNT(*) AS count
FROM SparkUsedCoinTags;
@@ -115,7 +119,8 @@ abstract class _Reader {
}) async {
final tagsConcat = tags.join("', '");
- final query = """
+ final query =
+ """
SELECT tag, GROUP_CONCAT(txid) AS txids
FROM SparkUsedCoinTags
WHERE tag IN ('$tagsConcat')
@@ -129,7 +134,8 @@ abstract class _Reader {
String txid, {
required Database db,
}) async {
- final query = """
+ final query =
+ """
SELECT tag
FROM SparkUsedCoinTags
WHERE txid = '$txid';
@@ -142,7 +148,8 @@ abstract class _Reader {
String tag, {
required Database db,
}) async {
- final query = """
+ final query =
+ """
SELECT EXISTS (
SELECT 1
FROM SparkUsedCoinTags
### lib/db/sqlite/firo_cache_worker.dart
@@ -3,15 +3,17 @@ part of 'firo_cache.dart';
enum FCFuncName {
_updateSparkAnonSetCoinsWith,
_updateSparkUsedTagsWith,
+ _reset,
_close,
}
class FCTask {
final id = const Uuid().v4();
final FCFuncName func;
final dynamic data;
+ final int generation;
- FCTask({required this.func, required this.data});
+ FCTask({required this.func, required this.data, this.generation = 0});
}
class _FiroCacheWorker {
@@ -102,7 +104,13 @@ class _FiroCacheWorker {
Database setCacheDb,
Database usedTagsCacheDb,
Mutex mutex,
+ String setCacheFilePath,
+ String usedTagsCacheFilePath,
) {
+ Database? activeSet = setCacheDb;
+ Database? activeTags = usedTagsCacheDb;
+ var setGeneration = 0;
+ var tagGeneration = 0;
receivePort.listen((message) {
final task = message as FCTask;
@@ -111,25 +119,55 @@ class _FiroCacheWorker {
final FCResult result;
switch (task.func) {
case FCFuncName._close:
- setCacheDb.close();
- usedTagsCacheDb.close();
+ activeSet?.close();
+ activeTags?.close();
receivePort.close();
sendPort.send((task.id, null));
return;
+ case FCFuncName._reset:
+ final (sets, nextSet, nextTags) = task.data as (bool, int, int);
+ // Change generation in the same serialized worker operation as
+ // the reset, including when a filesystem failure needs a retry.
+ if (sets) setGeneration = nextSet;
+ tagGeneration = nextTags;
+ if (sets) {
+ activeSet?.close();
+ activeSet = null;
+ await _FiroCache._recreateSetFile(setCacheFilePath);
+ activeSet = sqlite3.open(
+ setCacheFilePath,
+ mode: OpenMode.readWrite,
+ );
+ }
+ activeTags?.close();
+ activeTags = null;
+ await _FiroCache._recreateTagsFile(usedTagsCacheFilePath);
+ activeTags = sqlite3.open(
+ usedTagsCacheFilePath,
+ mode: OpenMode.readWrite,
+ );
+ sendPort.send((task.id, null));
+ return;
+
case FCFuncName._updateSparkAnonSetCoinsWith:
+ // A handle is missing only while a failed reset awaits retry.
+ final setDb = activeSet;
+ if (task.generation != setGeneration || setDb == null) {
+ throw const FiroCacheResetException();
+ }
final data =
task.data as (SparkAnonymitySetMeta, List<RawSparkCoin>);
- result = _updateSparkAnonSetCoinsWith(
- setCacheDb,
- data.$2,
- data.$1,
- );
+ result = _updateSparkAnonSetCoinsWith(setDb, data.$2, data.$1);
break;
case FCFuncName._updateSparkUsedTagsWith:
+ final tagsDb = activeTags;
+ if (task.generation != tagGeneration || tagsDb == null) {
+ throw const FiroCacheResetException();
+ }
result = _updateSparkUsedTagsWith(
- usedTagsCacheDb,
+ tagsDb,
task.data as List<List<dynamic>>,
);
break;
@@ -159,6 +197,8 @@ class _FiroCacheWorker {
setCacheDb,
usedTagsCacheDb,
mutex,
+ args.$2,
+ args.$3,
);
}
}
### lib/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart
@@ -12,7 +12,6 @@ import 'dart:async';
import 'dart:convert';
import 'dart:math';
-import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tuple/tuple.dart';
@@ -355,9 +354,8 @@ class _VerifyRecoveryPhraseViewState
context,
).popUntil(ModalRoute.withName(SelectWalletForTokenView.routeName));
} else {
- Navigator.of(
- context,
- ).popUntil(ModalRoute.withName(DesktopHomeView.routeName));
+ Navigator.of(context)
+ .popUntil(ModalRoute.withName(DesktopHomeView.routeName));
if (_coin is Ethereum || _coin is Solana) {
unawaited(
Navigator.of(context).pushNamed(
@@ -451,10 +449,6 @@ class _VerifyRecoveryPhraseViewState
result.insert(random.nextInt(wordsToShow), chosenWord);
- if (kDebugMode) {
- print("Mnemonic game correct word: $chosenWord");
- }
-
return Tuple2(result, chosenWord);
}
@@ -549,9 +543,9 @@ class _VerifyRecoveryPhraseViewState
SizedBox(height: isDesktop ? 16 : 12),
Container(
decoration: BoxDecoration(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG,
borderRadius: BorderRadius.circular(
Constants.size.circularBorderRadius,
),
@@ -563,10 +557,10 @@ class _VerifyRecoveryPhraseViewState
),
child: Text(
"${correctIndex + 1}",
+ key: const Key('recoveryPhraseWordIndex'),
textAlign: TextAlign.center,
- style: STextStyles.subtitle600(
- context,
- ).copyWith(fontSize: 32, letterSpacing: 0.25),
+ style: STextStyles.subtitle600(context)
+ .copyWith(fontSize: 32, letterSpacing: 0.25),
),
),
),
### lib/pages/exchange_view/exchange_form.dart
@@ -16,7 +16,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_svg/svg.dart';
import 'package:tuple/tuple.dart';
-import 'package:uuid/uuid.dart';
import '../../models/exchange/aggregate_currency.dart';
import '../../models/exchange/incomplete_exchange.dart';
@@ -409,6 +408,10 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
_receiveFocusNode.unfocus();
_sendFocusNode.unfocus();
+ // Estimated trades are always driven by the send amount.
+ if (newType == ExchangeRateType.estimated) {
+ ref.read(efReversedProvider.notifier).state = false;
+ }
ref.read(efRateTypeProvider.notifier).state = newType;
update();
}
@@ -727,8 +730,9 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
}
Future<void> update() async {
- final uuid = const Uuid().v1();
- _latestUuid = uuid;
+ if (!mounted) return;
+ final request = Object();
+ _refreshRequest = request;
final exchanges = usableExchanges;
final estimatesNotifiers = {
@@ -737,89 +741,93 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
efEstimatesListProvider(exchange.name).notifier,
),
};
- final refreshingNotifier = ref.read(efRefreshingProvider.notifier);
-
- _uuids.add(uuid);
- refreshingNotifier.state = true;
+ _refreshController.begin(request);
- void removeUpdate() {
- _uuids.remove(uuid);
- if (_uuids.isEmpty) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- refreshingNotifier.state = false;
- });
+ try {
+ for (final exchange in exchanges) {
+ estimatesNotifiers[exchange.name]!.state = null;
}
- }
- for (final exchange in exchanges) {
- estimatesNotifiers[exchange.name]!.state = null;
- }
+ final reversed = ref.read(efReversedProvider);
+ final amount = reversed
+ ? ref.read(efReceiveAmountProvider)
+ : ref.read(efSendAmountProvider);
- final reversed = ref.read(efReversedProvider);
- final amount = reversed
- ? ref.read(efReceiveAmountProvider)
- : ref.read(efSendAmountProvider);
-
- final pair = ref.read(efCurrencyPairProvider);
- if (amount == null ||
- amount <= Decimal.zero ||
- pair.send == null ||
- pair.receive == null) {
- removeUpdate();
- return;
- }
- final rateType = ref.read(efRateTypeProvider);
- final Map<String, Tuple2<ExchangeResponse<List<Estimate>>, Range?>>
- results = {};
-
- for (final exchange in exchanges) {
- final sendCurrency = pair.send?.forExchange(exchange.name);
- final receiveCurrency = pair.receive?.forExchange(exchange.name);
-
- if (sendCurrency != null && receiveCurrency != null) {
- final rangeResponse = await exchange.getRange(
- reversed ? receiveCurrency.ticker : sendCurrency.ticker,
- reversed ? receiveCurrency.network : sendCurrency.network,
- reversed ? sendCurrency.ticker : receiveCurrency.ticker,
- reversed ? sendCurrency.network : receiveCurrency.network,
- rateType == ExchangeRateType.fixed,
- );
+ final pair = ref.read(efCurrencyPairProvider);
+ if (amount == null ||
+ amount <= Decimal.zero ||
+ pair.send == null ||
+ pair.receive == null) {
+ return;
+ }
+ final rateType = ref.read(efRateTypeProvider);
+ final Map<String, Tuple2<ExchangeResponse<List<Estimate>>, Range?>>
+ results = {};
+
+ for (final exchange in exchanges) {
+ final sendCurrency = pair.send?.forExchange(exchange.name);
+ final receiveCurrency = pair.receive?.forExchange(exchange.name);
+
+ if (sendCurrency != null && receiveCurrency != null) {
+ final rangeResponse = await exchange.getRange(
+ reversed ? receiveCurrency.ticker : sendCurrency.ticker,
+ reversed ? receiveCurrency.network : sendCurrency.network,
+ reversed ? sendCurrency.ticker : receiveCurrency.ticker,
+ reversed ? sendCurrency.network : receiveCurrency.network,
+ rateType == ExchangeRateType.fixed,
+ );
+ if (!mounted || !_refreshController.owns(request)) {
+ return;
+ }
- Logging.instance.d(
- "${exchange.name}: rateType=$rateType, RANGE=$rangeResponse",
- );
+ Logging.instance.d(
+ "${exchange.name}: rateType=$rateType, RANGE=$rangeResponse",
+ );
- final estimateResponse = await exchange.getEstimates(
- sendCurrency.ticker,
- sendCurrency.network,
- receiveCurrency.ticker,
- receiveCurrency.network,
- amount,
- rateType == ExchangeRateType.fixed,
- reversed,
- );
+ final estimateResponse = await exchange.getEstimates(
+ sendCurrency.ticker,
+ sendCurrency.network,
+ receiveCurrency.ticker,
+ receiveCurrency.network,
+ amount,
+ rateType == ExchangeRateType.fixed,
+ reversed,
+ );
+ if (!mounted || !_refreshController.owns(request)) {
+ return;
+ }
- Logging.instance.d(
- "${exchange.name}: estimateResponse=$estimateResponse",
- );
+ Logging.instance.d(
+ "${exchange.name}: estimateResponse=$estimateResponse",
+ );
- results.addAll({
- exchange.name: Tuple2(estimateResponse, rangeResponse.value),
- });
+ results.addAll({
+ exchange.name: Tuple2(estimateResponse, rangeResponse.value),
+ });
+ }
}
- }
- for (final exchange in exchanges) {
- if (uuid == _latestUuid) {
- estimatesNotifiers[exchange.name]!.state = results[exchange.name];
+ for (final exchange in exchanges) {
+ if (mounted && _refreshController.owns(request)) {
+ estimatesNotifiers[exchange.name]!.state = results[exchange.name];
+ }
}
+ } finally {
+ _finishRefreshAfterFrame(request);
}
-
- removeUpdate();
}
- String? _latestUuid;
- final Set<String> _uuids = {};
+ late final ExchangeRefreshController _refreshController;
+ Object? _refreshRequest;
+
+ void _finishRefreshAfterFrame(Object request) {
+ final controller = _refreshController;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ controller.finish(request);
+ });
+ // A refresh that changed nothing else may have no frame pending.
+ WidgetsBinding.instance.ensureVisualUpdate();
+ }
void updateSend(Estimate? estimate) {
ref.read(efSendAmountProvider.notifier).state = estimate?.estimatedAmount;
@@ -832,6 +840,7 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
@override
void initState() {
+ _refreshController = ref.read(efRefreshingProvider.notifier);
_sendController = TextEditingController();
_receiveController = TextEditingController();
_amountInputLocale = ref.read(localeServiceChangeNotifierProvider).locale;
@@ -844,6 +853,7 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
if (_sendFocusNode.hasFocus) {
final reversed = ref.read(efReversedProvider);
WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
ref.read(efReversedProvider.notifier).state = false;
if (reversed == true) {
update();
@@ -855,6 +865,11 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
if (_receiveFocusNode.hasFocus) {
final reversed = ref.read(efReversedProvider);
WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ // The read-only estimated output can still receive focus.
+ if (ref.read(efRateTypeProvider) == ExchangeRateType.estimated) {
+ return;
+ }
ref.read(efReversedProvider.notifier).state = true;
if (reversed != true) {
update();
@@ -865,10 +880,11 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
if (walletInitiated) {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
+ if (!mounted) return;
ref.read(efSendAmountProvider.notifier).state = null;
ref.read(efReceiveAmountProvider.notifier).state = null;
ref.read(efReversedProvider.notifier).state = false;
- ref.read(efRefreshingProvider.notifier).state = false;
+ _refreshController.reset();
ref.read(efCurrencyPairProvider).setSend(null, notifyListeners: true);
ref
.read(efCurrencyPairProvider)
@@ -881,7 +897,7 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
widget.contract?.address,
)
.then((value) {
- if (value != null) {
+ if (mounted && value != null) {
ref
.read(efCurrencyPairProvider)
.setSend(value, notifyListeners: true);
@@ -890,6 +906,7 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
});
} else {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
+ if (!mounted) return;
_sendController.text = ref.read(efSendAmountStringProvider);
_receiveController.text = ref.read(efReceiveAmountStringProvider);
});
@@ -900,6 +917,10 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
@override
void dispose() {
+ final request = _refreshRequest;
+ if (request != null) {
+ _finishRefreshAfterFrame(request);
+ }
_sendFieldOnChangedTimer?.cancel();
_receiveFieldOnChangedTimer?.cancel();
_receiveController.dispose();
@@ -935,10 +956,12 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
if (!_receiveFocusNode.hasFocus) {
_receiveController.text = isEstimated && next.isEmpty ? "-" : next;
// if (_swapLock) {
- _sendController.text = ref.read(efSendAmountStringProvider);
+ if (_pendingSendAmountText == null) {
+ _sendController.text = ref.read(efSendAmountStringProvider);
+ }
// }
- if (_sendFocusNode.hasFocus) {
+ if (_sendFocusNode.hasFocus && _pendingSendAmountText == null) {
_sendController.selection = TextSelection.fromPosition(
TextPosition(offset: _sendController.text.length),
);
@@ -949,13 +972,15 @@ class _ExchangeFormState extends ConsumerState<ExchangeForm> {
if (!_sendFocusNode.hasFocus) {
_sendController.text = next;
// if (_swapLock) {
- _receiveController.text =
- isEstimated && ref.read(efReceiveAmountStringProvider).isEmpty
- ? "-"
- : ref.read(efReceiveAmountStringProvider);
+ if (_pendingReceiveAmountText == null) {
+ _receiveController.text =
+ isEstimated && ref.read(efReceiveAmountStringProvider).isEmpty
+ ? "-"
+ : ref.read(efReceiveAmountStringProvider);
+ }
// }
- if (_receiveFocusNode.hasFocus) {
+ if (_receiveFocusNode.hasFocus && _pendingReceiveAmountText == null) {
_receiveController.selection = TextSelection.fromPosition(
TextPosition(offset: _receiveController.text.length),
);
### lib/pages/send_view/confirm_transaction_view.dart
@@ -33,6 +33,7 @@ import '../../themes/stack_colors.dart';
import '../../themes/theme_providers.dart';
import '../../utilities/amount/amount.dart';
import '../../utilities/amount/amount_formatter.dart';
+import '../../utilities/amount/fee_rate_formatter.dart';
import '../../utilities/constants.dart';
import '../../utilities/logger.dart';
import '../../utilities/text_styles.dart';
@@ -688,6 +689,8 @@ class _ConfirmTransactionViewState
amountWithoutChange = widget.txData.amountWithoutChange!;
}
+ final feeRate = formatApproximateFeeRate(fee?.raw, widget.txData.vSize);
+
return ConditionalParent(
condition: !isDesktop,
builder: (child) => Background(
@@ -889,9 +892,8 @@ class _ConfirmTransactionViewState
],
),
),
- if (widget.txData.fee != null && widget.txData.vSize != null)
- const SizedBox(height: 12),
- if (widget.txData.fee != null && widget.txData.vSize != null)
+ if (feeRate != null) const SizedBox(height: 12),
+ if (feeRate != null)
RoundedWhiteContainer(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
@@ -902,7 +904,7 @@ class _ConfirmTransactionViewState
),
const SizedBox(height: 4),
SelectableText(
- "~${fee!.raw.toInt() ~/ widget.txData.vSize!}",
+ feeRate,
style: STextStyles.itemSubtitle12(context),
),
],
@@ -1505,21 +1507,15 @@ class _ConfirmTransactionViewState
),
),
),
- if (isDesktop &&
- !widget.isPaynymTransaction &&
- widget.txData.fee != null &&
- widget.txData.vSize != null)
+ if (isDesktop && !widget.isPaynymTransaction && feeRate != null)
Padding(
padding: const EdgeInsets.only(left: 32),
child: Text(
"sats/vByte",
style: STextStyles.desktopTextExtraExtraSmall(context),
),
),
- if (isDesktop &&
- !widget.isPaynymTransaction &&
- widget.txData.fee != null &&
- widget.txData.vSize != null)
+ if (isDesktop && !widget.isPaynymTransaction && feeRate != null)
Padding(
padding: const EdgeInsets.only(top: 10, left: 32, right: 32),
child: RoundedContainer(
@@ -1531,7 +1527,7 @@ class _ConfirmTransactionViewState
.extension<StackColors>()!
.textFieldDefaultBG,
child: SelectableText(
- "~${fee!.raw.toInt() ~/ widget.txData.vSize!}",
+ feeRate,
style: STextStyles.itemSubtitle(context),
),
),
### lib/pages/send_view/send_view.dart
@@ -602,7 +602,7 @@ class _SendViewState extends ConsumerState<SendView> {
cryptoAmountController.text = amountString;
_cryptoAmountChangeLock = false;
} else {
- amount = 0.toAmountAsRaw(fractionDigits: coin.fractionDigits);
+ amount = null;
_cachedAmountToSend = null;
_cryptoAmountChangeLock = true;
cryptoAmountController.text = "";
### lib/pages/send_view/sol_token_send_view.dart
@@ -296,6 +296,17 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
_updatePreviewButtonState(_address, _amountToSend);
}
+ // Controller assignments used for display must not edit the stored amount.
+ void _updateAmountDisplay(VoidCallback update) {
+ final wasLocked = _cryptoAmountChangeLock;
+ _cryptoAmountChangeLock = true;
+ try {
+ update();
+ } finally {
+ _cryptoAmountChangeLock = wasLocked;
+ }
+ }
+
void _cryptoAmountChanged() async {
if (!_cryptoAmountChangeLock) {
final tokenWallet = ref.read(pCurrentSolanaTokenWallet);
@@ -670,7 +681,7 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
listenForAmountRelocalization(
ref.listen,
controllers: [cryptoAmountController, baseAmountController],
- onRelocalized: _cryptoAmountChanged,
+ updateControllers: _updateAmountDisplay,
);
final tokenWallet = ref.watch(pCurrentSolanaTokenWallet);
@@ -708,6 +719,9 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
),
);
}
+ final amountFormatter = ref.watch(
+ pAmountFormatter(tokenWallet.cryptoCurrency),
+ );
return Background(
child: Scaffold(
@@ -1325,14 +1339,8 @@ class _SolTokenSendViewState extends ConsumerState<SolTokenSendView> {
if (snapshot.connectionState ==
ConnectionState.done &&
snapshot.hasData) {
- final formattedFee = ref
- .watch(
- pAmountFormatter(
- tokenWallet
- .cryptoCurrency,
- ),
- )
- .format(
+ final formattedFee =
+ amountFormatter.format(
snapshot.data!,
withUnitName: true,
indicatePrecisionLoss:
### lib/pages/send_view/token_send_view.dart
@@ -281,7 +281,7 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
.formatEditable(_amountToSend!);
_cryptoAmountChangeLock = false;
} else {
- _amountToSend = Amount.zero;
+ _amountToSend = null;
_cachedAmountToSend = null;
_cryptoAmountChangeLock = true;
cryptoAmountController.text = "";
### lib/pages/settings_views/global_settings_view/currency_view.dart
@@ -62,7 +62,7 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
ref.read(prefsChangeNotifierProvider).currency = current;
if (ref.read(prefsChangeNotifierProvider).externalCalls) {
- ref.read(priceAnd24hChangeNotifierProvider).updatePrice();
+ ref.read(priceAnd24hChangeNotifierProvider).start(true);
}
}
}
@@ -119,11 +119,10 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
);
}
- currenciesWithoutSelected =
- ref
- .watch(baseCurrenciesProvider.select((value) => value.map))
- .keys
- .toList();
+ currenciesWithoutSelected = ref
+ .watch(baseCurrenciesProvider.select((value) => value.map))
+ .keys
+ .toList();
if (current.isNotEmpty) {
currenciesWithoutSelected.remove(current);
@@ -137,8 +136,9 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
builder: (child) {
return Background(
child: Scaffold(
- backgroundColor:
- Theme.of(context).extension<StackColors>()!.background,
+ backgroundColor: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
appBar: AppBar(
leading: AppBarBackButton(
onPressed: () async {
@@ -180,8 +180,9 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
Expanded(
child: RoundedWhiteContainer(
padding: const EdgeInsets.all(20),
- borderColor:
- Theme.of(context).extension<StackColors>()!.background,
+ borderColor: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
child: child,
),
),
@@ -209,7 +210,7 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
.externalCalls) {
ref
.read(priceAnd24hChangeNotifierProvider)
- .updatePrice();
+ .start(true);
}
Navigator.of(context).pop();
@@ -246,44 +247,44 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
setState(() => filter = newString);
},
style: STextStyles.field(context),
- decoration: standardInputDecoration(
- "Search",
- _searchFocusNode,
- context,
- ).copyWith(
- prefixIcon: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 10,
- vertical: 16,
- ),
- child: SvgPicture.asset(
- Assets.svg.search,
- width: 16,
- height: 16,
- ),
- ),
- suffixIcon:
- _searchController.text.isNotEmpty
+ decoration:
+ standardInputDecoration(
+ "Search",
+ _searchFocusNode,
+ context,
+ ).copyWith(
+ prefixIcon: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 16,
+ ),
+ child: SvgPicture.asset(
+ Assets.svg.search,
+ width: 16,
+ height: 16,
+ ),
+ ),
+ suffixIcon: _searchController.text.isNotEmpty
? Padding(
- padding: const EdgeInsets.only(right: 0),
- child: UnconstrainedBox(
- child: Row(
- children: [
- TextFieldIconButton(
- child: const XIcon(),
- onTap: () async {
- setState(() {
- _searchController.text = "";
- filter = "";
- });
- },
- ),
- ],
+ padding: const EdgeInsets.only(right: 0),
+ child: UnconstrainedBox(
+ child: Row(
+ children: [
+ TextFieldIconButton(
+ child: const XIcon(),
+ onTap: () async {
+ setState(() {
+ _searchController.text = "";
+ filter = "";
+ });
+ },
+ ),
+ ],
+ ),
),
- ),
- )
+ )
: null,
- ),
+ ),
),
),
),
@@ -304,10 +305,9 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
delegate: SliverChildBuilderDelegate((context, index) {
return Container(
decoration: BoxDecoration(
- color:
- Theme.of(
- context,
- ).extension<StackColors>()!.popupBG,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .popupBG,
borderRadius: _borderRadius(index),
),
child: Padding(
@@ -317,14 +317,13 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
),
child: RoundedContainer(
padding: const EdgeInsets.all(0),
- color:
- currenciesWithoutSelected[index] == current
- ? Theme.of(context)
- .extension<StackColors>()!
- .currencyListItemBG
- : Theme.of(
- context,
- ).extension<StackColors>()!.popupBG,
+ color: currenciesWithoutSelected[index] == current
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .currencyListItemBG
+ : Theme.of(context)
+ .extension<StackColors>()!
+ .popupBG,
child: RawMaterialButton(
onPressed: () async {
onTap(index);
@@ -343,10 +342,9 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
width: 20,
height: 20,
child: Radio(
- activeColor:
- Theme.of(context)
- .extension<StackColors>()!
- .radioButtonIconEnabled,
+ activeColor: Theme.of(context)
+ .extension<StackColors>()!
+ .radioButtonIconEnabled,
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
value: true,
@@ -367,11 +365,11 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
currenciesWithoutSelected[index],
key:
(currenciesWithoutSelected[index] ==
- current)
- ? const Key(
- "selectedCurrencySettingsCurrencyText",
- )
- : null,
+ current)
+ ? const Key(
+ "selectedCurrencySettingsCurrencyText",
+ )
+ : null,
style: STextStyles.largeMedium14(
context,
),
@@ -386,11 +384,11 @@ class _CurrencyViewState extends ConsumerState<BaseCurrencySettingsView> {
"",
key:
(currenciesWithoutSelected[index] ==
- current)
- ? const Key(
- "selectedCurrencySettingsCurrencyTextDescription",
- )
- : null,
+ current)
+ ? const Key(
+ "selectedCurrencySettingsCurrencyTextDescription",
+ )
+ : null,
style: STextStyles.itemSubtitle(
context,
),
### lib/pages_desktop_specific/desktop_home_view.dart
@@ -67,8 +67,9 @@ class _DesktopHomeViewState extends ConsumerState<DesktopHomeView> {
}
late AutoLockInfo _autoLockInfo;
+ late final Prefs _prefs;
void _prefsTimeoutListener() {
- final prefs = ref.read(prefsChangeNotifierProvider);
+ final prefs = _prefs;
if (mounted && prefs.autoLockInfo != _autoLockInfo) {
_autoLockInfo = prefs.autoLockInfo;
if (_autoLockInfo.enabled) {
@@ -87,7 +88,8 @@ class _DesktopHomeViewState extends ConsumerState<DesktopHomeView> {
@override
void initState() {
- _autoLockInfo = ref.read(prefsChangeNotifierProvider).autoLockInfo;
+ _prefs = ref.read(prefsChangeNotifierProvider);
+ _autoLockInfo = _prefs.autoLockInfo;
if (_autoLockInfo.enabled) {
_idleMonitor = IdleMonitor(
timeout: Duration(minutes: _autoLockInfo.minutes),
@@ -102,7 +104,7 @@ class _DesktopHomeViewState extends ConsumerState<DesktopHomeView> {
);
_idleMonitor?.attach();
- ref.read(prefsChangeNotifierProvider).addListener(_prefsTimeoutListener);
+ _prefs.addListener(_prefsTimeoutListener);
// WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
// showOneTimeTorHasBeenAddedDialogIfRequired(context);
@@ -113,7 +115,7 @@ class _DesktopHomeViewState extends ConsumerState<DesktopHomeView> {
@override
dispose() {
- ref.read(prefsChangeNotifierProvider).removeListener(_prefsTimeoutListener);
+ _prefs.removeListener(_prefsTimeoutListener);
_idleMonitor?.detach();
super.dispose();
}
@@ -171,9 +173,8 @@ class _DesktopHomeViewState extends ConsumerState<DesktopHomeView> {
if (ref.read(prevDesktopMenuItemProvider.state).state ==
DesktopMenuItemId.myStack &&
ref.read(prevDesktopMenuItemProvider.state).state == newKey) {
- Navigator.of(
- myStackViewNavKey.currentContext!,
- ).popUntil(ModalRoute.withName(MyStackView.routeName));
+ Navigator.of(myStackViewNavKey.currentContext!)
+ .popUntil(ModalRoute.withName(MyStackView.routeName));
if (ref.read(currentWalletIdProvider.state).state != null) {
final wallet = ref
.read(pWallets)
### lib/pages_desktop_specific/my_stack_view/wallet_view/desktop_wallet_view.dart
@@ -134,8 +134,9 @@ class _DesktopWalletViewState extends ConsumerState<DesktopWalletView> {
controller.text = wallet.info.name;
- eventBus =
- widget.eventBus != null ? widget.eventBus! : GlobalEventBus.instance;
+ eventBus = widget.eventBus != null
+ ? widget.eventBus!
+ : GlobalEventBus.instance;
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(currentWalletIdProvider.notifier).state = wallet.walletId;
@@ -181,20 +182,19 @@ class _DesktopWalletViewState extends ConsumerState<DesktopWalletView> {
children: [
const SizedBox(width: 32),
AppBarIconButton(
+ key: const Key('desktopWalletBackButton'),
size: 32,
- color:
- Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG,
shadows: const [],
icon: SvgPicture.asset(
Assets.svg.arrowLeft,
width: 18,
height: 18,
- color:
- Theme.of(
- context,
- ).extension<StackColors>()!.topNavIconPrimary,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .topNavIconPrimary,
),
onPressed: onBackPressed,
),
@@ -217,10 +217,9 @@ class _DesktopWalletViewState extends ConsumerState<DesktopWalletView> {
Text(
"(View only)",
style: STextStyles.desktopTextExtraSmall(context).copyWith(
- color:
- Theme.of(context)
- .extension<StackColors>()!
- .textFieldActiveSearchIconLeft,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldActiveSearchIconLeft,
),
),
if (kDebugMode) const Spacer(),
@@ -247,21 +246,21 @@ class _DesktopWalletViewState extends ConsumerState<DesktopWalletView> {
Text(
wallet.isarTransactionVersion == 2
? ref
- .watch(mainDBProvider)
- .isar
- .transactionV2s
- .where()
- .walletIdEqualTo(widget.walletId)
- .countSync()
- .toString()
+ .watch(mainDBProvider)
+ .isar
+ .transactionV2s
+ .where()
+ .walletIdEqualTo(widget.walletId)
+ .countSync()
+ .toString()
: ref
- .watch(mainDBProvider)
- .isar
- .transactions
- .where()
- .walletIdEqualTo(widget.walletId)
- .countSync()
- .toString(),
+ .watch(mainDBProvider)
+ .isar
+ .transactions
+ .where()
+ .walletIdEqualTo(widget.walletId)
+ .countSync()
+ .toString(),
),
],
),
@@ -326,10 +325,9 @@ class _DesktopWalletViewState extends ConsumerState<DesktopWalletView> {
child: Text(
"My wallet",
style: STextStyles.desktopTextExtraSmall(context).copyWith(
- color:
- Theme.of(context)
- .extension<StackColors>()!
- .textFieldActiveSearchIconLeft,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldActiveSearchIconLeft,
),
),
),
@@ -342,29 +340,25 @@ class _DesktopWalletViewState extends ConsumerState<DesktopWalletView> {
wallet.cryptoCurrency.hasTokenSupport
? "Tokens"
: "Recent activity",
- style: STextStyles.desktopTextExtraSmall(
- context,
- ).copyWith(
- color:
- Theme.of(context)
+ style: STextStyles.desktopTextExtraSmall(context)
+ .copyWith(
+ color: Theme.of(context)
.extension<StackColors>()!
.textFieldActiveSearchIconLeft,
- ),
+ ),
),
CustomTextButton(
- text:
- wallet.cryptoCurrency.hasTokenSupport
- ? "Edit"
- : "See all",
+ text: wallet.cryptoCurrency.hasTokenSupport
+ ? "Edit"
+ : "See all",
onTap: () async {
if (wallet.cryptoCurrency.hasTokenSupport) {
final result = await showDialog<int?>(
context: context,
- builder:
- (context) => EditWalletTokensView(
- walletId: widget.walletId,
- isDesktopPopup: true,
- ),
+ builder: (context) => EditWalletTokensView(
+ walletId: widget.walletId,
+ isDesktopPopup: true,
+ ),
);
if (result == 42) {
@@ -397,12 +391,11 @@ class _DesktopWalletViewState extends ConsumerState<DesktopWalletView> {
),
const SizedBox(width: 16),
Expanded(
- child:
- wallet.cryptoCurrency.hasTokenSupport
- ? MyTokensView(walletId: widget.walletId)
- : wallet.isarTransactionVersion == 2
- ? TransactionsV2List(walletId: widget.walletId)
- : TransactionsList(walletId: widget.walletId),
+ child: wallet.cryptoCurrency.hasTokenSupport
+ ? MyTokensView(walletId: widget.walletId)
+ : wallet.isarTransactionVersion == 2
+ ? TransactionsV2List(walletId: widget.walletId)
+ : TransactionsList(walletId: widget.walletId),
),
],
),
@@ -442,33 +435,29 @@ class DesktopWalletHeaderRow extends ConsumerWidget {
if (wallet is FiroWallet)
FiroDesktopWalletSummary(
walletId: wallet.walletId,
- initialSyncStatus:
- wallet.refreshMutex.isLocked
- ? WalletSyncStatus.syncing
- : WalletSyncStatus.synced,
+ initialSyncStatus: wallet.refreshMutex.isLocked
+ ? WalletSyncStatus.syncing
+ : WalletSyncStatus.synced,
),
if (wallet is! FiroWallet)
wallet is MwebInterface &&
ref.watch(
- pWalletInfo(
- wallet.walletId,
- ).select((s) => s.isMwebEnabled),
+ pWalletInfo(wallet.walletId)
+ .select((s) => s.isMwebEnabled),
)
? MwebDesktopWalletSummary(
- walletId: wallet.walletId,
- initialSyncStatus:
- wallet.refreshMutex.isLocked
- ? WalletSyncStatus.syncing
- : WalletSyncStatus.synced,
- )
+ walletId: wallet.walletId,
+ initialSyncStatus: wallet.refreshMutex.isLocked
+ ? WalletSyncStatus.syncing
+ : WalletSyncStatus.synced,
+ )
: DesktopWalletSummary(
- walletId: wallet.walletId,
- initialSyncStatus:
- wallet.refreshMutex.isLocked
- ? WalletSyncStatus.syncing
- : WalletSyncStatus.synced,
- ),
+ walletId: wallet.walletId,
+ initialSyncStatus: wallet.refreshMutex.isLocked
+ ? WalletSyncStatus.syncing
+ : WalletSyncStatus.synced,
+ ),
Expanded(child: DesktopWalletFeatures(walletId: wallet.walletId)),
],
),
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart
@@ -1487,7 +1487,7 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
cryptoAmountController.text = amountString;
_cryptoAmountChangeLock = false;
} else {
- amount = Decimal.zero.toAmount(fractionDigits: coin.fractionDigits);
+ amount = null;
_cachedAmountToSend = null;
_cryptoAmountChangeLock = true;
cryptoAmountController.text = "";
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_sol_token_send.dart
@@ -387,11 +387,21 @@ class _DesktopSolTokenSendState extends ConsumerState<DesktopSolTokenSend> {
}
}
+ // Controller assignments used for display must not edit the stored amount.
+ void _updateAmountDisplay(VoidCallback update) {
+ final wasLocked = _cryptoAmountChangeLock;
+ _cryptoAmountChangeLock = true;
+ try {
+ update();
+ } finally {
+ _cryptoAmountChangeLock = wasLocked;
+ }
+ }
+
void _cryptoAmountChanged() async {
if (!_cryptoAmountChangeLock) {
// Get the token's decimal places for proper amount parsing. May still
- // be null while the token wallet is loading (e.g. a locale change
- // fires the relocalization listener before init completes).
+ // be null while the token wallet is loading.
final tokenWallet = ref.read(pCurrentSolanaTokenWallet);
if (tokenWallet == null) return;
@@ -697,7 +707,7 @@ class _DesktopSolTokenSendState extends ConsumerState<DesktopSolTokenSend> {
listenForAmountRelocalization(
ref.listen,
controllers: [cryptoAmountController, baseAmountController],
- onRelocalized: _cryptoAmountChanged,
+ updateControllers: _updateAmountDisplay,
);
final tokenWallet = ref.watch(pCurrentSolanaTokenWallet);
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart
@@ -599,7 +599,7 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
cryptoAmountController.text = amountString;
_cryptoAmountChangeLock = false;
} else {
- _amountToSend = Decimal.zero.toAmount(fractionDigits: tokenDecimals);
+ _amountToSend = null;
_cachedAmountToSend = null;
_cryptoAmountChangeLock = true;
cryptoAmountController.text = "";
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.dart
@@ -463,11 +463,10 @@ class _MoreFeaturesDialogState extends ConsumerState<MoreFeaturesDialog> {
child: DraggableSwitchButton(
isOn:
ref.watch(
- pWalletInfo(
- widget.walletId,
- ).select(
- (value) => value.otherData,
- ),
+ pWalletInfo(widget.walletId)
+ .select(
+ (value) => value.otherData,
+ ),
)[WalletInfoKeys.reuseAddress]
as bool? ??
false,
@@ -502,11 +501,10 @@ class _MoreFeaturesDialogState extends ConsumerState<MoreFeaturesDialog> {
child: DraggableSwitchButton(
isOn:
ref.watch(
- pWalletInfo(
- widget.walletId,
- ).select(
- (value) => value.otherData,
- ),
+ pWalletInfo(widget.walletId)
+ .select(
+ (value) => value.otherData,
+ ),
)[WalletInfoKeys.mwebEnabled]
as bool? ??
false,
@@ -606,17 +604,17 @@ class _MoreFeaturesItemState extends State<_MoreFeaturesItem> {
File(widget.iconAsset),
width: _MoreFeaturesItem.iconSize,
height: _MoreFeaturesItem.iconSize,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.settingsIconIcon,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .settingsIconIcon,
)
: SvgPicture.asset(
widget.iconAsset,
width: _MoreFeaturesItem.iconSize,
height: _MoreFeaturesItem.iconSize,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.settingsIconIcon,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .settingsIconIcon,
),
),
),
@@ -649,9 +647,9 @@ class _MoreFeaturesItemBase extends StatelessWidget {
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 32),
child: RoundedContainer(
color: Colors.transparent,
- borderColor: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG,
+ borderColor: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG,
onPressed: onPressed,
child: child,
),
@@ -690,6 +688,7 @@ class _MoreFeaturesClearSparkCacheItemState
await FiroCacheCoordinator.clearSharedCache(
widget.cryptoCurrency.network,
);
+ if (!mounted) return;
setState(() {
// trigger rebuild for cache size display
});
@@ -710,9 +709,9 @@ class _MoreFeaturesClearSparkCacheItemState
Assets.svg.x,
width: _MoreFeaturesItem.iconSize,
height: _MoreFeaturesItem.iconSize,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.settingsIconIcon,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .settingsIconIcon,
),
),
),
### lib/providers/exchange/exchange_form_state_provider.dart
@@ -120,4 +120,35 @@ final efCanExchangeProvider = StateProvider<bool>((ref) {
return !refreshing && estimate != null;
});
-final efRefreshingProvider = StateProvider<bool>((ref) => false);
+/// The latest quote owns the shared loading state across all exchange forms.
+class ExchangeRefreshController extends StateController<bool> {
+ ExchangeRefreshController() : super(false);
+
+ Object? _owner;
+
+ bool owns(Object request) => mounted && identical(_owner, request);
+
+ void begin(Object request) {
+ if (!mounted) return;
+ _owner = request;
+ state = true;
+ }
+
+ void finish(Object request) {
+ if (!owns(request)) return;
+ // A listener may start another quote while state=false is being notified.
+ _owner = null;
+ state = false;
+ }
+
+ void reset() {
+ if (!mounted) return;
+ _owner = null;
+ state = false;
+ }
+}
+
+final efRefreshingProvider =
+ StateNotifierProvider<ExchangeRefreshController, bool>(
+ (ref) => ExchangeRefreshController(),
+ );
### lib/providers/global/price_provider.dart
@@ -8,20 +8,16 @@
*
*/
-import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
+
import 'prefs_provider.dart';
import '../../services/price_service.dart';
-int _count = 0;
-
-final priceAnd24hChangeNotifierProvider =
- ChangeNotifierProvider<PriceService>((ref) {
- if (kDebugMode) {
- _count++;
- }
-
- final currency =
- ref.watch(prefsChangeNotifierProvider.select((value) => value.currency));
- return PriceService(currency);
+final priceAnd24hChangeNotifierProvider = ChangeNotifierProvider<PriceService>((
+ ref,
+) {
+ final currency = ref.watch(
+ prefsChangeNotifierProvider.select((value) => value.currency),
+ );
+ return PriceService(currency)..start(false);
});
### lib/providers/wallet/transaction_note_provider.dart
@@ -47,25 +47,24 @@ class _TransactionNoteWatcher extends ChangeNotifier {
}
}
-final _wiProvider = ChangeNotifierProvider.family<
- _TransactionNoteWatcher,
- ({String walletId, String txid})
->((ref, key) {
- final isar = ref.watch(mainDBProvider).isar;
+final _wiProvider =
+ ChangeNotifierProvider.family<
+ _TransactionNoteWatcher,
+ ({String walletId, String txid})
+ >((ref, key) {
+ final isar = ref.watch(mainDBProvider).isar;
- final watcher = _TransactionNoteWatcher(
- isar.transactionNotes
- .where()
- .txidWalletIdEqualTo(key.txid, key.walletId)
- .findFirstSync(),
- key,
- isar,
- );
+ final watcher = _TransactionNoteWatcher(
+ isar.transactionNotes
+ .where()
+ .txidWalletIdEqualTo(key.txid, key.walletId)
+ .findFirstSync(),
+ key,
+ isar,
+ );
- ref.onDispose(() => watcher.dispose());
-
- return watcher;
-});
+ return watcher;
+ });
final pTransactionNote =
Provider.family<TransactionNote?, ({String walletId, String txid})>((
### lib/services/notifications_api.dart
@@ -38,7 +38,10 @@ abstract final class NotificationApi {
);
}
- static Future<void> init({bool initScheduled = false}) async {
+ static Future<void> init({
+ bool initScheduled = false,
+ bool requestPermissions = true,
+ }) async {
if (_initCalledCompleter == null) {
_initCalledCompleter = Completer<void>();
} else {
@@ -50,11 +53,19 @@ abstract final class NotificationApi {
}
const android = AndroidInitializationSettings('app_icon_alpha');
- const iOS = DarwinInitializationSettings();
+ final iOS = DarwinInitializationSettings(
+ requestAlertPermission: requestPermissions,
+ requestBadgePermission: requestPermissions,
+ requestSoundPermission: requestPermissions,
+ );
const linux = LinuxInitializationSettings(
defaultActionName: "temporary_stack_wallet",
);
- const macOS = DarwinInitializationSettings();
+ final macOS = DarwinInitializationSettings(
+ requestAlertPermission: requestPermissions,
+ requestBadgePermission: requestPermissions,
+ requestSoundPermission: requestPermissions,
+ );
final (windowsAppUserModelId, windowsGuid) = switch (AppConfig.appName) {
"Campfire" => (
"CypherStack.Campfire",
### lib/services/price.dart
@@ -61,6 +61,9 @@ class PriceAPI {
);
static String _lastUsedBaseCurrency = "";
+ // Recreated API instances write the same currency cache,
+ // so request ownership is shared.
+ static final Map<String, Object> _latestRequests = {};
static const Duration refreshIntervalDuration = Duration(
seconds: refreshInterval,
@@ -77,6 +80,7 @@ class PriceAPI {
Future<void> _updateCachedPrices(
Map<CryptoCurrency, ({Decimal value, double change24h})> data,
+ String baseCurrency,
) async {
final Map<String, dynamic> map = {};
@@ -91,15 +95,22 @@ class PriceAPI {
await DB.instance.put<dynamic>(
boxName: DB.boxNamePriceCache,
- key: 'cache',
+ key: _cacheKey(baseCurrency),
value: map,
);
}
- Map<CryptoCurrency, ({Decimal value, double change24h})> get _cachedPrices {
+ String _cacheKey(String baseCurrency) =>
+ 'cache_${baseCurrency.toLowerCase()}';
+
+ Map<CryptoCurrency, ({Decimal value, double change24h})> _cachedPrices(
+ String baseCurrency,
+ ) {
final map =
- DB.instance.get<dynamic>(boxName: DB.boxNamePriceCache, key: 'cache')
- as Map? ??
+ DB.instance.get<dynamic>(
+ boxName: DB.boxNamePriceCache,
+ key: _cacheKey(baseCurrency),
+ ) as Map? ??
{};
// init with 0
final Map<CryptoCurrency, ({Decimal value, double change24h})> result = {};
@@ -122,21 +133,25 @@ class PriceAPI {
Future<Map<CryptoCurrency, ({Decimal value, double change24h})>>
getPricesAnd24hChange({required String baseCurrency}) async {
+ await DB.instance.migrateLegacyPriceCache();
final now = DateTime.now();
if (_lastUsedBaseCurrency != baseCurrency ||
now.difference(_lastCalled) > refreshIntervalDuration) {
_lastCalled = now;
_lastUsedBaseCurrency = baseCurrency;
} else {
- return _cachedPrices;
+ return _cachedPrices(baseCurrency);
}
final externalCalls = Prefs.instance.externalCalls;
if ((!Util.isTestEnv && !externalCalls) ||
!(await Prefs.instance.isExternalCallsSet())) {
Logging.instance.i("User does not want to use external calls");
- return _cachedPrices;
+ return _cachedPrices(baseCurrency);
}
+ final cacheKey = _cacheKey(baseCurrency);
+ final request = Object();
+ _latestRequests[cacheKey] = request;
final Map<CryptoCurrency, ({Decimal value, double change24h})> result = {};
try {
final uri = Uri.parse(
@@ -188,17 +203,20 @@ class PriceAPI {
}
// update cache
- await _updateCachedPrices(result);
+ if (!identical(_latestRequests[cacheKey], request)) {
+ return _cachedPrices(baseCurrency);
+ }
+ await _updateCachedPrices(result, baseCurrency);
- return _cachedPrices;
+ return _cachedPrices(baseCurrency);
} catch (e, s) {
Logging.instance.e(
"getPricesAnd24hChange($baseCurrency): ",
error: e,
stackTrace: s,
);
// return previous cached values
- return _cachedPrices;
+ return _cachedPrices(baseCurrency);
}
}
### lib/services/price_service.dart
@@ -31,13 +31,14 @@ class PriceService extends ChangeNotifier {
final Duration updateInterval = const Duration(seconds: 60);
Timer? _timer;
+ bool _disposed = false;
final Map<CryptoCurrency, ({Decimal value, double change24h})> _cachedPrices =
{};
final Map<String, ({Decimal value, double change24h})> _cachedTokenPrices =
{};
- final _priceAPI = PriceAPI(HTTP());
+ final _priceAPI = PriceAPI(const HTTP());
({Decimal value, double change24h})? getPrice(CryptoCurrency coin) =>
_cachedPrices[coin];
@@ -48,9 +49,21 @@ class PriceService extends ChangeNotifier {
PriceService(this.baseTicker);
Future<void> updatePrice() async {
+ try {
+ await _updatePrice();
+ } catch (_) {
+ // Queries already in flight can fail when their database is closed.
+ // A disposed service has no caller left to receive a polling error.
+ if (!_disposed) rethrow;
+ }
+ }
+
+ Future<void> _updatePrice() async {
+ if (_disposed) return;
final priceMap = await _priceAPI.getPricesAnd24hChange(
baseCurrency: baseTicker,
);
+ if (_disposed) return;
bool shouldNotify = false;
for (final map in priceMap.entries) {
@@ -61,12 +74,14 @@ class PriceService extends ChangeNotifier {
}
final _tokenContractAddressesToCheck = await tokenContractAddressesToCheck;
+ if (_disposed) return;
if (_tokenContractAddressesToCheck.isNotEmpty) {
final tokenPriceMap = await _priceAPI.getPricesAnd24hChangeForEthTokens(
contractAddresses: _tokenContractAddressesToCheck,
baseCurrency: baseTicker,
);
+ if (_disposed) return;
for (final map in tokenPriceMap.entries) {
if (_cachedTokenPrices[map.key] != map.value) {
@@ -76,13 +91,17 @@ class PriceService extends ChangeNotifier {
}
}
- final _solTokenContractAddressesToCheck = await solTokenContractAddressesToCheck;
+ final _solTokenContractAddressesToCheck =
+ await solTokenContractAddressesToCheck;
+ if (_disposed) return;
if (_solTokenContractAddressesToCheck.isNotEmpty) {
- final solTokenPriceMap = await _priceAPI.getPricesAnd24hChangeForSolTokens(
- contractAddresses: _solTokenContractAddressesToCheck,
- baseCurrency: baseTicker,
- );
+ final solTokenPriceMap = await _priceAPI
+ .getPricesAnd24hChangeForSolTokens(
+ contractAddresses: _solTokenContractAddressesToCheck,
+ baseCurrency: baseTicker,
+ );
+ if (_disposed) return;
for (final map in solTokenPriceMap.entries) {
if (_cachedTokenPrices[map.key] != map.value) {
@@ -103,6 +122,7 @@ class PriceService extends ChangeNotifier {
}
void start(bool rightAway) {
+ if (_disposed) return;
if (rightAway) {
updatePrice();
}
@@ -114,6 +134,7 @@ class PriceService extends ChangeNotifier {
@override
void dispose() {
+ _disposed = true;
cancel();
super.dispose();
}
### lib/services/solana/solana_token_api.dart
@@ -144,13 +144,11 @@ class SolanaTokenAPI {
try {
_checkClient();
- const splTokenProgramId = 'TokenkegQfeZyiNwAJsyFbPVwwQQfg5bgUiqhStM5QA';
-
final result = await _rpcClient!.getTokenAccountsByOwner(
ownerAddress,
mint != null
? TokenAccountsFilter.byMint(mint)
- : TokenAccountsFilter.byProgramId(splTokenProgramId),
+ : TokenAccountsFilter.byProgramId(TokenProgram.programId),
encoding: Encoding.jsonParsed,
);
@@ -274,7 +272,7 @@ class SolanaTokenAPI {
_checkClient();
// Return placeholder data.
- //
+ //
// TODO: Implement actual RPC call using proper client methods.
return SolanaTokenApiResponse<TokenAccountInfo>(
value: TokenAccountInfo(
@@ -332,9 +330,7 @@ class SolanaTokenAPI {
}
Future<SolanaTokenApiResponse<Map<String, dynamic>?>>
- fetchTokenMetadataByMint(
- String mintAddress,
- ) async {
+ fetchTokenMetadataByMint(String mintAddress) async {
try {
_checkClient();
@@ -351,14 +347,10 @@ class SolanaTokenAPI {
// Until then, return null to allow users to enter custom token details.
// Metadata PDA derivation not yet implemented
- return SolanaTokenApiResponse<Map<String, dynamic>?>(
- value: null,
- );
+ return SolanaTokenApiResponse<Map<String, dynamic>?>(value: null);
} on Exception {
// On error, return null to allow user to manually enter token details
- return SolanaTokenApiResponse<Map<String, dynamic>?>(
- value: null,
- );
+ return SolanaTokenApiResponse<Map<String, dynamic>?>(value: null);
}
}
@@ -408,16 +400,10 @@ class SolanaTokenAPI {
final owner = response.value!.owner;
- // Rough check which program owns this mint.
- //
- // For now all we need to know ius if it's SPL or newer.
- // TODO [prio=low]: Fix via program metadata parsing or similar.
- if (owner == 'TokenkegQfeZyiNwAJsyFbPVwwQQfg5bgUiqhStM5QA') {
+ if (owner == TokenProgram.programId) {
return 'spl';
- } else {
- if (owner.startsWith('Token')) {
- return 'token2022';
- }
+ } else if (owner == Token2022Program.programId) {
+ return 'token2022';
}
return null;
### lib/utilities/amount/fee_rate_formatter.dart
@@ -0,0 +1,15 @@
+/// Formats an approximate atomic-unit fee per virtual byte, rounded to tenths.
+/// Integer arithmetic preserves precision even for fees beyond double's range.
+String? formatApproximateFeeRate(BigInt? rawFee, int? virtualSize) {
+ if (rawFee == null ||
+ rawFee.isNegative ||
+ virtualSize == null ||
+ virtualSize <= 0) {
+ return null;
+ }
+ final size = BigInt.from(virtualSize);
+ final scaled = rawFee * BigInt.from(10);
+ var tenths = scaled ~/ size;
+ if ((scaled % size) * BigInt.two >= size) tenths += BigInt.one;
+ return '~${tenths ~/ BigInt.from(10)}.${tenths % BigInt.from(10)}';
+}
### lib/wallets/isar/providers/all_wallets_info_provider.dart
@@ -16,7 +16,7 @@ final pAllWalletsInfo = Provider((ref) {
final results = ref.watch(_pAllWalletsInfo.select((value) => value.value));
if (duress) {
- results.retainWhere((e) => e.isDuressVisible);
+ return results.where((e) => e.isDuressVisible).toList();
}
return results;
@@ -46,51 +46,41 @@ final pAllWalletsInfoByCoin = Provider((ref) {
return results;
});
-_WalletInfoWatcher? _globalInstance;
-
final _pAllWalletsInfo = ChangeNotifierProvider((ref) {
- if (_globalInstance == null) {
- final isar = ref.watch(mainDBProvider).isar;
-
- _globalInstance = _WalletInfoWatcher(
- isar.walletInfo
- .where()
- .filter()
- .anyOf<String, CryptoCurrency>(
- AppConfig.coins.map((e) => e.identifier),
- (q, element) => q.coinNameMatches(element),
- )
- .findAllSync(),
- isar,
- );
- }
-
- return _globalInstance!;
+ final isar = ref.watch(mainDBProvider).isar;
+
+ return _WalletInfoWatcher(
+ isar.walletInfo
+ .where()
+ .filter()
+ .anyOf<String, CryptoCurrency>(
+ AppConfig.coins.map((e) => e.identifier),
+ (q, element) => q.coinNameMatches(element),
+ )
+ .findAllSync(),
+ isar,
+ );
});
class _WalletInfoWatcher extends ChangeNotifier {
- late final StreamSubscription<void> _streamSubscription;
+ late final StreamSubscription<List<WalletInfo>> _streamSubscription;
List<WalletInfo> _value;
List<WalletInfo> get value => _value;
_WalletInfoWatcher(this._value, Isar isar) {
_streamSubscription = isar.walletInfo
- .watchLazy(fireImmediately: true)
- .listen((event) {
- isar.walletInfo
- .where()
- .filter()
- .anyOf<String, CryptoCurrency>(
- AppConfig.coins.map((e) => e.identifier),
- (q, element) => q.coinNameMatches(element),
- )
- .findAll()
- .then((value) {
- _value = value;
- notifyListeners();
- });
+ .where()
+ .filter()
+ .anyOf<String, CryptoCurrency>(
+ AppConfig.coins.map((e) => e.identifier),
+ (q, element) => q.coinNameMatches(element),
+ )
+ .watch(fireImmediately: true)
+ .listen((value) {
+ _value = value;
+ notifyListeners();
});
}
### lib/wallets/isar/providers/eth/token_balance_provider.dart
@@ -7,46 +7,47 @@ import '../../../../providers/db/main_db_provider.dart';
import '../../models/token_wallet_info.dart';
import '../util/watcher.dart';
-final _twiProvider = ChangeNotifierProvider.family<
- Watcher,
- ({String walletId, String contractAddress})
->((ref, data) {
- final isar = ref.watch(mainDBProvider).isar;
+final _twiProvider =
+ ChangeNotifierProvider.family<
+ Watcher,
+ ({String walletId, String contractAddress})
+ >((ref, data) {
+ final isar = ref.watch(mainDBProvider).isar;
- final collection = isar.tokenWalletInfo;
+ final collection = isar.tokenWalletInfo;
- TokenWalletInfo? initial =
- collection
+ TokenWalletInfo? initial = collection
.where()
.walletIdTokenAddressEqualTo(data.walletId, data.contractAddress)
.findFirstSync();
- if (initial == null) {
- initial = TokenWalletInfo(
- walletId: data.walletId,
- tokenAddress: data.contractAddress,
- tokenFractionDigits:
- isar.ethContracts.getByAddressSync(data.contractAddress)?.decimals ??
- 2,
- );
+ if (initial == null) {
+ initial = TokenWalletInfo(
+ walletId: data.walletId,
+ tokenAddress: data.contractAddress,
+ tokenFractionDigits:
+ isar.ethContracts
+ .getByAddressSync(data.contractAddress)
+ ?.decimals ??
+ 2,
+ );
- isar.writeTxnSync(() => isar.tokenWalletInfo.putSync(initial!));
- }
+ isar.writeTxnSync(() => isar.tokenWalletInfo.putSync(initial!));
+ }
- final watcher = Watcher(initial, collection: collection);
+ final watcher = Watcher(initial, collection: collection);
- ref.onDispose(() => watcher.dispose());
-
- return watcher;
-});
+ return watcher;
+ });
-final pTokenWalletInfo = Provider.family<
- TokenWalletInfo,
- ({String walletId, String contractAddress})
->((ref, data) {
- return ref.watch(_twiProvider(data).select((value) => value.value))
- as TokenWalletInfo;
-});
+final pTokenWalletInfo =
+ Provider.family<
+ TokenWalletInfo,
+ ({String walletId, String contractAddress})
+ >((ref, data) {
+ return ref.watch(_twiProvider(data).select((value) => value.value))
+ as TokenWalletInfo;
+ });
final pTokenBalance =
Provider.family<Balance, ({String walletId, String contractAddress})>((
### lib/wallets/isar/providers/favourite_wallets_provider.dart
@@ -61,8 +61,6 @@ final _wiProvider = ChangeNotifierProvider.family<_Watcher, bool>((
isar,
);
- ref.onDispose(() => watcher.dispose());
-
return watcher;
});
@@ -75,7 +73,7 @@ final pFavouriteWalletInfos = Provider.family<List<WalletInfo>, bool>((
final infos = ref.watch(_wiProvider(isFavourite)).value;
if (isDuress) {
- infos.retainWhere((e) => e.isDuressVisible);
+ return infos.where((e) => e.isDuressVisible).toList();
}
return infos;
### lib/wallets/isar/providers/solana/sol_token_balance_provider.dart
@@ -16,70 +16,69 @@ import '../util/watcher.dart';
/// final info = ref.watch(
/// pSolanaTokenWalletInfo((walletId: 'wallet1', tokenMint: 'EPjFWaJUwYUoRwzwkH4H8gNB7zHW9tLT6NCKB8S4yh6h'))
/// );
-final _wstwiProvider = ChangeNotifierProvider.family<
- Watcher,
- ({String walletId, String tokenMint})
->((ref, data) {
- final isar = ref.watch(mainDBProvider).isar;
-
- final collection = isar.walletSolanaTokenInfo;
-
- Logging.instance.i(
- "pSolanaTokenBalance: Looking up WalletSolanaTokenInfo for walletId=${data.walletId}, tokenMint=${data.tokenMint}",
- );
-
- WalletSolanaTokenInfo? initial = collection
- .where()
- .walletIdTokenAddressEqualTo(data.walletId, data.tokenMint)
- .findFirstSync();
-
- if (initial == null) {
- Logging.instance.i(
- "pSolanaTokenBalance: Creating new WalletSolanaTokenInfo entry",
- );
-
- // Create initial entry if not found.
- final solContract =
- isar.solContracts.getByAddressSync(data.tokenMint);
-
- initial = WalletSolanaTokenInfo(
- walletId: data.walletId,
- tokenAddress: data.tokenMint,
- tokenFractionDigits: solContract?.decimals ?? 6,
- );
-
- isar.writeTxnSync(() => isar.walletSolanaTokenInfo.putSync(initial!));
-
- // After insert, fetch the object again to get the assigned ID.
- initial = collection
- .where()
- .walletIdTokenAddressEqualTo(data.walletId, data.tokenMint)
- .findFirstSync()!;
-
- Logging.instance.i(
- "pSolanaTokenBalance: Created entry with ID=${initial.id}, balance=${initial.getCachedBalance().total}",
- );
- } else {
- Logging.instance.i(
- "pSolanaTokenBalance: Found existing entry with ID=${initial.id}, cachedBalance=${initial.getCachedBalance().total}",
- );
- }
-
- final watcher = Watcher(initial, collection: collection);
-
- ref.onDispose(() => watcher.dispose());
-
- return watcher;
-});
+final _wstwiProvider =
+ ChangeNotifierProvider.family<
+ Watcher,
+ ({String walletId, String tokenMint})
+ >((ref, data) {
+ final isar = ref.watch(mainDBProvider).isar;
+
+ final collection = isar.walletSolanaTokenInfo;
+
+ Logging.instance.i(
+ "pSolanaTokenBalance: Looking up WalletSolanaTokenInfo for walletId=${data.walletId}, tokenMint=${data.tokenMint}",
+ );
+
+ WalletSolanaTokenInfo? initial = collection
+ .where()
+ .walletIdTokenAddressEqualTo(data.walletId, data.tokenMint)
+ .findFirstSync();
+
+ if (initial == null) {
+ Logging.instance.i(
+ "pSolanaTokenBalance: Creating new WalletSolanaTokenInfo entry",
+ );
+
+ // Create initial entry if not found.
+ final solContract = isar.solContracts.getByAddressSync(data.tokenMint);
+
+ initial = WalletSolanaTokenInfo(
+ walletId: data.walletId,
+ tokenAddress: data.tokenMint,
+ tokenFractionDigits: solContract?.decimals ?? 6,
+ );
+
+ isar.writeTxnSync(() => isar.walletSolanaTokenInfo.putSync(initial!));
+
+ // After insert, fetch the object again to get the assigned ID.
+ initial = collection
+ .where()
+ .walletIdTokenAddressEqualTo(data.walletId, data.tokenMint)
+ .findFirstSync()!;
+
+ Logging.instance.i(
+ "pSolanaTokenBalance: Created entry with ID=${initial.id}, balance=${initial.getCachedBalance().total}",
+ );
+ } else {
+ Logging.instance.i(
+ "pSolanaTokenBalance: Found existing entry with ID=${initial.id}, cachedBalance=${initial.getCachedBalance().total}",
+ );
+ }
+
+ final watcher = Watcher(initial, collection: collection);
+
+ return watcher;
+ });
/// Provider for Solana token wallet info from the database.
-final pSolanaTokenWalletInfo = Provider.family<
- WalletSolanaTokenInfo,
- ({String walletId, String tokenMint})
->((ref, data) {
- return ref.watch(_wstwiProvider(data).select((value) => value.value))
- as WalletSolanaTokenInfo;
-});
+final pSolanaTokenWalletInfo =
+ Provider.family<
+ WalletSolanaTokenInfo,
+ ({String walletId, String tokenMint})
+ >((ref, data) {
+ return ref.watch(_wstwiProvider(data).select((value) => value.value))
+ as WalletSolanaTokenInfo;
+ });
/// Provider for Solana token balance from the database.
///
@@ -90,19 +89,20 @@ final pSolanaTokenWalletInfo = Provider.family<
/// final balance = ref.watch(
/// pSolanaTokenBalance((walletId: 'wallet1', tokenMint: 'EPjFWaJUwYUoRwzwkH4H8gNB7zHW9tLT6NCKB8S4yh6h'))
/// );
-final pSolanaTokenBalance = Provider.family<
- Balance,
- ({String walletId, String tokenMint})
->((ref, data) {
- final balance = ref.watch(
- _wstwiProvider(data).select(
- (value) => (value.value as WalletSolanaTokenInfo).getCachedBalance(),
- ),
- );
-
- Logging.instance.i(
- "pSolanaTokenBalance: Returning balance=${balance.total} for walletId=${data.walletId}, tokenMint=${data.tokenMint}",
- );
-
- return balance;
-});
+final pSolanaTokenBalance =
+ Provider.family<Balance, ({String walletId, String tokenMint})>((
+ ref,
+ data,
+ ) {
+ final balance = ref.watch(
+ _wstwiProvider(data).select(
+ (value) => (value.value as WalletSolanaTokenInfo).getCachedBalance(),
+ ),
+ );
+
+ Logging.instance.i(
+ "pSolanaTokenBalance: Returning balance=${balance.total} for walletId=${data.walletId}, tokenMint=${data.tokenMint}",
+ );
+
+ return balance;
+ });
### lib/wallets/isar/providers/wallet_info_provider.dart
@@ -18,8 +18,6 @@ final _wiProvider = ChangeNotifierProvider.family<Watcher, String>((
collection: collection,
);
- ref.onDispose(() => watcher.dispose());
-
return watcher;
});
@@ -35,9 +33,8 @@ final pWalletCoin = Provider.family<CryptoCurrency, String>((ref, walletId) {
final pWalletBalance = Provider.family<Balance, String>((ref, walletId) {
return ref.watch(
- _wiProvider(
- walletId,
- ).select((value) => (value.value as WalletInfo).cachedBalance),
+ _wiProvider(walletId)
+ .select((value) => (value.value as WalletInfo).cachedBalance),
);
});
@@ -46,9 +43,8 @@ final pWalletBalanceSecondary = Provider.family<Balance, String>((
walletId,
) {
return ref.watch(
- _wiProvider(
- walletId,
- ).select((value) => (value.value as WalletInfo).cachedBalanceSecondary),
+ _wiProvider(walletId)
+ .select((value) => (value.value as WalletInfo).cachedBalanceSecondary),
);
});
@@ -57,25 +53,22 @@ final pWalletBalanceTertiary = Provider.family<Balance, String>((
walletId,
) {
return ref.watch(
- _wiProvider(
- walletId,
- ).select((value) => (value.value as WalletInfo).cachedBalanceTertiary),
+ _wiProvider(walletId)
+ .select((value) => (value.value as WalletInfo).cachedBalanceTertiary),
);
});
final pWalletChainHeight = Provider.family<int, String>((ref, walletId) {
return ref.watch(
- _wiProvider(
- walletId,
- ).select((value) => (value.value as WalletInfo).cachedChainHeight),
+ _wiProvider(walletId)
+ .select((value) => (value.value as WalletInfo).cachedChainHeight),
);
});
final pWalletIsFavourite = Provider.family<bool, String>((ref, walletId) {
return ref.watch(
- _wiProvider(
- walletId,
- ).select((value) => (value.value as WalletInfo).isFavourite),
+ _wiProvider(walletId)
+ .select((value) => (value.value as WalletInfo).isFavourite),
);
});
@@ -90,9 +83,8 @@ final pWalletReceivingAddress = Provider.family<String, String>((
walletId,
) {
return ref.watch(
- _wiProvider(
- walletId,
- ).select((value) => (value.value as WalletInfo).cachedReceivingAddress),
+ _wiProvider(walletId)
+ .select((value) => (value.value as WalletInfo).cachedReceivingAddress),
);
});
### lib/wallets/wallet/impl/epiccash_wallet.dart
@@ -641,24 +641,29 @@ class EpiccashWallet extends Bip39Wallet {
}
}
- /// Only index 0 is currently used in stack wallet.
- Future<Address> _generateAndStoreReceivingAddressForIndex(int index) async {
+ /// Query the open native wallet, independently of the cached address.
+ Future<String> getNativeReceivingAddress() async {
if (_wallet == null) {
throw Exception('Wallet not opened. Call open() first.');
}
+ final epicBoxConfig = await getEpicBoxConfig();
+ return libEpic.getAddressInfo(
+ wallet: _wallet!,
+ index: 0,
+ epicboxConfig: epicBoxConfig.toString(),
+ );
+ }
+
+ /// Only index 0 is currently used in stack wallet.
+ Future<Address> _generateAndStoreReceivingAddressForIndex(int index) async {
// Since only 0 is a valid index in stack wallet at this time, lets just
// throw is not zero
if (index != 0) {
throw Exception("Invalid/unexpected address index used");
}
- final epicBoxConfig = await getEpicBoxConfig();
- final walletAddress = await libEpic.getAddressInfo(
- wallet: _wallet!,
- index: index,
- epicboxConfig: epicBoxConfig.toString(),
- );
+ final walletAddress = await getNativeReceivingAddress();
Logging.instance.d("WALLET_ADDRESS_IS $walletAddress");
### lib/wallets/wallet/impl/firo_wallet.dart
@@ -881,6 +881,16 @@ class FiroWallet<T extends ElectrumXCurrencyInterface> extends Bip39HDWallet<T>
electrumXClient,
cryptoCurrency.network,
);
+ // Handle errors as they happen while address discovery runs in
+ // parallel; the outcome is checked once discovery completes. A cache
+ // reset cancels these operations without waiting for RPCs.
+ final sparkCacheResult =
+ Future.wait([sparkUsedCoinTagsFuture, ...sparkAnonSetFutures])
+ .then<AsyncError?>(
+ (_) => null,
+ onError: (Object error, StackTrace stack) =>
+ AsyncError(error, stack),
+ );
// receiving addresses
Logging.instance.i("checking receiving addresses...");
@@ -924,7 +934,11 @@ class FiroWallet<T extends ElectrumXCurrencyInterface> extends Bip39HDWallet<T>
await Future.wait([updateTransactions(), updateUTXOs()]);
- await Future.wait([sparkUsedCoinTagsFuture, ...sparkAnonSetFutures]);
+ final cacheError = await sparkCacheResult;
+ if (cacheError != null &&
+ cacheError.error is! FiroCacheResetException) {
+ Error.throwWithStackTrace(cacheError.error, cacheError.stackTrace);
+ }
await recoverSparkWallet(latestSparkCoinId: latestSparkCoinId);
});
### lib/wallets/wallet/impl/sub_wallets/solana_token_wallet.dart
@@ -118,6 +118,7 @@ class SolanaTokenWallet extends Wallet {
);
}
+ final String tokenProgramId;
try {
final accountInfo = await rpcClient.getAccountInfo(
senderTokenAccount,
@@ -128,26 +129,27 @@ class SolanaTokenWallet extends Wallet {
"Sender token account $senderTokenAccount not found on-chain",
);
}
+ // Use the validated sender's program for every token instruction and ATA.
+ tokenProgramId = accountInfo.value!.owner;
+ if (tokenProgramId != TokenProgram.programId &&
+ tokenProgramId != Token2022Program.programId) {
+ throw Exception("Unsupported token program: $tokenProgramId");
+ }
} catch (e) {
throw Exception("Failed to validate sender token account: $e");
}
await rpcClient.getLatestBlockhash();
- final recipientTokenAccount = await _findOrDeriveRecipientTokenAccount(
- recipientAddress: recipientAddress,
+ // Derive the destination locally. A token account reported by the node
+ // could belong to any holder of this mint, so it must never choose
+ // where the transfer goes.
+ final recipientTokenAccount = await _deriveAtaAddress(
+ ownerAddress: recipientAddress,
mint: tokenMint,
- rpcClient: rpcClient,
+ tokenProgramId: tokenProgramId,
);
- if (recipientTokenAccount.isEmpty) {
- throw Exception(
- "Cannot determine recipient token account for mint $tokenMint. "
- "Recipient may not have a token account for this mint. "
- "Please ensure the recipient has initialized an Associated Token Account (ATA) first.",
- );
- }
-
final senderTokenAccountKey = Ed25519HDPublicKey.fromBase58(
senderTokenAccount,
);
@@ -156,32 +158,6 @@ class SolanaTokenWallet extends Wallet {
);
final mintPubkey = Ed25519HDPublicKey.fromBase58(tokenMint);
- String tokenProgramId;
- try {
- final mintInfo = await rpcClient.getAccountInfo(
- tokenMint,
- encoding: Encoding.jsonParsed,
- );
- if (mintInfo.value != null) {
- tokenProgramId = mintInfo.value!.owner;
- Logging.instance.i(
- "$runtimeType prepareSend: Token program owner = $tokenProgramId for mint $tokenMint",
- );
- } else {
- // Fallback to SPL Token.
- tokenProgramId = 'TokenkegQfeZyiNwAJsyFbPVwwQQfg5bgUiqhStM5QA';
- Logging.instance.w(
- "$runtimeType prepareSend: Could not query mint owner, using SPL Token",
- );
- }
- } catch (e) {
- // Fallback to SPL Token on error.
- tokenProgramId = 'TokenkegQfeZyiNwAJsyFbPVwwQQfg5bgUiqhStM5QA';
- Logging.instance.w(
- "$runtimeType prepareSend: Error querying mint owner: $e, using SPL Token",
- );
- }
-
final TokenProgramType tokenProgram =
tokenProgramId == Token2022Program.programId
? TokenProgramType.token2022Program
@@ -200,6 +176,7 @@ class SolanaTokenWallet extends Wallet {
address: recipientTokenAccountKey,
owner: Ed25519HDPublicKey.fromBase58(recipientAddress),
mint: mintPubkey,
+ tokenProgramId: Ed25519HDPublicKey.fromBase58(tokenProgramId),
);
} else {
try {
@@ -305,10 +282,22 @@ class SolanaTokenWallet extends Wallet {
);
}
- final recipientTokenAccount = await _findOrDeriveRecipientTokenAccount(
- recipientAddress: txData.recipients!.first.address,
+ // The transfer carries the validated token program. Do not depend on
+ // its position among the instructions.
+ final tokenProgramId = instructions
+ .map((instruction) => instruction.programId.toBase58())
+ .firstWhere(
+ (programId) =>
+ programId == TokenProgram.programId ||
+ programId == Token2022Program.programId,
+ orElse: () => throw Exception(
+ "Token transaction missing a token program instruction.",
+ ),
+ );
+ final recipientTokenAccount = await _deriveAtaAddress(
+ ownerAddress: txData.recipients!.first.address,
mint: tokenMint,
- rpcClient: rpcClient,
+ tokenProgramId: tokenProgramId,
);
// Create message.
@@ -357,7 +346,7 @@ class SolanaTokenWallet extends Wallet {
];
// Determine if this is a self-transfer.
- final isToSelf = senderTokenAccount == recipientTokenAccount;
+ final isToSelf = txData.recipients!.first.address == walletAddress;
// Create the temporary transaction record.
final tempTx = TransactionV2(
@@ -776,71 +765,16 @@ class SolanaTokenWallet extends Wallet {
}
}
- Future<String> _findOrDeriveRecipientTokenAccount({
- required String recipientAddress,
- required String mint,
- required RpcClient rpcClient,
- }) async {
- // First, try to find an existing token account
- final existingAccount = await _findTokenAccount(
- ownerAddress: recipientAddress,
- mint: mint,
- rpcClient: rpcClient,
- );
-
- if (existingAccount != null) {
- Logging.instance.i(
- "$runtimeType Found existing token account for recipient: $existingAccount",
- );
- return existingAccount;
- }
-
- // If no existing account found, try to derive the ATA
- Logging.instance.i(
- "$runtimeType No existing token account found, deriving ATA for recipient",
- );
-
- return await _deriveAtaAddress(
- ownerAddress: recipientAddress,
- mint: mint,
- rpcClient: rpcClient,
- );
- }
-
Future<String> _deriveAtaAddress({
required String ownerAddress,
required String mint,
- required RpcClient rpcClient,
+ required String tokenProgramId,
}) async {
final ownerPubkey = Ed25519HDPublicKey.fromBase58(ownerAddress);
final mintPubkey = Ed25519HDPublicKey.fromBase58(mint);
- final tokenApi = SolanaTokenAPI();
- tokenApi.initializeRpcClient(rpcClient);
-
- String tokenProgramId;
- try {
- final mintInfo = await rpcClient.getAccountInfo(
- mint,
- encoding: Encoding.jsonParsed,
- );
- if (mintInfo.value != null) {
- tokenProgramId = mintInfo.value!.owner;
- } else {
- tokenProgramId = 'TokenkegQfeZyiNwAJsyFbPVwwQQfg5bgUiqhStM5QA';
- }
- } catch (e) {
- tokenProgramId = 'TokenkegQfeZyiNwAJsyFbPVwwQQfg5bgUiqhStM5QA';
- }
-
final tokenProgramPubkey = Ed25519HDPublicKey.fromBase58(tokenProgramId);
- const associatedTokenProgramId =
- 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
- final associatedTokenProgramPubkey = Ed25519HDPublicKey.fromBase58(
- associatedTokenProgramId,
- );
-
final seeds = [
ownerPubkey.bytes,
tokenProgramPubkey.bytes,
@@ -849,7 +783,7 @@ class SolanaTokenWallet extends Wallet {
final ataAddress = await Ed25519HDPublicKey.findProgramAddress(
seeds: seeds,
- programId: associatedTokenProgramPubkey,
+ programId: AssociatedTokenAccountProgram.id,
);
final ataBase58 = ataAddress.toBase58();
@@ -910,37 +844,37 @@ class SolanaTokenWallet extends Wallet {
final startTime = DateTime.now();
while (true) {
+ SignatureStatus? txStatus;
try {
final status = await rpcClient.getSignatureStatuses([
signature,
], searchTransactionHistory: true);
if (status.value.isNotEmpty) {
- final txStatus = status.value.first;
-
- // Check if transaction failed
- if (txStatus?.err != null) {
- Logging.instance.e(
- "$runtimeType Transaction failed: ${txStatus?.err}",
- );
- return false;
- }
-
- // Check if transaction confirmed
- if (txStatus?.confirmationStatus == Commitment.confirmed ||
- txStatus?.confirmationStatus == Commitment.finalized) {
- Logging.instance.i(
- "$runtimeType Transaction confirmed: $signature",
- );
- return true;
- }
+ txStatus = status.value.first;
}
} catch (e) {
Logging.instance.w(
"$runtimeType Error checking transaction confirmation: $e",
);
}
+ if (txStatus?.err != null) {
+ await mainDB.isar.writeTxn(
+ () => mainDB.isar.transactionV2s
+ .where()
+ .txidWalletIdEqualTo(signature, walletId)
+ .deleteAll(),
+ );
+ throw Exception("Transaction failed: ${txStatus!.err}");
+ }
+
+ if (txStatus?.confirmationStatus == Commitment.confirmed ||
+ txStatus?.confirmationStatus == Commitment.finalized) {
+ Logging.instance.i("$runtimeType Transaction confirmed: $signature");
+ return true;
+ }
+
// Check timeout
final elapsed = DateTime.now().difference(startTime).inSeconds;
if (elapsed > maxWaitSeconds) {
### lib/wallets/wallet/intermediate/bip39_hd_wallet.dart
@@ -20,11 +20,11 @@ abstract class Bip39HDWallet<T extends Bip39HDCurrency> extends Bip39Wallet<T>
with MultiAddressInterface<T>, ViewOnlyOptionInterface<T> {
Bip39HDWallet(super.cryptoCurrency);
- Set<AddressType> get supportedAddressTypes =>
- cryptoCurrency.supportedDerivationPathTypes
- .where((e) => e != DerivePathType.bip49)
- .map((e) => e.getAddressType())
- .toSet();
+ Set<AddressType> get supportedAddressTypes => cryptoCurrency
+ .supportedDerivationPathTypes
+ .where((e) => e != DerivePathType.bip49)
+ .map((e) => e.getAddressType())
+ .toSet();
Future<coinlib.HDPrivateKey> getRootHDNode() async {
final seed = bip39.mnemonicToSeed(
@@ -65,14 +65,14 @@ abstract class Bip39HDWallet<T extends Bip39HDCurrency> extends Bip39Wallet<T>
);
}
- final current =
- await mainDB.isar.addresses
- .where()
- .walletIdEqualTo(walletId)
- .filter()
- .typeEqualTo(derivePathType.getAddressType())
- .sortByDerivationIndexDesc()
- .findFirst();
+ final current = await mainDB.isar.addresses
+ .where()
+ .walletIdEqualTo(walletId)
+ .filter()
+ .typeEqualTo(derivePathType.getAddressType())
+ .subTypeEqualTo(AddressSubType.receiving)
+ .sortByDerivationIndexDesc()
+ .findFirst();
final index = current == null ? 0 : current.derivationIndex + 1;
const chain = 0; // receiving address
final address = await _generateAddress(
@@ -294,8 +294,9 @@ abstract class Bip39HDWallet<T extends Bip39HDCurrency> extends Bip39Wallet<T>
value: convertAddressString(data.address.toString()),
publicKey: keys.publicKey.data,
derivationIndex: index,
- derivationPath:
- isViewOnly ? null : (DerivationPath()..value = derivationPath),
+ derivationPath: isViewOnly
+ ? null
+ : (DerivationPath()..value = derivationPath),
type: data.addressType,
subType: subType,
);
### lib/wallets/wallet/intermediate/lib_monero_wallet.dart
@@ -731,6 +731,7 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
@override
Future<void> exit() async {
+ await super.exit();
Logging.instance.i("exit called on monero $walletId!");
if (wallet != null) {
csMonero.stopAutoSaving(wallet!);
### lib/wallets/wallet/intermediate/lib_salvium_wallet.dart
@@ -726,6 +726,7 @@ abstract class LibSalviumWallet<T extends CryptonoteCurrency>
@override
Future<void> exit() async {
+ await super.exit();
Logging.instance.i("exit called on $walletId");
if (wallet != null) {
csSalvium.stopAutoSaving(wallet!);
### lib/wallets/wallet/intermediate/lib_wownero_wallet.dart
@@ -749,6 +749,7 @@ abstract class LibWowneroWallet<T extends CryptonoteCurrency>
@override
Future<void> exit() async {
+ await super.exit();
Logging.instance.i("exit called on $wallet!");
if (wallet != null) {
csWownero.stopAutoSaving(wallet!);
### lib/wallets/wallet/wallet.dart
@@ -455,6 +455,7 @@ abstract class Wallet<T extends CryptoCurrency> {
}
final bool hasNetwork = await pingCheck();
+ if (!shouldAutoSync) return;
if (_isConnected != hasNetwork) {
final NodeConnectionStatus status = hasNetwork
@@ -549,11 +550,16 @@ abstract class Wallet<T extends CryptoCurrency> {
}
bool doNotFireRefreshEvents = false;
+ Future<void>? _refreshFuture;
// Should fire events
- Future<void> refresh() async {
+ Future<void> refresh() {
+ final activeRefresh = _refreshFuture;
+ if (activeRefresh != null) return activeRefresh;
+ if (refreshMutex.isLocked) return Future<void>.value();
+
final refreshCompleter = Completer<void>();
- final future = refreshCompleter.future.then(
+ final future = refreshCompleter.future.then<void>(
(_) {
if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
@@ -564,7 +570,6 @@ abstract class Wallet<T extends CryptoCurrency> {
),
);
}
- ensurePeriodicRefreshTimer();
},
onError: (Object e, StackTrace s) {
if (!doNotFireRefreshEvents) {
@@ -591,9 +596,13 @@ abstract class Wallet<T extends CryptoCurrency> {
},
);
+ _refreshFuture = future.whenComplete(() {
+ _refreshFuture = null;
+ ensurePeriodicRefreshTimer();
+ });
unawaited(_refresh(refreshCompleter));
- return future;
+ return _refreshFuture!;
}
@protected
@@ -619,22 +628,15 @@ abstract class Wallet<T extends CryptoCurrency> {
// Should fire events
Future<void> _refresh(Completer<void> completer) async {
- // Awaiting this lock could be dangerous.
- // Since refresh is periodic (generally)
- if (refreshMutex.isLocked) {
- return;
- }
final start = DateTime.now();
- final viewOnly =
- this is ViewOnlyOptionInterface &&
- (this as ViewOnlyOptionInterface).isViewOnly;
-
try {
- // this acquire should be almost instant due to above check.
- // Slight possibility of race but should be irrelevant
await refreshMutex.acquire();
+ final viewOnly =
+ this is ViewOnlyOptionInterface &&
+ (this as ViewOnlyOptionInterface).isViewOnly;
+
if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
WalletSyncStatusChangedEvent(
@@ -712,9 +714,8 @@ abstract class Wallet<T extends CryptoCurrency> {
_fireRefreshPercentChange(0.6);
final utxosRefreshFuture = updateUTXOs();
_fireRefreshPercentChange(0.65);
- await utxosRefreshFuture;
+ await Future.wait([fetchFuture, utxosRefreshFuture]);
_fireRefreshPercentChange(0.70);
- await fetchFuture;
}
// TODO: [prio=low] handle this differently. Extra modification of this file for coin specific functionality should be avoided.
@@ -749,15 +750,14 @@ abstract class Wallet<T extends CryptoCurrency> {
Logging.instance.i(
"Refresh for "
- "$walletId::${info.name}: ${DateTime.now().difference(start)}",
+ "$walletId: ${DateTime.now().difference(start)}",
);
}
}
Future<void> exit() async {
Logging.instance.i("exit called on $walletId");
- _periodicRefreshTimer?.cancel();
- _networkAliveTimer?.cancel();
+ shouldAutoSync = false;
// If the syncing pref is currentWalletOnly or selectedWalletsAtStartup (and
// this wallet isn't in walletIdsSyncOnStartup), then we close subscriptions.
@@ -777,9 +777,9 @@ abstract class Wallet<T extends CryptoCurrency> {
final wallet = mainDB.isar.walletInfo
.where()
.walletIdEqualTo(id)
- .findFirstSync()!;
+ .findFirstSync();
- if (wallet.coin == cryptoCurrency) {
+ if (wallet?.coin == cryptoCurrency) {
walletIds.add(id);
}
}
### lib/wallets/wallet/wallet_mixin_interfaces/spark_interface.dart
@@ -1531,10 +1531,32 @@ mixin SparkInterface<T extends ElectrumXCurrencyInterface>
return current + increment;
}
+ /// Restarts allowed for one refresh while shared cache resets retire it.
+ static const int maxSparkRefreshResetRetries = 5;
+
// Linearly make calls so there is less chance of timing out or otherwise
// breaking
Future<void> refreshSparkData(
(double startingPercent, double endingPercent)? refreshProgressRange,
+ ) async {
+ for (var retries = 0; ; retries++) {
+ try {
+ await _refreshSparkData(refreshProgressRange);
+ return;
+ } on FiroCacheResetException {
+ // A shared local reset retired this batch, not the node connection.
+ // Restart against the new epoch; cache reads await the local reset.
+ if (retries >= maxSparkRefreshResetRetries) rethrow;
+ Logging.instance.d(
+ 'Retrying Spark refresh after a shared cache reset '
+ '(${retries + 1}/$maxSparkRefreshResetRetries)',
+ );
+ }
+ }
+ }
+
+ Future<void> _refreshSparkData(
+ (double startingPercent, double endingPercent)? refreshProgressRange,
) async {
final start = DateTime.now();
@@ -1832,6 +1854,8 @@ mixin SparkInterface<T extends ElectrumXCurrencyInterface>
);
await sparkNamesUpdateFuture;
+ } on FiroCacheResetException {
+ rethrow;
} catch (e, s) {
Logging.instance.e(
"$runtimeType $walletId ${info.name}: ",
### lib/widgets/custom_tab_view.dart
@@ -55,43 +55,40 @@ class _CustomTabViewState extends State<CustomTabView> {
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
+ key: ValueKey('customTab_${widget.titles[i]}'),
onTap: () => setState(() => _selectedIndex = i),
child: Container(
color: Colors.transparent,
child: Column(
children: [
- const SizedBox(
- height: 16,
- ),
+ const SizedBox(height: 16),
AnimatedCrossFade(
firstChild: Text(
widget.titles[i],
style:
STextStyles.desktopTextExtraSmall(context)
.copyWith(
- color: Theme.of(context)
- .extension<StackColors>()!
- .accentColorBlue,
- ),
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .accentColorBlue,
+ ),
),
secondChild: Text(
widget.titles[i],
style:
STextStyles.desktopTextExtraSmall(context)
.copyWith(
- color: Theme.of(context)
- .extension<StackColors>()!
- .textSubtitle1,
- ),
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle1,
+ ),
),
crossFadeState: _selectedIndex == i
? CrossFadeState.showFirst
: CrossFadeState.showSecond,
duration: const Duration(milliseconds: 250),
),
- const SizedBox(
- height: 19,
- ),
+ const SizedBox(height: 19),
],
),
),
@@ -128,10 +125,7 @@ class _CustomTabViewState extends State<CustomTabView> {
AnimatedSwitcher(
duration: duration,
transitionBuilder: (child, animation) {
- return FadeTransition(
- opacity: animation,
- child: child,
- );
+ return FadeTransition(opacity: animation, child: child);
},
layoutBuilder: (currentChild, prevChildren) {
return Stack(
### pubspec.lock
@@ -42,7 +42,7 @@ packages:
source: hosted
version: "4.0.9"
args:
- dependency: transitive
+ dependency: "direct dev"
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
@@ -2341,7 +2341,7 @@ packages:
source: hosted
version: "1.2.2"
test:
- dependency: transitive
+ dependency: "direct dev"
description:
name: test
sha256: ca578dc12bb8b2f40b67b7d3bd2fac4f31c01a6ff7130a14e2597b919934507f
### scripts/app_config/templates/pubspec.template.yaml
@@ -278,6 +278,8 @@ dependencies:
wallet: 0.0.18
dev_dependencies:
+ args: ^2.7.0
+ test: ^1.31.1
flutter_test:
sdk: flutter
integration_test:
### scripts/build_app.sh
@@ -2,10 +2,7 @@
set -e
-source ./env.sh
-
-APP_PLATFORMS=("android" "ios" "macos" "linux" "windows")
-APP_NAMED_IDS=("stack_wallet" "stack_duo" "campfire")
+source "$(dirname -- "${BASH_SOURCE[0]}")/env.sh"
# Function to display usage.
usage() {
@@ -76,6 +73,26 @@ if [ -z "$APP_NAMED_ID" ]; then
usage
fi
+case "$APP_BUILD_PLATFORM" in
+ android|ios|macos|linux|windows) ;;
+ *) echo "Invalid platform: ${APP_BUILD_PLATFORM}"; usage ;;
+esac
+
+case "$APP_NAMED_ID" in
+ stack_wallet|stack_duo|campfire) ;;
+ *) echo "Invalid app id: ${APP_NAMED_ID}"; usage ;;
+esac
+
+if [[ ! "$APP_VERSION_STRING" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then
+ echo "Invalid version: ${APP_VERSION_STRING}"
+ usage
+fi
+
+if [[ ! "$APP_BUILD_NUMBER" =~ ^[0-9]+$ ]]; then
+ echo "Invalid build number: ${APP_BUILD_NUMBER}"
+ usage
+fi
+
confirmDisclaimer
set -x
@@ -84,42 +101,27 @@ source "${APP_PROJECT_ROOT_DIR}/scripts/app_config/templates/configure_template_
export BUILD_ISAR_FROM_SOURCE
export USE_SYSTEM_SECURE_STORAGE_DEPS
-# checks for a valid platform
-if ! printf '%s\0' "${APP_PLATFORMS[@]}" | grep -Fxqz -- "${APP_BUILD_PLATFORM}"; then
- echo "Invalid platform: ${APP_BUILD_PLATFORM}"
- usage
-fi
-
PLAY_STORE_ICON_FILE="${APP_PROJECT_ROOT_DIR}/android/app/src/main/app_icon-playstore.png"
if [ -f "${PLAY_STORE_ICON_FILE}" ]; then
rm "${PLAY_STORE_ICON_FILE}"
fi
cp -rp "${APP_PROJECT_ROOT_DIR}/asset_sources/other/playstore_icon/${APP_NAMED_ID}/app_icon-playstore.png" "${PLAY_STORE_ICON_FILE}"
# apply config project wide change changes
-if printf '%s\0' "${APP_NAMED_IDS[@]}" | grep -Fxqz -- "${APP_NAMED_ID}"; then
- if cmp -s "${ACTUAL_PUBSPEC}" "${T_PUBSPEC}"; then
- rm "${ACTUAL_PUBSPEC}"
- cp "${T_PUBSPEC}" "${ACTUAL_PUBSPEC}"
- fi
- "${APP_PROJECT_ROOT_DIR}/scripts/app_config/shared/update_version.sh" -v "${APP_VERSION_STRING}" -b "${APP_BUILD_NUMBER}"
- "${APP_PROJECT_ROOT_DIR}/scripts/app_config/shared/link_assets.sh" "${APP_NAMED_ID}" "${APP_BUILD_PLATFORM}"
- # shellcheck disable=SC1090
- source "${APP_PROJECT_ROOT_DIR}/scripts/app_config/configure_${APP_NAMED_ID}.sh" "${APP_BUILD_PLATFORM}"
- if [ "$DOWNLOAD_CRYPTO_PLUGINS" -eq 1 ]; then
- # Enable CI prebuilt native assets (hooks user_defines) in pubspec.yaml so
- # native-assets plugins download verified binaries instead of compiling Rust.
- dart "${APP_PROJECT_ROOT_DIR}/tool/process_pubspec_deps.dart" "${ACTUAL_PUBSPEC}" NATIVE_PREBUILTS
- fi
- "${APP_PROJECT_ROOT_DIR}/scripts/app_config/platforms/${APP_BUILD_PLATFORM}/platform_config.sh"
-
- if [[ "$APP_BUILD_PLATFORM" != "linux" ]]; then
- # run icon and image generators after project config has completed for non linux
- "${APP_PROJECT_ROOT_DIR}/scripts/app_config/shared/asset_generators.sh" "${APP_BUILD_PLATFORM}"
- fi
-else
- echo "Invalid app id: ${APP_NAMED_ID}"
- exit 1
+"${APP_PROJECT_ROOT_DIR}/scripts/app_config/shared/update_version.sh" -v "${APP_VERSION_STRING}" -b "${APP_BUILD_NUMBER}"
+"${APP_PROJECT_ROOT_DIR}/scripts/app_config/shared/link_assets.sh" "${APP_NAMED_ID}" "${APP_BUILD_PLATFORM}"
+# shellcheck disable=SC1090
+source "${APP_PROJECT_ROOT_DIR}/scripts/app_config/configure_${APP_NAMED_ID}.sh" "${APP_BUILD_PLATFORM}"
+if [ "$DOWNLOAD_CRYPTO_PLUGINS" -eq 1 ]; then
+ # Enable CI prebuilt native assets (hooks user_defines) in pubspec.yaml so
+ # native-assets plugins download verified binaries instead of compiling Rust.
+ dart "${APP_PROJECT_ROOT_DIR}/tool/process_pubspec_deps.dart" "${ACTUAL_PUBSPEC}" NATIVE_PREBUILTS
+fi
+"${APP_PROJECT_ROOT_DIR}/scripts/app_config/platforms/${APP_BUILD_PLATFORM}/platform_config.sh"
+
+if [[ "$APP_BUILD_PLATFORM" != "linux" ]]; then
+ # run icon and image generators after project config has completed for non linux
+ "${APP_PROJECT_ROOT_DIR}/scripts/app_config/shared/asset_generators.sh" "${APP_BUILD_PLATFORM}"
fi
# Build platform native deps that are not provided by pub packages. The crypto
### scripts/prebuild.sh
@@ -1,5 +1,8 @@
#!/bin/bash
+set -e
+cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
+
# Create template lib/external_api_keys.dart file if it doesn't already exist
KEYS=../lib/external_api_keys.dart
if ! test -f "$KEYS"; then
### scripts/test_wallet_creation.dart
@@ -0,0 +1,514 @@
+#!/usr/bin/env dart
+
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+
+import 'package:args/args.dart';
+import 'package:path/path.dart' as p;
+
+import '../integration_test/wallet_creation/coin_matrix.dart';
+
+const _walletStages = {
+ 'select and name',
+ 'default options',
+ 'generate',
+ 'confirm recovery phrase',
+ 'open created wallet',
+ 'recovery identity',
+ 'check persisted wallet',
+};
+
+ArgParser argumentParser() => ArgParser()
+ ..addOption('device', help: 'Flutter device ID, e.g. macos, linux, windows.')
+ ..addOption(
+ 'platform',
+ allowed: ['macos', 'linux', 'windows', 'android', 'ios'],
+ help: 'Required for mobile; inferred from desktop device IDs.',
+ )
+ ..addMultiOption(
+ 'coin',
+ allowed: defaultWordCounts.keys.toList(),
+ help: 'Repeat to select coins; default: every coin independently.',
+ )
+ ..addFlag(
+ 'all-coins',
+ negatable: false,
+ help: 'Accumulate all 24 wallets in one installation.',
+ )
+ ..addFlag(
+ 'disposable-mobile',
+ negatable: false,
+ help: 'Confirm that the mobile app installation is clean and disposable.',
+ )
+ ..addOption(
+ 'flutter',
+ defaultsTo: Platform.environment['FLUTTER_BIN'] ?? 'flutter',
+ )
+ ..addOption('report', help: 'Write sanitized results to this JSON file.')
+ ..addFlag(
+ 'list',
+ negatable: false,
+ help: 'List coin IDs without launching the app.',
+ )
+ ..addFlag('help', abbr: 'h', negatable: false, help: 'Show usage.');
+
+class RunOptions {
+ RunOptions.fromResults(ArgResults args)
+ : device = args['device'] as String? ?? '',
+ platform =
+ args['platform'] as String? ??
+ (const ['macos', 'linux', 'windows'].contains(args['device'])
+ ? args['device'] as String
+ : ''),
+ coins = List<String>.from(args['coin'] as List),
+ allCoins = args['all-coins'] as bool,
+ disposableMobile = args['disposable-mobile'] as bool,
+ flutter = args['flutter'] as String,
+ report = args['report'] == null ? null : File(args['report'] as String) {
+ if (args.rest.isNotEmpty) {
+ throw const FormatException('Unexpected positional arguments.');
+ }
+ if (device.isEmpty) throw const FormatException('--device is required.');
+ if (platform.isEmpty) {
+ throw const FormatException(
+ 'Pass --platform android or ios for a mobile device ID.',
+ );
+ }
+ if (mobile && !disposableMobile) {
+ throw const FormatException(
+ 'Mobile tests require --disposable-mobile '
+ 'and a clean dedicated app install.',
+ );
+ }
+ if (const ['macos', 'linux', 'windows'].contains(device) &&
+ device != platform) {
+ throw const FormatException(
+ 'The desktop device and platform must match.',
+ );
+ }
+ if (allCoins && coins.isNotEmpty) {
+ throw const FormatException('--all-coins and --coin cannot be combined.');
+ }
+ }
+
+ factory RunOptions.parse(List<String> arguments) =>
+ RunOptions.fromResults(argumentParser().parse(arguments));
+
+ final String device;
+ final String platform;
+ final List<String> coins;
+ final bool allCoins;
+ final bool disposableMobile;
+ final String flutter;
+ final File? report;
+
+ bool get mobile => platform == 'android' || platform == 'ios';
+ List<String> get cases => allCoins
+ ? ['all']
+ : coins.isEmpty
+ ? defaultWordCounts.keys.toList()
+ : coins;
+}
+
+typedef ProcessStarter = Future<Process> Function(
+ String executable,
+ List<String> arguments, {
+ required String workingDirectory,
+ required Map<String, String> environment,
+});
+
+Future<Process> _startProcess(
+ String executable,
+ List<String> arguments, {
+ required String workingDirectory,
+ required Map<String, String> environment,
+}) => Process.start(
+ executable,
+ arguments,
+ workingDirectory: workingDirectory,
+ environment: environment,
+ runInShell: Platform.isWindows,
+);
+
+void _printProgress(String message) => stdout.writeln(message);
+
+/// Runs real create/reopen processes against a fresh directory for each case.
+class WalletCreationRunner {
+ WalletCreationRunner({
+ required this.repository,
+ this.temporaryParent,
+ this.phaseTimeout,
+ this.shutdownTimeout = const Duration(seconds: 20),
+ this.log = _printProgress,
+ this.startProcess = _startProcess,
+ });
+
+ final Directory repository;
+ final Directory? temporaryParent;
+ final Duration? phaseTimeout;
+ final Duration shutdownTimeout;
+ final void Function(String) log;
+ final ProcessStarter startProcess;
+ final results = <Map<String, Object?>>[];
+ Process? _active;
+ Future<void>? _stopping;
+ bool _interrupted = false;
+ bool _cleanupFailed = false;
+
+ void interrupt() {
+ _interrupted = true;
+ // runPhase awaits this same future before deleting any test files.
+ _stopActive().ignore();
+ }
+
+ Future<Directory> _parent(RunOptions options) async {
+ if (temporaryParent != null) return temporaryParent!;
+ if (options.platform != 'macos') return Directory.systemTemp;
+ final config = await File(
+ p.join(repository.path, 'macos/Runner/Configs/AppInfo.xcconfig'),
+ ).readAsString();
+ final bundle = RegExp(
+ r'^PRODUCT_BUNDLE_IDENTIFIER\s*=\s*([A-Za-z0-9_.-]+)\s*$',
+ multiLine: true,
+ ).firstMatch(config)?.group(1);
+ if (bundle == null) {
+ throw const FormatException(
+ 'Configure the macOS app before running integration tests.',
+ );
+ }
+ final home = Platform.environment['HOME'];
+ if (home == null) {
+ throw const FormatException('Cannot locate the macOS home directory.');
+ }
+ return Directory(
+ p.join(home, 'Library', 'Containers', bundle, 'Data', 'tmp'),
+ )..createSync(recursive: true);
+ }
+
+ Future<int> run(RunOptions options) async {
+ try {
+ final parent = await _parent(options);
+ for (final coin in options.cases) {
+ if (_interrupted) break;
+ final root = await parent.createTemp('stack_wallet_creation_');
+ final random = Random.secure();
+ final runId = List.generate(
+ 16,
+ (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'),
+ ).join();
+ try {
+ final created = await runPhase(options, coin, 'create', root, runId);
+ results.add(created);
+ if (created['status'] == 'passed' && !_interrupted) {
+ results.add(await runPhase(options, coin, 'reopen', root, runId));
+ } else {
+ results.add({
+ 'platform': options.platform,
+ 'coin': coin,
+ 'phase': 'reopen',
+ 'status': 'blocked',
+ 'reason': 'creation did not complete',
+ });
+ }
+ } finally {
+ if (!_cleanupFailed) await root.delete(recursive: true);
+ }
+ // A failed mobile install requires explicit reset by its operator.
+ if (options.mobile && results.any((r) => r['status'] != 'passed')) {
+ break;
+ }
+ }
+ } finally {
+ final report = options.report;
+ if (report != null) {
+ await report.parent.create(recursive: true);
+ await report.writeAsString(
+ '${const JsonEncoder.withIndent(' ').convert(results)}\n',
+ );
+ }
+ }
+ log(
+ jsonEncode({
+ for (final status in ['passed', 'failed', 'blocked'])
+ status: results.where((r) => r['status'] == status).length,
+ }),
+ );
+ if (_interrupted) return 130;
+ return results.isNotEmpty && results.every((r) => r['status'] == 'passed')
+ ? 0
+ : 1;
+ }
+
+ Future<Map<String, Object?>> runPhase(
+ RunOptions options,
+ String coin,
+ String phase,
+ Directory root,
+ String runId,
+ ) async {
+ final target = options.allCoins
+ ? 'all_coins_test.dart'
+ : 'fresh_install_test.dart';
+ final arguments = [
+ 'test',
+ '--no-pub',
+ '--no-uninstall',
+ '-d',
+ options.device,
+ 'integration_test/wallet_creation/$target',
+ '--reporter',
+ 'expanded',
+ '--dart-define=IS_INTEGRATION_TEST=true',
+ '--dart-define=WALLET_TEST_PLATFORM=${options.platform}',
+ '--dart-define=WALLET_TEST_PHASE=$phase',
+ '--dart-define=WALLET_TEST_COIN=$coin',
+ if (options.mobile) ...[
+ '--dart-define=WALLET_TEST_DISPOSABLE_DEVICE=true',
+ '--dart-define=WALLET_TEST_RUN_ID=$runId',
+ ] else
+ '--dart-define=WALLET_TEST_ROOT=${p.join(root.path, 'state')}',
+ ];
+ final environment = Map<String, String>.from(Platform.environment);
+ const xcode = '/Applications/Xcode.app/Contents/Developer';
+ if (Platform.isMacOS && Directory(xcode).existsSync()) {
+ environment.putIfAbsent('DEVELOPER_DIR', () => xcode);
+ }
+ final watch = Stopwatch()..start();
+ final output = File(p.join(root.path, '$phase.log')).openWrite();
+ final completed = <String>{};
+ String? lastStage;
+ bool buildFailed = false;
+ bool appException = false;
+ bool timedOut = false;
+ int code;
+
+ Future<void> consume(Stream<List<int>> stream) async {
+ await for (final line
+ in stream
+ .map((bytes) {
+ output.add(bytes);
+ return bytes;
+ })
+ .transform(const Utf8Decoder(allowMalformed: true))
+ .transform(const LineSplitter())) {
+ // Native output can include generated seeds. Only fixed-schema progress
+ // is forwarded to the terminal; raw logs stay in the disposable root.
+ final ok = RegExp(
+ r'\bWALLET_CREATION_OK (\w+) (\w+) (create|reopen)\s*$',
+ ).firstMatch(line);
+ if (ok != null &&
+ ok[1] == options.platform &&
+ ok[3] == phase &&
+ defaultWordCounts.containsKey(ok[2]) &&
+ completed.add(ok[2]!)) {
+ log('WALLET_CREATION_OK ${ok[1]} ${ok[2]} ${ok[3]}');
+ }
+ final stage = RegExp(r'\bWALLET_CREATION_STAGE (.+)$')
+ .firstMatch(line)?[1];
+ final parts = stage?.split(': ');
+ final knownStage =
+ stage == 'fresh install onboarding' ||
+ parts != null &&
+ parts.length == 2 &&
+ defaultWordCounts.containsKey(parts[0]) &&
+ _walletStages.contains(parts[1]);
+ if (stage != null && knownStage && stage != lastStage) {
+ lastStage = stage;
+ log('Stage: $stage');
+ }
+ buildFailed |=
+ line.contains('BUILD FAILED') || line.contains('Failed to load "');
+ appException |= line.contains('EXCEPTION CAUGHT');
+ }
+ }
+
+ log('${options.platform} $coin $phase: starting');
+ try {
+ final process = _active = await startProcess(
+ options.flutter,
+ arguments,
+ workingDirectory: repository.path,
+ environment: environment,
+ );
+ _stopping = null;
+ final streams = Future.wait([
+ consume(process.stdout),
+ consume(process.stderr),
+ ]);
+ if (_interrupted) await _stopActive();
+ try {
+ code = await process.exitCode.timeout(
+ phaseTimeout ?? Duration(minutes: options.allCoins ? 90 : 30),
+ );
+ } on TimeoutException {
+ timedOut = true;
+ await _stopActive();
+ code = 124;
+ } finally {
+ try {
+ await _stopping;
+ } finally {
+ await streams;
+ }
+ }
+ } finally {
+ _active = null;
+ _stopping = null;
+ await output.close();
+ }
+ final expected = options.allCoins ? defaultWordCounts.keys.toSet() : {coin};
+ final complete =
+ completed.length == expected.length && completed.containsAll(expected);
+ final passed =
+ code == 0 && complete && !_interrupted && !buildFailed && !appException;
+ final seconds = (watch.elapsedMilliseconds / 100).round() / 10;
+ final failure = _interrupted
+ ? 'interrupted'
+ : timedOut
+ ? 'timeout'
+ : code == 0 && !complete
+ ? 'incomplete_results'
+ : buildFailed
+ ? 'build_or_launch'
+ : appException
+ ? 'test_or_app_exception'
+ : 'process_failure';
+ log(
+ '${options.platform} $coin $phase: '
+ '${passed ? 'passed' : 'failed'} (${seconds}s)',
+ );
+ if (!passed) {
+ log('Failure: $failure');
+ if (lastStage != null) log('Last stage: $lastStage');
+ }
+ return {
+ 'platform': options.platform,
+ 'device': options.device,
+ 'coin': coin,
+ 'phase': phase,
+ 'status': passed ? 'passed' : 'failed',
+ 'seconds': seconds,
+ 'exit_code': code,
+ 'timed_out': timedOut,
+ 'completed_coins': completed.toList(),
+ 'last_stage': lastStage,
+ 'failure': passed ? null : failure,
+ };
+ }
+
+ Future<void> _stopActive() {
+ final process = _active;
+ if (process == null) return Future.value();
+ return _stopping ??= stopProcessTree(process, grace: shutdownTimeout)
+ .catchError((Object error) {
+ _cleanupFailed = true;
+ throw error;
+ });
+ }
+}
+
+/// Stop the child app as well as Flutter before removing their test storage.
+Future<void> stopProcessTree(Process process, {required Duration grace}) async {
+ if (Platform.isWindows) {
+ await Process.run('taskkill', ['/PID', '${process.pid}', '/T', '/F']);
+ await process.exitCode.timeout(grace);
+ return;
+ }
+ final table = await Process.run('ps', ['-eo', 'pid=,ppid=']);
+ if (table.exitCode != 0) {
+ throw StateError('Cannot identify test subprocesses.');
+ }
+ final rows = (table.stdout as String)
+ .split('\n')
+ .map((line) => line.trim().split(RegExp(r'\s+')))
+ .where((row) => row.length == 2)
+ .map((row) => (pid: int.parse(row[0]), parent: int.parse(row[1])))
+ .toList();
+ final ids = <int>{process.pid};
+ int previous;
+ do {
+ previous = ids.length;
+ for (final row in rows) {
+ if (ids.contains(row.parent)) ids.add(row.pid);
+ }
+ } while (ids.length != previous);
+ for (final id in ids.toList().reversed) {
+ Process.killPid(id, ProcessSignal.sigterm);
+ }
+ Future<List<int>> alive() async {
+ final result = await Process.run('ps', [
+ '-p',
+ ids.join(','),
+ '-o',
+ 'pid=,stat=',
+ ]);
+ return (result.stdout as String)
+ .split('\n')
+ .map((line) => line.trim().split(RegExp(r'\s+')))
+ .where((row) => row.length == 2 && !row[1].startsWith('Z'))
+ .map((row) => int.parse(row[0]))
+ .toList();
+ }
+
+ final watch = Stopwatch()..start();
+ var remaining = await alive();
+ while (remaining.isNotEmpty && watch.elapsed < grace) {
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ remaining = await alive();
+ }
+ for (final id in remaining) {
+ Process.killPid(id, ProcessSignal.sigkill);
+ }
+ await process.exitCode.timeout(const Duration(seconds: 5));
+ for (var attempt = 0; attempt < 50; attempt++) {
+ if ((await alive()).isEmpty) return;
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ }
+ throw StateError(
+ 'Test subprocesses are still alive; disposable data was retained.',
+ );
+}
+
+Future<void> main(List<String> arguments) async {
+ final parser = argumentParser();
+ try {
+ final args = parser.parse(arguments);
+ if (args['help'] as bool) {
+ stdout.writeln(
+ 'Run wallet creation and separate-process reopening:\n${parser.usage}',
+ );
+ return;
+ }
+ if (args['list'] as bool) {
+ stdout.writeln(defaultWordCounts.keys.join('\n'));
+ return;
+ }
+ final options = RunOptions.fromResults(args);
+ final runner = WalletCreationRunner(
+ repository: File.fromUri(Platform.script).absolute.parent.parent,
+ );
+ final signals = <StreamSubscription<ProcessSignal>>[
+ ProcessSignal.sigint.watch().listen((_) => runner.interrupt()),
+ if (!Platform.isWindows)
+ ProcessSignal.sigterm.watch().listen((_) => runner.interrupt()),
+ ];
+ try {
+ exitCode = await runner.run(options);
+ } finally {
+ for (final signal in signals) {
+ await signal.cancel();
+ }
+ }
+ } on FormatException catch (error) {
+ stderr.writeln('${error.message}\n${parser.usage}');
+ exitCode = 64;
+ } catch (error) {
+ stderr.writeln(
+ 'Wallet creation runner failed (${error.runtimeType}). '
+ 'Raw app output was not printed.',
+ );
+ exitCode = 1;
+ }
+}
### scripts/tests/build_input_test.dart
@@ -0,0 +1,190 @@
+// Run with: dart scripts/tests/build_input_test.dart
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:path/path.dart' as p;
+import 'package:test/test.dart';
+
+void main() {
+ final repository = File.fromUri(Platform.script)
+ .absolute
+ .parent
+ .parent
+ .parent;
+ late Directory root;
+ late Directory scripts;
+ late File pubspec;
+ const originalConfiguration = 'existing project configuration\n';
+
+ setUp(() async {
+ // Spaces also exercise path quoting in build_app.sh and env.sh.
+ root = await Directory.systemTemp.createTemp('stack wallet build inputs ');
+ scripts = await Directory(p.join(root.path, 'scripts')).create();
+ for (final name in ['build_app.sh', 'env.sh', 'prebuild.sh']) {
+ await File(p.join(repository.path, 'scripts', name))
+ .copy(p.join(scripts.path, name));
+ }
+ pubspec = File(p.join(root.path, 'pubspec.yaml'));
+ await pubspec.writeAsString(originalConfiguration);
+
+ // If validation or confirmation moves after configuration, record the
+ // unwanted write and stop before any real build tools can run.
+ final templates = await Directory(
+ p.join(scripts.path, 'app_config', 'templates'),
+ ).create(recursive: true);
+ await File(p.join(templates.path, 'configure_template_files.sh'))
+ .writeAsString(r'''
+printf 'unexpected configuration write\n' > "${APP_PROJECT_ROOT_DIR}/pubspec.yaml"
+exit 91
+''');
+ });
+ tearDown(() => root.delete(recursive: true));
+
+ Future<ProcessResult> runBuild({
+ required bool fromScripts,
+ required String confirmation,
+ Map<String, String> overrides = const {},
+ }) async {
+ final options = {
+ 'v': '1.2.3',
+ 'b': '12',
+ 'p': 'macos',
+ 'a': 'stack_wallet',
+ ...overrides,
+ };
+ final process = await Process.start('bash', [
+ fromScripts ? 'build_app.sh' : 'scripts/build_app.sh',
+ for (final option in options.entries) ...['-${option.key}', option.value],
+ ], workingDirectory: fromScripts ? scripts.path : root.path);
+ final output = process.stdout.transform(utf8.decoder).join();
+ final errors = process.stderr.transform(utf8.decoder).join();
+ try {
+ process.stdin.writeln(confirmation);
+ await process.stdin.close();
+ } on IOException {
+ // Invalid inputs can terminate before bash reads its confirmation input.
+ }
+ final int code;
+ try {
+ code = await process.exitCode.timeout(const Duration(seconds: 10));
+ } on TimeoutException {
+ process.kill(ProcessSignal.sigkill);
+ await process.exitCode;
+ await Future.wait([output, errors]);
+ rethrow;
+ }
+ return ProcessResult(process.pid, code, await output, await errors);
+ }
+
+ group('build input validation', () {
+ for (final fromScripts in [false, true]) {
+ final location = fromScripts ? 'scripts directory' : 'project root';
+ for (final invalid in [
+ (option: 'p', value: 'unsupported', message: 'Invalid platform'),
+ (option: 'a', value: 'unknown', message: 'Invalid app id'),
+ (option: 'v', value: '1.2.3/invalid', message: 'Invalid version'),
+ (option: 'b', value: '12-invalid', message: 'Invalid build number'),
+ ]) {
+ test('rejects invalid -${invalid.option} before writes '
+ 'from $location', () async {
+ final result = await runBuild(
+ fromScripts: fromScripts,
+ // A late check must not be hidden by declining confirmation first.
+ confirmation: 'yes',
+ overrides: {invalid.option: invalid.value},
+ );
+ expect(result.exitCode, isNot(0), reason: result.stderr as String);
+ expect(result.stdout, contains(invalid.message));
+ expect(result.stdout, isNot(contains('Continuing...')));
+ expect(await pubspec.readAsString(), originalConfiguration);
+ });
+ }
+
+ for (final version in ['1.2.3', '0.0.0-staging.123', '1.2.3-rc-1']) {
+ test(
+ 'accepts $version and honors cancellation from $location',
+ () async {
+ final result = await runBuild(
+ fromScripts: fromScripts,
+ confirmation: 'no',
+ overrides: {'v': version},
+ );
+ expect(result.exitCode, 0, reason: result.stderr as String);
+ expect(result.stdout, isNot(contains('Invalid')));
+ expect(result.stdout, isNot(contains('Continuing...')));
+ expect(await pubspec.readAsString(), originalConfiguration);
+ },
+ );
+ }
+ }
+ }, skip: Platform.isWindows ? 'Requires POSIX bash' : false);
+
+ group('prebuild', () {
+ const coins = [
+ 'bitcoin',
+ 'bitcoincash',
+ 'dogecoin',
+ 'namecoin',
+ 'firo',
+ 'particl',
+ ];
+ File parameters(String coin) => File(
+ p.join(
+ root.path,
+ 'test',
+ 'services',
+ 'coins',
+ coin,
+ '${coin}_wallet_test_parameters.dart',
+ ),
+ );
+ File getKeys() => File(p.join(root.path, 'lib', 'external_api_keys.dart'));
+ setUp(() async {
+ await Directory(p.join(root.path, 'lib')).create();
+ for (final coin in coins) {
+ await parameters(coin).parent.create(recursive: true);
+ }
+ });
+ Future<ProcessResult> runPrebuild(Directory cwd) => Process.run('bash', [
+ p.join(scripts.path, 'prebuild.sh'),
+ ], workingDirectory: cwd.path);
+ for (final outsideScripts in [false, true]) {
+ final location = outsideScripts
+ ? 'another directory'
+ : 'the project root';
+ test('creates stubs in its project from $location', () async {
+ final cwd = outsideScripts
+ ? await Directory(p.join(root.path, 'elsewhere')).create()
+ : root;
+ final result = await runPrebuild(cwd);
+ expect(result.exitCode, 0, reason: result.stderr as String);
+ expect(await getKeys().exists(), isTrue);
+ for (final coin in coins) {
+ expect(await parameters(coin).exists(), isTrue);
+ }
+ });
+ }
+ test('preserves existing keys and wallet parameters', () async {
+ await getKeys().writeAsString('existing test keys\n');
+ await parameters('bitcoin').writeAsString('existing test parameters\n');
+ final result = await runPrebuild(root);
+ expect(result.exitCode, 0, reason: result.stderr as String);
+ expect(await getKeys().readAsString(), 'existing test keys\n');
+ expect(
+ await parameters('bitcoin').readAsString(),
+ 'existing test parameters\n',
+ );
+ });
+ test(
+ 'stops at a failed write before creating later wallet stubs',
+ () async {
+ await Directory(parameters('bitcoin').path).create();
+ final result = await runPrebuild(root);
+ expect(result.exitCode, isNot(0));
+ expect(result.stderr, contains('bitcoin_wallet_test_parameters.dart'));
+ expect(await parameters('bitcoincash').exists(), isFalse);
+ },
+ );
+ }, skip: Platform.isWindows ? 'Requires POSIX bash' : false);
+}
### scripts/tests/wallet_creation_runner_test.dart
@@ -0,0 +1,436 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:path/path.dart' as p;
+import 'package:test/test.dart';
+
+import '../../integration_test/wallet_creation/coin_matrix.dart';
+import '../test_wallet_creation.dart';
+
+void main() {
+ late Directory root;
+ late Directory fixtures;
+ late File audit;
+ late File fakeFlutter;
+ late File report;
+ late List<String> output;
+
+ setUp(() async {
+ root = await Directory.systemTemp.createTemp('wallet runner ');
+ fixtures = await Directory(p.join(root.path, 'fixtures')).create();
+ audit = File(p.join(root.path, 'audit.jsonl'));
+ report = File(p.join(root.path, 'report.json'));
+ fakeFlutter = File(p.join(root.path, 'flutter_fixture.dart'));
+ await fakeFlutter.writeAsString(
+ _fixture.replaceFirst(
+ 'COIN_MATRIX_LITERAL',
+ jsonEncode(defaultWordCounts.keys.toList()),
+ ),
+ );
+ output = [];
+ });
+ tearDown(() => root.delete(recursive: true));
+
+ WalletCreationRunner runner({
+ String mode = 'pass',
+ Duration? timeout,
+ String? omitCoin,
+ }) => WalletCreationRunner(
+ repository: root,
+ temporaryParent: fixtures,
+ phaseTimeout: timeout,
+ shutdownTimeout: const Duration(milliseconds: 100),
+ log: output.add,
+ startProcess:
+ (
+ executable,
+ arguments, {
+ required workingDirectory,
+ required environment,
+ }) => Process.start(
+ Platform.resolvedExecutable,
+ [fakeFlutter.path, ...arguments],
+ workingDirectory: workingDirectory,
+ environment: {
+ ...environment,
+ 'FIXTURE_MODE': mode,
+ 'FIXTURE_AUDIT': audit.path,
+ 'FIXTURE_DEVICE_STORAGE': p.join(root.path, 'device'),
+ if (omitCoin != null) 'FIXTURE_OMIT_COIN': omitCoin,
+ },
+ ),
+ );
+
+ RunOptions options(List<String> arguments) =>
+ RunOptions.parse([...arguments, '--report', report.path]);
+ Future<List<Map<String, dynamic>>> events() async =>
+ (await audit.readAsLines())
+ .map((line) => jsonDecode(line) as Map<String, dynamic>)
+ .toList();
+
+ test('the shared matrix covers the 24 base wallets and excludes FROST', () {
+ expect(defaultWordCounts, hasLength(24));
+ expect(
+ defaultWordCounts.keys,
+ containsAll(['eCash', 'epicCash', 'monero', 'solana']),
+ );
+ expect(defaultWordCounts, isNot(contains('bitcoinFrost')));
+ });
+
+ test('rejects unsafe or ambiguous targets before launching a process', () {
+ for (final arguments in [
+ <String>[],
+ ['--device', 'phone'],
+ ['--device', 'phone', '--platform', 'android'],
+ ['--device', 'macos', '--platform', 'linux'],
+ ['--device', 'linux', '--all-coins', '--coin', 'bitcoin'],
+ ['--device', 'linux', '--coin', 'bitcoinFrost'],
+ ]) {
+ expect(
+ () => RunOptions.parse(arguments),
+ throwsFormatException,
+ reason: arguments.join(' '),
+ );
+ }
+ });
+
+ test(
+ 'each desktop coin creates fresh data and reopens only its own state',
+ () async {
+ final suite = runner();
+ expect(
+ await suite.run(
+ options([
+ '--device',
+ 'linux',
+ '--coin',
+ 'bitcoin',
+ '--coin',
+ 'monero',
+ ]),
+ ),
+ 0,
+ );
+ final calls = await events();
+ expect(calls.map((e) => '${e['coin']} ${e['phase']}'), [
+ 'bitcoin create',
+ 'bitcoin reopen',
+ 'monero create',
+ 'monero reopen',
+ ]);
+ expect(calls[0]['root'], calls[1]['root']);
+ expect(calls[2]['root'], calls[3]['root']);
+ expect(calls[0]['root'], isNot(calls[2]['root']));
+ expect(await fixtures.list().isEmpty, isTrue);
+ expect(suite.results.every((r) => r['status'] == 'passed'), isTrue);
+ expect(output.join('\n'), isNot(contains('FAKE_RECOVERY_DATA')));
+ expect(
+ await report.readAsString(),
+ isNot(contains('FAKE_RECOVERY_DATA')),
+ );
+ },
+ );
+
+ test(
+ 'a desktop creation failure blocks its reopen and continues other coins',
+ () async {
+ final suite = runner(mode: 'fail-bitcoin');
+ expect(
+ await suite.run(
+ options([
+ '--device',
+ 'linux',
+ '--coin',
+ 'bitcoin',
+ '--coin',
+ 'monero',
+ ]),
+ ),
+ 1,
+ );
+ expect((await events()).map((e) => '${e['coin']} ${e['phase']}'), [
+ 'bitcoin create',
+ 'monero create',
+ 'monero reopen',
+ ]);
+ expect(suite.results.map((r) => r['status']), [
+ 'failed',
+ 'blocked',
+ 'passed',
+ 'passed',
+ ]);
+ expect(await fixtures.list().isEmpty, isTrue);
+ expect(output.join('\n'), isNot(contains('FAKE_RECOVERY_DATA')));
+ expect(
+ await report.readAsString(),
+ isNot(contains('FAKE_RECOVERY_DATA')),
+ );
+ },
+ );
+
+ test(
+ 'mobile phases keep their run ID and use the native platform arguments',
+ () async {
+ final suite = runner();
+ expect(
+ await suite.run(
+ options([
+ '--device',
+ 'phone',
+ '--platform',
+ 'android',
+ '--disposable-mobile',
+ '--coin',
+ 'bitcoin',
+ ]),
+ ),
+ 0,
+ );
+ final calls = await events();
+ expect(calls, hasLength(2));
+ expect(calls[0]['run_id'], isNotEmpty);
+ expect(calls[0]['run_id'], calls[1]['run_id']);
+ for (final call in calls) {
+ final args = (call['arguments'] as List).cast<String>();
+ expect(args, contains('--no-uninstall'));
+ expect(args, contains('--dart-define=WALLET_TEST_PLATFORM=android'));
+ expect(
+ args,
+ contains('--dart-define=WALLET_TEST_DISPOSABLE_DEVICE=true'),
+ );
+ expect(args.any((arg) => arg.contains('WALLET_TEST_ROOT')), isFalse);
+ expect(args.any((arg) => arg.contains('layoutPlatform')), isFalse);
+ }
+ },
+ );
+
+ test(
+ 'a failed mobile case stops and leaves device reset to its operator',
+ () async {
+ final suite = runner(mode: 'fail-bitcoin');
+ expect(
+ await suite.run(
+ options([
+ '--device',
+ 'phone',
+ '--platform',
+ 'ios',
+ '--disposable-mobile',
+ '--coin',
+ 'bitcoin',
+ '--coin',
+ 'monero',
+ ]),
+ ),
+ 1,
+ );
+ expect(await events(), hasLength(1));
+ expect(
+ File(p.join(root.path, 'device', 'identity')).existsSync(),
+ isTrue,
+ );
+ expect(await fixtures.list().isEmpty, isTrue);
+ },
+ );
+
+ test(
+ 'a zero process exit without completed wallet checks cannot pass',
+ () async {
+ final suite = runner(mode: 'no-markers');
+ expect(
+ await suite.run(options(['--device', 'linux', '--coin', 'bitcoin'])),
+ 1,
+ );
+ expect(await events(), hasLength(1));
+ expect(suite.results.first['failure'], 'incomplete_results');
+ expect(suite.results.last['status'], 'blocked');
+ },
+ );
+
+ test(
+ 'all-coins requires a completion marker for every wallet in both phases',
+ () async {
+ final suite = runner();
+ expect(await suite.run(options(['--device', 'linux', '--all-coins'])), 0);
+ for (final result in suite.results) {
+ expect(
+ result['completed_coins'],
+ unorderedEquals(defaultWordCounts.keys),
+ );
+ }
+ expect(await events(), hasLength(2));
+ },
+ );
+
+ test(
+ 'an all-coins run missing one wallet fails even when Flutter exits zero',
+ () async {
+ final suite = runner(omitCoin: 'xelis');
+ expect(await suite.run(options(['--device', 'linux', '--all-coins'])), 1);
+ expect(suite.results.first['failure'], 'incomplete_results');
+ expect(suite.results.first['completed_coins'], hasLength(23));
+ expect(await events(), hasLength(1));
+ },
+ );
+
+ test(
+ 'timeout stops Flutter and its child before deleting their storage',
+ () async {
+ final suite = runner(mode: 'stall', timeout: const Duration(seconds: 3));
+ expect(
+ await suite.run(options(['--device', 'linux', '--coin', 'bitcoin'])),
+ 1,
+ );
+ expect(suite.results.first['exit_code'], 124);
+ expect(suite.results.first['timed_out'], isTrue);
+ final child = int.parse(
+ await File(p.join(root.path, 'child.pid')).readAsString(),
+ );
+ final state = await Process.run('ps', ['-p', '$child', '-o', 'stat=']);
+ expect((state.stdout as String).trim(), anyOf(isEmpty, startsWith('Z')));
+ expect(await fixtures.list().isEmpty, isTrue);
+ },
+ skip: Platform.isWindows ? 'POSIX subprocess signal test' : false,
+ );
+
+ test('interruption stops the case and writes its report '
+ 'without starting another coin', () async {
+ final suite = runner(mode: 'stall', timeout: const Duration(seconds: 10));
+ final running = suite.run(
+ options(['--device', 'linux', '--coin', 'bitcoin', '--coin', 'monero']),
+ );
+ final childFile = File(p.join(root.path, 'child.pid'));
+ final deadline = DateTime.now().add(const Duration(seconds: 5));
+ while (!await childFile.exists() && DateTime.now().isBefore(deadline)) {
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ }
+ expect(await childFile.exists(), isTrue);
+ suite.interrupt();
+ expect(await running, 130);
+ expect(await events(), hasLength(1));
+ expect(suite.results.first['failure'], 'interrupted');
+ expect(await fixtures.list().isEmpty, isTrue);
+ expect((jsonDecode(await report.readAsString()) as List), hasLength(2));
+ }, skip: Platform.isWindows ? 'POSIX subprocess signal test' : false);
+
+ for (final mode in [
+ 'false-success-app',
+ 'false-success-build',
+ 'false-success-load',
+ ]) {
+ test(
+ 'explicit failure rejects zero-exit completion markers: $mode',
+ () async {
+ final suite = runner(mode: mode);
+ expect(
+ await suite.run(options(['--device', 'linux', '--coin', 'bitcoin'])),
+ 1,
+ );
+ expect(suite.results.first['status'], 'failed');
+ expect(
+ suite.results.first['failure'],
+ mode == 'false-success-app'
+ ? 'test_or_app_exception'
+ : 'build_or_launch',
+ );
+ expect(suite.results.last['status'], 'blocked');
+ },
+ );
+ }
+
+ test('ordinary load warning permits a healthy launch', () async {
+ final suite = runner(mode: 'benign-load-warning');
+ expect(
+ await suite.run(options(['--device', 'linux', '--coin', 'bitcoin'])),
+ 0,
+ );
+ expect(
+ suite.results.every((result) => result['status'] == 'passed'),
+ isTrue,
+ );
+ });
+}
+
+const _fixture = r'''
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+const supportedCoins = COIN_MATRIX_LITERAL;
+
+Future<void> main(List<String> arguments) async {
+ final env = Platform.environment;
+ final audit = File(env['FIXTURE_AUDIT']!);
+ if (arguments.firstOrNull == 'hold') {
+ ProcessSignal.sigterm.watch().listen((_) {});
+ Timer.periodic(const Duration(seconds: 1), (_) {});
+ await File('${audit.parent.path}/child.pid').writeAsString('${pid}');
+ await Completer<void>().future;
+ return;
+ }
+ String? optionalDefine(String name) {
+ final prefix = '--dart-define=$name=';
+ for (final arg in arguments) {
+ if (arg.startsWith(prefix)) return arg.substring(prefix.length);
+ }
+ return null;
+ }
+ String define(String name) => optionalDefine(name)!;
+ final platform = define('WALLET_TEST_PLATFORM');
+ final coin = define('WALLET_TEST_COIN');
+ final phase = define('WALLET_TEST_PHASE');
+ final root = Directory(platform == 'android' || platform == 'ios'
+ ? env['FIXTURE_DEVICE_STORAGE']!
+ : define('WALLET_TEST_ROOT'));
+ await root.create(recursive: true);
+ await audit.writeAsString('${jsonEncode({
+ 'coin': coin, 'phase': phase, 'platform': platform, 'root': root.path,
+ 'run_id': optionalDefine('WALLET_TEST_RUN_ID'), 'arguments': arguments,
+ })}\n', mode: FileMode.append);
+ stdout.writeln('FAKE_RECOVERY_DATA_NOT_FOR_REPORT');
+ stdout.writeln('WALLET_CREATION_STAGE $coin: generate');
+ stdout.writeln('WALLET_CREATION_STAGE bitcoin: FAKE_RECOVERY_DATA_NOT_FOR_REPORT');
+ if (env['FIXTURE_MODE'] == 'stall') {
+ ProcessSignal.sigterm.watch().listen((_) {});
+ await Process.start(Platform.resolvedExecutable,
+ [Platform.script.toFilePath(), 'hold'],
+ mode: ProcessStartMode.inheritStdio, environment: env);
+ Timer.periodic(const Duration(seconds: 1), (_) {});
+ await Completer<void>().future;
+ return;
+ }
+ final identity = File('${root.path}/identity');
+ if (phase == 'create') {
+ if (await identity.exists()) throw StateError('Creation reused old state');
+ await identity.writeAsString(coin);
+ } else {
+ if (await identity.readAsString() != coin) {
+ throw StateError('Reopen used another coin fixture');
+ }
+ }
+ if (env['FIXTURE_MODE'] == 'fail-bitcoin' && coin == 'bitcoin') {
+ stderr.writeln('EXCEPTION CAUGHT FAKE_RECOVERY_DATA_NOT_FOR_REPORT');
+ exitCode = 1;
+ return;
+ }
+ if (env['FIXTURE_MODE'] == 'no-markers') return;
+ if (env['FIXTURE_MODE'] == 'false-success-app') {
+ stderr.writeln('EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK');
+ }
+ if (env['FIXTURE_MODE'] == 'false-success-build') {
+ stderr.writeln('BUILD FAILED');
+ }
+ if (env['FIXTURE_MODE'] == 'false-success-load') {
+ stderr.writeln('Failed to load "/tmp/fixture_test.dart": Compilation failed');
+ }
+ if (env['FIXTURE_MODE'] == 'benign-load-warning') {
+ stderr.writeln('Failed to load price data; using cached values');
+ }
+ for (final id in coin == 'all' ? supportedCoins : [coin]) {
+ if (id != env['FIXTURE_OMIT_COIN']) {
+ stdout.writeln('flutter: WALLET_CREATION_OK $platform $id $phase');
+ }
+ }
+}
+''';
### test/db/firo_cache_clear_test.dart
@@ -0,0 +1,497 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mockito/mockito.dart';
+import 'package:sqlite3/sqlite3.dart';
+import 'package:stackwallet/db/sqlite/firo_cache.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/models/electrumx_response/spark_models.dart';
+import 'package:stackwallet/utilities/stack_file_system.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+class _TagsClient extends Mock implements ElectrumXClient {
+ final started = Completer<void>();
+ final response = Completer<List<List<dynamic>>>();
+ @override
+ Future<List<List<dynamic>>> getSparkUnhashedUsedCoinsTagsWithTxHashes({
+ String? requestID,
+ required int startNumber,
+ }) {
+ started.complete();
+ return response.future;
+ }
+}
+
+class _SetClient extends Mock implements ElectrumXClient {
+ final started = Completer<void>();
+ final response = Completer<SparkAnonymitySetMeta>();
+ final sectorStarted = Completer<void>();
+ final sectorResponse = Completer<List<dynamic>>();
+ @override
+ Future<SparkAnonymitySetMeta> getSparkAnonymitySetMeta({
+ String? requestID,
+ required int coinGroupId,
+ }) {
+ started.complete();
+ return response.future;
+ }
+
+ @override
+ Future<List<dynamic>> getSparkAnonymitySetBySector({
+ String? requestID,
+ required int coinGroupId,
+ required String latestBlock,
+ required int startIndex,
+ required int endIndex,
+ }) {
+ sectorStarted.complete();
+ return sectorResponse.future;
+ }
+
+ void releaseMeta({int size = 1}) => response.complete(
+ SparkAnonymitySetMeta(
+ coinGroupId: 1,
+ blockHash: 'block',
+ setHash: 'set',
+ size: size,
+ ),
+ );
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Directory root;
+ late Directory cache;
+ const network = CryptoCurrencyNetwork.main;
+ const other = CryptoCurrencyNetwork.test;
+ setUpAll(() async {
+ root = await Directory.systemTemp.createTemp('firo-immediate-clear-');
+ StackFileSystem.setDesktopOverrideDir(root.path);
+ await FiroCacheCoordinator.init();
+ cache = await StackFileSystem.applicationFiroCacheSQLiteDirectory();
+ });
+ tearDownAll(() async {
+ await FiroCacheCoordinator.close();
+ await root.delete(recursive: true);
+ });
+ setUp(() => FiroCacheCoordinator.clearSharedCache(network));
+
+ Future<void> cancelled(Future<void> fetch) =>
+ expectLater(fetch, throwsA(isA<FiroCacheResetException>()));
+ Future<void> empty() async {
+ expect(await FiroCacheCoordinator.getUsedCoinTagsCount(network), 0);
+ expect(
+ await FiroCacheCoordinator.getLatestSetInfoForGroupId(1, network),
+ isNull,
+ );
+ expect(
+ await FiroCacheCoordinator.getSetCoinsForGroupId(1, network: network),
+ isEmpty,
+ );
+ }
+
+ test('tags reset completes while its RPC never completes', () async {
+ final db = sqlite3.open(
+ '${cache.path}/${FiroCacheCoordinator.usedTagsCacheFileName(network)}',
+ );
+ db.execute(
+ "INSERT INTO SparkUsedCoinTags (tag, txid) VALUES ('old', 'txid');",
+ );
+ db.close();
+ final client = _TagsClient();
+ final fetch = FiroCacheCoordinator.runFetchAndUpdateSparkUsedCoinTags(
+ client,
+ network,
+ );
+ final stopped = cancelled(fetch);
+ await client.started.future;
+ await FiroCacheCoordinator.clearSharedCache(
+ network,
+ clearOnlyUsedTagsCache: true,
+ ).timeout(const Duration(seconds: 3));
+ await stopped;
+ expect(client.response.isCompleted, isFalse);
+ await empty();
+ client.response.completeError(StateError('late network failure'));
+ await Future<void>.delayed(Duration.zero);
+ await empty();
+ });
+
+ test(
+ 'full reset cancels a stalled metadata fetch and queued old batch',
+ () async {
+ final client = _SetClient();
+ final first =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ client,
+ network,
+ null,
+ );
+ final stopped = cancelled(first);
+ await client.started.future;
+ final queuedClient = _SetClient();
+ final queued =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ queuedClient,
+ network,
+ null,
+ );
+ final queuedStopped = cancelled(queued);
+ await FiroCacheCoordinator.clearSharedCache(network)
+ .timeout(const Duration(seconds: 3));
+ await Future.wait([stopped, queuedStopped]);
+ expect(client.response.isCompleted, isFalse);
+ expect(queuedClient.started.isCompleted, isFalse);
+ client.releaseMeta();
+ await Future<void>.delayed(Duration.zero);
+ expect(client.sectorStarted.isCompleted, isFalse);
+ await empty();
+ },
+ );
+
+ test('a late sector cannot repopulate the reset cache', () async {
+ final client = _SetClient();
+ final fetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ client,
+ network,
+ null,
+ );
+ final stopped = cancelled(fetch);
+ await client.started.future;
+ client.releaseMeta();
+ await client.sectorStarted.future;
+ await FiroCacheCoordinator.clearSharedCache(network)
+ .timeout(const Duration(seconds: 3));
+ await stopped;
+ client.sectorResponse.complete([
+ ['serialized', 'tx', 'context'],
+ ]);
+ await Future<void>.delayed(Duration.zero);
+ await empty();
+ });
+
+ test(
+ 'reset orders deletion after an already submitted worker write',
+ () async {
+ final client = _SetClient();
+ final fetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ client,
+ network,
+ null,
+ );
+ // It may complete before reset, or be invalidated during its local write.
+ final observed = fetch.onError<FiroCacheResetException>((_, __) {});
+ await client.started.future;
+ client.releaseMeta();
+ await client.sectorStarted.future;
+ client.sectorResponse.complete([
+ ['serialized', 'tx', 'context'],
+ ]);
+ await Future<void>.delayed(Duration.zero);
+ await FiroCacheCoordinator.clearSharedCache(network);
+ await observed;
+ await empty();
+ },
+ );
+
+ test(
+ 'tags-only reset preserves sets, including an active set fetch',
+ () async {
+ final client = _SetClient();
+ final fetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ client,
+ network,
+ null,
+ );
+ await client.started.future;
+ await FiroCacheCoordinator.clearSharedCache(
+ network,
+ clearOnlyUsedTagsCache: true,
+ );
+ client.releaseMeta();
+ await client.sectorStarted.future;
+ client.sectorResponse.complete([
+ ['serialized', 'tx', 'context'],
+ ]);
+ await fetch;
+ expect(
+ await FiroCacheCoordinator.getSetCoinsForGroupId(1, network: network),
+ hasLength(1),
+ );
+ await FiroCacheCoordinator.clearSharedCache(
+ network,
+ clearOnlyUsedTagsCache: true,
+ );
+ expect(
+ await FiroCacheCoordinator.getSetCoinsForGroupId(1, network: network),
+ hasLength(1),
+ );
+ },
+ );
+
+ test('a new fetch starts while the retired RPC remains unresolved', () async {
+ final old = _SetClient();
+ final oldFetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ old,
+ network,
+ null,
+ );
+ final stopped = cancelled(oldFetch);
+ await old.started.future;
+ await FiroCacheCoordinator.clearSharedCache(network);
+ await stopped;
+ final fresh = _SetClient();
+ final freshFetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ fresh,
+ network,
+ null,
+ );
+ await fresh.started.future.timeout(const Duration(seconds: 3));
+ fresh.releaseMeta();
+ await fresh.sectorStarted.future;
+ fresh.sectorResponse.complete([
+ ['fresh', 'tx', 'context'],
+ ]);
+ await freshFetch;
+ expect(old.response.isCompleted, isFalse);
+ expect(
+ (await FiroCacheCoordinator.getSetCoinsForGroupId(
+ 1,
+ network: network,
+ )).single.serialized,
+ 'fresh',
+ );
+ });
+
+ test('reset of one network does not cancel another network update', () async {
+ final client = _SetClient();
+ final fetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ client,
+ other,
+ null,
+ );
+ await client.started.future;
+ await FiroCacheCoordinator.clearSharedCache(network);
+ client.releaseMeta();
+ await client.sectorStarted.future;
+ client.sectorResponse.complete([
+ ['testnet', 'tx', 'context'],
+ ]);
+ await fetch;
+ expect(
+ await FiroCacheCoordinator.getSetCoinsForGroupId(1, network: other),
+ hasLength(1),
+ );
+ await FiroCacheCoordinator.clearSharedCache(other);
+ });
+
+ test('a failed local reset is retried by the next read', () async {
+ final db = sqlite3.open(
+ '${cache.path}/${FiroCacheCoordinator.usedTagsCacheFileName(network)}',
+ );
+ db.execute(
+ "INSERT INTO SparkUsedCoinTags (tag, txid) VALUES ('old', 'txid');",
+ );
+ db.close();
+ final obstruction = Directory('${cache.path}/spark_reset_main.pending');
+ await obstruction.create();
+ await expectLater(
+ FiroCacheCoordinator.clearSharedCache(
+ network,
+ clearOnlyUsedTagsCache: true,
+ ),
+ throwsA(isA<FileSystemException>()),
+ );
+ // Reads retry the reset rather than serve the stale row; it still fails.
+ await expectLater(
+ FiroCacheCoordinator.getUsedCoinTagsCount(network),
+ throwsA(isA<FileSystemException>()),
+ );
+ await obstruction.delete();
+ // The next read completes the reset by itself.
+ expect(await FiroCacheCoordinator.getUsedCoinTagsCount(network), 0);
+ });
+
+ test(
+ 'full reset recovery retains its scope and restores set writes',
+ () async {
+ final db = sqlite3.open('${cache.path}/spark_set_v2.sqlite3');
+ db.execute('''
+ INSERT INTO SparkSet (blockHash, setHash, groupId, size)
+ VALUES ('old', 'old', 1, 0);
+ ''');
+ db.close();
+ final obstruction = Directory('${cache.path}/spark_reset_main.pending');
+ await obstruction.create();
+ try {
+ await expectLater(
+ FiroCacheCoordinator.clearSharedCache(network),
+ throwsA(isA<FileSystemException>()),
+ );
+ await expectLater(
+ FiroCacheCoordinator.getUsedCoinTagsCount(network),
+ throwsA(isA<FileSystemException>()),
+ );
+ } finally {
+ await obstruction.delete();
+ }
+
+ // A read must recover the full reset, including removal of the old set.
+ await empty();
+ final client = _SetClient();
+ final fetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ client,
+ network,
+ null,
+ );
+ await client.started.future;
+ client.releaseMeta();
+ await client.sectorStarted.future;
+ client.sectorResponse.complete([
+ ['fresh', 'tx', 'context'],
+ ]);
+ await fetch;
+
+ // Successful recovery must also retire the remembered full-reset intent.
+ await FiroCacheCoordinator.clearSharedCache(
+ network,
+ clearOnlyUsedTagsCache: true,
+ );
+ expect(
+ (await FiroCacheCoordinator.getSetCoinsForGroupId(
+ 1,
+ network: network,
+ )).single.serialized,
+ 'fresh',
+ );
+ },
+ );
+
+ test(
+ 'a checkpoint from before a full reset reads the whole new set',
+ () async {
+ final db = sqlite3.open('${cache.path}/spark_set_v2.sqlite3');
+ db.execute('''
+ INSERT INTO SparkSet (blockHash, setHash, groupId, size)
+ VALUES ('old', 'old', 1, 1);
+ INSERT INTO SparkCoin (serialized, txHash, context, groupId)
+ VALUES ('known', 'tx', 'context', 1);
+ INSERT INTO SparkSetCoins (setId, coinId) VALUES (1, 1);
+ ''');
+ db.close();
+ // Nothing newer than the checkpoint exists yet.
+ expect(
+ await FiroCacheCoordinator.getSetCoinsForGroupId(
+ 1,
+ afterBlockHash: 'old',
+ network: network,
+ ),
+ isEmpty,
+ );
+
+ await FiroCacheCoordinator.clearSharedCache(network);
+ final client = _SetClient();
+ final fetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ client,
+ network,
+ null,
+ );
+ await client.started.future;
+ client.releaseMeta(size: 2);
+ await client.sectorStarted.future;
+ client.sectorResponse.complete([
+ ['known', 'tx', 'context'],
+ ['received', 'tx2', 'context'],
+ ]);
+ await fetch;
+
+ // The rebuilt cache no longer holds the wallet's checkpoint hash. The
+ // wallet advances its checkpoint after this read, so it must see every
+ // coin rather than none.
+ final coins = await FiroCacheCoordinator.getSetCoinsForGroupId(
+ 1,
+ afterBlockHash: 'old',
+ network: network,
+ );
+ expect(
+ coins.map((e) => e.serialized),
+ unorderedEquals(['known', 'received']),
+ );
+ // A checkpoint the cache does know still reads incrementally.
+ expect(
+ await FiroCacheCoordinator.getSetCoinsForGroupId(
+ 1,
+ afterBlockHash: 'block',
+ network: network,
+ ),
+ isEmpty,
+ );
+ },
+ );
+
+ test('a checkpoint hash stored under another group is ignored', () async {
+ final db = sqlite3.open('${cache.path}/spark_set_v2.sqlite3');
+ db.execute('''
+ INSERT INTO SparkSet (blockHash, setHash, groupId, size)
+ VALUES ('new', 'new', 1, 1), ('old', 'old', 2, 1);
+ INSERT INTO SparkCoin (serialized, txHash, context, groupId)
+ VALUES ('received', 'tx', 'context', 1), ('other', 'tx2', 'context', 2);
+ INSERT INTO SparkSetCoins (setId, coinId) VALUES (1, 1), (2, 2);
+ ''');
+ db.close();
+ // Group 1 no longer holds the wallet's checkpoint hash. Another group
+ // holding that hash must not set the cutoff for group 1.
+ final coins = await FiroCacheCoordinator.getSetCoinsForGroupId(
+ 1,
+ afterBlockHash: 'old',
+ network: network,
+ );
+ expect(coins.map((e) => e.serialized), ['received']);
+ expect(
+ await FiroCacheCoordinator.getSetCoinsForGroupId(
+ 2,
+ afterBlockHash: 'old',
+ network: network,
+ ),
+ isEmpty,
+ );
+ });
+
+ test(
+ 'concurrent reset requests finish with readable empty databases',
+ () async {
+ await Future.wait([
+ FiroCacheCoordinator.clearSharedCache(network),
+ FiroCacheCoordinator.clearSharedCache(
+ network,
+ clearOnlyUsedTagsCache: true,
+ ),
+ FiroCacheCoordinator.clearSharedCache(network),
+ ]);
+ await empty();
+ expect(
+ await File('${cache.path}/spark_reset_main.pending').exists(),
+ isFalse,
+ );
+ },
+ );
+}
### test/db/firo_cache_error_contract_test.dart
@@ -0,0 +1,47 @@
+import 'dart:io';
+import 'dart:isolate';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/db/sqlite/firo_cache.dart';
+import 'package:stackwallet/utilities/stack_file_system.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+Future<bool> _failsThroughFuture({required bool closed}) async {
+ Directory? root;
+ if (closed) {
+ root = await Directory.systemTemp.createTemp('firo-close-error-');
+ StackFileSystem.setDesktopOverrideDir(root.path);
+ await FiroCacheCoordinator.init();
+ await FiroCacheCoordinator.close();
+ }
+ try {
+ final Future<void> result;
+ try {
+ result = FiroCacheCoordinator.clearSharedCache(
+ CryptoCurrencyNetwork.main,
+ );
+ } catch (_) {
+ return false;
+ }
+ try {
+ await result;
+ } catch (_) {
+ return true;
+ }
+ return false;
+ } finally {
+ await root?.delete(recursive: true);
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ for (final closed in [false, true]) {
+ test('reset errors arrive through a Future closed=$closed', () async {
+ expect(
+ await Isolate.run(() => _failsThroughFuture(closed: closed)),
+ isTrue,
+ );
+ });
+ }
+}
### test/db/firo_cache_reset_lifecycle_test.dart
@@ -0,0 +1,145 @@
+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:google_fonts/google_fonts.dart';
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/db/sqlite/firo_cache.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/models/electrumx_response/spark_models.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_wallet_features.dart';
+import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/more_features/more_features_dialog.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_providers.dart';
+import 'package:stackwallet/utilities/stack_file_system.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+import '../sample_data/theme_json.dart';
+
+class _Wallet extends Mock implements Wallet {
+ @override
+ CryptoCurrency get cryptoCurrency => Firo(CryptoCurrencyNetwork.main);
+}
+
+class _Wallets extends Mock implements Wallets {
+ @override
+ Wallet getWallet(String walletId) => _Wallet();
+}
+
+class _Client extends Mock implements ElectrumXClient {
+ final started = Completer<void>();
+ final response = Completer<SparkAnonymitySetMeta>();
+
+ @override
+ Future<SparkAnonymitySetMeta> getSparkAnonymitySetMeta({
+ String? requestID,
+ required int coinGroupId,
+ }) {
+ started.complete();
+ return response.future;
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Directory directory;
+
+ setUpAll(() async {
+ GoogleFonts.inter(fontWeight: FontWeight.w500);
+ GoogleFonts.inter(fontWeight: FontWeight.w600);
+ await GoogleFonts.pendingFonts();
+ directory = await Directory.systemTemp.createTemp('firo-reset-dialog-');
+ StackFileSystem.setDesktopOverrideDir(directory.path);
+ await FiroCacheCoordinator.init();
+ });
+ tearDownAll(() async {
+ await FiroCacheCoordinator.close();
+ await directory.delete(recursive: true);
+ });
+
+ testWidgets('closing the dialog during an immediate reset is safe', (
+ tester,
+ ) async {
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ final container = ProviderContainer(
+ overrides: [
+ pWallets.overrideWithValue(_Wallets()),
+ themeProvider.overrideWithValue(StateController(theme)),
+ ],
+ );
+ addTearDown(container.dispose);
+ await tester.pumpWidget(
+ UncontrolledProviderScope(
+ container: container,
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showDialog<void>(
+ context: context,
+ builder: (_) => MoreFeaturesDialog(
+ walletId: 'firo',
+ options: [(WalletFeature.clearSparkCache, '', () {})],
+ ),
+ ),
+ child: const Text('Open features'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open features'));
+ await tester.pumpAndSettle();
+
+ late _Client client;
+ late Future<void> stopped;
+ await tester.runAsync(() async {
+ client = _Client();
+ final fetch =
+ FiroCacheCoordinator.runFetchAndUpdateSparkAnonSetCacheForGroupId(
+ 1,
+ client,
+ CryptoCurrencyNetwork.main,
+ null,
+ );
+ stopped = expectLater(fetch, throwsA(isA<FiroCacheResetException>()));
+ await client.started.future;
+ });
+ // File operations may still be in progress when the dialog is dismissed.
+ final context = tester.element(find.byType(MoreFeaturesDialog));
+ await tester.runAsync(() async {
+ await tester.tap(find.text('Reset Spark electrumx cache'));
+ Navigator.of(context).pop();
+ await stopped;
+ expect(
+ await FiroCacheCoordinator.getUsedCoinTagsCount(
+ CryptoCurrencyNetwork.main,
+ ).timeout(const Duration(seconds: 3)),
+ 0,
+ );
+ expect(client.response.isCompleted, isFalse);
+ client.response.complete(
+ SparkAnonymitySetMeta(
+ coinGroupId: 1,
+ blockHash: 'block',
+ setHash: 'set',
+ size: 0,
+ ),
+ );
+ await Future<void>.delayed(Duration.zero);
+ });
+ await tester.pumpAndSettle();
+ expect(find.byType(MoreFeaturesDialog), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+}
### test/db/firo_cache_reset_recovery_test.dart
@@ -0,0 +1,60 @@
+import 'dart:io';
+import 'dart:isolate';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:sqlite3/sqlite3.dart';
+import 'package:stackwallet/db/sqlite/firo_cache.dart';
+import 'package:stackwallet/utilities/stack_file_system.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+// Each isolate simulates a new process opening cache files after termination.
+Future<(int, bool, bool)> recover(String root, String intent) async {
+ StackFileSystem.setDesktopOverrideDir(root);
+ final dir = await StackFileSystem.applicationFiroCacheSQLiteDirectory();
+ final sets = sqlite3.open('${dir.path}/spark_set_v2.sqlite3');
+ sets.execute('''
+ CREATE TABLE SparkSet (id INTEGER PRIMARY KEY, blockHash TEXT,
+ setHash TEXT, groupId INTEGER, size INTEGER);
+ INSERT INTO SparkSet VALUES (1, 'old', 'old', 1, 1);
+ ''');
+ sets.close();
+ final tags = sqlite3.open('${dir.path}/spark_tags_v2.sqlite3');
+ tags.execute('''
+ CREATE TABLE SparkUsedCoinTags (id INTEGER PRIMARY KEY, tag TEXT, txid TEXT);
+ INSERT INTO SparkUsedCoinTags VALUES (1, 'old', 'tx');
+ ''');
+ tags.close();
+ final marker = File('${dir.path}/spark_reset_main.pending');
+ await marker.writeAsString(intent, flush: true);
+ await FiroCacheCoordinator.init();
+ try {
+ return (
+ await FiroCacheCoordinator.getUsedCoinTagsCount(
+ CryptoCurrencyNetwork.main,
+ ),
+ await FiroCacheCoordinator.getLatestSetInfoForGroupId(
+ 1,
+ CryptoCurrencyNetwork.main,
+ ) ==
+ null,
+ await marker.exists(),
+ );
+ } finally {
+ await FiroCacheCoordinator.close();
+ }
+}
+
+void main() {
+ for (final intent in ['all-v1', 'tags-v1', '']) {
+ test('startup replays persisted reset intent "$intent"', () async {
+ final dir = await Directory.systemTemp.createTemp('firo-reset-recovery-');
+ final root = dir.path;
+ try {
+ final result = await Isolate.run(() => recover(root, intent));
+ expect(result, (0, intent != 'tags-v1', false));
+ } finally {
+ await dir.delete(recursive: true);
+ }
+ });
+ }
+}
### test/pages/exchange_view/exchange_form_debounce_test.dart
@@ -4,13 +4,16 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:stackwallet/models/exchange/aggregate_currency.dart';
+import 'package:stackwallet/models/exchange/response_objects/estimate.dart';
import 'package:stackwallet/models/isar/exchange_cache/currency.dart';
import 'package:stackwallet/models/isar/exchange_cache/pair.dart';
import 'package:stackwallet/models/isar/stack_theme.dart';
import 'package:stackwallet/pages/exchange_view/exchange_form.dart';
+import 'package:stackwallet/pages/exchange_view/sub_widgets/rate_type_toggle.dart';
import 'package:stackwallet/providers/exchange/exchange_form_state_provider.dart';
import 'package:stackwallet/providers/global/locale_provider.dart';
import 'package:stackwallet/providers/global/prefs_provider.dart';
+import 'package:stackwallet/services/exchange/exchange_response.dart';
import 'package:stackwallet/services/locale_service.dart';
import 'package:stackwallet/themes/stack_colors.dart';
import 'package:stackwallet/themes/theme_service.dart';
@@ -161,6 +164,84 @@ void main() {
expect(tester.widget<TextField>(sendField).controller!.text, "1.12345678");
});
+ testWidgets("estimated receive focus preserves amounts without refreshing", (
+ tester,
+ ) async {
+ final container = await pumpForm(
+ tester,
+ receive: currency("RECEIVE"),
+ sendAmount: Decimal.one,
+ receiveAmount: Decimal.fromInt(2),
+ );
+ final sendField = find.byType(TextField).first;
+ final receiveField = find.byType(TextField).last;
+ final refreshChanges = <bool>[];
+ final subscription = container.listen(
+ efRefreshingProvider,
+ (_, next) => refreshChanges.add(next),
+ );
+ addTearDown(subscription.close);
+
+ await tester.tap(sendField);
+ await tester.pump();
+ await tester.tap(receiveField);
+ await tester.pumpAndSettle();
+
+ expect(tester.widget<TextField>(receiveField).focusNode!.hasFocus, isTrue);
+ expect(container.read(efReversedProvider), isFalse);
+ expect(container.read(efSendAmountProvider), Decimal.one);
+ expect(container.read(efReceiveAmountProvider), Decimal.fromInt(2));
+ expect(tester.widget<TextField>(sendField).controller!.text, "1");
+ expect(tester.widget<TextField>(receiveField).controller!.text, "2");
+ expect(refreshChanges, isEmpty);
+ });
+
+ testWidgets("switching from reverse fixed to estimated uses send amount", (
+ tester,
+ ) async {
+ final container = await pumpForm(
+ tester,
+ receive: currency("RECEIVE"),
+ sendAmount: Decimal.one,
+ receiveAmount: Decimal.fromInt(2),
+ fixedRate: true,
+ );
+ await tester.tap(find.byType(TextField).last);
+ await tester.pumpAndSettle();
+ expect(container.read(efReversedProvider), isTrue);
+
+ // Supply the reverse quote's calculated send amount without network calls.
+ final exchangeName = container.read(efExchangeProvider).name;
+ container
+ .read(efEstimatesListProvider(exchangeName).notifier)
+ .state = Tuple2(
+ ExchangeResponse(
+ value: [
+ Estimate(
+ estimatedAmount: Decimal.one,
+ fixedRate: true,
+ reversed: true,
+ exchangeProvider: exchangeName,
+ ),
+ ],
+ ),
+ null,
+ );
+ await tester.pumpAndSettle();
+ expect(container.read(efSendAmountProvider), Decimal.one);
+
+ await tester.tap(find.byType(RateTypeToggle));
+ await tester.pumpAndSettle();
+
+ expect(container.read(efRateTypeProvider), ExchangeRateType.estimated);
+ expect(container.read(efReversedProvider), isFalse);
+ expect(container.read(efSendAmountProvider), Decimal.one);
+ expect(
+ tester.widget<TextField>(find.byType(TextField).first).controller!.text,
+ "1",
+ );
+ });
+
testWidgets("swap commits amount before canceling its debounce", (
tester,
) async {
@@ -273,4 +354,86 @@ void main() {
expect(container.read(efSendAmountProvider), amount);
});
+
+ for (final receive in [false, true]) {
+ testWidgets(
+ "queued ${receive ? 'receive' : 'send'} focus ignores a disposed form",
+ (tester) async {
+ final container = await pumpForm(
+ tester,
+ receive: currency("RECEIVE"),
+ sendAmount: Decimal.one,
+ receiveAmount: Decimal.fromInt(2),
+ fixedRate: true,
+ );
+ final fields = find.byType(TextField);
+ final field = tester.widget<TextField>(
+ receive ? fields.last : fields.first,
+ );
+ expect(field.focusNode!.hasFocus, isFalse);
+ field.focusNode!.requestFocus();
+ // Queue the real focus callback, then unmount before its post-frame
+ // provider access. Keep the mounted guard in each listener.
+ FocusManager.instance.applyFocusChangesIfNeeded();
+ expect(field.focusNode!.hasFocus, isTrue);
+
+ await tester.pumpWidget(const SizedBox.shrink());
+
+ expect(tester.takeException(), isNull);
+ expect(container.read(efReversedProvider), isFalse);
+ expect(container.read(efRefreshingProvider), isFalse);
+ },
+ );
+ }
+
+ testWidgets("disposed form clears its orphaned refresh on the next frame", (
+ tester,
+ ) async {
+ final container = await pumpForm(tester);
+ final dynamic state = tester.state(find.byType(ExchangeForm));
+ // A pair with no amount completes immediately but queues its loading-state
+ // cleanup for the next frame. With no replacement request, it must clear.
+ await state.update();
+ expect(container.read(efRefreshingProvider), isTrue);
+
+ await tester.pumpWidget(const SizedBox.shrink());
+
+ expect(container.read(efRefreshingProvider), isFalse);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets("update ignores an already disposed form", (tester) async {
+ final container = await pumpForm(tester);
+ final dynamic state = tester.state(find.byType(ExchangeForm));
+ await tester.pumpWidget(const SizedBox.shrink());
+
+ await state.update();
+
+ expect(container.read(efRefreshingProvider), isFalse);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets("refresh that changes nothing still clears its loading state", (
+ tester,
+ ) async {
+ final container = await pumpForm(tester);
+ final dynamic state = tester.state(find.byType(ExchangeForm));
+ // Leave the loading state set with no frame pending, as an older quote
+ // would. The replacement request below changes nothing else.
+ container.read(efRefreshingProvider.notifier).begin(Object());
+ await tester.pumpAndSettle(
+ const Duration(milliseconds: 16),
+ EnginePhase.sendSemanticsUpdate,
+ const Duration(seconds: 5),
+ );
+ expect(tester.binding.hasScheduledFrame, isFalse);
+
+ await state.update();
+
+ expect(container.read(efRefreshingProvider), isTrue);
+ expect(tester.binding.hasScheduledFrame, isTrue);
+ await tester.pump();
+ expect(container.read(efRefreshingProvider), isFalse);
+ expect(tester.takeException(), isNull);
+ });
}
### test/pages/exchange_view/exchange_form_lifecycle_test.dart
@@ -0,0 +1,573 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:decimal/decimal.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mockito/mockito.dart';
+import 'package:platform/platform.dart' as platform;
+import 'package:stackwallet/models/exchange/aggregate_currency.dart';
+import 'package:stackwallet/models/exchange/incomplete_exchange.dart';
+import 'package:stackwallet/models/isar/exchange_cache/currency.dart';
+import 'package:stackwallet/models/isar/exchange_cache/pair.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/pages/exchange_view/exchange_form.dart';
+import 'package:stackwallet/providers/exchange/exchange_form_state_provider.dart';
+import 'package:stackwallet/providers/global/locale_provider.dart';
+import 'package:stackwallet/providers/global/prefs_provider.dart';
+import 'package:stackwallet/services/exchange/change_now/change_now_exchange.dart';
+import 'package:stackwallet/services/locale_service.dart';
+import 'package:stackwallet/themes/stack_colors.dart';
+import 'package:stackwallet/themes/theme_service.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/util.dart';
+import 'package:stackwallet/utilities/enums/exchange_rate_type_enum.dart';
+import 'package:tuple/tuple.dart';
+
+import '../../sample_data/theme_json.dart';
+
+class _ThemeService extends Mock implements ThemeService {}
+
+class _Prefs extends Mock implements Prefs {
+ @override
+ bool get useTor => false;
+}
+
+class _LocaleService extends LocaleService {
+ @override
+ String get locale => 'en_US';
+}
+
+class _Headers extends Mock implements HttpHeaders {
+ @override
+ void add(String name, Object value, {bool preserveHeaderCase = false}) {}
+
+ @override
+ void forEach(void Function(String, List<String>) action) {}
+}
+
+class _Response extends Mock implements HttpClientResponse {
+ _Response(Map<String, dynamic> body)
+ : _body = Stream.value(utf8.encode(jsonEncode(body)));
+
+ final Stream<List<int>> _body;
+
+ @override
+ int get statusCode => 200;
+
+ @override
+ HttpHeaders get headers => _Headers();
+
+ @override
+ StreamSubscription<List<int>> listen(
+ void Function(List<int>)? onData, {
+ Function? onError,
+ void Function()? onDone,
+ bool? cancelOnError,
+ }) => _body.listen(
+ onData,
+ onError: onError,
+ onDone: onDone,
+ cancelOnError: cancelOnError,
+ );
+}
+
+class _PendingRequest {
+ _PendingRequest(this.uri);
+
+ final Uri uri;
+ final response = Completer<HttpClientResponse>();
+
+ bool get isEstimate => uri.path.endsWith('/estimated-amount');
+
+ void complete({int amount = 2}) {
+ response.complete(
+ _Response(
+ isEstimate
+ ? {
+ 'fromCurrency': uri.queryParameters['fromCurrency'],
+ 'fromNetwork': uri.queryParameters['fromNetwork'],
+ 'toCurrency': uri.queryParameters['toCurrency'],
+ 'toNetwork': uri.queryParameters['toNetwork'],
+ 'fromAmount': uri.queryParameters['fromAmount'] ?? '1',
+ 'toAmount': '$amount',
+ 'flow': uri.queryParameters['flow'],
+ 'type': uri.queryParameters['type'],
+ 'depositFee': '0',
+ 'withdrawalFee': '0',
+ }
+ : {'minAmount': '0.1', 'maxAmount': '100'},
+ ),
+ );
+ }
+}
+
+class _Request extends Mock implements HttpClientRequest {
+ _Request(this.pending);
+
+ final _PendingRequest pending;
+
+ @override
+ HttpHeaders get headers => _Headers();
+
+ @override
+ Future<HttpClientResponse> close() => pending.response.future;
+}
+
+class _HttpClient extends Mock implements HttpClient {
+ _HttpClient(this.requests);
+
+ final List<_PendingRequest> requests;
+
+ @override
+ Future<HttpClientRequest> getUrl(Uri url) async {
+ final pending = _PendingRequest(url);
+ requests.add(pending);
+ return _Request(pending);
+ }
+
+ @override
+ void close({bool force = false}) {}
+}
+
+class _HttpOverrides extends HttpOverrides {
+ final requests = <_PendingRequest>[];
+
+ @override
+ HttpClient createHttpClient(SecurityContext? context) =>
+ _HttpClient(requests);
+
+ Future<void> completeQuote(
+ WidgetTester tester,
+ _PendingRequest range, {
+ int amount = 2,
+ }) async {
+ final previousCount = requests.length;
+ range.complete();
+ await tester.pump();
+ // A retired/superseded request stops after its range; the old implementation
+ // still asks for an estimate, which we complete to avoid stranded tests.
+ for (final request in requests.skip(previousCount)) {
+ expect(request.isEstimate, isTrue);
+ request.complete(amount: amount);
+ }
+ await tester.pump();
+ }
+}
+
+const _first = ValueKey('first form');
+const _second = ValueKey('second form');
+
+AggregateCurrency _currency(String ticker, String exchange) =>
+ AggregateCurrency(
+ exchangeCurrencyPairs: [
+ Tuple2(
+ exchange,
+ Currency(
+ exchangeName: exchange,
+ ticker: ticker,
+ name: ticker,
+ network: ticker.toLowerCase(),
+ image: '',
+ isFiat: false,
+ rateType: SupportedRateType.both,
+ isStackCoin: false,
+ tokenContract: null,
+ ),
+ ),
+ ],
+ );
+
+class _Harness {
+ _Harness({required bool quotes}) {
+ final themeService = _ThemeService();
+ when(themeService.getTheme(themeId: 'light')).thenReturn(theme);
+ container = ProviderContainer(
+ overrides: [
+ pThemeService.overrideWithValue(themeService),
+ prefsChangeNotifierProvider.overrideWithValue(_Prefs()),
+ localeServiceChangeNotifierProvider.overrideWithValue(_LocaleService()),
+ ],
+ );
+ addTearDown(container.dispose);
+ setPair(quotes: quotes);
+ container.read(efSendAmountProvider.notifier).state = quotes
+ ? Decimal.one
+ : null;
+ }
+
+ void setPair({required bool quotes}) {
+ final exchange = quotes ? ChangeNowExchange.exchangeName : 'Majestic Bank';
+ container.read(efCurrencyPairProvider)
+ ..setSend(_currency('UNKNOWN', exchange))
+ ..setReceive(_currency('RECEIVE', exchange));
+ }
+
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ late final ProviderContainer container;
+ Object? navigationArguments;
+ bool _surfaceSet = false;
+
+ bool get refreshing => container.read(efRefreshingProvider);
+
+ Decimal? get estimate => container
+ .read(efEstimatesListProvider(ChangeNowExchange.exchangeName))
+ ?.item1
+ .value
+ ?.single
+ .estimatedAmount;
+
+ Future<void> pump(WidgetTester tester, List<Key> keys) async {
+ if (!_surfaceSet) {
+ _surfaceSet = true;
+ await tester.binding.setSurfaceSize(const Size(1200, 2000));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ }
+ await tester.pumpWidget(
+ UncontrolledProviderScope(
+ container: container,
+ child: MaterialApp(
+ onGenerateRoute: (settings) {
+ navigationArguments = settings.arguments;
+ return MaterialPageRoute<void>(
+ builder: (_) => const Scaffold(body: Text('Next exchange step')),
+ );
+ },
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: Scaffold(
+ body: Column(
+ children: [for (final key in keys) ExchangeForm(key: key)],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Future<void> update(WidgetTester tester, Key key) {
+ final dynamic state = tester.state(find.byKey(key));
+ return state.update() as Future<void>;
+ }
+}
+
+void main() {
+ test('a loading listener can begin a replacement refresh', () {
+ final container = ProviderContainer();
+ addTearDown(container.dispose);
+ final controller = container.read(efRefreshingProvider.notifier);
+ final first = Object();
+ final second = Object();
+ controller.begin(first);
+ controller.addListener((loading) {
+ if (!loading) controller.begin(second);
+ }, fireImmediately: false);
+ controller.finish(first);
+ expect(container.read(efRefreshingProvider), isTrue);
+ expect(controller.owns(second), isTrue);
+ // Repeated cleanup for the previous request must leave the successor alone.
+ controller.finish(first);
+ expect(container.read(efRefreshingProvider), isTrue);
+ });
+
+ testWidgets('reopening clears a retired form refresh', (tester) async {
+ final harness = _Harness(quotes: false);
+ await harness.pump(tester, [_first]);
+ await harness.update(tester, _first);
+ expect(harness.refreshing, isTrue);
+ await harness.pump(tester, []);
+ await harness.pump(tester, [_second]);
+ await tester.pump(const Duration(seconds: 5));
+ expect(harness.refreshing, isFalse);
+ });
+
+ for (final duringEstimate in [false, true]) {
+ testWidgets(
+ 'disposal during ${duringEstimate ? 'estimate' : 'range'} clears refresh',
+ (tester) async {
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: true);
+ await harness.pump(tester, [_first]);
+ final Future<void> pending = harness.update(tester, _first);
+ await tester.pump();
+ expect(http.requests, hasLength(1));
+ if (duringEstimate) {
+ http.requests.single.complete();
+ await tester.pump();
+ expect(http.requests, hasLength(2));
+ }
+ final request = http.requests.last;
+ await harness.pump(tester, []);
+ expect(harness.refreshing, isFalse);
+ request.complete();
+ await pending;
+ await tester.pump();
+ expect(harness.estimate, isNull);
+ expect(tester.takeException(), isNull);
+ }, http);
+ },
+ );
+ }
+
+ testWidgets('latest quote finishes while an older quote is pending', (
+ tester,
+ ) async {
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: true);
+ await harness.pump(tester, [_first]);
+ final Future<void> older = harness.update(tester, _first);
+ await tester.pump();
+ final firstRange = http.requests.single;
+ final Future<void> newer = harness.update(tester, _first);
+ await tester.pump();
+ await http.completeQuote(tester, http.requests.last, amount: 2);
+ await newer;
+ await tester.pump();
+ expect(harness.refreshing, isFalse);
+ expect(harness.estimate, Decimal.fromInt(2));
+ await http.completeQuote(tester, firstRange, amount: 99);
+ await older;
+ await tester.pump();
+ expect(harness.estimate, Decimal.fromInt(2));
+ }, http);
+ });
+
+ testWidgets('estimated output updates while its read-only field has focus', (
+ tester,
+ ) async {
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: true);
+ await harness.pump(tester, [_first]);
+ final pending = harness.update(tester, _first);
+ await tester.pump();
+ final range = http.requests.single;
+ final receiveField = find.byType(TextField).last;
+ await tester.tap(receiveField);
+ await tester.pump();
+ expect(tester.widget<TextField>(receiveField).readOnly, isTrue);
+ expect(harness.container.read(efReversedProvider), isFalse);
+
+ await http.completeQuote(tester, range, amount: 6);
+ await pending;
+ await tester.pump();
+
+ expect(harness.refreshing, isFalse);
+ expect(
+ harness.container.read(efReceiveAmountProvider),
+ Decimal.fromInt(6),
+ );
+ final field = tester.widget<TextField>(receiveField);
+ expect(field.focusNode!.hasFocus, isTrue);
+ expect(field.controller!.text, '6');
+ }, http);
+ });
+
+ for (final reversed in [false, true]) {
+ testWidgets(
+ 'a completed quote preserves ${reversed ? 'receive' : 'send'} text '
+ 'edited during debounce',
+ (tester) async {
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: true);
+ if (reversed) {
+ harness.container.read(efRateTypeProvider.notifier).state =
+ ExchangeRateType.fixed;
+ harness.container.read(efReversedProvider.notifier).state = true;
+ harness.container.read(efReceiveAmountProvider.notifier).state =
+ Decimal.one;
+ }
+ await harness.pump(tester, [_first]);
+ final pending = harness.update(tester, _first);
+ await tester.pump();
+ final range = http.requests.single;
+ final field = reversed
+ ? find.byType(TextField).last
+ : find.byType(TextField).first;
+ await tester.tap(field);
+ await tester.pump();
+ await tester.enterText(field, '3.12000001');
+ final controller = tester.widget<TextField>(field).controller!;
+ controller.selection = const TextSelection.collapsed(offset: 3);
+ await http.completeQuote(tester, range);
+ await pending;
+ await tester.pump();
+ expect(
+ tester.widget<TextField>(field).controller!.text,
+ '3.12000001',
+ );
+ expect(
+ controller.selection,
+ const TextSelection.collapsed(offset: 3),
+ );
+ await tester.pump(const Duration(milliseconds: 1500));
+ expect(
+ harness.container.read(
+ reversed ? efReceiveAmountProvider : efSendAmountProvider,
+ ),
+ Decimal.parse('3.12000001'),
+ );
+ await http.completeQuote(tester, http.requests.last);
+ await tester.pumpWidget(const SizedBox.shrink());
+ expect(tester.takeException(), isNull);
+ }, http);
+ },
+ );
+ }
+
+ testWidgets('swap commits pending text and waits for its refreshed quote', (
+ tester,
+ ) async {
+ final previousPlatform = Util.layoutPlatform;
+ Util.layoutPlatform = platform.FakePlatform(operatingSystem: 'android');
+ addTearDown(() => Util.layoutPlatform = previousPlatform);
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: true);
+ await harness.pump(tester, [_first]);
+ final first = harness.update(tester, _first);
+ await tester.pump();
+ await http.completeQuote(tester, http.requests.single);
+ await first;
+ await tester.pump();
+ final sendField = find.byType(TextField).first;
+ await tester.tap(sendField);
+ await tester.pump();
+ await tester.enterText(sendField, '3.12000001');
+ await tester.tap(find.text('Swap'));
+ await tester.pump();
+ expect(harness.navigationArguments, isNull);
+ final range = http.requests.last;
+ range.complete();
+ await tester.pump();
+ final estimate = http.requests.last;
+ expect(estimate.isEstimate, isTrue);
+ expect(estimate.uri.queryParameters['fromAmount'], '3.12000001');
+ expect(harness.navigationArguments, isNull);
+ estimate.complete(amount: 6);
+ await tester.pumpAndSettle();
+ final model = harness.navigationArguments as IncompleteExchangeModel;
+ expect(model.sendAmount, Decimal.parse('3.12000001'));
+ expect(model.receiveAmount, Decimal.fromInt(6));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox.shrink());
+ }, http);
+ });
+
+ testWidgets('older live form cannot publish or clear a newer form quote', (
+ tester,
+ ) async {
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: true);
+ await harness.pump(tester, [_first, _second]);
+ final Future<void> older = harness.update(tester, _first);
+ await tester.pump();
+ final firstRange = http.requests.single;
+ final Future<void> newer = harness.update(tester, _second);
+ await tester.pump();
+ final secondRange = http.requests.last;
+ await http.completeQuote(tester, firstRange, amount: 99);
+ await older;
+ await tester.pump();
+ expect(harness.refreshing, isTrue);
+ expect(harness.estimate, isNull);
+ await http.completeQuote(tester, secondRange, amount: 2);
+ await newer;
+ await tester.pump();
+ expect(harness.refreshing, isFalse);
+ expect(harness.estimate, Decimal.fromInt(2));
+ }, http);
+ });
+
+ testWidgets('older estimate cannot replace a newer live form result', (
+ tester,
+ ) async {
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: true);
+ await harness.pump(tester, [_first, _second]);
+ final older = harness.update(tester, _first);
+ await tester.pump();
+ http.requests.single.complete();
+ await tester.pump();
+ final firstEstimate = http.requests.last;
+ expect(firstEstimate.isEstimate, isTrue);
+ final newer = harness.update(tester, _second);
+ await tester.pump();
+ await http.completeQuote(tester, http.requests.last, amount: 2);
+ await newer;
+ await tester.pump();
+ expect(harness.estimate, Decimal.fromInt(2));
+ firstEstimate.complete(amount: 99);
+ await older;
+ await tester.pump();
+ expect(harness.estimate, Decimal.fromInt(2));
+ expect(harness.refreshing, isFalse);
+ }, http);
+ });
+
+ testWidgets('retired owner cannot clear an active replacement quote', (
+ tester,
+ ) async {
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: true);
+ await harness.pump(tester, [_first, _second]);
+ final Future<void> older = harness.update(tester, _first);
+ await tester.pump();
+ final firstRange = http.requests.single;
+ final Future<void> newer = harness.update(tester, _second);
+ await tester.pump();
+ final secondRange = http.requests.last;
+ await harness.pump(tester, [_second]);
+ expect(harness.refreshing, isTrue);
+ firstRange.complete();
+ await older;
+ await tester.pump();
+ expect(harness.refreshing, isTrue);
+ await http.completeQuote(tester, secondRange);
+ await newer;
+ await tester.pump();
+ expect(harness.refreshing, isFalse);
+ }, http);
+ });
+
+ testWidgets('queued cleanup cannot clear another live form quote', (
+ tester,
+ ) async {
+ final http = _HttpOverrides();
+ await HttpOverrides.runWithHttpOverrides(() async {
+ final harness = _Harness(quotes: false);
+ await harness.pump(tester, [_first, _second]);
+ await harness.update(tester, _first);
+ // Retain the first form's pending cleanup while a second form starts.
+ harness.setPair(quotes: true);
+ harness.container.read(efSendAmountProvider.notifier).state = Decimal.one;
+ final Future<void> newer = harness.update(tester, _second);
+ await tester.pump();
+ expect(harness.refreshing, isTrue);
+ await http.completeQuote(tester, http.requests.single);
+ await newer;
+ await tester.pump();
+ expect(harness.refreshing, isFalse);
+ }, http);
+ });
+
+ testWidgets('queued cleanup ignores a disposed provider container', (
+ tester,
+ ) async {
+ final harness = _Harness(quotes: false);
+ await harness.pump(tester, [_first]);
+ await harness.update(tester, _first);
+ harness.container.dispose();
+ await tester.pumpWidget(const SizedBox.shrink());
+ expect(tester.takeException(), isNull);
+ });
+}
### test/pages/send_view/amount_display_updates_test.dart
@@ -12,9 +12,11 @@ import 'package:stackwallet/pages/salvium_stake/salvium_create_stake_view.dart';
import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart';
import 'package:stackwallet/providers/global/locale_provider.dart';
import 'package:stackwallet/providers/global/prefs_provider.dart';
+import 'package:stackwallet/providers/global/price_provider.dart';
import 'package:stackwallet/providers/global/wallets_provider.dart';
import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart';
import 'package:stackwallet/services/locale_service.dart';
+import 'package:stackwallet/services/price_service.dart';
import 'package:stackwallet/themes/coin_icon_provider.dart';
import 'package:stackwallet/themes/stack_colors.dart';
import 'package:stackwallet/themes/theme_providers.dart';
@@ -121,6 +123,10 @@ void main() {
pWalletBalance(walletId)
.overrideWithValue(Balance.zeroFor(currency: coin)),
prefsChangeNotifierProvider.overrideWithValue(prefs),
+ // This fixture checks amount formatting, without background polling.
+ priceAnd24hChangeNotifierProvider.overrideWithValue(
+ PriceService('USD'),
+ ),
localeServiceChangeNotifierProvider.overrideWithValue(locale),
themeProvider.overrideWithProvider(StateProvider((ref) => theme)),
coinIconProvider(coin).overrideWithValue(
### test/pages/send_view/confirmation_fee_rate_test.dart
@@ -0,0 +1,116 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:platform/platform.dart' as platform;
+import 'package:stackwallet/models/isar/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/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/stack_file_system.dart';
+import 'package:stackwallet/utilities/util.dart';
+import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart';
+import 'package:stackwallet/wallets/models/tx_data.dart';
+
+import '../../sample_data/theme_json.dart';
+import '../../wallets/support/xelis_test_fakes.dart';
+
+void main() {
+ for (final desktop in [false, true]) {
+ for (final size in <int?>[100, 0, -1, null]) {
+ testWidgets('confirmation fee rate desktop=$desktop size=$size', (
+ tester,
+ ) async {
+ final previousPlatform = Util.layoutPlatform;
+ final previousWidth = Util.screenWidth;
+ final previousIpad = Util.isIpad;
+ final previousThemes = StackFileSystem.themesDir;
+ Util.layoutPlatform = platform.FakePlatform(
+ operatingSystem: desktop ? 'macos' : 'android',
+ );
+ Util.screenWidth = null;
+ Util.isIpad = false;
+ StackFileSystem.themesDir = Directory('test/sample_data').absolute;
+ tester.view.physicalSize = const Size(1400, 1800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(() {
+ Util.layoutPlatform = previousPlatform;
+ Util.screenWidth = previousWidth;
+ Util.isIpad = previousIpad;
+ StackFileSystem.themesDir = previousThemes;
+ tester.view.resetPhysicalSize();
+ tester.view.resetDevicePixelRatio();
+ });
+ final wallet = TestWallet(FakeNative());
+ final coin = wallet.cryptoCurrency;
+ final amount = Amount(rawValue: BigInt.from(1000), fractionDigits: 8);
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [
+ pWallets.overrideWithValue(ConfirmationWallets(wallet)),
+ pWalletCoin('review-test').overrideWithValue(coin),
+ prefsChangeNotifierProvider.overrideWithValue(
+ ConfirmationPrefs(),
+ ),
+ themeProvider.overrideWithProvider(StateProvider((ref) => theme)),
+ pAmountFormatter(coin).overrideWithValue(
+ AmountFormatter(
+ unit: AmountUnit.normal,
+ locale: 'en_US',
+ coin: coin,
+ maxDecimals: 8,
+ ),
+ ),
+ ],
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: Scaffold(
+ body: ConfirmTransactionView(
+ walletId: 'review-test',
+ onSuccess: () {},
+ txData: TxData(
+ note: '',
+ noteOnChain: '',
+ fee: Amount(rawValue: BigInt.from(125), fractionDigits: 8),
+ vSize: size,
+ recipients: [
+ TxRecipient(
+ address: 'destination',
+ amount: amount,
+ isChange: false,
+ addressType: AddressType.xelis,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ final rate = find.byWidgetPredicate(
+ (widget) => widget is SelectableText && widget.data == '~1.3',
+ );
+ expect(rate, size == 100 ? findsOneWidget : findsNothing);
+ expect(
+ find.text('sats/vByte'),
+ size == 100 ? findsOneWidget : findsNothing,
+ );
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ });
+ }
+ }
+}
### test/pages/send_view/fiat_clear_unit_change_test.dart
@@ -0,0 +1,318 @@
+import 'dart:io';
+
+import 'package:decimal/decimal.dart';
+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/balance.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/models/isar/models/ethereum/eth_contract.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/models/paymint/fee_object_model.dart';
+import 'package:stackwallet/pages/send_view/send_view.dart';
+import 'package:stackwallet/pages/send_view/token_send_view.dart';
+import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart';
+import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_token_send.dart';
+import 'package:stackwallet/providers/global/locale_provider.dart';
+import 'package:stackwallet/providers/global/prefs_provider.dart';
+import 'package:stackwallet/providers/global/price_provider.dart';
+import 'package:stackwallet/providers/global/wallets_provider.dart';
+import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart';
+import 'package:stackwallet/services/locale_service.dart';
+import 'package:stackwallet/services/price_service.dart';
+import 'package:stackwallet/themes/coin_icon_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_unit.dart';
+import 'package:stackwallet/utilities/default_eth_tokens.dart';
+import 'package:stackwallet/utilities/stack_file_system.dart';
+import 'package:stackwallet/utilities/util.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/isar/providers/eth/current_token_wallet_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/eth/token_balance_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart';
+import 'package:stackwallet/wallets/wallet/impl/sub_wallets/eth_token_wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+import '../../sample_data/theme_json.dart';
+import '../../wallets/support/xelis_test_fakes.dart';
+
+class _Locale extends LocaleService {
+ @override
+ String get locale => 'en_US';
+}
+
+class _Prefs extends ConfirmationPrefs {
+ AmountUnit selectedUnit = AmountUnit.normal;
+ @override
+ bool get enableCoinControl => false;
+ @override
+ bool get externalCalls => true;
+ @override
+ AmountUnit amountUnit(CryptoCurrency coin) => selectedUnit;
+ @override
+ int maxDecimals(CryptoCurrency coin) => coin.fractionDigits;
+ void changeUnit(AmountUnit next) {
+ selectedUnit = next;
+ notifyListeners();
+ }
+}
+
+class _Price extends PriceService {
+ _Price() : super('USD');
+ @override
+ ({Decimal value, double change24h})? getPrice(CryptoCurrency coin) =>
+ (value: Decimal.one, change24h: 0);
+ @override
+ ({Decimal value, double change24h})? getTokenPrice(String contractAddress) =>
+ (value: Decimal.one, change24h: 0);
+}
+
+class _XelisWallet extends TestWallet {
+ _XelisWallet(this.info) : super(FakeNative());
+ final _coin = Xelis(CryptoCurrencyNetwork.test);
+ @override
+ Xelis get cryptoCurrency => _coin;
+ @override
+ final WalletInfo info;
+}
+
+EthFeeObject get _fees => EthFeeObject(
+ suggestBaseFee: BigInt.one,
+ numberOfBlocksFast: 1,
+ numberOfBlocksAverage: 1,
+ numberOfBlocksSlow: 1,
+ fast: BigInt.one,
+ medium: BigInt.one,
+ slow: BigInt.one,
+);
+
+class _ParentWallet extends Fake implements Wallet<Ethereum> {
+ _ParentWallet(this.info);
+ @override
+ final WalletInfo info;
+ @override
+ Ethereum get cryptoCurrency => info.coin as Ethereum;
+ @override
+ Future<FeeObject> get fees async => _fees;
+ @override
+ Future<Amount> estimateFeeFor(Amount amount, BigInt feeRate) async =>
+ Amount.zeroWith(fractionDigits: 18);
+}
+
+class _TokenWallet extends Fake implements EthTokenWallet {
+ _TokenWallet(this.tokenContract, this.info);
+ @override
+ final EthContract tokenContract;
+ @override
+ final WalletInfo info;
+ @override
+ Ethereum get cryptoCurrency => info.coin as Ethereum;
+ @override
+ Future<EthFeeObject> get fees async => _fees;
+ @override
+ Future<Amount> estimateFeeFor(Amount amount, BigInt feeRate) async =>
+ Amount.zeroWith(fractionDigits: 18);
+}
+
+void main() {
+ const walletId = 'fiat-clear';
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+
+ List<Override> commonOverrides({
+ required WalletInfo info,
+ required CryptoCurrency coin,
+ required _Prefs prefs,
+ }) => [
+ pWalletInfo(walletId).overrideWithValue(info),
+ pWalletCoin(walletId).overrideWithValue(coin),
+ pWalletName(walletId).overrideWithValue(info.name),
+ prefsChangeNotifierProvider.overrideWithValue(prefs),
+ localeServiceChangeNotifierProvider.overrideWithValue(_Locale()),
+ priceAnd24hChangeNotifierProvider.overrideWithValue(_Price()),
+ themeProvider.overrideWithProvider(StateProvider((ref) => theme)),
+ coinIconProvider(coin).overrideWithValue(
+ File('test/sample_data/light/assets/dummy.svg').absolute.path,
+ ),
+ ];
+
+ Future<ProviderContainer> mount(
+ WidgetTester tester, {
+ required bool desktop,
+ required List<Override> overrides,
+ required Widget child,
+ }) async {
+ final oldPlatform = Util.layoutPlatform;
+ final oldThemes = StackFileSystem.themesDir;
+ Util.layoutPlatform = platform.FakePlatform(
+ operatingSystem: desktop ? 'linux' : 'android',
+ );
+ StackFileSystem.themesDir = Directory('test/sample_data').absolute;
+ tester.view.physicalSize = const Size(1200, 1800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(() {
+ Util.layoutPlatform = oldPlatform;
+ StackFileSystem.themesDir = oldThemes;
+ tester.view.resetPhysicalSize();
+ tester.view.resetDevicePixelRatio();
+ });
+ final container = ProviderContainer(overrides: overrides);
+ addTearDown(container.dispose);
+ await tester.pumpWidget(
+ UncontrolledProviderScope(
+ container: container,
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: desktop
+ ? Scaffold(body: SingleChildScrollView(child: child))
+ : child,
+ ),
+ ),
+ );
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ });
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ return container;
+ }
+
+ // Types a fiat amount, clears it again, then switches the display unit.
+ // The crypto field must stay blank: a cleared field has no amount to
+ // reformat, so the unit change must not write "0" into it.
+ Future<void> clearFiatThenChangeUnit(
+ WidgetTester tester,
+ _Prefs prefs, {
+ required void Function() expectCleared,
+ }) async {
+ final fiat = find.byKey(const Key('amountInputFieldFiatTextFieldKey'));
+ final crypto = find.byKey(const Key('amountInputFieldCryptoTextFieldKey'));
+ expect(fiat, findsOneWidget);
+ String cryptoText() => tester.widget<TextField>(crypto).controller!.text;
+
+ await tester.enterText(fiat, '1');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(cryptoText(), '1');
+
+ await tester.enterText(fiat, '');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(cryptoText(), '');
+ expectCleared();
+
+ prefs.changeUnit(AmountUnit.milli);
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(tester.takeException(), isNull);
+ expect(
+ cryptoText(),
+ '',
+ reason: 'A unit change must not fill a cleared amount field',
+ );
+ expectCleared();
+ }
+
+ for (final desktop in [false, true]) {
+ testWidgets('cleared fiat stays blank after unit change desktop=$desktop', (
+ tester,
+ ) async {
+ final info = WalletInfo(
+ walletId: walletId,
+ name: 'Test wallet',
+ mainAddressType: AddressType.xelis,
+ coinName: Xelis(CryptoCurrencyNetwork.test).identifier,
+ );
+ final wallet = _XelisWallet(info);
+ final coin = wallet.cryptoCurrency;
+ final prefs = _Prefs();
+ final spendable = Amount(
+ rawValue: BigInt.from(1000000000),
+ fractionDigits: coin.fractionDigits,
+ );
+ final zero = Amount.zeroWith(fractionDigits: coin.fractionDigits);
+ final container = await mount(
+ tester,
+ desktop: desktop,
+ overrides: [
+ ...commonOverrides(info: info, coin: coin, prefs: prefs),
+ pWallets.overrideWithValue(ConfirmationWallets(wallet)),
+ pWalletBalance(walletId).overrideWithValue(
+ Balance(
+ total: spendable,
+ spendable: spendable,
+ blockedTotal: zero,
+ pendingSpendable: zero,
+ ),
+ ),
+ ],
+ child: desktop
+ ? const DesktopSend(walletId: walletId)
+ : SendView(walletId: walletId, coin: coin),
+ );
+ await clearFiatThenChangeUnit(
+ tester,
+ prefs,
+ expectCleared: () => expect(container.read(pSendAmount), isNull),
+ );
+ });
+
+ testWidgets(
+ 'cleared token fiat stays blank after unit change desktop=$desktop',
+ (tester) async {
+ final coin = Ethereum(CryptoCurrencyNetwork.main);
+ final contract = DefaultTokens.rsFiro;
+ final info = WalletInfo(
+ walletId: walletId,
+ name: 'Token test',
+ mainAddressType: AddressType.ethereum,
+ coinName: coin.identifier,
+ );
+ final prefs = _Prefs();
+ final zero = Amount.zeroWith(fractionDigits: contract.decimals);
+ final container = await mount(
+ tester,
+ desktop: desktop,
+ overrides: [
+ ...commonOverrides(info: info, coin: coin, prefs: prefs),
+ pWallets.overrideWithValue(
+ ConfirmationWallets(_ParentWallet(info)),
+ ),
+ pCurrentTokenWallet.overrideWithValue(_TokenWallet(contract, info)),
+ pTokenBalance((
+ walletId: walletId,
+ contractAddress: contract.address,
+ )).overrideWithValue(
+ Balance(
+ total: zero,
+ spendable: zero,
+ blockedTotal: zero,
+ pendingSpendable: zero,
+ ),
+ ),
+ ],
+ child: desktop
+ ? const DesktopTokenSend(walletId: walletId)
+ : TokenSendView(
+ walletId: walletId,
+ coin: coin,
+ tokenContract: contract,
+ ),
+ );
+ // The token views keep their amount in widget state, so the blank
+ // field is the only observable after the clear.
+ await clearFiatThenChangeUnit(
+ tester,
+ prefs,
+ expectCleared: () => expect(
+ container.read(previewTokenTxButtonStateProvider.state).state,
+ isFalse,
+ ),
+ );
+ },
+ );
+ }
+}
### test/pages/send_view/open_alias_preview_test.dart
@@ -17,6 +17,7 @@ import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub
import 'package:stackwallet/providers/providers.dart';
import 'package:stackwallet/providers/ui/preview_tx_button_state_provider.dart';
import 'package:stackwallet/services/openalias/open_alias_service.dart';
+import 'package:stackwallet/services/price_service.dart';
import 'package:stackwallet/services/wallets.dart';
import 'package:stackwallet/themes/coin_icon_provider.dart';
import 'package:stackwallet/themes/coin_image_provider.dart';
@@ -236,6 +237,10 @@ class _Harness {
.overrideWithValue('test/sample_data/light/assets/dummy.svg'),
coinImageSecondaryProvider(coin).overrideWithValue('dummy.svg'),
pOpenAliasService.overrideWithValue(service),
+ // Alias resolution tests do not run the application's price timer.
+ priceAnd24hChangeNotifierProvider.overrideWithValue(
+ PriceService('USD'),
+ ),
],
);
addTearDown(() async {
### test/pages/send_view/sol_token_send_locale_change_test.dart
@@ -0,0 +1,326 @@
+import 'dart:io';
+
+import 'package:decimal/decimal.dart';
+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/balance.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/models/isar/models/solana/sol_contract.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/models/paymint/fee_object_model.dart';
+import 'package:stackwallet/pages/send_view/sol_token_send_view.dart';
+import 'package:stackwallet/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_sol_token_send.dart';
+import 'package:stackwallet/providers/global/locale_provider.dart';
+import 'package:stackwallet/providers/global/prefs_provider.dart';
+import 'package:stackwallet/providers/global/price_provider.dart';
+import 'package:stackwallet/providers/global/wallets_provider.dart';
+import 'package:stackwallet/services/locale_service.dart';
+import 'package:stackwallet/services/price_service.dart';
+import 'package:stackwallet/themes/coin_icon_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_unit.dart';
+import 'package:stackwallet/utilities/stack_file_system.dart';
+import 'package:stackwallet/utilities/util.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/isar/providers/solana/current_sol_token_wallet_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/solana/sol_token_balance_provider.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/sub_wallets/solana_token_wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/widgets/desktop/primary_button.dart';
+
+import '../../sample_data/theme_json.dart';
+import '../../wallets/support/xelis_test_fakes.dart';
+
+class _Locale extends LocaleService {
+ String value = 'en_US';
+ @override
+ String get locale => value;
+ void change(String next) {
+ value = next;
+ notifyListeners();
+ }
+}
+
+class _Prefs extends ConfirmationPrefs {
+ @override
+ bool get enableCoinControl => false;
+ @override
+ bool get externalCalls => true;
+ @override
+ AmountUnit amountUnit(CryptoCurrency coin) => AmountUnit.normal;
+ @override
+ int maxDecimals(CryptoCurrency coin) => coin.fractionDigits;
+}
+
+class _Price extends PriceService {
+ _Price() : super('USD');
+ @override
+ ({Decimal value, double change24h})? getTokenPrice(String contractAddress) =>
+ (value: Decimal.one, change24h: 0);
+}
+
+final _fee = Amount(rawValue: BigInt.from(5000), fractionDigits: 9);
+
+FeeObject get _fees => FeeObject(
+ numberOfBlocksFast: 1,
+ numberOfBlocksAverage: 1,
+ numberOfBlocksSlow: 1,
+ fast: _fee.raw,
+ medium: _fee.raw,
+ slow: _fee.raw,
+);
+
+class _ParentWallet extends Fake implements Wallet<Solana> {
+ _ParentWallet(this.info);
+ @override
+ final WalletInfo info;
+ @override
+ Solana get cryptoCurrency => info.coin as Solana;
+ @override
+ Future<FeeObject> get fees async => _fees;
+ @override
+ Future<Amount> estimateFeeFor(Amount amount, BigInt feeRate) async => _fee;
+}
+
+class _SolTokenWallet extends Fake implements SolanaTokenWallet {
+ _SolTokenWallet(this.solContract, this.info);
+ @override
+ final SolContract solContract;
+ @override
+ final WalletInfo info;
+ @override
+ String get walletId => info.walletId;
+ @override
+ CryptoCurrency get cryptoCurrency => info.coin;
+ @override
+ String get tokenMint => solContract.address;
+ @override
+ String get tokenSymbol => solContract.symbol;
+ @override
+ int get tokenDecimals => solContract.decimals;
+ @override
+ Future<FeeObject> get fees async => _fees;
+ @override
+ Future<Amount> estimateFeeFor(Amount amount, BigInt feeRate) async => _fee;
+
+ TxData? captured;
+ @override
+ Future<TxData> prepareSend({required TxData txData, String? assetId}) async {
+ captured = txData;
+ throw StateError('capture');
+ }
+}
+
+void main() {
+ const walletId = 'sol-locale';
+ const mint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+ Future<(_Locale, _SolTokenWallet)> mount(
+ WidgetTester tester, {
+ required bool desktop,
+ }) async {
+ final oldPlatform = Util.layoutPlatform;
+ final oldThemes = StackFileSystem.themesDir;
+ Util.layoutPlatform = platform.FakePlatform(
+ operatingSystem: desktop ? 'linux' : 'android',
+ );
+ StackFileSystem.themesDir = Directory('test/sample_data').absolute;
+ tester.view.physicalSize = const Size(1200, 1800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(() {
+ Util.layoutPlatform = oldPlatform;
+ StackFileSystem.themesDir = oldThemes;
+ tester.view.resetPhysicalSize();
+ tester.view.resetDevicePixelRatio();
+ });
+ final coin = Solana(CryptoCurrencyNetwork.main);
+ final contract = SolContract(
+ address: mint,
+ name: 'USD Coin',
+ symbol: 'USDC',
+ decimals: 6,
+ );
+ final info = WalletInfo(
+ walletId: walletId,
+ name: 'Sol test',
+ mainAddressType: AddressType.solana,
+ coinName: coin.identifier,
+ );
+ final locale = _Locale();
+ final tokenWallet = _SolTokenWallet(contract, info);
+ final zero = Amount.zeroWith(fractionDigits: contract.decimals);
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ final container = ProviderContainer(
+ overrides: [
+ pWallets.overrideWithValue(ConfirmationWallets(_ParentWallet(info))),
+ pCurrentSolanaTokenWallet.overrideWithValue(tokenWallet),
+ pWalletInfo(walletId).overrideWithValue(info),
+ pWalletCoin(walletId).overrideWithValue(coin),
+ pWalletName(walletId).overrideWithValue(info.name),
+ pSolanaTokenBalance((walletId: walletId, tokenMint: mint))
+ .overrideWithValue(
+ Balance(
+ total: zero,
+ spendable: zero,
+ blockedTotal: zero,
+ pendingSpendable: zero,
+ ),
+ ),
+ prefsChangeNotifierProvider.overrideWithValue(_Prefs()),
+ localeServiceChangeNotifierProvider.overrideWithValue(locale),
+ priceAnd24hChangeNotifierProvider.overrideWithValue(_Price()),
+ themeProvider.overrideWithProvider(StateProvider((ref) => theme)),
+ coinIconProvider(coin).overrideWithValue(
+ File('test/sample_data/light/assets/dummy.svg').absolute.path,
+ ),
+ ],
+ );
+ addTearDown(container.dispose);
+ await tester.pumpWidget(
+ UncontrolledProviderScope(
+ container: container,
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: desktop
+ ? const Scaffold(
+ body: SingleChildScrollView(
+ child: DesktopSolTokenSend(walletId: walletId),
+ ),
+ )
+ : const SolTokenSendView(walletId: walletId, tokenMint: mint),
+ ),
+ ),
+ );
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ });
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ return (locale, tokenWallet);
+ }
+
+ testWidgets(
+ 'SOL token send survives a locale change while the fee is pending',
+ (tester) async {
+ final (locale, _) = await mount(tester, desktop: false);
+ expect(find.textContaining('~0.000005'), findsOneWidget);
+
+ final fiat = find.byKey(const Key('solAmountInputFieldFiatTextFieldKey'));
+ final crypto = find.byKey(
+ const Key('solAmountInputFieldCryptoTextFieldKey'),
+ );
+ String cryptoText() => tester.widget<TextField>(crypto).controller!.text;
+
+ // Each fiat edit schedules a fee recalculation half a second later. A
+ // 600 ms pump fires that timer and renders the pending fee row, so the
+ // fee row is not subscribed to the amount formatter when the locale
+ // changes below. The locale change then has to refresh the formatter
+ // lazily, which must not happen from inside the fee row's build.
+ await tester.enterText(fiat, '1');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(tester.takeException(), isNull);
+ expect(cryptoText(), '1');
+
+ await tester.enterText(fiat, '');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(tester.takeException(), isNull);
+ expect(cryptoText(), '');
+
+ locale.change('de_DE');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(tester.takeException(), isNull);
+ expect(find.textContaining('~0,000005'), findsOneWidget);
+
+ locale.change('fr_FR');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(tester.takeException(), isNull);
+ expect(find.textContaining('~0,000005'), findsOneWidget);
+ expect(cryptoText(), '');
+ },
+ );
+
+ for (final desktop in [false, true]) {
+ testWidgets(
+ 'SOL token locale display preserves the next send desktop=$desktop',
+ (tester) async {
+ final (locale, tokenWallet) = await mount(tester, desktop: desktop);
+ final crypto = find.byKey(
+ Key(
+ desktop
+ ? 'amountInputFieldCryptoTextFieldKey'
+ : 'solAmountInputFieldCryptoTextFieldKey',
+ ),
+ );
+ final fiat = find.byKey(
+ Key(
+ desktop
+ ? 'amountInputFieldFiatTextFieldKey'
+ : 'solAmountInputFieldFiatTextFieldKey',
+ ),
+ );
+ final controller = tester.widget<TextField>(crypto).controller!;
+ await tester.enterText(crypto, '1.250001');
+ await tester.pump(const Duration(milliseconds: 600));
+ controller.selection = const TextSelection.collapsed(offset: 3);
+
+ locale.change('de_DE');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(tester.takeException(), isNull);
+ expect(controller.text, '1,250001');
+ expect(controller.selection, const TextSelection.collapsed(offset: 3));
+ expect(tester.widget<TextField>(fiat).controller!.text, '1,25');
+
+ // A real edit after relocalization must still update the send amount.
+ await tester.enterText(crypto, '2,500002');
+ await tester.pump(const Duration(milliseconds: 600));
+ locale.change('en_US');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(tester.takeException(), isNull);
+ expect(controller.text, '2.500002');
+
+ await tester.enterText(
+ find.byKey(
+ Key(
+ desktop
+ ? 'sendViewAddressFieldKey'
+ : 'solTokenSendViewAddressFieldKey',
+ ),
+ ),
+ mint,
+ );
+ await tester.pump();
+ if (desktop) {
+ final preview = tester.widget<PrimaryButton>(
+ find.widgetWithText(PrimaryButton, 'Preview send'),
+ );
+ expect(preview.enabled, isTrue);
+ preview.onPressed!();
+ } else {
+ final preview = tester.widget<TextButton>(
+ find.widgetWithText(TextButton, 'Preview'),
+ );
+ expect(preview.onPressed, isNotNull);
+ preview.onPressed!();
+ }
+ await tester.pump(const Duration(milliseconds: 150));
+ await tester.pump(const Duration(milliseconds: 2600));
+ expect(tokenWallet.captured, isNotNull);
+ final amount = tokenWallet.captured!.recipients!.single.amount;
+ expect(
+ amount,
+ Amount(rawValue: BigInt.from(2500002), fractionDigits: 6),
+ );
+ },
+ );
+ }
+}
### test/pages/settings_views/currency_view_test.dart
@@ -0,0 +1,195 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:platform/platform.dart' as platform;
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/pages/settings_views/global_settings_view/currency_view.dart';
+import 'package:stackwallet/providers/global/prefs_provider.dart';
+import 'package:stackwallet/providers/global/price_provider.dart';
+import 'package:stackwallet/services/price_service.dart';
+import 'package:stackwallet/themes/stack_colors.dart';
+import 'package:stackwallet/themes/theme_providers.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/util.dart';
+
+import '../../sample_data/theme_json.dart';
+
+class _TestPrefs extends ChangeNotifier implements Prefs {
+ String _currency = 'USD';
+
+ @override
+ String get currency => _currency;
+
+ @override
+ set currency(String value) {
+ _currency = value;
+ notifyListeners();
+ }
+
+ @override
+ bool get externalCalls => true;
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+class _PollingPriceService extends PriceService {
+ _PollingPriceService(super.baseTicker);
+ int requests = 0;
+
+ @override
+ Future<void> updatePrice() async {
+ requests++;
+ }
+}
+
+class _PollingTimer implements Timer {
+ @override
+ bool isActive = true;
+
+ @override
+ int get tick => 0;
+
+ @override
+ void cancel() => isActive = false;
+}
+
+void main() {
+ test('a preference change outside settings preserves provider polling', () {
+ final timers = <_PollingTimer>[];
+ runZoned(
+ () {
+ final prefs = _TestPrefs();
+ final container = ProviderContainer(
+ overrides: [prefsChangeNotifierProvider.overrideWithValue(prefs)],
+ );
+ final previous = container.read(priceAnd24hChangeNotifierProvider);
+ previous.start(false);
+ expect(timers.where((timer) => timer.isActive), hasLength(1));
+
+ prefs.currency = 'EUR';
+ final current = container.read(priceAnd24hChangeNotifierProvider);
+ expect(current.baseTicker, 'EUR');
+ expect(timers.where((timer) => timer.isActive), hasLength(1));
+ container.dispose();
+ expect(timers.where((timer) => timer.isActive), isEmpty);
+ },
+ zoneSpecification: ZoneSpecification(
+ createPeriodicTimer: (self, parent, zone, duration, callback) {
+ final timer = _PollingTimer();
+ timers.add(timer);
+ return timer;
+ },
+ ),
+ );
+ });
+
+ testWidgets('starting after provider polling fetches once with one timer', (
+ tester,
+ ) async {
+ final service = _PollingPriceService('USD');
+ service.start(false);
+ expect(service.requests, 0);
+ service.start(true);
+ expect(service.requests, 1);
+ await tester.pump(service.updateInterval);
+ expect(service.requests, 2);
+ service.dispose();
+ });
+
+ for (final desktop in [false, true]) {
+ testWidgets(
+ '${desktop ? 'desktop' : 'mobile'} currency change keeps polling',
+ (tester) async {
+ final previousPlatform = Util.layoutPlatform;
+ final previousWidth = Util.screenWidth;
+ final previousIsIpad = Util.isIpad;
+ Util.layoutPlatform = platform.FakePlatform(
+ operatingSystem: desktop ? 'macos' : 'android',
+ );
+ Util.screenWidth = null;
+ Util.isIpad = false;
+ addTearDown(() {
+ Util.layoutPlatform = previousPlatform;
+ Util.screenWidth = previousWidth;
+ Util.isIpad = previousIsIpad;
+ });
+ final prefs = _TestPrefs();
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ final container = ProviderContainer(
+ overrides: [
+ prefsChangeNotifierProvider.overrideWithValue(prefs),
+ themeProvider.overrideWithProvider(
+ StateProvider<StackTheme>((ref) => theme),
+ ),
+ priceAnd24hChangeNotifierProvider.overrideWithProvider(
+ ChangeNotifierProvider<PriceService>((ref) {
+ return _PollingPriceService(
+ ref.watch(
+ prefsChangeNotifierProvider.select((p) => p.currency),
+ ),
+ );
+ }),
+ ),
+ ],
+ );
+ addTearDown(container.dispose);
+ final previousService = container.read(
+ priceAnd24hChangeNotifierProvider,
+ ) as _PollingPriceService;
+ previousService.start(false);
+ await tester.pumpWidget(
+ UncontrolledProviderScope(
+ container: container,
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => Navigator.of(context).push(
+ MaterialPageRoute<void>(
+ builder: (_) =>
+ const Scaffold(body: BaseCurrencySettingsView()),
+ ),
+ ),
+ child: const Text('Open currencies'),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open currencies'));
+ await tester.pumpAndSettle();
+ await tester.enterText(find.byType(TextField), 'EUR');
+ await tester.pump();
+ await tester.tap(
+ find.byWidgetPredicate(
+ (widget) => widget is Text && widget.data == 'EUR',
+ ),
+ );
+ await tester.pump();
+ if (desktop) {
+ await tester.tap(find.text('Save changes'));
+ await tester.pumpAndSettle();
+ }
+
+ final service = container.read(
+ priceAnd24hChangeNotifierProvider,
+ ) as _PollingPriceService;
+ expect(prefs.currency, 'EUR');
+ expect(service.baseTicker, 'EUR');
+ expect(service.requests, 1);
+ await tester.pump(service.updateInterval);
+ expect(service.requests, 2);
+ expect(previousService.requests, 0);
+ service.cancel();
+ await tester.pumpWidget(const SizedBox.shrink());
+ },
+ );
+ }
+}
### test/price_test.dart
@@ -1,14 +1,17 @@
// TODO MWC
+import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'package:decimal/decimal.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:stackwallet/db/hive/db.dart';
import 'package:stackwallet/networking/http.dart';
import 'package:stackwallet/services/price.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
import 'hive/hive_ce_test_utils.dart';
import 'price_test.mocks.dart';
@@ -392,6 +395,328 @@ void main() {
expectEmptyPriceSnapshot(price.toString());
});
+ Response bitcoinPrice(int value) => Response(
+ utf8.encode(
+ jsonEncode([
+ {"id": "bitcoin", "name": "Bitcoin", "current_price": value},
+ ]),
+ ),
+ 200,
+ );
+
+ test(
+ "failed currency change never returns another currency's prices",
+ () async {
+ final client = MockHTTP();
+ when(
+ client.get(
+ proxyInfo: null,
+ url: anyNamed('url'),
+ headers: {'Content-Type': 'application/json'},
+ ),
+ ).thenAnswer((invocation) async {
+ final uri = invocation.namedArguments[#url] as Uri;
+ if (uri.queryParameters['vs_currency'] == 'usd') {
+ return bitcoinPrice(50000);
+ }
+ throw const SocketException('offline');
+ });
+ final api = PriceAPI(client)
+ ..resetLastCalledToForceNextCallToUpdateCache();
+ final bitcoin = Bitcoin(CryptoCurrencyNetwork.main);
+
+ expect(
+ (await api.getPricesAnd24hChange(baseCurrency: 'USD'))[bitcoin]?.value,
+ Decimal.fromInt(50000),
+ );
+ expect(await api.getPricesAnd24hChange(baseCurrency: 'BTC'), isEmpty);
+ // The throttled path must enforce the same currency boundary.
+ expect(await api.getPricesAnd24hChange(baseCurrency: 'BTC'), isEmpty);
+ expect(
+ (await api.getPricesAnd24hChange(baseCurrency: 'USD'))[bitcoin]?.value,
+ Decimal.fromInt(50000),
+ );
+ },
+ );
+
+ test("overlapping requests retain separate currency caches", () async {
+ final client = MockHTTP();
+ final usdResponse = Completer<Response>();
+ when(
+ client.get(
+ proxyInfo: null,
+ url: anyNamed('url'),
+ headers: {'Content-Type': 'application/json'},
+ ),
+ ).thenAnswer((invocation) async {
+ final uri = invocation.namedArguments[#url] as Uri;
+ return uri.queryParameters['vs_currency'] == 'usd'
+ ? usdResponse.future
+ : bitcoinPrice(1);
+ });
+ final api = PriceAPI(client)..resetLastCalledToForceNextCallToUpdateCache();
+ final bitcoin = Bitcoin(CryptoCurrencyNetwork.main);
+ final pendingUsd = api.getPricesAnd24hChange(baseCurrency: 'usd');
+ await Future<void>.delayed(Duration.zero);
+
+ expect(
+ (await api.getPricesAnd24hChange(baseCurrency: 'btc'))[bitcoin]?.value,
+ Decimal.one,
+ );
+ usdResponse.complete(bitcoinPrice(50000));
+ expect((await pendingUsd)[bitcoin]?.value, Decimal.fromInt(50000));
+ expect(
+ (await api.getPricesAnd24hChange(baseCurrency: 'btc'))[bitcoin]?.value,
+ Decimal.one,
+ );
+ });
+
+ test(
+ "returning to a currency discards its older in-flight response",
+ () async {
+ final client = MockHTTP();
+ final olderUsdResponse = Completer<Response>();
+ var usdRequests = 0;
+ when(
+ client.get(
+ proxyInfo: null,
+ url: anyNamed('url'),
+ headers: {'Content-Type': 'application/json'},
+ ),
+ ).thenAnswer((invocation) async {
+ final uri = invocation.namedArguments[#url] as Uri;
+ if (uri.queryParameters['vs_currency'] == 'btc') return bitcoinPrice(1);
+ return usdRequests++ == 0
+ ? olderUsdResponse.future
+ : bitcoinPrice(75000);
+ });
+ final olderApi = PriceAPI(client)
+ ..resetLastCalledToForceNextCallToUpdateCache();
+ final bitcoin = Bitcoin(CryptoCurrencyNetwork.main);
+ final pendingOlder = olderApi.getPricesAnd24hChange(baseCurrency: 'USD');
+ await Future<void>.delayed(Duration.zero);
+ await PriceAPI(client).getPricesAnd24hChange(baseCurrency: 'BTC');
+ final currentApi = PriceAPI(client);
+ expect(
+ (await currentApi.getPricesAnd24hChange(
+ baseCurrency: 'USD',
+ ))[bitcoin]?.value,
+ Decimal.fromInt(75000),
+ );
+ olderUsdResponse.complete(bitcoinPrice(50000));
+ expect((await pendingOlder)[bitcoin]?.value, Decimal.fromInt(75000));
+ expect(
+ (await currentApi.getPricesAnd24hChange(
+ baseCurrency: 'USD',
+ ))[bitcoin]?.value,
+ Decimal.fromInt(75000),
+ );
+ expect(usdRequests, 2);
+ },
+ );
+
+ test("a throttled read leaves the accepted pending fetch current", () async {
+ final client = MockHTTP();
+ final response = Completer<Response>();
+ when(
+ client.get(
+ proxyInfo: null,
+ url: anyNamed('url'),
+ headers: {'Content-Type': 'application/json'},
+ ),
+ ).thenAnswer((_) => response.future);
+ final api = PriceAPI(client)..resetLastCalledToForceNextCallToUpdateCache();
+ final pending = api.getPricesAnd24hChange(baseCurrency: 'USD');
+ await Future<void>.delayed(Duration.zero);
+ final secondApi = PriceAPI(client);
+ expect(await secondApi.getPricesAnd24hChange(baseCurrency: 'USD'), isEmpty);
+ response.complete(bitcoinPrice(50000));
+ final bitcoin = Bitcoin(CryptoCurrencyNetwork.main);
+ expect((await pending)[bitcoin]?.value, Decimal.fromInt(50000));
+ expect(
+ (await secondApi.getPricesAnd24hChange(
+ baseCurrency: 'USD',
+ ))[bitcoin]?.value,
+ Decimal.fromInt(50000),
+ );
+ verify(
+ client.get(
+ proxyInfo: null,
+ url: anyNamed('url'),
+ headers: {'Content-Type': 'application/json'},
+ ),
+ ).called(1);
+ });
+
+ test("legacy prices are not reused for a different currency", () async {
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePriceCache,
+ key: 'cache',
+ value: {
+ 'Bitcoin': ['50000', 0.0],
+ },
+ );
+ final client = MockHTTP();
+ when(
+ client.get(
+ proxyInfo: null,
+ url: anyNamed('url'),
+ headers: {'Content-Type': 'application/json'},
+ ),
+ ).thenThrow(const SocketException('offline'));
+ final api = PriceAPI(client)..resetLastCalledToForceNextCallToUpdateCache();
+
+ expect(await api.getPricesAnd24hChange(baseCurrency: 'btc'), isEmpty);
+ });
+
+ test(
+ 'offline upgrade migrates legacy prices to the saved currency once',
+ () async {
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePrefs,
+ key: 'currency',
+ value: 'EUR',
+ );
+ // No consent means this test must use cache only, even under Flutter's
+ // external-call test-environment override.
+ await DB.instance.delete<dynamic>(
+ boxName: DB.boxNamePrefs,
+ key: 'externalCalls',
+ );
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePriceCache,
+ key: 'cache',
+ value: {
+ 'Bitcoin': ['42000', 1.5],
+ },
+ );
+ final client = MockHTTP();
+ final api = PriceAPI(client)
+ ..resetLastCalledToForceNextCallToUpdateCache();
+ final bitcoin = Bitcoin(CryptoCurrencyNetwork.main);
+ expect(
+ (await api.getPricesAnd24hChange(baseCurrency: 'EUR'))[bitcoin]?.value,
+ Decimal.fromInt(42000),
+ );
+ expect(
+ (await PriceAPI(
+ client,
+ ).getPricesAnd24hChange(baseCurrency: 'eur'))[bitcoin]?.value,
+ Decimal.fromInt(42000),
+ );
+ expect(await api.getPricesAnd24hChange(baseCurrency: 'USD'), isEmpty);
+ expect(
+ DB.instance.get<dynamic>(boxName: DB.boxNamePriceCache, key: 'cache'),
+ isNull,
+ );
+ verifyZeroInteractions(client);
+ },
+ );
+
+ test('legacy migration preserves a newer currency cache', () async {
+ await DB.instance.delete<dynamic>(
+ boxName: DB.boxNamePrefs,
+ key: 'externalCalls',
+ );
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePriceCache,
+ key: 'cache',
+ value: {
+ 'Bitcoin': ['42000', 0.0],
+ },
+ );
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePriceCache,
+ key: 'cache_usd',
+ value: {
+ 'Bitcoin': ['75000', 0.0],
+ },
+ );
+ final api = PriceAPI(MockHTTP())
+ ..resetLastCalledToForceNextCallToUpdateCache();
+ final bitcoin = Bitcoin(CryptoCurrencyNetwork.main);
+ expect(
+ (await api.getPricesAnd24hChange(baseCurrency: 'USD'))[bitcoin]?.value,
+ Decimal.fromInt(75000),
+ );
+ expect(
+ DB.instance.get<dynamic>(boxName: DB.boxNamePriceCache, key: 'cache'),
+ isNull,
+ );
+ });
+
+ test(
+ 'startup migration claims old prices before settings change currency',
+ () async {
+ await DB.instance.delete<dynamic>(
+ boxName: DB.boxNamePrefs,
+ key: 'externalCalls',
+ );
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePriceCache,
+ key: 'cache',
+ value: {
+ 'Bitcoin': ['50000', 0.0],
+ },
+ );
+ await DB.instance.migrateLegacyPriceCache();
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePrefs,
+ key: 'currency',
+ value: 'EUR',
+ );
+ final api = PriceAPI(MockHTTP())
+ ..resetLastCalledToForceNextCallToUpdateCache();
+ expect(await api.getPricesAnd24hChange(baseCurrency: 'EUR'), isEmpty);
+ final bitcoin = Bitcoin(CryptoCurrencyNetwork.main);
+ expect(
+ (await api.getPricesAnd24hChange(baseCurrency: 'USD'))[bitcoin]?.value,
+ Decimal.fromInt(50000),
+ );
+ },
+ );
+
+ test('concurrent migration uses the saved currency even when USD is requested first', () async {
+ await DB.instance.delete<dynamic>(
+ boxName: DB.boxNamePrefs,
+ key: 'externalCalls',
+ );
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePrefs,
+ key: 'currency',
+ value: 'EUR',
+ );
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePriceCache,
+ key: 'cache',
+ value: {
+ 'Bitcoin': ['42000', 0.0],
+ },
+ );
+ final first = PriceAPI(MockHTTP())
+ ..resetLastCalledToForceNextCallToUpdateCache();
+ final second = PriceAPI(MockHTTP());
+ final results = await Future.wait([
+ first.getPricesAnd24hChange(baseCurrency: 'USD'),
+ second.getPricesAnd24hChange(baseCurrency: 'EUR'),
+ ]);
+ final bitcoin = Bitcoin(CryptoCurrencyNetwork.main);
+ expect(results.first, isEmpty);
+ expect(results.last[bitcoin]?.value, Decimal.fromInt(42000));
+ await DB.instance.hive.box<dynamic>(DB.boxNamePriceCache).close();
+ await DB.instance.hive.openBox<dynamic>(DB.boxNamePriceCache);
+ expect(
+ (await PriceAPI(
+ MockHTTP(),
+ ).getPricesAnd24hChange(baseCurrency: 'EUR'))[bitcoin]?.value,
+ Decimal.fromInt(42000),
+ );
+ expect(
+ DB.instance.get<dynamic>(boxName: DB.boxNamePriceCache, key: 'cache'),
+ isNull,
+ );
+ });
+
tearDown(() async {
await tearDownHiveCeTest();
});
### test/providers/transaction_note_provider_test.dart
@@ -0,0 +1,71 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/models/isar/models/transaction_note.dart';
+import 'package:stackwallet/providers/db/main_db_provider.dart';
+import 'package:stackwallet/providers/wallet/transaction_note_provider.dart';
+
+import '../support/isar_test_utils.dart';
+
+class _TestMainDB extends Mock implements MainDB {
+ _TestMainDB(this.isar);
+
+ @override
+ final Isar isar;
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test('transaction note watcher updates and disposes exactly once', () async {
+ await initializeTestIsar();
+ final directory = await Directory.systemTemp.createTemp('note_provider_');
+ final isar = await Isar.open(
+ [TransactionNoteSchema],
+ directory: directory.path,
+ name: 'notes',
+ inspector: false,
+ );
+ addTearDown(() async {
+ await isar.close();
+ await directory.delete(recursive: true);
+ });
+ final errors = <Object>[];
+ final container = ProviderContainer(
+ overrides: [mainDBProvider.overrideWithValue(_TestMainDB(isar))],
+ );
+ var disposed = false;
+ addTearDown(() {
+ if (!disposed) container.dispose();
+ });
+ const key = (walletId: 'wallet', txid: 'transaction');
+ final noteObserved = Completer<void>();
+ final subscription = container.listen(pTransactionNote(key), (_, next) {
+ if (next?.value == 'note' && !noteObserved.isCompleted) {
+ noteObserved.complete();
+ }
+ });
+ expect(container.read(pTransactionNote(key)), isNull);
+ await isar.writeTxn(() async {
+ await isar.transactionNotes.put(
+ TransactionNote(walletId: key.walletId, txid: key.txid, value: 'note'),
+ );
+ });
+ await noteObserved.future.timeout(const Duration(seconds: 5));
+ expect(container.read(pTransactionNote(key))?.value, 'note');
+
+ subscription.close();
+ runZonedGuarded<void>(container.dispose, (error, _) => errors.add(error));
+ disposed = true;
+ expect(errors, isEmpty);
+
+ await isar.writeTxn(() => isar.transactionNotes.clear());
+ await Future<void>.delayed(Duration.zero);
+ expect(errors, isEmpty);
+ });
+}
### test/services/price_service_disposal_test.dart
@@ -0,0 +1,147 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:decimal/decimal.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/db/hive/db.dart';
+import 'package:stackwallet/networking/http.dart';
+import 'package:stackwallet/services/price.dart';
+import 'package:stackwallet/services/price_service.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import '../hive/hive_ce_test_utils.dart';
+import '../price_test.mocks.dart';
+
+class _Service extends PriceService {
+ _Service() : super('USD');
+
+ int contractQueries = 0;
+ Completer<Set<String>>? contracts;
+ Completer<Set<String>>? solContracts;
+ int solQueries = 0;
+
+ @override
+ Future<Set<String>> get tokenContractAddressesToCheck {
+ contractQueries++;
+ return contracts?.future ?? Future.value({});
+ }
+
+ @override
+ Future<Set<String>> get solTokenContractAddressesToCheck {
+ solQueries++;
+ return solContracts?.future ?? Future.value({});
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ setUp(() async {
+ await setUpHiveCeTest();
+ await DB.instance.hive.openBox<dynamic>(DB.boxNamePriceCache);
+ await DB.instance.hive.openBox<dynamic>(DB.boxNamePrefs);
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNamePrefs,
+ key: 'externalCalls',
+ value: true,
+ );
+ final client = MockHTTP();
+ when(
+ client.get(
+ url: anyNamed('url'),
+ headers: anyNamed('headers'),
+ proxyInfo: anyNamed('proxyInfo'),
+ ),
+ ).thenAnswer(
+ (_) async => Response(
+ utf8.encode(
+ '[{"id":"bitcoin","name":"Bitcoin","current_price":50000}]',
+ ),
+ 200,
+ ),
+ );
+ final priceAPI = PriceAPI(client)
+ ..resetLastCalledToForceNextCallToUpdateCache();
+ final prices = await priceAPI.getPricesAnd24hChange(baseCurrency: 'USD');
+ expect(
+ prices[Bitcoin(CryptoCurrencyNetwork.main)]?.value,
+ Decimal.fromInt(50000),
+ );
+ });
+ tearDown(tearDownHiveCeTest);
+
+ test('disposal during a price read discards the result', () async {
+ final service = _Service();
+ final pending = service.updatePrice();
+ service.dispose();
+ await pending;
+
+ expect(service.getPrice(Bitcoin(CryptoCurrencyNetwork.main)), isNull);
+ expect(service.contractQueries, 0);
+ service.start(true);
+ await service.updatePrice();
+ expect(service.contractQueries, 0);
+ });
+
+ test('disposal during a contract query stops the update', () async {
+ final service = _Service()..contracts = Completer<Set<String>>();
+ final pending = service.updatePrice();
+ await Future<void>.delayed(Duration.zero);
+ expect(service.contractQueries, 1);
+ service.dispose();
+ service.contracts!.complete({'token'});
+ await pending;
+ expect(service.getTokenPrice('token'), isNull);
+ expect(service.solQueries, 0);
+ });
+
+ test(
+ 'disposal during a Solana contract query suppresses notification',
+ () async {
+ final service = _Service()..solContracts = Completer<Set<String>>();
+ var notifications = 0;
+ service.addListener(() => notifications++);
+ final pending = service.updatePrice();
+ await Future<void>.delayed(Duration.zero);
+ expect(service.solQueries, 1);
+ service.dispose();
+ service.solContracts!.complete({'token'});
+ await pending;
+ expect(service.getTokenPrice('token'), isNull);
+ expect(notifications, 0);
+ },
+ );
+
+ testWidgets('disposal cancels polling and prevents restarting', (
+ tester,
+ ) async {
+ final service = _Service();
+ service.start(false);
+ service.dispose();
+ service.start(true);
+ await tester.pump(service.updateInterval * 2);
+ expect(service.contractQueries, 0);
+ expect(service.getPrice(Bitcoin(CryptoCurrencyNetwork.main)), isNull);
+ });
+
+ for (final disposed in [false, true]) {
+ final outcome = disposed
+ ? 'discarded after disposal'
+ : 'reported while active';
+ test('a late query error is $outcome', () async {
+ final service = _Service()..contracts = Completer<Set<String>>();
+ final pending = service.updatePrice();
+ await Future<void>.delayed(Duration.zero);
+ expect(service.contractQueries, 1);
+ if (disposed) service.dispose();
+ final observed = expectLater(
+ pending,
+ disposed ? completes : throwsA(isA<StateError>()),
+ );
+ service.contracts!.completeError(StateError('database closed'));
+ await observed;
+ if (!disposed) service.dispose();
+ });
+ }
+}
### test/services/solana/solana_token_api_test.dart
@@ -0,0 +1,84 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:solana/solana.dart';
+import 'package:stackwallet/services/solana/solana_token_api.dart';
+
+void main() {
+ late HttpServer server;
+ late HttpClient httpClient;
+ late SolanaTokenAPI api;
+ late List<Map<String, dynamic>> requests;
+ Object? resultValue;
+
+ setUp(() async {
+ requests = [];
+ resultValue = [];
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((request) async {
+ final body = jsonDecode(
+ await utf8.decoder.bind(request).join(),
+ ) as Map<String, dynamic>;
+ requests.add(body);
+ request.response.headers.contentType = ContentType.json;
+ request.response.write(
+ jsonEncode({
+ 'jsonrpc': '2.0',
+ 'id': body['id'],
+ 'result': {
+ 'context': {'slot': 1},
+ 'value': resultValue,
+ },
+ }),
+ );
+ await request.response.close();
+ });
+ httpClient = HttpClient();
+ final client = RpcClient(
+ 'http://127.0.0.1:${server.port}',
+ httpClient: httpClient,
+ );
+ api = SolanaTokenAPI()..initializeRpcClient(client);
+ });
+
+ tearDown(() async {
+ httpClient.close(force: true);
+ await server.close(force: true);
+ });
+
+ test('all-token query uses the official SPL program', () async {
+ final result = await api.getTokenAccountsByOwner('owner');
+
+ expect(result.isSuccess, isTrue);
+ expect(requests.single['method'], 'getTokenAccountsByOwner');
+ expect((requests.single['params'] as List)[1], {
+ 'programId': 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
+ });
+ });
+
+ test('mint-filtered query keeps its explicit mint', () async {
+ final result = await api.getTokenAccountsByOwner('owner', mint: 'mint');
+
+ expect(result.isSuccess, isTrue);
+ expect((requests.single['params'] as List)[1], {'mint': 'mint'});
+ });
+
+ test('mint ownership distinguishes SPL and Token-2022 exactly', () async {
+ Future<String?> programType(String owner) async {
+ resultValue = {
+ 'data': ['', 'base64'],
+ 'executable': false,
+ 'lamports': 1,
+ 'owner': owner,
+ 'rentEpoch': 0,
+ };
+ return api.getTokenProgramType('mint');
+ }
+
+ expect(await programType(TokenProgram.programId), 'spl');
+ expect(await programType(Token2022Program.programId), 'token2022');
+ expect(await programType(SystemProgram.programId), isNull);
+ expect(await programType('TokenUnknownProgram'), isNull);
+ });
+}
### test/utilities/fee_rate_formatter_test.dart
@@ -0,0 +1,27 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/utilities/amount/fee_rate_formatter.dart';
+
+void main() {
+ test('fractional fee rates retain one decimal place', () {
+ expect(formatApproximateFeeRate(BigInt.from(125), 100), '~1.3');
+ expect(formatApproximateFeeRate(BigInt.from(124), 100), '~1.2');
+ expect(formatApproximateFeeRate(BigInt.one, 3), '~0.3');
+ expect(formatApproximateFeeRate(BigInt.from(100), 100), '~1.0');
+ expect(formatApproximateFeeRate(BigInt.zero, 100), '~0.0');
+ });
+
+ test('unknown and invalid fees or sizes have no display value', () {
+ expect(formatApproximateFeeRate(null, 100), isNull);
+ expect(formatApproximateFeeRate(BigInt.one, null), isNull);
+ expect(formatApproximateFeeRate(BigInt.one, 0), isNull);
+ expect(formatApproximateFeeRate(BigInt.one, -1), isNull);
+ expect(formatApproximateFeeRate(-BigInt.one, 100), isNull);
+ });
+
+ test('large atomic fees are formatted without floating point loss', () {
+ expect(
+ formatApproximateFeeRate(BigInt.parse('9007199254740993125'), 100),
+ '~90071992547409931.3',
+ );
+ });
+}
### test/wallets/duress_wallet_filter_test.dart
@@ -0,0 +1,91 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/providers/global/duress_provider.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/isar/providers/all_wallets_info_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/favourite_wallets_provider.dart';
+
+import '../support/isar_test_utils.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ test('duress toggles preserve all cached wallet lists', () async {
+ await initializeTestIsar();
+ final directory = await Directory.systemTemp.createTemp('duress-wallets-');
+ final isar = await Isar.open(
+ [WalletInfoSchema],
+ directory: directory.path,
+ name: 'duress-wallets',
+ inspector: false,
+ );
+ addTearDown(() async {
+ await isar.close();
+ await directory.delete(recursive: true);
+ });
+ await MainDB.instance.initMainDB(mock: isar);
+ WalletInfo wallet(String id, {bool visible = false, int favourite = -1}) =>
+ WalletInfo(
+ walletId: id,
+ name: id,
+ coinName: 'bitcoin',
+ mainAddressType: AddressType.p2wpkh,
+ favouriteOrderIndex: favourite,
+ otherDataJsonString: jsonEncode({
+ WalletInfoKeys.duressMarkedVisibleWalletKey: visible,
+ }),
+ );
+ await isar.writeTxn(
+ () => isar.walletInfo.putAll([
+ wallet('visible', visible: true, favourite: 0),
+ wallet('hidden', favourite: 1),
+ wallet('not-favourite'),
+ ]),
+ );
+ final container = ProviderContainer();
+ addTearDown(container.dispose);
+ final subscriptions = [
+ container.listen(pAllWalletsInfo, (_, __) {}),
+ container.listen(pFavouriteWalletInfos(true), (_, __) {}),
+ container.listen(pFavouriteWalletInfos(false), (_, __) {}),
+ ];
+ addTearDown(() {
+ for (final subscription in subscriptions) {
+ subscription.close();
+ }
+ });
+ await Future<void>.delayed(Duration.zero);
+ final all = container.read(pAllWalletsInfo);
+ final favourites = container.read(pFavouriteWalletInfos(true));
+ final others = container.read(pFavouriteWalletInfos(false));
+ for (var cycle = 0; cycle < 2; cycle++) {
+ container.read(pDuress.notifier).state = true;
+ expect(container.read(pAllWalletsInfo).map((w) => w.walletId), [
+ 'visible',
+ ]);
+ expect(
+ container.read(pFavouriteWalletInfos(true)).map((w) => w.walletId),
+ ['visible'],
+ );
+ expect(container.read(pFavouriteWalletInfos(false)), isEmpty);
+ expect(all, hasLength(3));
+ expect(favourites, hasLength(2));
+ expect(others, hasLength(1));
+ container.read(pDuress.notifier).state = false;
+ expect(container.read(pAllWalletsInfo), hasLength(3));
+ expect(
+ container.read(pFavouriteWalletInfos(true)).map((w) => w.walletId),
+ ['visible', 'hidden'],
+ );
+ expect(
+ container.read(pFavouriteWalletInfos(false)).single.walletId,
+ 'not-favourite',
+ );
+ }
+ });
+}
### test/wallets/firo_cache_refresh_reset_test.dart
@@ -0,0 +1,199 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/db/sqlite/firo_cache.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/models/electrumx_response/spark_models.dart';
+import 'package:stackwallet/models/isar/models/isar_models.dart';
+import 'package:stackwallet/services/event_bus/events/global/node_connection_status_changed_event.dart';
+import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart';
+import 'package:stackwallet/services/event_bus/global_event_bus.dart';
+import 'package:stackwallet/utilities/stack_file_system.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/spark_coin.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/wallet/impl/firo_wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/spark_interface.dart';
+
+import '../support/isar_test_utils.dart';
+
+class _Client extends Mock implements ElectrumXClient {
+ final started = Completer<void>();
+ final pendingTags = Completer<List<List<dynamic>>>();
+ int tagRequests = 0;
+ @override
+ Future<int> getSparkLatestCoinId({String? requestID}) async => 1;
+ @override
+ Future<SparkAnonymitySetMeta> getSparkAnonymitySetMeta({
+ String? requestID,
+ required int coinGroupId,
+ }) async => SparkAnonymitySetMeta(
+ coinGroupId: coinGroupId,
+ blockHash: 'block',
+ setHash: 'set',
+ size: 0,
+ );
+ @override
+ Future<List<List<dynamic>>> getSparkUnhashedUsedCoinsTagsWithTxHashes({
+ String? requestID,
+ required int startNumber,
+ }) {
+ tagRequests++;
+ if (tagRequests == 1) {
+ started.complete();
+ return pendingTags.future;
+ }
+ return Future.value([]);
+ }
+
+ @override
+ Future<Set<String>> getMempoolTxids({String? requestID}) async => {};
+}
+
+class _ResettingClient extends _Client {
+ @override
+ Future<List<List<dynamic>>> getSparkUnhashedUsedCoinsTagsWithTxHashes({
+ String? requestID,
+ required int startNumber,
+ }) async {
+ tagRequests++;
+ // Every batch is retired by another shared reset before it lands.
+ await FiroCacheCoordinator.clearSharedCache(
+ CryptoCurrencyNetwork.main,
+ clearOnlyUsedTagsCache: true,
+ );
+ return [];
+ }
+}
+
+class _Wallet extends FiroWallet {
+ _Wallet(_Client client) : super(CryptoCurrencyNetwork.main) {
+ mainDB = MainDB.instance;
+ electrumXClient = client;
+ }
+ @override
+ String get walletId => 'firo-reset-refresh';
+ @override
+ WalletInfo get info => mainDB.isar.walletInfo.getByWalletIdSync(walletId)!;
+ @override
+ bool get isViewOnly => false;
+ @override
+ Future<int> get chainHeight async => 1000;
+ @override
+ Future<void> updateChainHeight() async {}
+ @override
+ Future<void> checkReceivingAddressForTransactions() async {}
+ @override
+ Future<void> checkChangeAddressForTransactions() async {}
+ @override
+ Future<void> updateTransactions() async {}
+ @override
+ Future<bool> updateUTXOs() async => false;
+ @override
+ Future<void> updateBalance() async {}
+ @override
+ Future<void> refreshSparkNames() async {}
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Directory root;
+ late Isar isar;
+ setUpAll(() async {
+ await initializeTestIsar();
+ root = await Directory.systemTemp.createTemp('firo-wallet-reset-');
+ StackFileSystem.setDesktopOverrideDir(root.path);
+ await FiroCacheCoordinator.init();
+ });
+ setUp(() async {
+ isar = await Isar.open(
+ [WalletInfoSchema, SparkCoinSchema],
+ directory: root.path,
+ name: 'firo-wallet-reset',
+ inspector: false,
+ );
+ await MainDB.instance.initMainDB(mock: isar);
+ await isar.writeTxn(
+ () => isar.walletInfo.put(
+ WalletInfo(
+ walletId: 'firo-reset-refresh',
+ name: 'Firo fixture',
+ coinName: 'firo',
+ mainAddressType: AddressType.p2pkh,
+ ),
+ ),
+ );
+ await FiroCacheCoordinator.clearSharedCache(CryptoCurrencyNetwork.main);
+ });
+ tearDown(() => isar.close(deleteFromDisk: true));
+ tearDownAll(() async {
+ await FiroCacheCoordinator.close();
+ await root.delete(recursive: true);
+ });
+ for (final tagsOnly in [false, true]) {
+ test(
+ 'cache reset retries real wallet refresh without disconnecting tagsOnly=$tagsOnly',
+ () async {
+ final client = _Client();
+ final wallet = _Wallet(client);
+ final statuses = <WalletSyncStatus>[];
+ final connections = <NodeConnectionStatus>[];
+ final sync = GlobalEventBus.instance
+ .on<WalletSyncStatusChangedEvent>()
+ .listen((e) => statuses.add(e.newStatus));
+ final connection = GlobalEventBus.instance
+ .on<NodeConnectionStatusChangedEvent>()
+ .listen((e) => connections.add(e.newStatus));
+ addTearDown(sync.cancel);
+ addTearDown(connection.cancel);
+ final refresh = wallet.refresh();
+ await client.started.future.timeout(const Duration(seconds: 5));
+ await FiroCacheCoordinator.clearSharedCache(
+ CryptoCurrencyNetwork.main,
+ clearOnlyUsedTagsCache: tagsOnly,
+ ).timeout(const Duration(seconds: 3));
+ await refresh.timeout(const Duration(seconds: 5));
+ await Future<void>.delayed(Duration.zero);
+ expect(client.tagRequests, 2);
+ expect(statuses, [WalletSyncStatus.syncing, WalletSyncStatus.synced]);
+ expect(connections, isNot(contains(NodeConnectionStatus.disconnected)));
+ client.pendingTags.completeError(StateError('late retired response'));
+ await Future<void>.delayed(Duration.zero);
+ },
+ );
+ }
+ test('a real node error still reports unable to sync', () async {
+ final client = _Client();
+ final wallet = _Wallet(client);
+ final statuses = <WalletSyncStatus>[];
+ final subscription = GlobalEventBus.instance
+ .on<WalletSyncStatusChangedEvent>()
+ .listen((e) => statuses.add(e.newStatus));
+ addTearDown(subscription.cancel);
+ final refresh = wallet.refresh();
+ await client.started.future.timeout(const Duration(seconds: 5));
+ client.pendingTags.completeError(const SocketException('node unavailable'));
+ await refresh.timeout(const Duration(seconds: 5));
+ await Future<void>.delayed(Duration.zero);
+ expect(statuses, [WalletSyncStatus.syncing, WalletSyncStatus.unableToSync]);
+ expect(client.tagRequests, 1);
+ });
+
+ test('repeated resets stop retrying and report a failed refresh', () async {
+ final client = _ResettingClient();
+ final wallet = _Wallet(client);
+ final statuses = <WalletSyncStatus>[];
+ final subscription = GlobalEventBus.instance
+ .on<WalletSyncStatusChangedEvent>()
+ .listen((e) => statuses.add(e.newStatus));
+ addTearDown(subscription.cancel);
+ await wallet.refresh().timeout(const Duration(seconds: 10));
+ await Future<void>.delayed(Duration.zero);
+ expect(client.tagRequests, SparkInterface.maxSparkRefreshResetRetries + 1);
+ expect(statuses, [WalletSyncStatus.syncing, WalletSyncStatus.unableToSync]);
+ });
+}
### test/wallets/native_wallet_exit_polling_test.dart
@@ -0,0 +1,156 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/utilities/enums/sync_type_enum.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/crypto_currency/intermediate/cryptonote_currency.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/wallet/impl/monero_wallet.dart';
+import 'package:stackwallet/wallets/wallet/impl/wownero_wallet.dart';
+import 'package:stackwallet/wallets/wallet/impl/salvium_wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+import '../support/isar_test_utils.dart';
+
+class _Prefs extends Fake implements Prefs {
+ _Prefs(this.syncType);
+
+ @override
+ final SyncingType syncType;
+
+ @override
+ List<String> get walletIdsSyncOnStartup => ['deleted-wallet', 'live-wallet'];
+}
+
+mixin _PollingProbe on Wallet<CryptonoteCurrency> {
+ int pings = 0;
+ @override
+ String get walletId => 'native-exit-fixture';
+ @override
+ Future<bool> pingCheck() async {
+ pings++;
+ return false;
+ }
+
+ @override
+ Future<void> refresh() async {}
+}
+
+class _Monero extends MoneroWallet with _PollingProbe {
+ _Monero() : super(CryptoCurrencyNetwork.main);
+}
+
+class _Wownero extends WowneroWallet with _PollingProbe {
+ _Wownero() : super(CryptoCurrencyNetwork.main);
+}
+
+class _Salvium extends SalviumWallet with _PollingProbe {
+ _Salvium() : super(CryptoCurrencyNetwork.main);
+}
+
+class _OwnedTimer implements Timer {
+ bool _active = true;
+ @override
+ bool get isActive => _active;
+ @override
+ int get tick => 0;
+ @override
+ void cancel() => _active = false;
+}
+
+void main() {
+ late Directory directory;
+ late Isar isar;
+ setUpAll(() async {
+ await initializeTestIsar();
+ directory = await Directory.systemTemp.createTemp('native-exit-');
+ isar = await Isar.open(
+ [WalletInfoSchema],
+ directory: directory.path,
+ name: 'native-exit',
+ inspector: false,
+ );
+ await MainDB.instance.initMainDB(mock: isar);
+ await isar.writeTxn(
+ () => isar.walletInfo.put(
+ WalletInfo(
+ walletId: 'live-wallet',
+ name: 'Live selected wallet',
+ mainAddressType: AddressType.p2wpkh,
+ coinName: 'bitcoin',
+ ),
+ ),
+ );
+ });
+ tearDownAll(() async {
+ await isar.close();
+ await directory.delete(recursive: true);
+ });
+
+ for (final entry in <String, _PollingProbe Function()>{
+ "Monero": _Monero.new,
+ "Wownero": _Wownero.new,
+ "Salvium": _Salvium.new,
+ }.entries) {
+ test("native exit stops base polling ${entry.key}", () async {
+ final periodic = <_OwnedTimer>[];
+ await runZoned(
+ () async {
+ final wallet = entry.value()
+ ..doNotFireRefreshEvents = true
+ ..prefs = Prefs.instance;
+ try {
+ wallet.shouldAutoSync = true;
+ expect(periodic.where((timer) => timer.isActive), isNotEmpty);
+ await wallet.exit();
+ expect(wallet.shouldAutoSync, isFalse);
+ expect(periodic.where((timer) => timer.isActive), isEmpty);
+ } finally {
+ wallet.shouldAutoSync = false;
+ }
+ },
+ zoneSpecification: ZoneSpecification(
+ // Native constructors defer a DB watcher by two seconds. Keep that
+ // unrelated initialization out of this polling-ownership test.
+ createTimer: (self, parent, zone, duration, callback) =>
+ _OwnedTimer(),
+ createPeriodicTimer: (self, parent, zone, duration, callback) {
+ final timer = _OwnedTimer();
+ periodic.add(timer);
+ return timer;
+ },
+ ),
+ );
+ });
+
+ for (final syncType in [
+ SyncingType.currentWalletOnly,
+ SyncingType.selectedWalletsAtStartup,
+ ]) {
+ test(
+ '${entry.key} exits with a deleted ${syncType.name} wallet',
+ () async {
+ await runZoned(
+ () async {
+ final wallet = entry.value()
+ ..mainDB = MainDB.instance
+ ..prefs = _Prefs(syncType);
+ await wallet.exit();
+ expect(wallet.shouldAutoSync, isFalse);
+ },
+ zoneSpecification: ZoneSpecification(
+ // Prevent the unrelated deferred native DB watcher from starting.
+ createTimer: (self, parent, zone, duration, callback) =>
+ _OwnedTimer(),
+ ),
+ );
+ },
+ );
+ }
+ }
+}
### test/wallets/receiving_address_index_test.dart
@@ -0,0 +1,97 @@
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:coinlib_flutter/coinlib_flutter.dart' as coinlib;
+import 'package:flutter_test/flutter_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart';
+import 'package:stackwallet/utilities/enums/derive_path_type_enum.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/impl/bitcoin_wallet.dart';
+
+import '../support/isar_test_utils.dart';
+
+class _Wallet extends BitcoinWallet {
+ _Wallet() : super(CryptoCurrencyNetwork.main) {
+ mainDB = MainDB.instance;
+ }
+
+ @override
+ String get walletId => 'address-index-test';
+
+ @override
+ bool get isViewOnly => false;
+
+ @override
+ Future<coinlib.HDPrivateKey> getRootHDNode() async =>
+ coinlib.HDPrivateKey.fromSeed(Uint8List.fromList(List.filled(32, 1)));
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Isar isar;
+ late _Wallet wallet;
+
+ setUpAll(() async {
+ await initializeTestIsar();
+ await coinlib.loadCoinlib();
+ });
+ setUp(() async {
+ final directory = await Directory.systemTemp.createTemp(
+ 'stack_address_index_',
+ );
+ addTearDown(() => directory.delete(recursive: true));
+ isar = await Isar.open(
+ [AddressSchema, TransactionSchema],
+ directory: directory.path,
+ name: 'address-index-test',
+ inspector: false,
+ );
+ addTearDown(() => isar.close());
+ await MainDB.instance.initMainDB(mock: isar);
+ wallet = _Wallet();
+ });
+
+ Address address(String value, int index, AddressSubType subType) => Address(
+ walletId: wallet.walletId,
+ value: value,
+ publicKey: [],
+ derivationIndex: index,
+ derivationPath: null,
+ type: AddressType.p2wpkh,
+ subType: subType,
+ );
+
+ test(
+ 'change and Paynym indexes do not advance the receiving chain',
+ () async {
+ await MainDB.instance.putAddresses([
+ address('receiving', 2, AddressSubType.receiving),
+ address('change', 100, AddressSubType.change),
+ address('paynym', 200, AddressSubType.paynymReceive),
+ ]);
+ final generated = await wallet.generateNextReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+ expect(generated.derivationIndex, 3);
+ expect(generated.derivationPath!.value, "m/84'/0'/0'/0/3");
+ expect(generated.subType, AddressSubType.receiving);
+ },
+ );
+
+ test(
+ 'a receiving chain starts at zero when only change addresses exist',
+ () async {
+ await MainDB.instance.putAddress(
+ address('change', 100, AddressSubType.change),
+ );
+ final generated = await wallet.generateNextReceivingAddress(
+ derivePathType: DerivePathType.bip84,
+ );
+ expect(generated.derivationIndex, 0);
+ expect(generated.derivationPath!.value, "m/84'/0'/0'/0/0");
+ },
+ );
+}
### test/wallets/solana_token_account_creation_test.dart
@@ -0,0 +1,350 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mockito/mockito.dart';
+import 'package:isar_community/isar.dart';
+import 'package:solana/encoder.dart' show SignedTx;
+import 'package:solana/solana.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/models/isar/models/isar_models.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart';
+import 'package:stackwallet/utilities/amount/amount.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/models/tx_data.dart';
+import 'package:stackwallet/wallets/wallet/impl/solana_wallet.dart';
+import 'package:stackwallet/wallets/wallet/impl/sub_wallets/solana_token_wallet.dart';
+
+import '../support/isar_test_utils.dart';
+
+class _ParentWallet extends Mock implements SolanaWallet {
+ _ParentWallet(this.client, this.keyPair);
+
+ final RpcClient client;
+ final Ed25519HDKeyPair keyPair;
+
+ @override
+ Solana get cryptoCurrency => Solana(CryptoCurrencyNetwork.main);
+
+ @override
+ RpcClient getRpcClient() => client;
+
+ @override
+ Future<Ed25519HDKeyPair> getKeyPair() async => keyPair;
+}
+
+class _TokenWallet extends SolanaTokenWallet {
+ _TokenWallet(super.parentSolanaWallet, super.solContract, MainDB db) {
+ mainDB = db;
+ }
+
+ @override
+ String get walletId => 'token-send-test';
+}
+
+void main() {
+ setUpAll(initializeTestIsar);
+ final scenarios = [
+ for (final program in [TokenProgram.programId, Token2022Program.programId])
+ for (final recipientExists in [false, true])
+ (program: program, recipientExists: recipientExists, failed: false),
+ (program: SystemProgram.programId, recipientExists: false, failed: false),
+ (program: Token2022Program.programId, recipientExists: false, failed: true),
+ ];
+ for (final scenario in scenarios) {
+ final program = scenario.program;
+ test(
+ program == SystemProgram.programId
+ ? 'rejects unsupported sender token program'
+ : scenario.failed
+ ? 'on-chain token failure is reported to the confirmation caller'
+ : 'recipient account uses $program '
+ '(exists: ${scenario.recipientExists})',
+ () async {
+ final keyPair = await Ed25519HDKeyPair.fromSeedWithHdPath(
+ seed: List.filled(32, 1),
+ hdPath: "m/44'/501'/0'/0'",
+ );
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ final http = HttpClient();
+ addTearDown(() async {
+ http.close(force: true);
+ await server.close(force: true);
+ });
+ final account = {
+ 'owner': program,
+ 'lamports': 1,
+ 'executable': false,
+ 'rentEpoch': 0,
+ 'data': ['', 'base64'],
+ };
+ // A hostile node reports another holder's account for the recipient.
+ final decoy = await Ed25519HDKeyPair.fromSeedWithHdPath(
+ seed: List.filled(32, 2),
+ hdPath: "m/44'/501'/0'/0'",
+ );
+ final expectedAddress = (await Ed25519HDPublicKey.findProgramAddress(
+ seeds: [
+ Ed25519HDPublicKey.fromBase58(SystemProgram.programId).bytes,
+ Ed25519HDPublicKey.fromBase58(program).bytes,
+ Ed25519HDPublicKey.fromBase58(Token2022Program.programId).bytes,
+ ],
+ programId: AssociatedTokenAccountProgram.id,
+ )).toBase58();
+ var mintLookupCount = 0;
+ var statusLookupCount = 0;
+ late final Isar isar;
+ final retryStatusLookup =
+ program == TokenProgram.programId && scenario.recipientExists;
+ SignedTx? sentTransaction;
+ server.listen((request) async {
+ final body =
+ jsonDecode(await utf8.decoder.bind(request).join()) as Map;
+ final params = body['params'] as List;
+ final isMintLookup =
+ body['method'] == 'getAccountInfo' &&
+ params.first == Token2022Program.programId;
+ if (isMintLookup) {
+ mintLookupCount++;
+ }
+ request.response.headers.contentType = ContentType.json;
+ if (isMintLookup) {
+ request.response.write(
+ jsonEncode({
+ 'jsonrpc': '2.0',
+ 'id': body['id'],
+ 'error': {
+ 'code': -32000,
+ 'message': 'Unexpected mint owner lookup',
+ },
+ }),
+ );
+ await request.response.close();
+ return;
+ }
+ if (body['method'] == 'sendTransaction') {
+ sentTransaction = SignedTx.decode(params.first as String);
+ request.response.write(
+ jsonEncode({
+ 'jsonrpc': '2.0',
+ 'id': body['id'],
+ 'result': sentTransaction!.id,
+ }),
+ );
+ await request.response.close();
+ return;
+ }
+ if (body['method'] == 'getSignatureStatuses') {
+ statusLookupCount++;
+ if (retryStatusLookup && statusLookupCount == 1) {
+ expect(
+ isar.transactionV2s.countSync(),
+ 1,
+ reason: 'An uncertain RPC result must retain the broadcast transfer',
+ );
+ request.response.write(
+ jsonEncode({
+ 'jsonrpc': '2.0',
+ 'id': body['id'],
+ 'error': {
+ 'code': -32000,
+ 'message': 'Temporarily unavailable',
+ },
+ }),
+ );
+ await request.response.close();
+ return;
+ }
+ }
+ final value = switch (body['method']) {
+ 'getTokenAccountsByOwner' =>
+ params.first == keyPair.address
+ ? <Map<String, Object>>[
+ {'pubkey': TokenProgram.programId, 'account': account},
+ ]
+ : <Map<String, Object>>[
+ {'pubkey': decoy.address, 'account': account},
+ ],
+ 'getAccountInfo' =>
+ (params.first == TokenProgram.programId ||
+ params.first == Token2022Program.programId ||
+ params.first == decoy.address ||
+ (params.first == expectedAddress &&
+ scenario.recipientExists))
+ ? account
+ : null,
+ 'getLatestBlockhash' => {
+ 'blockhash': SystemProgram.programId,
+ 'lastValidBlockHeight': 1,
+ },
+ 'getFeeForMessage' => 5000,
+ 'getSignatureStatuses' => [
+ {
+ 'slot': 1,
+ 'confirmations': 1,
+ 'confirmationStatus': 'confirmed',
+ 'err': scenario.failed
+ ? {
+ 'InstructionError': [0, 'InvalidAccountData'],
+ }
+ : null,
+ },
+ ],
+ _ => throw StateError('Unexpected RPC: ${body['method']}'),
+ };
+ request.response.write(
+ jsonEncode({
+ 'jsonrpc': '2.0',
+ 'id': body['id'],
+ 'result': {
+ 'context': {'slot': 1},
+ 'value': value,
+ },
+ }),
+ );
+ await request.response.close();
+ });
+ final client = RpcClient(
+ 'http://127.0.0.1:${server.port}',
+ httpClient: http,
+ );
+ final directory = await Directory.systemTemp.createTemp(
+ 'sol-token-confirmation-',
+ );
+ isar = await Isar.open(
+ [TransactionV2Schema],
+ directory: directory.path,
+ name: 'sol-token-confirmation',
+ inspector: false,
+ );
+ addTearDown(() async {
+ await isar.close();
+ await directory.delete(recursive: true);
+ });
+ final db = MainDB.instance;
+ await db.initMainDB(mock: isar);
+ final wallet = _TokenWallet(
+ _ParentWallet(client, keyPair),
+ SolContract(
+ address: Token2022Program.programId,
+ name: 'Test token',
+ symbol: 'TEST',
+ decimals: 6,
+ ),
+ db,
+ );
+ final amount = Amount(rawValue: BigInt.one, fractionDigits: 6);
+ final prepared = wallet.prepareSend(
+ txData: TxData(
+ recipients: [
+ TxRecipient(
+ address: SystemProgram.programId,
+ amount: amount,
+ isChange: false,
+ addressType: AddressType.solana,
+ ),
+ ],
+ memo: 'token memo',
+ ),
+ );
+ if (program == SystemProgram.programId) {
+ await expectLater(
+ prepared,
+ throwsA(
+ isA<Exception>().having(
+ (error) => error.toString(),
+ 'message',
+ contains('Unsupported token program'),
+ ),
+ ),
+ );
+ expect(mintLookupCount, 0);
+ return;
+ }
+ final result = await prepared;
+ expect(mintLookupCount, 0);
+ expect(result.solInstructions!.last.programId.toBase58(), program);
+ // The destination is the recipient's derived ATA whatever token
+ // account the node claims the recipient holds.
+ expect(
+ result.solInstructions!.last.accounts[2].pubKey.toBase58(),
+ expectedAddress,
+ reason: 'A node-reported account must never choose the destination',
+ );
+ if (scenario.recipientExists) {
+ expect(result.solInstructions, hasLength(1));
+ } else {
+ final creation = result.solInstructions!.first;
+ expect(creation.accounts[5].pubKey.toBase58(), program);
+ expect(creation.accounts[1].pubKey.toBase58(), expectedAddress);
+ }
+ // A trailing instruction must not change which program the pending
+ // record derives the recipient account from.
+ final sending = scenario.recipientExists
+ ? [
+ ...result.solInstructions!,
+ MemoInstruction(signers: const [], memo: 'trailing'),
+ ]
+ : result.solInstructions!;
+ final confirmation = wallet.confirmSend(
+ txData: result.copyWith(solInstructions: sending),
+ );
+ if (scenario.failed) {
+ await expectLater(
+ confirmation,
+ throwsA(
+ isA<Exception>().having(
+ (error) => error.toString(),
+ 'message',
+ contains('Transaction failed'),
+ ),
+ ),
+ );
+ expect(
+ isar.transactionV2s.countSync(),
+ 0,
+ reason: 'A definitive on-chain failure must not leave a pending transfer',
+ );
+ } else {
+ final confirmed = await confirmation;
+ expect(confirmed.txids, [sentTransaction!.id]);
+ }
+ expect(mintLookupCount, 0);
+ expect(statusLookupCount, retryStatusLookup ? 2 : 1);
+ expect(sentTransaction!.signatures, hasLength(1));
+ final signedInstructions = sentTransaction!
+ .decompileMessage()
+ .instructions;
+ expect(signedInstructions.first.programId, MemoProgram.id);
+ expect(signedInstructions, hasLength(sending.length + 1));
+ for (var i = 0; i < sending.length; i++) {
+ final expected = sending[i];
+ final actual = signedInstructions[i + 1];
+ expect(actual.programId, expected.programId);
+ expect(actual.data.toList(), expected.data.toList());
+ expect(
+ actual.accounts.map((e) => e.pubKey),
+ expected.accounts.map((e) => e.pubKey),
+ );
+ }
+ if (!scenario.failed) {
+ expect(
+ isar.transactionV2s
+ .where()
+ .findAllSync()
+ .single
+ .outputs
+ .single
+ .addresses,
+ [
+ signedInstructions[result.solInstructions!.length]
+ .accounts[2]
+ .pubKey
+ .toBase58(),
+ ],
+ );
+ }
+ },
+ );
+ }
+}
### test/wallets/wallet_exit_network_stall_test.dart
@@ -0,0 +1,73 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/utilities/enums/sync_type_enum.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+class _Prefs extends Fake implements Prefs {
+ @override
+ SyncingType get syncType => SyncingType.allWalletsOnStartup;
+}
+
+class _Wallet extends Wallet<Bitcoin> {
+ _Wallet() : super(Bitcoin(CryptoCurrencyNetwork.main)) {
+ prefs = _Prefs();
+ doNotFireRefreshEvents = true;
+ }
+
+ final history = Completer<void>();
+ final utxos = Completer<bool>();
+
+ @override
+ String get walletId => 'stalled-exit-test';
+
+ @override
+ WalletInfo get info => WalletInfo(
+ walletId: walletId,
+ name: 'Stalled node fixture',
+ mainAddressType: AddressType.p2wpkh,
+ coinName: 'bitcoin',
+ );
+
+ @override
+ Future<void> updateChainHeight() async {}
+
+ @override
+ Future<void> updateTransactions() => history.future;
+
+ @override
+ Future<bool> updateUTXOs() => utxos.future;
+
+ @override
+ Future<void> updateBalance() async {}
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) =>
+ throw UnsupportedError('${invocation.memberName}');
+}
+
+void main() {
+ testWidgets('exit remains responsive while node requests are stalled', (
+ tester,
+ ) async {
+ final wallet = _Wallet();
+ final refresh = wallet.refresh();
+ await tester.pump(const Duration(milliseconds: 300));
+ var exited = false;
+ final exit = wallet.exit().then((_) => exited = true);
+ await tester.pump();
+ final exitedBeforeNodeResponded = exited;
+ // Release fixture requests after checking exit so teardown leaves no
+ // pending work behind.
+ wallet.history.complete();
+ wallet.utxos.complete(false);
+ await tester.pump();
+ await refresh;
+ await exit;
+ expect(exitedBeforeNodeResponded, isTrue);
+ });
+}
### test/wallets/wallet_provider_disposal_test.dart
@@ -0,0 +1,68 @@
+import 'dart:io';
+
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/models/isar/models/isar_models.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/isar/providers/favourite_wallets_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart';
+
+import '../support/isar_test_utils.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Directory directory;
+ late Isar isar;
+
+ setUpAll(initializeTestIsar);
+ setUp(() async {
+ directory = await Directory.systemTemp.createTemp('wallet_disposal_');
+ isar = await Isar.open(
+ [WalletInfoSchema],
+ directory: directory.path,
+ name: 'wallet-disposal',
+ inspector: false,
+ );
+ await MainDB.instance.initMainDB(mock: isar);
+ await isar.writeTxn(
+ () => isar.walletInfo.put(
+ WalletInfo(
+ walletId: 'fixture',
+ name: 'Fixture wallet',
+ mainAddressType: AddressType.p2wpkh,
+ coinName: 'bitcoin',
+ ),
+ ),
+ );
+ });
+ tearDown(() async {
+ await isar.close();
+ await directory.delete(recursive: true);
+ });
+
+ for (final favourite in [false, true]) {
+ testWidgets('wallet scope disposes its '
+ '${favourite ? 'favourite list' : 'wallet info'} watcher once', (
+ tester,
+ ) async {
+ final container = ProviderContainer();
+ if (favourite) {
+ container.read(pFavouriteWalletInfos(true));
+ } else {
+ expect(container.read(pWalletInfo('fixture')).name, 'Fixture wallet');
+ }
+ container.dispose();
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+
+ // A later onboarding/unlock scope must still be able to use the DB.
+ final reopened = ProviderContainer();
+ expect(reopened.read(pWalletInfo('fixture')).name, 'Fixture wallet');
+ reopened.dispose();
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ });
+ }
+}
### test/wallets/wallet_refresh_concurrency_test.dart
@@ -0,0 +1,224 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart';
+import 'package:stackwallet/services/event_bus/global_event_bus.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+class _Wallet extends Wallet<Bitcoin> {
+ _Wallet() : super(Bitcoin(CryptoCurrencyNetwork.main)) {
+ doNotFireRefreshEvents = true;
+ prefs = Prefs.instance;
+ }
+
+ final historyStarted = Completer<void>();
+ final historyRelease = Completer<void>();
+ final utxosStarted = Completer<void>();
+ final utxosRelease = Completer<bool>();
+ int historyReads = 0;
+ int balanceReads = 0;
+ int pingReads = 0;
+ Completer<bool>? ping;
+
+ @override
+ String get walletId => 'refresh-test';
+
+ @override
+ WalletInfo get info => WalletInfo(
+ walletId: walletId,
+ name: 'Fixture wallet',
+ mainAddressType: AddressType.p2wpkh,
+ coinName: 'bitcoin',
+ );
+
+ @override
+ Future<bool> pingCheck() {
+ pingReads++;
+ return ping?.future ?? Future.value(true);
+ }
+
+ @override
+ Future<void> updateChainHeight() async {}
+
+ @override
+ Future<void> updateTransactions() {
+ historyReads++;
+ if (!historyStarted.isCompleted) historyStarted.complete();
+ return historyRelease.future;
+ }
+
+ @override
+ Future<bool> updateUTXOs() {
+ if (!utxosStarted.isCompleted) utxosStarted.complete();
+ return utxosRelease.future;
+ }
+
+ @override
+ Future<void> updateBalance() async {
+ balanceReads++;
+ }
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) =>
+ throw UnsupportedError('${invocation.memberName}');
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets('exit returns before refresh and stops background polling', (
+ tester,
+ ) async {
+ final wallet = _Wallet();
+ wallet.shouldAutoSync = true;
+ final active = wallet.refresh();
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(wallet.historyReads, 1);
+ var exited = false;
+ final exit = wallet.exit().then((_) => exited = true);
+ await tester.pump();
+ expect(exited, isTrue);
+ expect(wallet.shouldAutoSync, isFalse);
+ expect(wallet.historyRelease.isCompleted, isFalse);
+ expect(wallet.utxosRelease.isCompleted, isFalse);
+ final pingsAtExit = wallet.pingReads;
+ await tester.pump(const Duration(seconds: 150));
+ expect(wallet.pingReads, pingsAtExit);
+ expect(wallet.historyReads, 1);
+ wallet.historyRelease.complete();
+ wallet.utxosRelease.complete(false);
+ await tester.pump();
+ await active;
+ await exit;
+ final autoSyncAfterExit = wallet.shouldAutoSync;
+ await tester.pump(const Duration(seconds: 150));
+ await tester.pump(const Duration(milliseconds: 300));
+ final readsAfterExit = wallet.historyReads;
+ final balanceReadsAfterExit = wallet.balanceReads;
+
+ wallet.shouldAutoSync = true;
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.pump();
+ wallet.shouldAutoSync = false;
+
+ expect(autoSyncAfterExit, isFalse);
+ expect(readsAfterExit, 1);
+ expect(balanceReadsAfterExit, 1);
+ expect(wallet.historyReads, 2);
+ expect(wallet.balanceReads, 2);
+ });
+
+ for (final historyFails in [true, false]) {
+ testWidgets('exit returns while ${historyFails ? 'history' : 'UTXO'} fails '
+ 'and the other request remains pending', (tester) async {
+ final wallet = _Wallet();
+ wallet.shouldAutoSync = true;
+ final refresh = wallet.refresh();
+ await tester.pump(const Duration(milliseconds: 300));
+ if (historyFails) {
+ wallet.historyRelease.completeError(StateError('History unavailable'));
+ } else {
+ wallet.utxosRelease.completeError(StateError('UTXOs unavailable'));
+ }
+ await tester.pump();
+ var exited = false;
+ final exit = wallet.exit().then((_) => exited = true);
+ await tester.pump();
+ expect(exited, isTrue);
+ expect(wallet.shouldAutoSync, isFalse);
+ expect(wallet.refreshMutex.isLocked, isTrue);
+ final pingsAtExit = wallet.pingReads;
+ await tester.pump(const Duration(seconds: 150));
+ expect(wallet.pingReads, pingsAtExit);
+ expect(wallet.historyReads, 1);
+ if (historyFails) {
+ wallet.utxosRelease.complete(false);
+ } else {
+ wallet.historyRelease.complete();
+ }
+ await tester.pump();
+ await refresh;
+ await exit;
+ await tester.pump(const Duration(seconds: 150));
+ expect(wallet.shouldAutoSync, isFalse);
+ expect(wallet.historyReads, 1);
+ expect(wallet.balanceReads, 0);
+ expect(wallet.pingReads, pingsAtExit);
+ });
+ }
+
+ testWidgets('late ping cannot restart an exited wallet', (tester) async {
+ final wallet = _Wallet()..ping = Completer<bool>();
+ wallet.shouldAutoSync = true;
+ final active = wallet.refresh();
+ await tester.pump(const Duration(milliseconds: 300));
+ wallet.historyRelease.complete();
+ wallet.utxosRelease.complete(false);
+ await tester.pump();
+ await active;
+ await wallet.exit();
+ wallet.ping!.complete(true);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ final readsAfterExit = wallet.historyReads;
+ wallet.shouldAutoSync = false;
+ expect(readsAfterExit, 1);
+ expect(wallet.balanceReads, 1);
+ });
+
+ test(
+ 'concurrent refreshes wait for one update and emit synced once',
+ () async {
+ final wallet = _Wallet();
+ wallet.doNotFireRefreshEvents = false;
+ final statuses = <WalletSyncStatus>[];
+ final subscription = GlobalEventBus.instance
+ .on<WalletSyncStatusChangedEvent>()
+ .listen((event) => statuses.add(event.newStatus));
+ addTearDown(subscription.cancel);
+ final first = wallet.refresh();
+ await wallet.historyStarted.future;
+ final second = wallet.refresh();
+ var secondFinished = false;
+ final observed = second.then((_) => secondFinished = true);
+ await Future<void>.delayed(Duration.zero);
+ expect(second, same(first));
+ expect(secondFinished, isFalse);
+ expect(statuses, [WalletSyncStatus.syncing]);
+ expect(wallet.historyReads, 1);
+ wallet.historyRelease.complete();
+ wallet.utxosRelease.complete(false);
+ await first;
+ await observed;
+ await Future<void>.delayed(Duration.zero);
+ expect(statuses, [WalletSyncStatus.syncing, WalletSyncStatus.synced]);
+ expect(wallet.balanceReads, 1);
+
+ await wallet.refresh();
+ expect(wallet.historyReads, 2);
+ },
+ );
+
+ test(
+ 'a separate operation holding the mutex does not report synced',
+ () async {
+ final wallet = _Wallet();
+ wallet.doNotFireRefreshEvents = false;
+ final statuses = <WalletSyncStatus>[];
+ final subscription = GlobalEventBus.instance
+ .on<WalletSyncStatusChangedEvent>()
+ .listen((event) => statuses.add(event.newStatus));
+ addTearDown(subscription.cancel);
+ await wallet.refreshMutex.acquire();
+ addTearDown(wallet.refreshMutex.release);
+ await wallet.refresh();
+ await Future<void>.delayed(Duration.zero);
+ expect(statuses, isEmpty);
+ expect(wallet.historyReads, 0);
+ },
+ );
+}
### test/wallets/wallet_refresh_errors_test.dart
@@ -0,0 +1,146 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+class _Wallet extends Wallet<Bitcoin> {
+ _Wallet() : super(Bitcoin(CryptoCurrencyNetwork.main)) {
+ doNotFireRefreshEvents = true;
+ prefs = Prefs.instance;
+ }
+
+ final historyStarted = Completer<void>();
+ final historyRelease = Completer<void>();
+ final utxosStarted = Completer<void>();
+ final utxosRelease = Completer<bool>();
+ int historyReads = 0;
+ int balanceReads = 0;
+ bool rowDeleted = false;
+ int pingReads = 0;
+
+ @override
+ String get walletId => 'refresh-test';
+
+ @override
+ WalletInfo get info => rowDeleted
+ ? throw StateError('Wallet row deleted')
+ : WalletInfo(
+ walletId: walletId,
+ name: 'Fixture wallet',
+ mainAddressType: AddressType.p2wpkh,
+ coinName: 'bitcoin',
+ );
+
+ @override
+ Future<bool> pingCheck() async {
+ pingReads++;
+ return true;
+ }
+
+ @override
+ Future<void> updateChainHeight() async {}
+
+ @override
+ Future<void> updateTransactions() {
+ historyReads++;
+ if (!historyStarted.isCompleted) historyStarted.complete();
+ return historyRelease.future;
+ }
+
+ @override
+ Future<bool> updateUTXOs() {
+ if (!utxosStarted.isCompleted) utxosStarted.complete();
+ return utxosRelease.future;
+ }
+
+ @override
+ Future<void> updateBalance() async {
+ balanceReads++;
+ }
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) =>
+ throw UnsupportedError('${invocation.memberName}');
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ testWidgets('automatic sync retries failures until disabled', (tester) async {
+ final wallet = _Wallet();
+ wallet.shouldAutoSync = true;
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(wallet.historyReads, 1);
+ wallet.historyRelease.completeError(StateError('History unavailable'));
+ wallet.utxosRelease.complete(false);
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 150));
+ await tester.pump(const Duration(milliseconds: 300));
+ await tester.pump();
+ final readsBeforeExit = wallet.historyReads;
+ final healthyPings = wallet.pingReads;
+ wallet.shouldAutoSync = false;
+ await wallet.exit();
+ await tester.pump(const Duration(seconds: 150));
+ await tester.pump(const Duration(milliseconds: 300));
+
+ expect(readsBeforeExit, 2);
+ expect(healthyPings, greaterThan(1));
+ expect(wallet.historyReads, 2);
+ expect(wallet.balanceReads, 0);
+ });
+
+ test('retired wallet row cannot escape refresh error handling', () async {
+ final errors = <Object>[];
+ await runZonedGuarded(() async {
+ final wallet = _Wallet();
+ final refresh = wallet.refresh();
+ await wallet.historyStarted.future;
+ await wallet.utxosStarted.future;
+ // Deletion can remove this row while the refresh is still pending.
+ wallet.rowDeleted = true;
+ wallet.historyRelease.complete();
+ wallet.utxosRelease.complete(false);
+ await refresh.timeout(const Duration(seconds: 3));
+ await Future<void>.delayed(Duration.zero);
+ }, (error, _) => errors.add(error));
+ expect(errors, isEmpty);
+ });
+
+ for (final historyFails in [true, false]) {
+ test(
+ '${historyFails ? 'history' : 'UTXO'} errors wait for the other request '
+ 'before releasing the refresh lock',
+ () async {
+ final wallet = _Wallet();
+ final refresh = wallet.refresh();
+ var finished = false;
+ final observed = refresh.then((_) => finished = true);
+ await wallet.historyStarted.future;
+ await wallet.utxosStarted.future;
+ if (historyFails) {
+ wallet.historyRelease.completeError(
+ StateError('History unavailable'),
+ );
+ } else {
+ wallet.utxosRelease.completeError(StateError('UTXOs unavailable'));
+ }
+ await Future<void>.delayed(Duration.zero);
+ expect(finished, isFalse);
+ expect(wallet.refreshMutex.isLocked, isTrue);
+ if (historyFails) {
+ wallet.utxosRelease.complete(false);
+ } else {
+ wallet.historyRelease.complete();
+ }
+ await observed;
+ expect(wallet.refreshMutex.isLocked, isFalse);
+ expect(wallet.balanceReads, 0);
+ },
+ );
+ }
+}
### test/wallets/wallet_refresh_view_only_test.dart
@@ -0,0 +1,37 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/view_only_option_interface.dart';
+
+class _UnavailableWallet extends Wallet<Bitcoin>
+ with ViewOnlyOptionInterface<Bitcoin> {
+ _UnavailableWallet() : super(Bitcoin(CryptoCurrencyNetwork.main)) {
+ doNotFireRefreshEvents = true;
+ }
+
+ @override
+ String get walletId => 'unavailable-view-only-test';
+
+ @override
+ bool get isViewOnly => throw StateError('Wallet row is no longer available');
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) =>
+ throw UnsupportedError('${invocation.memberName}');
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test(
+ 'failure reading view-only state completes and releases refresh',
+ () async {
+ final wallet = _UnavailableWallet();
+ await wallet.refresh().timeout(const Duration(seconds: 1));
+ expect(wallet.refreshMutex.isLocked, isFalse);
+ // A failed attempt must not leave a permanently pending shared future.
+ await wallet.refresh().timeout(const Duration(seconds: 1));
+ expect(wallet.refreshMutex.isLocked, isFalse);
+ },
+ );
+}
### test/wallets/wallet_watcher_lifecycle_test.dart
@@ -0,0 +1,111 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:isar_community/isar.dart';
+import 'package:stackwallet/db/isar/main_db.dart';
+import 'package:stackwallet/models/isar/models/isar_models.dart';
+import 'package:stackwallet/wallets/isar/models/token_wallet_info.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/isar/providers/all_wallets_info_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/eth/token_balance_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/favourite_wallets_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/solana/sol_token_balance_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart';
+
+import '../support/isar_test_utils.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late Isar isar;
+
+ setUpAll(initializeTestIsar);
+ setUp(() async {
+ final directory = await Directory.systemTemp.createTemp(
+ 'stack_wallet_providers_',
+ );
+ addTearDown(() => directory.delete(recursive: true));
+ isar = await Isar.open(
+ [
+ WalletInfoSchema,
+ TokenWalletInfoSchema,
+ WalletSolanaTokenInfoSchema,
+ EthContractSchema,
+ SolContractSchema,
+ ],
+ directory: directory.path,
+ name: 'wallet-providers-test',
+ inspector: false,
+ );
+ addTearDown(() => isar.close());
+ await MainDB.instance.initMainDB(mock: isar);
+ await isar.writeTxn(() async {
+ await isar.walletInfo.putAll([
+ WalletInfo(
+ walletId: 'visible',
+ name: 'Visible wallet',
+ mainAddressType: AddressType.p2wpkh,
+ coinName: 'bitcoin',
+ favouriteOrderIndex: 0,
+ otherDataJsonString: jsonEncode({
+ WalletInfoKeys.duressMarkedVisibleWalletKey: true,
+ }),
+ ),
+ WalletInfo(
+ walletId: 'hidden',
+ name: 'Hidden wallet',
+ mainAddressType: AddressType.p2wpkh,
+ coinName: 'bitcoin',
+ favouriteOrderIndex: 1,
+ ),
+ ]);
+ });
+ });
+
+ test('a new provider container gets a live wallet watcher', () async {
+ final first = ProviderContainer();
+ expect(first.read(pAllWalletsInfo), hasLength(2));
+ first.dispose();
+
+ final second = ProviderContainer();
+ addTearDown(second.dispose);
+ final changed = second.listen(pAllWalletsInfo, (_, __) {});
+ addTearDown(changed.close);
+ expect(second.read(pAllWalletsInfo), hasLength(2));
+ final nextValue = Completer<List<WalletInfo>>();
+ final subscription = second.listen(pAllWalletsInfo, (_, value) {
+ if (value.any((wallet) => wallet.name == 'Renamed wallet') &&
+ !nextValue.isCompleted) {
+ nextValue.complete(value);
+ }
+ });
+ addTearDown(subscription.close);
+ final wallet = await isar.walletInfo.getByWalletId('visible');
+ await isar.writeTxn(
+ () => isar.walletInfo.put(wallet!.copyWith(name: 'Renamed wallet')),
+ );
+ expect(
+ await nextValue.future.timeout(const Duration(seconds: 5)),
+ hasLength(2),
+ );
+ });
+
+ testWidgets('wallet notifiers dispose once when their scope closes', (
+ tester,
+ ) async {
+ final container = ProviderContainer();
+ container.read(pWalletInfo('visible'));
+ container.read(pFavouriteWalletInfos(true));
+ container.read(
+ pTokenBalance((walletId: 'visible', contractAddress: 'token')),
+ );
+ container.read(
+ pSolanaTokenBalance((walletId: 'visible', tokenMint: 'mint')),
+ );
+ container.dispose();
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ });
+}Why this scored 38/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.