Merge branch 'staging' into fix/eth-add-token-new-wallet
What changed, and why it matters
This is a large merge commit that brings in many changes, most of which are defensive hardening and testing rather than a single obvious vulnerability fix. The most user-visible security improvements are: network images (token icons, exchange logos, card images) now route through the app's Tor-aware HTTP client instead of going directly over clearnet; Firo's Spark anonymity-set cache gets safer reset/recovery logic to avoid corrupting privacy data; and new integration tests verify that wallet creation actually produces recoverable seeds and addresses. There is also a database migration that enables Tor for the Fact0rn default node. The commit does not describe a specific CVE or credit an external researcher, and the diff is too broad to treat as a focused security patch.
Treat this as a routine hardening merge rather than an urgent vulnerability fix. Review the Tor-aware image loader for completeness (ensure no remaining Image.network/SvgPicture.network calls), run the new wallet-creation integration tests, and verify the Firo cache reset logic under failure injection. No immediate user action is required.
Security signals we found
Network image loading now routed through Tor-aware HTTP client, reducing clearnet exposure when Tor is enabled
Firo Spark cache reset logic hardened with epoch tracking, marker files, and worker coordination
New integration tests verify mnemonic generation, secure-storage consistency, and address recovery across 24 coins
Database migration enables Tor for previously clearnet-only Fact0rn default node if user has not customized it
Debug print of recovery-phrase challenge word removed from verify_recovery_phrase_view.dart
Native-library startup check added before wallets are loaded
Evidence from the diff
The commit merges the ‘staging’ branch into ‘fix/eth-add-token-new-wallet’ and touches 151 files. Security-relevant changes observed in the diff include: (1) introduction of TorAwareNetworkImage/TorAwareSvgNetworkLoader and replacement of Image.network/SvgPicture.network calls in token, exchange, and CakePay UI components so image fetches respect the Tor proxy setting; (2) a substantial refactor of the Firo Spark SQLite cache reset lifecycle with epoch tracking, marker files, and worker-isolate coordination to prevent races and partial resets; (3) a new wallet-creation integration-test harness that creates/reopens mainnet mnemonic wallets and validates seed-to-address recovery for 24 coins; (4) a DB migration (_v17) that flips torEnabled=true for untouched Fact0rn default nodes; (5) removal of libopencv-dev from build dependencies; and (6) a native-library startup check hook. The commit message and diff do not identify a specific vulnerability, CVE, or reporter.
Changed components
lib/networking/tor_aware_network_image.dartlib/db/sqlite/firo_cache.dartlib/db/sqlite/firo_cache_coordinator.dartlib/db/sqlite/firo_cache_reader.dartlib/db/sqlite/firo_cache_worker.dartlib/db/db_version_migration.dartintegration_test/wallet_creation/*lib/main.dartlib/utilities/native_library_check.dartlib/pages/add_wallet_views/add_token_view/sub_widgets/add_token_list_element.dartlib/pages/add_wallet_views/add_wallet_view/sub_widgets/coin_select_item.dartlib/pages/cakepay/cakepay_card_detail_view.dartlib/pages/cakepay/cakepay_vendors_view.dartlib/pages/exchange_view/exchange_coin_selection/exchange_currency_selection_view.dartlib/pages/exchange_view/sub_widgets/exchange_provider_option.dartInspect captured patch +12554 / −1686
### .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
### Dockerfile
@@ -15,7 +15,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
clang libclang-dev llvm \
libgcrypt20-dev libgirepository1.0-dev libgit2-dev libglib2.0-dev libgtk-3-dev \
libjsoncpp-dev liblzma-dev libncurses5-dev libncursesw5-dev \
- libopencv-dev \
libsecret-1-dev libssl-dev libtss2-dev \
ocl-icd-opencl-dev opencl-headers valac zlib1g-dev \
g++-aarch64-linux-gnu gcc-aarch64-linux-gnu \
### docs/building.md
@@ -47,7 +47,7 @@ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-
### Build dependencies
Install basic dependencies
```
-sudo apt-get install libssl-dev curl unzip automake build-essential file pkg-config git python3 libtool libtinfo6 cmake libgit2-dev clang libncurses5-dev libncursesw5-dev zlib1g-dev llvm lld g++ gcc gperf libopencv-dev python3-typogrify xsltproc valac gobject-introspection meson pipx libgcrypt20-dev libglib2.0-dev libsecret-1-dev
+sudo apt-get install libssl-dev curl unzip automake build-essential file pkg-config git python3 libtool libtinfo6 cmake libgit2-dev clang libncurses5-dev libncursesw5-dev zlib1g-dev llvm lld g++ gcc gperf python3-typogrify xsltproc valac gobject-introspection meson pipx libgcrypt20-dev libglib2.0-dev libsecret-1-dev
pipx install meson==0.64.1 markdown==3.4.1 markupsafe==2.1.1 jinja2==3.1.2 pygments==2.13.0 toml==0.10.2 typogrify==2.0.7 tomli==2.0.1
```
### 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.
### flatpak/com.cypherstack.campfire.yaml
@@ -9,7 +9,7 @@ finish-args:
- --share=ipc
- --socket=fallback-x11
- --socket=wayland
- - --device=dri
+ - --device=all
- --filesystem=~/.campfire:create
- --talk-name=org.freedesktop.secrets
- --talk-name=org.freedesktop.Notifications
### flatpak/com.cypherstack.stackduo.yaml
@@ -9,7 +9,7 @@ finish-args:
- --share=ipc
- --socket=fallback-x11
- --socket=wayland
- - --device=dri
+ - --device=all
- --filesystem=~/.stackduo:create
- --talk-name=org.freedesktop.secrets
- --talk-name=org.freedesktop.Notifications
### flatpak/com.cypherstack.stackwallet.yaml
@@ -9,7 +9,7 @@ finish-args:
- --share=ipc
- --socket=fallback-x11
- --socket=wayland
- - --device=dri
+ - --device=all
- --filesystem=~/.stackwallet:create
- --talk-name=org.freedesktop.secrets
- --talk-name=org.freedesktop.Notifications
### 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/db_version_migration.dart
@@ -25,6 +25,7 @@ import '../services/wallets_service.dart';
import '../utilities/amount/amount.dart';
import '../utilities/constants.dart';
import '../utilities/default_eth_tokens.dart';
+import '../utilities/default_nodes.dart';
import '../utilities/flutter_secure_storage_interface.dart';
import '../utilities/logger.dart';
import '../utilities/prefs.dart';
@@ -423,6 +424,16 @@ class DbVersionMigrator with WalletDB {
);
return await migrate(17, secureStore: secureStore);
+ case 17:
+ await _v17();
+
+ await DB.instance.put<dynamic>(
+ boxName: DB.boxNameDBInfo,
+ key: "hive_data_version",
+ value: 18,
+ );
+ return await migrate(18, secureStore: secureStore);
+
default:
// finally return
return;
@@ -711,4 +722,37 @@ class DbVersionMigrator with WalletDB {
await primariesBox.deleteFromDisk();
}
+
+ Future<void> _v17() async {
+ final nodesBox = await DB.instance.hive.openBox<NodeModel>(
+ DB.boxNameNodeModels,
+ );
+ final id = DefaultNodes.buildId(Fact0rn(CryptoCurrencyNetwork.main));
+ final node = nodesBox.get(id);
+
+ // The Fact0rn default node used to ship clearnet only. Only touch a node
+ // that still matches everything the user could have edited on it, so a
+ // customised node keeps its settings.
+ final untouched =
+ node != null &&
+ node.host == "electrumx2.projectfactor.io" &&
+ node.port == 50002 &&
+ node.name == DefaultNodes.defaultName &&
+ node.useSSL &&
+ node.isFailover &&
+ node.loginName == null &&
+ !node.torEnabled &&
+ node.clearnetEnabled;
+
+ if (untouched) {
+ await nodesBox.put(
+ id,
+ node.copyWith(
+ loginName: node.loginName,
+ trusted: node.trusted,
+ torEnabled: true,
+ ),
+ );
+ }
+ }
}
### 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/main.dart
@@ -71,6 +71,7 @@ import 'utilities/desktop_startup_and_reset.dart';
import 'utilities/enums/backup_frequency_type.dart';
import 'utilities/flutter_secure_storage_interface.dart';
import 'utilities/logger.dart';
+import 'utilities/native_library_check.dart';
import 'utilities/prefs.dart';
import 'utilities/stack_file_system.dart';
import 'utilities/util.dart';
@@ -100,7 +101,7 @@ void main(List<String> args) async {
StackFileSystem.setDesktopOverrideDir(args.last);
}
- final loadCoinlibFuture = loadCoinlib();
+ final loadCoinlibFuture = loadCoinlibOrRecordFailure(loadCoinlib);
GoogleFonts.config.allowRuntimeFetching = false;
if (Platform.isIOS) {
@@ -303,6 +304,10 @@ void main(List<String> args) async {
await loadCoinlibFuture;
+ // Before any wallet loads, so a quarantined library is reported once on
+ // the home screen instead of surfacing as wallets that fail to open.
+ checkNativeLibrariesOnStartup();
+
await MainDB.instance.initMainDB();
ThemeService.instance.init(MainDB.instance);
### lib/networking/tor_aware_network_image.dart
@@ -0,0 +1,138 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:ui' as ui;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/widgets.dart';
+import 'package:flutter_svg/flutter_svg.dart';
+
+import '../app_config.dart';
+import '../services/tor_service.dart';
+import '../utilities/prefs.dart';
+import 'http.dart';
+
+/// Fetches [url] through the app's [HTTP] client, routing over Tor when it is
+/// enabled. Throws if Tor is enabled but not connected, so nothing falls back
+/// to clearnet.
+Future<Uint8List> fetchTorAwareBytes(
+ String url, {
+ Map<String, String>? headers,
+}) async {
+ final response = await const HTTP().get(
+ url: Uri.parse(url),
+ headers: headers,
+ proxyInfo: !AppConfig.hasFeature(AppFeature.tor)
+ ? null
+ : Prefs.instance.useTor
+ ? TorService.sharedInstance.getProxyInfo()
+ : null,
+ );
+
+ if (response.code != 200) {
+ throw Exception("Failed to load $url: status=${response.code}");
+ }
+
+ return Uint8List.fromList(response.bodyBytes);
+}
+
+/// Drop-in replacement for [NetworkImage] that respects the Tor preference.
+/// Use with [Image] instead of [Image.network], which always goes clearnet.
+@immutable
+class TorAwareNetworkImage extends ImageProvider<TorAwareNetworkImage> {
+ const TorAwareNetworkImage(this.url, {this.headers, this.cacheScope});
+
+ final String url;
+
+ /// Sent with the request but not part of the cache key, so e.g. a refreshed
+ /// auth token doesn't cause a refetch.
+ final Map<String, String>? headers;
+
+ /// Part of the cache key, unlike [headers]. Set it to a stable identity
+ /// (e.g. a customer key) when the same [url] can serve different content
+ /// depending on who is asking, so one identity never sees another's image.
+ final String? cacheScope;
+
+ @override
+ Future<TorAwareNetworkImage> obtainKey(ImageConfiguration configuration) =>
+ SynchronousFuture<TorAwareNetworkImage>(this);
+
+ @override
+ ImageStreamCompleter loadImage(
+ TorAwareNetworkImage key,
+ ImageDecoderCallback decode,
+ ) {
+ final chunkEvents = StreamController<ImageChunkEvent>();
+ return MultiFrameImageStreamCompleter(
+ codec: _load(key, decode, chunkEvents),
+ chunkEvents: chunkEvents.stream,
+ scale: 1.0,
+ debugLabel: key.url,
+ );
+ }
+
+ Future<ui.Codec> _load(
+ TorAwareNetworkImage key,
+ ImageDecoderCallback decode,
+ StreamController<ImageChunkEvent> chunkEvents,
+ ) async {
+ try {
+ // Lets loadingBuilder show its indicator while the request runs.
+ chunkEvents.add(
+ const ImageChunkEvent(
+ cumulativeBytesLoaded: 0,
+ expectedTotalBytes: null,
+ ),
+ );
+ final bytes = await fetchTorAwareBytes(key.url, headers: key.headers);
+ final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
+ return await decode(buffer);
+ } catch (_) {
+ // Don't keep a failed load in the cache.
+ scheduleMicrotask(() {
+ PaintingBinding.instance.imageCache.evict(key);
+ });
+ rethrow;
+ } finally {
+ unawaited(chunkEvents.close());
+ }
+ }
+
+ @override
+ bool operator ==(Object other) =>
+ other is TorAwareNetworkImage &&
+ other.url == url &&
+ other.cacheScope == cacheScope;
+
+ @override
+ int get hashCode => Object.hash(url, cacheScope);
+
+ @override
+ String toString() =>
+ "${objectRuntimeType(this, "TorAwareNetworkImage")}"
+ "(\"$url\")";
+}
+
+/// Drop-in replacement for the loader behind [SvgPicture.network] that
+/// respects the Tor preference.
+/// Use as `SvgPicture(TorAwareSvgNetworkLoader(url))`.
+@immutable
+class TorAwareSvgNetworkLoader extends SvgLoader<Uint8List> {
+ const TorAwareSvgNetworkLoader(this.url);
+
+ final String url;
+
+ @override
+ Future<Uint8List?> prepareMessage(BuildContext? context) =>
+ fetchTorAwareBytes(url);
+
+ @override
+ String provideSvg(Uint8List? message) =>
+ utf8.decode(message!, allowMalformed: true);
+
+ @override
+ bool operator ==(Object other) =>
+ other is TorAwareSvgNetworkLoader && other.url == url;
+
+ @override
+ int get hashCode => url.hashCode;
+}
### lib/pages/add_wallet_views/add_token_view/sub_widgets/add_token_list_element.dart
@@ -16,6 +16,7 @@ import 'package:isar_community/isar.dart';
import '../../../../models/isar/exchange_cache/currency.dart';
import '../../../../models/isar/models/contract.dart';
import '../../../../models/isar/models/ethereum/eth_contract.dart';
+import '../../../../networking/tor_aware_network_image.dart';
import '../../../../services/exchange/change_now/change_now_exchange.dart';
import '../../../../services/exchange/exchange_data_loading_service.dart';
import '../../../../themes/stack_colors.dart';
@@ -101,8 +102,8 @@ class _AddTokenListElementState extends ConsumerState<AddTokenListElement> {
)
else
currency != null
- ? SvgPicture.network(
- currency!.image,
+ ? SvgPicture(
+ TorAwareSvgNetworkLoader(currency!.image),
width: iconSize,
height: iconSize,
placeholderBuilder: (_) =>
### lib/pages/add_wallet_views/add_wallet_view/sub_widgets/coin_select_item.dart
@@ -19,6 +19,7 @@ import '../../../../models/add_wallet_list_entity/add_wallet_list_entity.dart';
import '../../../../models/add_wallet_list_entity/sub_classes/eth_token_entity.dart';
import '../../../../models/add_wallet_list_entity/sub_classes/sol_token_entity.dart';
import '../../../../models/isar/exchange_cache/currency.dart';
+import '../../../../networking/tor_aware_network_image.dart';
import '../../../../providers/providers.dart';
import '../../../../services/exchange/change_now/change_now_exchange.dart';
import '../../../../services/exchange/exchange_data_loading_service.dart';
@@ -146,15 +147,15 @@ class _CoinSelectItemState extends ConsumerState<CoinSelectItem> {
else
tokenImageUri != null
? tokenImageUri!.toLowerCase().endsWith(".svg")
- ? SvgPicture.network(
- tokenImageUri!,
+ ? SvgPicture(
+ TorAwareSvgNetworkLoader(tokenImageUri!),
width: 26,
height: 26,
placeholderBuilder: (_) =>
const AppIcon(width: 26, height: 26),
)
- : Image.network(
- tokenImageUri!,
+ : Image(
+ image: TorAwareNetworkImage(tokenImageUri!),
width: 26,
height: 26,
errorBuilder: (_, _, _) => SvgPicture.file(
### 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/cakepay/cakepay_card_detail_view.dart
@@ -3,6 +3,7 @@ import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
+import '../../networking/tor_aware_network_image.dart';
import '../../providers/global/locale_provider.dart';
import '../../services/cakepay/cakepay_service.dart';
import '../../services/cakepay/src/models/card.dart';
@@ -340,8 +341,8 @@ class _CardImage extends StatelessWidget {
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
- child: Image.network(
- imageUrl,
+ child: Image(
+ image: TorAwareNetworkImage(imageUrl),
width: isDesktop ? 300 : null,
fit: isDesktop ? .contain : .fitWidth,
loadingBuilder: (_, child, event) {
### lib/pages/cakepay/cakepay_vendors_view.dart
@@ -2,6 +2,7 @@ import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
+import '../../networking/tor_aware_network_image.dart';
import '../../services/cakepay/cakepay_service.dart';
import '../../services/cakepay/src/models/card.dart';
import '../../themes/stack_colors.dart';
@@ -87,9 +88,8 @@ class _CakePayVendorsViewState extends State<CakePayVendorsView> {
}
Future<void> _onCardTapped(CakePayCard card) async {
- await Navigator.of(
- context,
- ).pushNamed(CakePayCardDetailView.routeName, arguments: card);
+ await Navigator.of(context)
+ .pushNamed(CakePayCardDetailView.routeName, arguments: card);
}
@override
@@ -130,9 +130,9 @@ class _CakePayVendorsViewState extends State<CakePayVendorsView> {
condition: !isDesktop,
builder: (child) => Background(
child: Scaffold(
- backgroundColor: Theme.of(
- context,
- ).extension<StackColors>()!.background,
+ backgroundColor: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
appBar: AppBar(
leading: AppBarBackButton(
onPressed: () => Navigator.of(context).pop(),
@@ -210,9 +210,9 @@ class _CakePayVendorsViewState extends State<CakePayVendorsView> {
child: Text(
"No items",
style: STextStyles.w500_14(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textSubtitle1,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle1,
),
),
),
@@ -226,9 +226,9 @@ class _CakePayVendorsViewState extends State<CakePayVendorsView> {
Text(
error.toString(),
style: STextStyles.w500_14(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textSubtitle1,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle1,
),
),
const SizedBox(height: 16),
@@ -276,9 +276,9 @@ class _SearchField extends StatelessWidget {
focusNode: focusNode,
style: isDesktop
? STextStyles.desktopTextExtraSmall(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldActiveText,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldActiveText,
)
: STextStyles.field(context),
decoration:
@@ -313,6 +313,14 @@ class _CountryDropdown extends StatelessWidget {
required this.onChanged,
});
+ // Cake Pay lists the United States under multiple country names.
+ static const _usCountryAliases = {
+ "us",
+ "usa",
+ "united states",
+ "united states of america",
+ };
+
final List<String> countryNames;
final String? selectedCountry;
final TextEditingController searchController;
@@ -327,9 +335,8 @@ class _CountryDropdown extends StatelessWidget {
);
final itemStyle = isDesktop
- ? STextStyles.desktopTextExtraSmall(
- context,
- ).copyWith(color: colors.textFieldActiveText)
+ ? STextStyles.desktopTextExtraSmall(context)
+ .copyWith(color: colors.textFieldActiveText)
: STextStyles.w500_14(context);
return ClipRRect(
@@ -341,9 +348,8 @@ class _CountryDropdown extends StatelessWidget {
hint: Text(
"All countries",
style: isDesktop
- ? STextStyles.desktopTextExtraSmall(
- context,
- ).copyWith(color: colors.textFieldDefaultSearchIconLeft)
+ ? STextStyles.desktopTextExtraSmall(context)
+ .copyWith(color: colors.textFieldDefaultSearchIconLeft)
: STextStyles.fieldLabel(context),
),
items: [
@@ -408,12 +414,14 @@ class _CountryDropdown extends StatelessWidget {
),
),
searchMatchFn: (item, searchValue) {
- if (item.value == null) {
- return "all countries".contains(searchValue.toLowerCase());
- }
- return item.value!.toLowerCase().contains(
- searchValue.toLowerCase(),
- );
+ final country = (item.value ?? "all countries")
+ .trim()
+ .toLowerCase();
+ final query = searchValue.trim().toLowerCase();
+
+ return country.contains(query) ||
+ (_usCountryAliases.contains(country) &&
+ _usCountryAliases.any((alias) => alias.contains(query)));
},
),
menuItemStyleData: const MenuItemStyleData(
@@ -446,8 +454,8 @@ class _CardTile extends StatelessWidget {
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: card.cardImageUrl != null
- ? Image.network(
- card.cardImageUrl!,
+ ? Image(
+ image: TorAwareNetworkImage(card.cardImageUrl!),
width: isDesktop ? 60 : 48,
height: isDesktop ? 40 : 32,
fit: BoxFit.cover,
@@ -483,9 +491,8 @@ class _CardTile extends StatelessWidget {
].join(' '),
style: isDesktop
? STextStyles.desktopTextExtraExtraSmall(context)
- : STextStyles.itemSubtitle12(
- context,
- ).copyWith(color: colors.textSubtitle1),
+ : STextStyles.itemSubtitle12(context)
+ .copyWith(color: colors.textSubtitle1),
),
],
),
### lib/pages/exchange_view/exchange_coin_selection/exchange_currency_selection_view.dart
@@ -19,6 +19,7 @@ import '../../../app_config.dart';
import '../../../models/exchange/aggregate_currency.dart';
import '../../../models/isar/exchange_cache/currency.dart';
import '../../../models/isar/exchange_cache/pair.dart';
+import '../../../networking/tor_aware_network_image.dart';
import '../../../services/exchange/exchange.dart';
import '../../../services/exchange/exchange_data_loading_service.dart';
import '../../../themes/stack_colors.dart';
@@ -73,19 +74,19 @@ class _ExchangeCurrencySelectionViewState
showDialog<void>(
context: context,
barrierDismissible: false,
- builder:
- (_) => WillPopScope(
- onWillPop: () async => false,
- child: Container(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.overlay.withOpacity(0.6),
- child: const CustomLoadingOverlay(
- message: "Loading currencies",
- eventBus: null,
- ),
- ),
+ builder: (_) => WillPopScope(
+ onWillPop: () async => false,
+ child: Container(
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .overlay
+ .withOpacity(0.6),
+ child: const CustomLoadingOverlay(
+ message: "Loading currencies",
+ eventBus: null,
),
+ ),
+ ),
),
);
@@ -101,36 +102,33 @@ class _ExchangeCurrencySelectionViewState
Future<List<AggregateCurrency>> _loadCurrencies() async {
await ExchangeDataLoadingService.instance.initDB();
final isar = await ExchangeDataLoadingService.instance.isar;
- final currencies =
- await isar.currencies
- .where()
- .filter()
- .isFiatEqualTo(false)
- .and()
- .group(
- (q) =>
- widget.isFixedRate
- ? q
- .rateTypeEqualTo(SupportedRateType.both)
- .or()
- .rateTypeEqualTo(SupportedRateType.fixed)
- : q
- .rateTypeEqualTo(SupportedRateType.both)
- .or()
- .rateTypeEqualTo(SupportedRateType.estimated),
- )
- .sortByIsStackCoin()
- .thenByName()
- .findAll();
+ final currencies = await isar.currencies
+ .where()
+ .filter()
+ .isFiatEqualTo(false)
+ .and()
+ .group(
+ (q) => widget.isFixedRate
+ ? q
+ .rateTypeEqualTo(SupportedRateType.both)
+ .or()
+ .rateTypeEqualTo(SupportedRateType.fixed)
+ : q
+ .rateTypeEqualTo(SupportedRateType.both)
+ .or()
+ .rateTypeEqualTo(SupportedRateType.estimated),
+ )
+ .sortByIsStackCoin()
+ .thenByName()
+ .findAll();
// If using Tor, filter exchanges which do not support Tor.
if (Prefs.instance.useTor) {
if (Exchange.exchangeNamesWithTorSupport.isNotEmpty) {
currencies.removeWhere(
- (element) =>
- !Exchange.exchangeNamesWithTorSupport.contains(
- element.exchangeName,
- ),
+ (element) => !Exchange.exchangeNamesWithTorSupport.contains(
+ element.exchangeName,
+ ),
);
}
}
@@ -163,20 +161,18 @@ class _ExchangeCurrencySelectionViewState
results.remove(widget.pairedCurrency);
}
- final walletCoins =
- results
- .where(
- (currency) =>
- AppConfig.coins
- .where(
- (coin) =>
- coin.ticker.toLowerCase() ==
- currency.ticker.toLowerCase() &&
- currency.fuzzyNet == coin.ticker.toLowerCase(),
- )
- .isNotEmpty,
- )
- .toList();
+ final walletCoins = results
+ .where(
+ (currency) => AppConfig.coins
+ .where(
+ (coin) =>
+ coin.ticker.toLowerCase() ==
+ currency.ticker.toLowerCase() &&
+ currency.fuzzyNet == coin.ticker.toLowerCase(),
+ )
+ .isNotEmpty,
+ )
+ .toList();
final list = results.toList();
@@ -240,8 +236,9 @@ class _ExchangeCurrencySelectionViewState
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 {
@@ -286,45 +283,45 @@ class _ExchangeCurrencySelectionViewState
focusNode: _searchFocusNode,
onChanged: (value) => setState(() => _searchString = value),
style: STextStyles.field(context),
- decoration: standardInputDecoration(
- "Search",
- _searchFocusNode,
- context,
- desktopMed: isDesktop,
- ).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,
+ desktopMed: isDesktop,
+ ).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 = "";
- _searchString = "";
- });
- },
- ),
- ],
+ padding: const EdgeInsets.only(right: 0),
+ child: UnconstrainedBox(
+ child: Row(
+ children: [
+ TextFieldIconButton(
+ child: const XIcon(),
+ onTap: () async {
+ setState(() {
+ _searchController.text = "";
+ _searchString = "";
+ });
+ },
+ ),
+ ],
+ ),
),
- ),
- )
+ )
: null,
- ),
+ ),
),
),
const SizedBox(height: 20),
@@ -358,23 +355,20 @@ class _ExchangeCurrencySelectionViewState
height: 24,
child:
AppConfig.isStackCoin(
- items[index].ticker,
- )
- ? CoinIconForTicker(
- ticker: items[index].ticker,
- size: 24,
- )
- : hasImageUrl
- ? _NetImage(
- url: image,
- key: ValueKey(
- image + items[index].fuzzyNet,
- ),
- )
- : const SizedBox(
- width: 24,
- height: 24,
+ items[index].ticker,
+ )
+ ? CoinIconForTicker(
+ ticker: items[index].ticker,
+ size: 24,
+ )
+ : hasImageUrl
+ ? _NetImage(
+ url: image,
+ key: ValueKey(
+ image + items[index].fuzzyNet,
),
+ )
+ : const SizedBox(width: 24, height: 24),
),
const SizedBox(width: 10),
Expanded(
@@ -399,24 +393,21 @@ class _ExchangeCurrencySelectionViewState
left: 12,
),
child: CoinTickerTag(
- ticker:
- items[index].fuzzyNet
- .toUpperCase(),
+ ticker: items[index].fuzzyNet
+ .toUpperCase(),
),
),
],
),
const SizedBox(height: 2),
Text(
items[index].ticker.toUpperCase(),
- style: STextStyles.smallMed12(
- context,
- ).copyWith(
- color:
- Theme.of(context)
+ style: STextStyles.smallMed12(context)
+ .copyWith(
+ color: Theme.of(context)
.extension<StackColors>()!
.textSubtitle1,
- ),
+ ),
),
],
),
@@ -447,15 +438,20 @@ class _NetImage extends StatelessWidget {
@override
Widget build(BuildContext context) {
if (url.endsWith(".svg")) {
- return SvgPicture.network(
+ return SvgPicture(
key: key,
- url,
+ TorAwareSvgNetworkLoader(url),
width: 24,
height: 24,
placeholderBuilder: (_) => const LoadingIndicator(),
);
} else {
- return Image.network(url, width: 24, height: 24, key: key);
+ return Image(
+ image: TorAwareNetworkImage(url),
+ width: 24,
+ height: 24,
+ key: key,
+ );
}
}
}
### 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/exchange_view/sub_widgets/exchange_provider_option.dart
@@ -15,6 +15,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../app_config.dart';
import '../../../models/exchange/aggregate_currency.dart';
import '../../../models/exchange/response_objects/estimate.dart';
+import '../../../networking/tor_aware_network_image.dart';
import '../../../providers/exchange/exchange_form_state_provider.dart';
import '../../../providers/global/locale_provider.dart';
import '../../../services/exchange/exchange.dart';
@@ -164,9 +165,9 @@ class _ExchangeOptionState extends ConsumerState<ExchangeOption> {
isDesktop
? Container(
height: 1,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.background,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
)
: const SizedBox(height: 16),
child,
@@ -215,9 +216,9 @@ class _ExchangeOptionState extends ConsumerState<ExchangeOption> {
estimate: null,
pair: pair,
rateString: message ?? "Failed to fetch rate",
- rateColor: Theme.of(
- context,
- ).extension<StackColors>()!.textError,
+ rateColor: Theme.of(context)
+ .extension<StackColors>()!
+ .textError,
);
},
);
@@ -354,9 +355,9 @@ class _ProviderOptionState extends ConsumerState<ExchProviderOption> {
child: Padding(
padding: EdgeInsets.only(top: isDesktop ? 20.0 : 15.0),
child: Radio(
- activeColor: Theme.of(
- context,
- ).extension<StackColors>()!.radioButtonIconEnabled,
+ activeColor: Theme.of(context)
+ .extension<StackColors>()!
+ .radioButtonIconEnabled,
value: _id,
groupValue: groupValue,
onChanged: (_) {
@@ -382,8 +383,10 @@ class _ProviderOptionState extends ConsumerState<ExchProviderOption> {
widget.estimate!.exchangeProviderLogo!.isNotEmpty
? ClipRRect(
borderRadius: BorderRadius.circular(5),
- child: Image.network(
- widget.estimate!.exchangeProviderLogo!,
+ child: Image(
+ image: TorAwareNetworkImage(
+ widget.estimate!.exchangeProviderLogo!,
+ ),
loadingBuilder:
(context, child, loadingProgress) {
if (loadingProgress == null) {
@@ -427,9 +430,9 @@ class _ProviderOptionState extends ConsumerState<ExchProviderOption> {
widget.estimate?.exchangeProvider ??
widget.exchange.name,
style: STextStyles.titleBold12(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textDark2,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textDark2,
),
),
),
@@ -443,9 +446,9 @@ class _ProviderOptionState extends ConsumerState<ExchProviderOption> {
],
style: STextStyles.itemSubtitle12(context)
.copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textSubtitle1,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle1,
),
)
: Text(
### lib/pages/home_view/home_view.dart
@@ -35,6 +35,7 @@ import '../../widgets/animated_widgets/rotate_icon.dart';
import '../../widgets/app_icon.dart';
import '../../widgets/background.dart';
import '../../widgets/custom_buttons/app_bar_icon_button.dart';
+import '../../widgets/onetime_popups/native_library_warning_dialog.dart';
import '../../widgets/small_tor_icon.dart';
import '../../widgets/stack_dialog.dart';
import '../buy_view/buy_view.dart';
@@ -243,6 +244,10 @@ class _HomeViewState extends ConsumerState<HomeView> {
// showOneTimeTorHasBeenAddedDialogIfRequired(context);
// });
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ unawaited(showNativeLibraryWarningIfRequired(context));
+ });
+
_idleMonitor?.attach();
ref.read(prefsChangeNotifierProvider).addListener(_prefsTimeoutListener);
@@ -306,9 +311,9 @@ class _HomeViewState extends ConsumerState<HomeView> {
key: _key,
appBar: AppBar(
automaticallyImplyLeading: false,
- backgroundColor: Theme.of(
- context,
- ).extension<StackColors>()!.backgroundAppBar,
+ backgroundColor: Theme.of(context)
+ .extension<StackColors>()!
+ .backgroundAppBar,
title: Row(
children: [
GestureDetector(
@@ -343,11 +348,10 @@ class _HomeViewState extends ConsumerState<HomeView> {
key: const Key("walletsViewAlertsButton"),
size: 36,
shadows: const [],
- color: Theme.of(
- context,
- ).extension<StackColors>()!.backgroundAppBar,
- icon:
- ref.watch(pAnyGlobalUnreadNotifications)
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .backgroundAppBar,
+ icon: ref.watch(pAnyGlobalUnreadNotifications)
? SvgPicture.file(
File(
ref.watch(
@@ -358,60 +362,58 @@ class _HomeViewState extends ConsumerState<HomeView> {
),
width: 20,
height: 20,
- color:
- ref.watch(pAnyGlobalUnreadNotifications)
+ color: ref.watch(pAnyGlobalUnreadNotifications)
? null
- : Theme.of(
- context,
- ).extension<StackColors>()!.topNavIconPrimary,
+ : Theme.of(context)
+ .extension<StackColors>()!
+ .topNavIconPrimary,
)
: SvgPicture.asset(
Assets.svg.bell,
width: 20,
height: 20,
- color:
- ref.watch(pAnyGlobalUnreadNotifications)
+ color: ref.watch(pAnyGlobalUnreadNotifications)
? null
- : Theme.of(
- context,
- ).extension<StackColors>()!.topNavIconPrimary,
+ : Theme.of(context)
+ .extension<StackColors>()!
+ .topNavIconPrimary,
),
onPressed: () {
// reset unread state
ref.refresh(unreadNotificationsStateProvider);
- Navigator.of(
- context,
- ).pushNamed(NotificationsView.routeName).then((_) {
- final Set<int> unreadNotificationIds = ref
- .read(unreadNotificationsStateProvider.state)
- .state;
- if (unreadNotificationIds.isEmpty) return;
-
- final List<Future<void>> futures = [];
- for (
- int i = 0;
- i < unreadNotificationIds.length - 1;
- i++
- ) {
- futures.add(
- ref
- .read(notificationsProvider)
- .markAsRead(
- unreadNotificationIds.elementAt(i),
- false,
- ),
- );
- }
-
- // wait for multiple to update if any
- Future.wait(futures).then((_) {
- // only notify listeners once
- ref
- .read(notificationsProvider)
- .markAsRead(unreadNotificationIds.last, true);
- });
- });
+ Navigator.of(context)
+ .pushNamed(NotificationsView.routeName)
+ .then((_) {
+ final Set<int> unreadNotificationIds = ref
+ .read(unreadNotificationsStateProvider.state)
+ .state;
+ if (unreadNotificationIds.isEmpty) return;
+
+ final List<Future<void>> futures = [];
+ for (
+ int i = 0;
+ i < unreadNotificationIds.length - 1;
+ i++
+ ) {
+ futures.add(
+ ref
+ .read(notificationsProvider)
+ .markAsRead(
+ unreadNotificationIds.elementAt(i),
+ false,
+ ),
+ );
+ }
+
+ // wait for multiple to update if any
+ Future.wait(futures).then((_) {
+ // only notify listeners once
+ ref
+ .read(notificationsProvider)
+ .markAsRead(unreadNotificationIds.last, true);
+ });
+ });
},
),
),
@@ -425,23 +427,22 @@ class _HomeViewState extends ConsumerState<HomeView> {
key: const Key("walletsViewSettingsButton"),
size: 36,
shadows: const [],
- color: Theme.of(
- context,
- ).extension<StackColors>()!.backgroundAppBar,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .backgroundAppBar,
icon: SvgPicture.asset(
Assets.svg.gear,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.topNavIconPrimary,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .topNavIconPrimary,
width: 20,
height: 20,
),
onPressed: () {
//todo: check if print needed
// debugPrint("main view settings tapped");
- Navigator.of(
- context,
- ).pushNamed(GlobalSettingsView.routeName);
+ Navigator.of(context)
+ .pushNamed(GlobalSettingsView.routeName);
},
),
),
@@ -455,9 +456,9 @@ class _HomeViewState extends ConsumerState<HomeView> {
ref.watch(prefsChangeNotifierProvider).enableExchange)
Container(
decoration: BoxDecoration(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.backgroundAppBar,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .backgroundAppBar,
boxShadow:
Theme.of(context)
.extension<StackColors>()!
### lib/pages/salvium_stake/salvium_create_stake_view.dart
@@ -11,6 +11,7 @@ import '../../themes/stack_colors.dart';
import '../../utilities/amount/amount.dart';
import '../../utilities/amount/amount_field_relocalization.dart';
import '../../utilities/amount/amount_formatter.dart';
+import '../../utilities/amount/amount_parser.dart';
import '../../utilities/amount/amount_input_formatter.dart';
import '../../utilities/amount/amount_unit.dart';
import '../../utilities/enums/fee_rate_type_enum.dart';
@@ -58,9 +59,14 @@ class _SalviumCreateStakeViewState
}
void _parseAmount(String string) {
- final cryptoAmount = ref
- .read(pAmountFormatter(ref.read(pWalletCoin(widget.walletId))))
- .tryParseEditable(string);
+ if (_updatingAmountDisplay) return;
+ final coin = ref.read(pWalletCoin(widget.walletId));
+ final cryptoAmount = AmountParser.tryParseEditable(
+ string,
+ locale: ref.read(localeServiceChangeNotifierProvider).locale,
+ unit: ref.read(pAmountUnit(coin)),
+ coin: coin,
+ );
if (_amount != cryptoAmount) {
setState(() {
@@ -69,6 +75,18 @@ class _SalviumCreateStakeViewState
}
}
+ bool _updatingAmountDisplay = false;
+
+ void _updateAmountDisplay(VoidCallback update) {
+ final wasUpdating = _updatingAmountDisplay;
+ _updatingAmountDisplay = true;
+ try {
+ update();
+ } finally {
+ _updatingAmountDisplay = wasUpdating;
+ }
+ }
+
bool _lock = false;
Future<void> _previewPressed() async {
if (_lock) return;
@@ -289,7 +307,18 @@ class _SalviumCreateStakeViewState
final locale = ref.watch(
localeServiceChangeNotifierProvider.select((s) => s.locale),
);
- listenForAmountRelocalization(ref.listen, controllers: [_amountController]);
+ listenForAmountRelocalization(
+ ref.listen,
+ controllers: [_amountController],
+ updateControllers: _updateAmountDisplay,
+ );
+ ref.listen<AmountFormatter>(pAmountFormatter(coin), (previous, next) {
+ if (previous?.unit != next.unit && _amount != null) {
+ _updateAmountDisplay(() {
+ _amountController.text = next.formatEditable(_amount!);
+ });
+ }
+ });
return ConditionalParent(
condition: !Util.isDesktop,
### 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/frost_ms/recipient.dart
@@ -8,6 +8,7 @@ import '../../../utilities/address_utils.dart';
import '../../../utilities/amount/amount.dart';
import '../../../utilities/amount/amount_field_relocalization.dart';
import '../../../utilities/amount/amount_formatter.dart';
+import '../../../utilities/amount/amount_parser.dart';
import '../../../utilities/amount/amount_input_formatter.dart';
import '../../../utilities/amount/amount_unit.dart';
import '../../../utilities/barcode_scanner_interface.dart';
@@ -85,17 +86,32 @@ class _RecipientState extends ConsumerState<Recipient> {
late final FocusNode addressFocusNode, amountFocusNode;
bool _addressIsEmpty = true;
- final bool _cryptoAmountChangeLock = false;
+ bool _cryptoAmountChangeLock = false;
bool get isSingle => widget.remove == null;
RecipientId get _id => (walletId: widget.walletId, index: widget.index);
+ Amount? _parseAmount() => AmountParser.tryParseEditable(
+ amountController.text,
+ locale: ref.read(localeServiceChangeNotifierProvider).locale,
+ unit: ref.read(pAmountUnit(widget.coin)),
+ coin: widget.coin,
+ );
+
+ void _updateAmountDisplay(VoidCallback update) {
+ final wasLocked = _cryptoAmountChangeLock;
+ _cryptoAmountChangeLock = true;
+ try {
+ update();
+ } finally {
+ _cryptoAmountChangeLock = wasLocked;
+ }
+ }
+
void _updateRecipientData({String? label, bool replaceLabel = false}) {
final address = addressController.text;
- final amount = ref
- .read(pAmountFormatter(widget.coin))
- .tryParseEditable(amountController.text);
+ final amount = _parseAmount();
final previous = ref.read(pRecipient(_id));
ref.read(pRecipient(_id).notifier).state = (
@@ -174,9 +190,7 @@ class _RecipientState extends ConsumerState<Recipient> {
void _cryptoAmountChanged() async {
if (!_cryptoAmountChangeLock) {
- Amount? cryptoAmount = ref
- .read(pAmountFormatter(widget.coin))
- .tryParseEditable(amountController.text);
+ Amount? cryptoAmount = _parseAmount();
if (cryptoAmount != null) {
if (ref.read(pRecipient(_id))?.amount != null &&
ref.read(pRecipient(_id))?.amount == cryptoAmount) {
@@ -299,15 +313,21 @@ class _RecipientState extends ConsumerState<Recipient> {
final String locale = ref.watch(
localeServiceChangeNotifierProvider.select((value) => value.locale),
);
- listenForAmountRelocalization(ref.listen, controllers: [amountController]);
+ listenForAmountRelocalization(
+ ref.listen,
+ controllers: [amountController],
+ updateControllers: _updateAmountDisplay,
+ );
// Keep the amount, rather than the number typed, when the unit changes.
ref.listen<AmountFormatter>(pAmountFormatter(widget.coin), (
previous,
next,
) {
final amount = ref.read(pRecipient(_id))?.amount;
if (previous?.unit != next.unit && amount != null) {
- amountController.text = next.formatEditable(amount);
+ _updateAmountDisplay(() {
+ amountController.text = next.formatEditable(amount);
+ });
}
});
### lib/pages/send_view/send_view.dart
@@ -39,6 +39,7 @@ import '../../utilities/address_utils.dart';
import '../../utilities/amount/amount.dart';
import '../../utilities/amount/amount_field_relocalization.dart';
import '../../utilities/amount/amount_formatter.dart';
+import '../../utilities/amount/amount_parser.dart';
import '../../utilities/amount/amount_input_formatter.dart';
import '../../utilities/amount/amount_unit.dart';
import '../../utilities/assets.dart';
@@ -567,6 +568,7 @@ class _SendViewState extends ConsumerState<SendView> {
}
void _fiatFieldChanged(String baseAmountString) {
+ _xelisSendAll = false;
final baseAmount = Amount.tryParseFiatString(
baseAmountString,
locale: ref.read(localeServiceChangeNotifierProvider).locale,
@@ -600,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 = "";
@@ -616,12 +618,26 @@ class _SendViewState extends ConsumerState<SendView> {
bool _xelisSendAll = false;
+ // 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 {
- _xelisSendAll = false;
if (!_cryptoAmountChangeLock) {
- final cryptoAmount = ref
- .read(pAmountFormatter(coin))
- .tryParseEditable(cryptoAmountController.text);
+ _xelisSendAll = false;
+ final cryptoAmount = AmountParser.tryParseEditable(
+ cryptoAmountController.text,
+ locale: ref.read(localeServiceChangeNotifierProvider).locale,
+ unit: ref.read(pAmountUnit(coin)),
+ coin: coin,
+ );
final Amount? amount;
if (cryptoAmount != null) {
amount = cryptoAmount;
@@ -1710,15 +1726,17 @@ class _SendViewState extends ConsumerState<SendView> {
listenForAmountRelocalization(
ref.listen,
controllers: [cryptoAmountController, baseAmountController],
- onRelocalized: _cryptoAmountChanged,
+ updateControllers: _updateAmountDisplay,
);
// Keep the amount, rather than the number typed, when the unit changes.
ref.listen<AmountFormatter>(pAmountFormatter(coin), (previous, next) {
final amount = ref.read(pSendAmount);
if (previous?.unit != next.unit && amount != null) {
// Only the display changes, so keep the send all intent.
final xelisSendAll = _xelisSendAll;
- cryptoAmountController.text = next.formatEditable(amount);
+ _updateAmountDisplay(() {
+ cryptoAmountController.text = next.formatEditable(amount);
+ });
_xelisSendAll = xelisSendAll;
}
});
### 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
@@ -27,6 +27,7 @@ import '../../utilities/address_utils.dart';
import '../../utilities/amount/amount.dart';
import '../../utilities/amount/amount_field_relocalization.dart';
import '../../utilities/amount/amount_formatter.dart';
+import '../../utilities/amount/amount_parser.dart';
import '../../utilities/amount/amount_input_formatter.dart';
import '../../utilities/amount/amount_unit.dart';
import '../../utilities/assets.dart';
@@ -280,7 +281,7 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
.formatEditable(_amountToSend!);
_cryptoAmountChangeLock = false;
} else {
- _amountToSend = Amount.zero;
+ _amountToSend = null;
_cachedAmountToSend = null;
_cryptoAmountChangeLock = true;
cryptoAmountController.text = "";
@@ -294,14 +295,26 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
_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 cryptoAmount = ref
- .read(pAmountFormatter(coin))
- .tryParseEditable(
- cryptoAmountController.text,
- tokenContract: tokenContract,
- );
+ final cryptoAmount = AmountParser.tryParseEditable(
+ cryptoAmountController.text,
+ locale: ref.read(localeServiceChangeNotifierProvider).locale,
+ unit: ref.read(pAmountUnit(coin)),
+ coin: coin,
+ tokenContract: tokenContract,
+ );
if (cryptoAmount != null) {
_amountToSend = cryptoAmount;
if (_cachedAmountToSend != null &&
@@ -656,8 +669,15 @@ class _TokenSendViewState extends ConsumerState<TokenSendView> {
listenForAmountRelocalization(
ref.listen,
controllers: [cryptoAmountController, baseAmountController],
- onRelocalized: _cryptoAmountChanged,
+ updateControllers: _updateAmountDisplay,
);
+ ref.listen<AmountFormatter>(pAmountFormatter(coin), (previous, next) {
+ if (previous?.unit != next.unit && _amountToSend != null) {
+ _updateAmountDisplay(() {
+ cryptoAmountController.text = next.formatEditable(_amountToSend!);
+ });
+ }
+ });
// ethFee is checked in the ValueListenableBuilder around the preview
// button so fee keystrokes don't rebuild this whole view.
final previewEnabled = ref
### lib/pages/settings_views/global_settings_view/appearance_settings/sub_widgets/stack_theme_card.dart
@@ -17,6 +17,7 @@ import 'package:flutter_svg/svg.dart';
import 'package:isar_community/isar.dart';
import '../../../../../models/isar/stack_theme.dart';
+import '../../../../../networking/tor_aware_network_image.dart';
import '../../../../../notifications/show_flush_bar.dart';
import '../../../../../providers/db/main_db_provider.dart';
import '../../../../../providers/global/prefs_provider.dart';
@@ -69,18 +70,16 @@ class _StackThemeCardState extends ConsumerState<StackThemeCard> {
}
Future<void> _downloadPressed() async {
- final result =
- (await showLoading(
- whileFuture: _downloadAndInstall(),
- context: context,
- message: "Downloading and installing theme...",
- ))!;
+ final result = (await showLoading(
+ whileFuture: _downloadAndInstall(),
+ context: context,
+ message: "Downloading and installing theme...",
+ ))!;
if (mounted) {
- final message =
- result
- ? "${widget.data.name} theme installed!"
- : "Failed to install ${widget.data.name} theme";
+ final message = result
+ ? "${widget.data.name} theme installed!"
+ : "Failed to install ${widget.data.name} theme";
if (isDesktop) {
await showFloatingFlushBar(
type: result ? FlushBarType.success : FlushBarType.warning,
@@ -90,16 +89,15 @@ class _StackThemeCardState extends ConsumerState<StackThemeCard> {
} else {
await showDialog<void>(
context: context,
- builder:
- (_) => StackOkDialog(
- title: message,
- onOkPressed: (_) {
- setState(() {
- _needsUpdate = !result;
- _hasTheme = result;
- });
- },
- ),
+ builder: (_) => StackOkDialog(
+ title: message,
+ onOkPressed: (_) {
+ setState(() {
+ _needsUpdate = !result;
+ _hasTheme = result;
+ });
+ },
+ ),
);
}
}
@@ -155,14 +153,13 @@ class _StackThemeCardState extends ConsumerState<StackThemeCard> {
}
}
- StackTheme? getInstalled() =>
- ref
- .read(mainDBProvider)
- .isar
- .stackThemes
- .where()
- .themeIdEqualTo(widget.data.id)
- .findFirstSync();
+ StackTheme? getInstalled() => ref
+ .read(mainDBProvider)
+ .isar
+ .stackThemes
+ .where()
+ .themeIdEqualTo(widget.data.id)
+ .findFirstSync();
@override
void initState() {
@@ -207,39 +204,41 @@ class _StackThemeCardState extends ConsumerState<StackThemeCard> {
Widget build(BuildContext context) {
return RoundedWhiteContainer(
radiusMultiplier: isDesktop ? 2.5 : 1,
- borderColor:
- isDesktop
- ? Theme.of(context).extension<StackColors>()!.textSubtitle6
- : null,
+ borderColor: isDesktop
+ ? Theme.of(context).extension<StackColors>()!.textSubtitle6
+ : null,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 18),
- child:
- widget.data.previewImageUrl.isNotEmpty
- ? AspectRatio(
- aspectRatio: 1,
- child: ClipRRect(
- borderRadius: BorderRadius.circular(100),
- child: Image.network(widget.data.previewImageUrl),
+ child: widget.data.previewImageUrl.isNotEmpty
+ ? AspectRatio(
+ aspectRatio: 1,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(100),
+ child: Image(
+ image: TorAwareNetworkImage(
+ widget.data.previewImageUrl,
+ ),
),
- )
- : Builder(
- builder: (context) {
- final themePreview =
- ref
- .watch(pThemeService)
- .getTheme(themeId: widget.data.id)
- ?.assets
- .themePreview ??
- "";
-
- return (themePreview.endsWith(".png"))
- ? Image.file(File(themePreview), height: 100)
- : SvgPicture.file(File(themePreview), height: 100);
- },
),
+ )
+ : Builder(
+ builder: (context) {
+ final themePreview =
+ ref
+ .watch(pThemeService)
+ .getTheme(themeId: widget.data.id)
+ ?.assets
+ .themePreview ??
+ "";
+
+ return (themePreview.endsWith(".png"))
+ ? Image.file(File(themePreview), height: 100)
+ : SvgPicture.file(File(themePreview), height: 100);
+ },
+ ),
),
const SizedBox(height: 12),
Text(widget.data.name, style: STextStyles.itemSubtitle12(context)),
@@ -276,10 +275,9 @@ class _StackThemeCardState extends ConsumerState<StackThemeCard> {
const SizedBox(height: 12),
AnimatedCrossFade(
duration: const Duration(milliseconds: 300),
- crossFadeState:
- _hasTheme
- ? CrossFadeState.showSecond
- : CrossFadeState.showFirst,
+ crossFadeState: _hasTheme
+ ? CrossFadeState.showSecond
+ : CrossFadeState.showFirst,
firstChild: PrimaryButton(
label: "Download",
buttonHeight: isDesktop ? ButtonHeight.s : ButtonHeight.l,
### 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/settings_views/global_settings_view/hidden_settings.dart
@@ -41,17 +41,17 @@ class HiddenSettings extends StatelessWidget {
padding: const EdgeInsets.all(8.0),
child: AppBarIconButton(
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: Navigator.of(context).pop,
),
### lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart
@@ -1048,15 +1048,19 @@ class _NodeFormState extends ConsumerState<NodeForm> {
final port = uri.hasPort ? uri.port : 0;
if (port != 0) {
_portController.text = port.toString();
- final noPortUri = Uri(
- scheme: uri.scheme,
- userInfo: uri.userInfo,
- host: uri.host,
- path: uri.path,
- query: uri.hasQuery ? uri.query : null,
- fragment: uri.fragment.isNotEmpty ? uri.fragment : null,
- );
- _hostController.text = noPortUri.toString();
+ // eth connects to the host url as is and ignores the port
+ // field, so the port has to stay in the url
+ if (widget.coin is! Ethereum) {
+ final noPortUri = Uri(
+ scheme: uri.scheme,
+ userInfo: uri.userInfo,
+ host: uri.host,
+ path: uri.path,
+ query: uri.hasQuery ? uri.query : null,
+ fragment: uri.fragment.isNotEmpty ? uri.fragment : null,
+ );
+ _hostController.text = noPortUri.toString();
+ }
}
} catch (_) {
if (newValue.contains(":")) {
@@ -1471,60 +1475,57 @@ class _NodeFormState extends ConsumerState<NodeForm> {
),
],
),
- if (widget.coin is! Ethereum) const SizedBox(height: 16),
- if (widget.coin is! Ethereum)
- Row(
- children: [
- RadioTextButton(
- label: "Only TOR traffic",
- enabled: !widget.readOnly,
- value: TorPlainNetworkOption.tor,
- groupValue: netOption,
- onChanged: (value) {
- if (!widget.readOnly) {
- setState(() => netOption = TorPlainNetworkOption.tor);
- _updateState();
- }
- },
- ),
- ],
- ),
- if (widget.coin is! Ethereum) const SizedBox(height: 8),
- if (widget.coin is! Ethereum)
- Row(
- children: [
- RadioTextButton(
- label: "Only non-TOR traffic",
- enabled: !widget.readOnly,
- value: TorPlainNetworkOption.clear,
- groupValue: netOption,
- onChanged: (value) {
- if (!widget.readOnly) {
- setState(() => netOption = TorPlainNetworkOption.clear);
- _updateState();
- }
- },
- ),
- ],
- ),
- if (widget.coin is! Ethereum) const SizedBox(height: 8),
- if (widget.coin is! Ethereum)
- Row(
- children: [
- RadioTextButton(
- label: "Allow both",
- enabled: !widget.readOnly,
- value: TorPlainNetworkOption.both,
- groupValue: netOption,
- onChanged: (value) {
- if (!widget.readOnly) {
- setState(() => netOption = TorPlainNetworkOption.both);
- _updateState();
- }
- },
- ),
- ],
- ),
+ const SizedBox(height: 16),
+ Row(
+ children: [
+ RadioTextButton(
+ label: "Only TOR traffic",
+ enabled: !widget.readOnly,
+ value: TorPlainNetworkOption.tor,
+ groupValue: netOption,
+ onChanged: (value) {
+ if (!widget.readOnly) {
+ setState(() => netOption = TorPlainNetworkOption.tor);
+ _updateState();
+ }
+ },
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ RadioTextButton(
+ label: "Only non-TOR traffic",
+ enabled: !widget.readOnly,
+ value: TorPlainNetworkOption.clear,
+ groupValue: netOption,
+ onChanged: (value) {
+ if (!widget.readOnly) {
+ setState(() => netOption = TorPlainNetworkOption.clear);
+ _updateState();
+ }
+ },
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ RadioTextButton(
+ label: "Allow both",
+ enabled: !widget.readOnly,
+ value: TorPlainNetworkOption.both,
+ groupValue: netOption,
+ onChanged: (value) {
+ if (!widget.readOnly) {
+ setState(() => netOption = TorPlainNetworkOption.both);
+ _updateState();
+ }
+ },
+ ),
+ ],
+ ),
if (widget.coin is CryptonoteCurrency && _isLocalNode())
const SizedBox(height: 8),
if (widget.coin is CryptonoteCurrency && _isLocalNode())
### lib/pages/shopinbit/shopinbit_ticket_detail.dart
@@ -10,6 +10,7 @@ import 'package:url_launcher/url_launcher.dart';
import '../../db/drift/shared_db/shared_database.dart';
import '../../models/shopinbit/shopinbit_enums.dart';
+import '../../networking/tor_aware_network_image.dart';
import '../../notifications/show_flush_bar.dart';
import '../../providers/db/drift_provider.dart';
import '../../providers/global/shopin_bit_service_provider.dart';
@@ -432,9 +433,8 @@ class _ShopInBitTicketDetailState extends ConsumerState<ShopInBitTicketDetail>
);
}
if (context.mounted) {
- await Navigator.of(
- context,
- ).pushNamed(ShopInBitOfferView.routeName, arguments: _id);
+ await Navigator.of(context)
+ .pushNamed(ShopInBitOfferView.routeName, arguments: _id);
}
}
@@ -443,9 +443,9 @@ class _ShopInBitTicketDetailState extends ConsumerState<ShopInBitTicketDetail>
padding: .only(bottom: isDesktop ? 12 : 8),
child: RoundedWhiteContainer(
borderColor: isDesktop
- ? Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG
: null,
child: ConditionalParent(
condition: Util.isDesktop,
@@ -559,9 +559,9 @@ class _ShopInBitTicketDetailState extends ConsumerState<ShopInBitTicketDetail>
? STextStyles.desktopTextExtraSmall(context)
: STextStyles.field(context))
.copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textDark,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textDark,
),
decoration: InputDecoration(
hintText: "Type a message...",
@@ -585,9 +585,9 @@ class _ShopInBitTicketDetailState extends ConsumerState<ShopInBitTicketDetail>
Assets.svg.send,
width: 24,
height: 24,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.accentColorBlue,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .accentColorBlue,
),
),
],
@@ -600,9 +600,9 @@ class _ShopInBitTicketDetailState extends ConsumerState<ShopInBitTicketDetail>
padding: EdgeInsets.only(bottom: isDesktop ? 12 : 8),
child: RoundedWhiteContainer(
borderColor: isDesktop
- ? Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG
: null,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -698,9 +698,9 @@ class _ShopInBitTicketDetailState extends ConsumerState<ShopInBitTicketDetail>
condition: !isDesktop,
builder: (child) => Background(
child: Scaffold(
- backgroundColor: Theme.of(
- context,
- ).extension<StackColors>()!.background,
+ backgroundColor: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
appBar: AppBar(
leading: AppBarBackButton(
onPressed: () => Navigator.of(context).pop(),
@@ -827,9 +827,14 @@ class _AttachmentChip extends StatelessWidget {
/// Renders an authenticated `/attachment-proxy/` image.
///
-/// The signed URL future is built once in [initState] (and only rebuilt when
+/// The request future is built once in [initState] (and only rebuilt when
/// [proxyPath] or [customerKey] actually change) so the surrounding 30s poll
-/// can't re-fire `getAttachmentUrl`/re-fetch the image on every rebuild.
+/// can't re-fire `getAttachmentRequest`/re-fetch the image on every rebuild.
+typedef _AttachmentLoad = ({
+ ApiResponse<AttachmentRequest> response,
+ String customerKey,
+});
+
class _ProxyImage extends StatefulWidget {
const _ProxyImage({
required this.client,
@@ -848,26 +853,31 @@ class _ProxyImage extends StatefulWidget {
}
class _ProxyImageState extends State<_ProxyImage> {
- late Future<ApiResponse<Uri>> _urlFuture;
-
- Future<ApiResponse<Uri>> _buildFuture() => widget.client.getAttachmentUrl(
- widget.proxyPath,
- useQueryAuth: true,
- customerKey: widget.customerKey,
- );
+ late Future<_AttachmentLoad> _requestFuture;
+
+ // Header auth: a query-auth URL would put the token and customer key into
+ // logged HTTP errors. The customer key travels with the response because
+ // FutureBuilder keeps showing the previous snapshot while a new future is
+ // pending, and that snapshot must not be paired with a newer key.
+ Future<_AttachmentLoad> _buildFuture() {
+ final customerKey = widget.customerKey;
+ return widget.client
+ .getAttachmentRequest(widget.proxyPath, customerKey: customerKey)
+ .then((response) => (response: response, customerKey: customerKey));
+ }
@override
void initState() {
super.initState();
- _urlFuture = _buildFuture();
+ _requestFuture = _buildFuture();
}
@override
void didUpdateWidget(covariant _ProxyImage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.proxyPath != widget.proxyPath ||
oldWidget.customerKey != widget.customerKey) {
- _urlFuture = _buildFuture();
+ _requestFuture = _buildFuture();
}
}
@@ -879,23 +889,30 @@ class _ProxyImageState extends State<_ProxyImage> {
borderRadius: BorderRadius.circular(8),
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: _kAttachmentMaxHeight),
- child: FutureBuilder<ApiResponse<Uri>>(
- future: _urlFuture,
+ child: FutureBuilder<_AttachmentLoad>(
+ future: _requestFuture,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const SizedBox(
height: _kAttachmentLoaderHeight,
child: LoadingIndicator(width: _kAttachmentLoaderWidth),
);
}
- final resp = snapshot.data!;
+ final resp = snapshot.data!.response;
if (resp.hasError || resp.value == null) {
return widget.fallback();
}
- return Image.network(
- resp.value!.toString(),
+ return Image(
+ image: ResizeImage.resizeIfNeeded(
+ null,
+ _kAttachmentDecodeHeight,
+ TorAwareNetworkImage(
+ resp.value!.uri.toString(),
+ headers: resp.value!.headers,
+ cacheScope: snapshot.data!.customerKey,
+ ),
+ ),
fit: BoxFit.contain,
- cacheHeight: _kAttachmentDecodeHeight,
semanticLabel: "Image attachment",
errorBuilder: (_, _, _) => widget.fallback(),
);
### lib/pages/wallet_view/transaction_views/transaction_search_filter_view.dart
@@ -19,6 +19,8 @@ import '../../../themes/theme_providers.dart';
import '../../../utilities/amount/amount.dart';
import '../../../utilities/amount/amount_field_relocalization.dart';
import '../../../utilities/amount/amount_formatter.dart';
+import '../../../utilities/amount/amount_parser.dart';
+import '../../../utilities/amount/amount_unit.dart';
import '../../../utilities/amount/amount_input_formatter.dart';
import '../../../utilities/constants.dart';
import '../../../utilities/text_styles.dart';
@@ -39,15 +41,21 @@ import '../../../widgets/textfield_icon_button.dart';
({bool isValid, Amount? amount}) parseTransactionFilterAmountInput({
required String text,
required String locale,
- required AmountFormatter formatter,
+ required AmountUnit unit,
+ required CryptoCurrency coin,
}) {
final decimalSeparator =
Util.getSymbolsFor(locale: locale)?.DECIMAL_SEP ?? ".";
if (text.isEmpty || text == decimalSeparator) {
return (isValid: true, amount: null);
}
- final amount = formatter.tryParseEditable(text);
+ final amount = AmountParser.tryParseEditable(
+ text,
+ locale: locale,
+ unit: unit,
+ coin: coin,
+ );
return (isValid: amount != null, amount: amount);
}
@@ -653,7 +661,8 @@ class _TransactionSearchViewState
final parsedAmount = parseTransactionFilterAmountInput(
text: _amountTextEditingController.text,
locale: locale,
- formatter: ref.read(pAmountFormatter(widget.coin)),
+ unit: ref.read(pAmountUnit(widget.coin)),
+ coin: widget.coin,
);
if (!parsedAmount.isValid) {
return;
### lib/pages_desktop_specific/address_book_view/desktop_address_book.dart
@@ -13,8 +13,6 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import '../../app_config.dart';
-import '../../models/isar/models/blockchain_data/address.dart';
-import '../../models/isar/models/contact_entry.dart';
import '../../pages/address_book_views/subviews/add_address_book_entry_view.dart';
import '../../pages/address_book_views/subviews/address_book_filter_view.dart';
import '../../providers/global/address_book_service_provider.dart';
@@ -26,7 +24,6 @@ import '../../utilities/constants.dart';
import '../../utilities/text_styles.dart';
import '../../utilities/util.dart';
import '../../wallets/crypto_currency/crypto_currency.dart';
-import '../../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart';
import '../../widgets/address_book_card.dart';
import '../../widgets/desktop/desktop_app_bar.dart';
import '../../widgets/desktop/desktop_dialog.dart';
@@ -119,35 +116,9 @@ class _DesktopAddressBook extends ConsumerState<DesktopAddressBook> {
// }
WidgetsBinding.instance.addPostFrameCallback((_) async {
- final List<ContactAddressEntry> addresses = [];
- final wallets = ref.read(pWallets).wallets;
- for (final wallet in wallets) {
- final String addressString;
- if (wallet is SparkInterface &&
- !(wallet.isViewOnly && wallet.viewOnlyType != .spark)) {
- Address? address = await wallet.getCurrentReceivingSparkAddress();
- address ??= await wallet.generateNextSparkAddress(saveToDB: true);
- addressString = address.value;
- } else {
- final address = await wallet.getCurrentReceivingAddress();
- addressString = address?.value ?? wallet.info.cachedReceivingAddress;
- }
-
- addresses.add(
- ContactAddressEntry()
- ..coinName = wallet.info.coin.identifier
- ..address = addressString
- ..label = "Current Receiving"
- ..other = wallet.info.name,
- );
- }
- final self = ContactEntry(
- name: "My ${AppConfig.prefix}",
- addresses: addresses,
- isFavorite: true,
- customId: "default",
- );
- await ref.read(addressBookServiceProvider).editContact(self);
+ await ref
+ .read(addressBookServiceProvider)
+ .updateMyStackContact(ref.read(pWallets).wallets);
});
super.initState();
@@ -286,9 +257,9 @@ class _DesktopAddressBook extends ConsumerState<DesktopAddressBook> {
buttonHeight: ButtonHeight.l,
icon: SvgPicture.asset(
Assets.svg.filter,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.buttonTextSecondary,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .buttonTextSecondary,
),
onPressed: selectCryptocurrency,
),
@@ -299,9 +270,9 @@ class _DesktopAddressBook extends ConsumerState<DesktopAddressBook> {
buttonHeight: ButtonHeight.l,
icon: SvgPicture.asset(
Assets.svg.circlePlus,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.buttonTextPrimary,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .buttonTextPrimary,
),
onPressed: newContact,
),
@@ -343,9 +314,9 @@ class _DesktopAddressBook extends ConsumerState<DesktopAddressBook> {
children: [
if (i > 0)
Container(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.background,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
height: 1,
),
Padding(
@@ -414,9 +385,9 @@ class _DesktopAddressBook extends ConsumerState<DesktopAddressBook> {
children: [
if (i > 0)
Container(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.background,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
height: 1,
),
Padding(
### lib/pages_desktop_specific/desktop_home_view.dart
@@ -27,6 +27,7 @@ import '../utilities/enums/backup_frequency_type.dart';
import '../utilities/idle_monitor.dart';
import '../utilities/prefs.dart';
import '../widgets/background.dart';
+import '../widgets/onetime_popups/native_library_warning_dialog.dart';
import 'address_book_view/desktop_address_book.dart';
import 'desktop_buy/desktop_buy_view.dart';
import 'desktop_exchange/desktop_exchange_view.dart';
@@ -67,8 +68,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 +89,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,18 +105,22 @@ class _DesktopHomeViewState extends ConsumerState<DesktopHomeView> {
);
_idleMonitor?.attach();
- ref.read(prefsChangeNotifierProvider).addListener(_prefsTimeoutListener);
+ _prefs.addListener(_prefsTimeoutListener);
// WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
// showOneTimeTorHasBeenAddedDialogIfRequired(context);
// });
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ unawaited(showNativeLibraryWarningIfRequired(context));
+ });
+
super.initState();
}
@override
dispose() {
- ref.read(prefsChangeNotifierProvider).removeListener(_prefsTimeoutListener);
+ _prefs.removeListener(_prefsTimeoutListener);
_idleMonitor?.detach();
super.dispose();
}
@@ -171,9 +178,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/address_book_address_chooser/address_book_address_chooser.dart
@@ -14,6 +14,7 @@ import 'package:flutter_svg/flutter_svg.dart';
import '../../../../../models/isar/models/contact_entry.dart';
import '../../../../../providers/global/address_book_service_provider.dart';
+import '../../../../../providers/providers.dart';
import '../../../../../themes/stack_colors.dart';
import '../../../../../utilities/assets.dart';
import '../../../../../utilities/constants.dart';
@@ -25,20 +26,18 @@ import '../../../../../widgets/stack_text_field.dart';
import '../../../../../widgets/textfield_icon_button.dart';
import 'sub_widgets/contact_list_item.dart';
-class AddressBookAddressChooser extends StatefulWidget {
- const AddressBookAddressChooser({
- super.key,
- this.coin,
- });
+class AddressBookAddressChooser extends ConsumerStatefulWidget {
+ const AddressBookAddressChooser({super.key, this.coin});
final CryptoCurrency? coin;
@override
- State<AddressBookAddressChooser> createState() =>
+ ConsumerState<AddressBookAddressChooser> createState() =>
_AddressBookAddressChooserState();
}
-class _AddressBookAddressChooserState extends State<AddressBookAddressChooser> {
+class _AddressBookAddressChooserState
+ extends ConsumerState<AddressBookAddressChooser> {
late final bool isDesktop;
late final TextEditingController _searchController;
late final FocusNode searchFieldFocusNode;
@@ -109,6 +108,16 @@ class _AddressBookAddressChooserState extends State<AddressBookAddressChooser> {
isDesktop = Util.isDesktop;
searchFieldFocusNode = FocusNode();
_searchController = TextEditingController();
+
+ // the "My Stack" contact is otherwise only created by the address book
+ // view, so make sure it exists and is current before choosing from it
+ WidgetsBinding.instance.addPostFrameCallback((_) async {
+ if (!mounted) return;
+ await ref
+ .read(addressBookServiceProvider)
+ .updateMyStackContact(ref.read(pWallets).wallets);
+ });
+
super.initState();
}
@@ -125,9 +134,7 @@ class _AddressBookAddressChooserState extends State<AddressBookAddressChooser> {
children: [
// search field
Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 32,
- ),
+ padding: const EdgeInsets.symmetric(horizontal: 32),
child: ClipRRect(
borderRadius: BorderRadius.circular(
Constants.size.circularBorderRadius,
@@ -150,71 +157,68 @@ class _AddressBookAddressChooserState extends State<AddressBookAddressChooser> {
height: 1.8,
)
: STextStyles.field(context),
- decoration: standardInputDecoration(
- "Search",
- searchFieldFocusNode,
- context,
- desktopMed: isDesktop,
- ).copyWith(
- prefixIcon: Padding(
- padding: EdgeInsets.symmetric(
- horizontal: isDesktop ? 12 : 10,
- vertical: isDesktop ? 18 : 16,
- ),
- child: SvgPicture.asset(
- Assets.svg.search,
- width: isDesktop ? 20 : 16,
- height: isDesktop ? 20 : 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 = "";
- _searchTerm = "";
- });
- },
+ decoration:
+ standardInputDecoration(
+ "Search",
+ searchFieldFocusNode,
+ context,
+ desktopMed: isDesktop,
+ ).copyWith(
+ prefixIcon: Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: isDesktop ? 12 : 10,
+ vertical: isDesktop ? 18 : 16,
+ ),
+ child: SvgPicture.asset(
+ Assets.svg.search,
+ width: isDesktop ? 20 : 16,
+ height: isDesktop ? 20 : 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 = "";
+ _searchTerm = "";
+ });
+ },
+ ),
+ ],
),
- ],
- ),
- ),
- )
- : null,
- ),
+ ),
+ )
+ : null,
+ ),
),
),
),
- const SizedBox(
- height: 16,
- ),
+ const SizedBox(height: 16),
Expanded(
child: Padding(
- padding: const EdgeInsets.only(
- left: 32,
- right: 32,
- bottom: 32,
- ),
+ padding: const EdgeInsets.only(left: 32, right: 32, bottom: 32),
child: Consumer(
builder: (context, ref, _) {
List<ContactEntry> contacts = ref
.watch(
- addressBookServiceProvider
- .select((value) => value.contacts),
+ addressBookServiceProvider.select(
+ (value) => value.contacts,
+ ),
)
.toList();
contacts = filter(contacts, _searchTerm);
final favorites = pullOutFavorites(contacts);
- final totalLength = favorites.length +
+ final totalLength =
+ favorites.length +
contacts.length +
2; // +2 for "fav" and "all" headers
@@ -223,23 +227,20 @@ class _AddressBookAddressChooserState extends State<AddressBookAddressChooser> {
shrinkWrap: true,
itemCount: totalLength,
separatorBuilder: (context, index) {
- return const SizedBox(
- height: 10,
- );
+ return const SizedBox(height: 10);
},
itemBuilder: (context, index) {
if (index == 0) {
return Padding(
key: const Key(
"addressBookCAddressChooserFavoritesHeaderItemKey",
),
- padding: const EdgeInsets.only(
- bottom: 10,
- ),
+ padding: const EdgeInsets.only(bottom: 10),
child: Text(
"Favorites",
- style:
- STextStyles.desktopTextExtraExtraSmall(context),
+ style: STextStyles.desktopTextExtraExtraSmall(
+ context,
+ ),
),
);
} else if (index < favorites.length + 1) {
@@ -254,13 +255,12 @@ class _AddressBookAddressChooserState extends State<AddressBookAddressChooser> {
key: const Key(
"addressBookCAddressChooserAllContactsHeaderItemKey",
),
- padding: const EdgeInsets.symmetric(
- vertical: 10,
- ),
+ padding: const EdgeInsets.symmetric(vertical: 10),
child: Text(
"All contacts",
- style:
- STextStyles.desktopTextExtraExtraSmall(context),
+ style: STextStyles.desktopTextExtraExtraSmall(
+ context,
+ ),
),
);
} else {
### lib/pages_desktop_specific/my_stack_view/wallet_view/sub_widgets/desktop_send.dart
@@ -45,6 +45,7 @@ import '../../../../utilities/address_utils.dart';
import '../../../../utilities/amount/amount.dart';
import '../../../../utilities/amount/amount_field_relocalization.dart';
import '../../../../utilities/amount/amount_formatter.dart';
+import '../../../../utilities/amount/amount_parser.dart';
import '../../../../utilities/amount/amount_input_formatter.dart';
import '../../../../utilities/amount/amount_unit.dart';
import '../../../../utilities/assets.dart';
@@ -996,12 +997,26 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
bool _xelisSendAll = false;
+ // 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 {
- _xelisSendAll = false;
if (!_cryptoAmountChangeLock) {
- final cryptoAmount = ref
- .read(pAmountFormatter(coin))
- .tryParseEditable(cryptoAmountController.text);
+ _xelisSendAll = false;
+ final cryptoAmount = AmountParser.tryParseEditable(
+ cryptoAmountController.text,
+ locale: ref.read(localeServiceChangeNotifierProvider).locale,
+ unit: ref.read(pAmountUnit(coin)),
+ coin: coin,
+ );
final Amount? amount;
if (cryptoAmount != null) {
amount = cryptoAmount;
@@ -1438,6 +1453,7 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
}
void fiatTextFieldOnChanged(String baseAmountString) {
+ _xelisSendAll = false;
final baseAmount = Amount.tryParseFiatString(
baseAmountString,
locale: ref.read(localeServiceChangeNotifierProvider).locale,
@@ -1471,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 = "";
@@ -1648,15 +1664,17 @@ class _DesktopSendState extends ConsumerState<DesktopSend> {
listenForAmountRelocalization(
ref.listen,
controllers: [cryptoAmountController, baseAmountController],
- onRelocalized: _cryptoAmountChanged,
+ updateControllers: _updateAmountDisplay,
);
// Keep the amount, rather than the number typed, when the unit changes.
ref.listen<AmountFormatter>(pAmountFormatter(coin), (previous, next) {
final amount = ref.read(pSendAmount);
if (previous?.unit != next.unit && amount != null) {
// Only the display changes, so keep the send all intent.
final xelisSendAll = _xelisSendAll;
- cryptoAmountController.text = next.formatEditable(amount);
+ _updateAmountDisplay(() {
+ cryptoAmountController.text = next.formatEditable(amount);
+ });
_xelisSendAll = xelisSendAll;
}
});
### 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
@@ -29,6 +29,7 @@ import '../../../../utilities/address_utils.dart';
import '../../../../utilities/amount/amount.dart';
import '../../../../utilities/amount/amount_field_relocalization.dart';
import '../../../../utilities/amount/amount_formatter.dart';
+import '../../../../utilities/amount/amount_parser.dart';
import '../../../../utilities/amount/amount_input_formatter.dart';
import '../../../../utilities/amount/amount_unit.dart';
import '../../../../utilities/clipboard_interface.dart';
@@ -373,14 +374,26 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
amount ?? Amount.zeroWith(fractionDigits: tokenDecimals);
}
+ // 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 cryptoAmount = ref
- .read(pAmountFormatter(coin))
- .tryParseEditable(
- cryptoAmountController.text,
- tokenContract: ref.read(pCurrentTokenWallet)!.tokenContract,
- );
+ final cryptoAmount = AmountParser.tryParseEditable(
+ cryptoAmountController.text,
+ locale: ref.read(localeServiceChangeNotifierProvider).locale,
+ unit: ref.read(pAmountUnit(coin)),
+ coin: coin,
+ tokenContract: ref.read(pCurrentTokenWallet)!.tokenContract,
+ );
if (cryptoAmount != null) {
_amountToSend = cryptoAmount;
@@ -586,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 = "";
@@ -700,8 +713,15 @@ class _DesktopTokenSendState extends ConsumerState<DesktopTokenSend> {
listenForAmountRelocalization(
ref.listen,
controllers: [cryptoAmountController, baseAmountController],
- onRelocalized: _cryptoAmountChanged,
+ updateControllers: _updateAmountDisplay,
);
+ ref.listen<AmountFormatter>(pAmountFormatter(coin), (previous, next) {
+ if (previous?.unit != next.unit && _amountToSend != null) {
+ _updateAmountDisplay(() {
+ cryptoAmountController.text = next.formatEditable(_amountToSend!);
+ });
+ }
+ });
final isCustomFee = ref.watch(feeRateTypeDesktopStateProvider).isCustom;
// ethFee is checked in the ValueListenableBuilder around the preview
// button so fee keystrokes don't rebuild this whole view.
### 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/pages_desktop_specific/password/forgotten_passphrase_restore_from_swb.dart
@@ -37,6 +37,7 @@ import '../../widgets/desktop/desktop_dialog.dart';
import '../../widgets/desktop/desktop_scaffold.dart';
import '../../widgets/desktop/primary_button.dart';
import '../../widgets/loading_indicator.dart';
+import '../../widgets/onetime_popups/native_library_warning_dialog.dart';
import '../../widgets/stack_text_field.dart';
import 'create_password_view.dart';
@@ -95,9 +96,9 @@ class _ForgottenPassphraseRestoreFromSWBState
child: Text(
"Decrypting ${AppConfig.prefix} backup file",
style: STextStyles.pageTitleH2(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textWhite,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textWhite,
),
),
),
@@ -188,6 +189,13 @@ class _ForgottenPassphraseRestoreFromSWBState
passwordFocusNode = FocusNode();
+ // On a fresh install this screen comes before any home view, and a
+ // restore with a library missing would fail its cryptonote wallets
+ // with no explanation.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ unawaited(showNativeLibraryWarningIfRequired(context));
+ });
+
super.initState();
}
@@ -214,9 +222,8 @@ class _ForgottenPassphraseRestoreFromSWBState
ref.refresh(storageCryptoHandlerProvider);
await DB.instance.init();
if (mounted) {
- Navigator.of(
- context,
- ).popUntil(ModalRoute.withName(CreatePasswordView.routeName));
+ Navigator.of(context)
+ .popUntil(ModalRoute.withName(CreatePasswordView.routeName));
Navigator.of(context).pop();
}
},
@@ -241,9 +248,9 @@ class _ForgottenPassphraseRestoreFromSWBState
"Use your ${AppConfig.prefix} backup file to restore your wallets, address book, and wallet preferences.",
textAlign: TextAlign.center,
style: STextStyles.desktopTextSmall(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textSubtitle1,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle1,
),
),
const SizedBox(height: 40),
@@ -283,9 +290,9 @@ class _ForgottenPassphraseRestoreFromSWBState
const SizedBox(width: 24),
SvgPicture.asset(
Assets.svg.folder,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textDark3,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textDark3,
width: 24,
height: 24,
),
@@ -323,9 +330,8 @@ class _ForgottenPassphraseRestoreFromSWBState
key: const Key("restoreFromFilePasswordFieldKey"),
focusNode: passwordFocusNode,
controller: passwordController,
- style: STextStyles.desktopTextMedium(
- context,
- ).copyWith(height: 2),
+ style: STextStyles.desktopTextMedium(context)
+ .copyWith(height: 2),
obscureText: hidePassword,
enableSuggestions: false,
autocorrect: false,
@@ -356,9 +362,9 @@ class _ForgottenPassphraseRestoreFromSWBState
hidePassword
? Assets.svg.eye
: Assets.svg.eyeSlash,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textDark3,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textDark3,
width: 24,
height: 24,
),
### 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/address_book_service.dart
@@ -10,10 +10,19 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
+import 'package:mutex/mutex.dart';
+
+import '../app_config.dart';
import '../db/isar/main_db.dart';
+import '../models/isar/models/blockchain_data/address.dart';
import '../models/isar/models/contact_entry.dart';
+import '../utilities/logger.dart';
+import '../wallets/wallet/wallet.dart';
+import '../wallets/wallet/wallet_mixin_interfaces/spark_interface.dart';
class AddressBookService extends ChangeNotifier {
+ final Mutex _myStackContactLock = Mutex();
+
ContactEntry getContactById(String id) {
final ContactEntry? contactEntry = MainDB.instance.getContactEntry(id: id);
if (contactEntry == null) {
@@ -78,6 +87,65 @@ class AddressBookService extends ChangeNotifier {
return true;
}
+ /// Rebuilds the "My Stack" contact from the current receiving address of
+ /// each of [wallets].
+ Future<void> updateMyStackContact(Iterable<Wallet> wallets) =>
+ _myStackContactLock.protect(() => _updateMyStackContact(wallets));
+
+ Future<void> _updateMyStackContact(Iterable<Wallet> wallets) async {
+ final List<ContactAddressEntry> addresses = [];
+ for (final wallet in wallets) {
+ final SparkInterface? sparkWallet =
+ wallet is SparkInterface &&
+ !(wallet.isViewOnly && wallet.viewOnlyType != .spark)
+ ? wallet
+ : null;
+ String addressString;
+ try {
+ if (sparkWallet != null) {
+ Address? address = await sparkWallet
+ .getCurrentReceivingSparkAddress();
+ address ??= await sparkWallet.generateNextSparkAddress(
+ saveToDB: true,
+ );
+ addressString = address.value;
+ } else {
+ final address = await wallet.getCurrentReceivingAddress();
+ addressString = address?.value ?? wallet.info.cachedReceivingAddress;
+ }
+ } catch (e, s) {
+ // A Spark wallet's cached address is its transparent one, so leave it
+ // out rather than offer a public address. Other wallets fall back to
+ // the cached address so one failure doesn't drop them or stop the rest.
+ Logging.instance.e(
+ "Failed to get a wallet address for My Stack",
+ error: e,
+ stackTrace: s,
+ );
+ if (sparkWallet != null) continue;
+ addressString = wallet.info.cachedReceivingAddress;
+ }
+ if (addressString.isEmpty) continue;
+
+ addresses.add(
+ ContactAddressEntry()
+ ..coinName = wallet.info.coin.identifier
+ ..address = addressString
+ ..label = "Current Receiving"
+ ..other = wallet.info.name,
+ );
+ }
+
+ await editContact(
+ ContactEntry(
+ name: "My ${AppConfig.prefix}",
+ addresses: addresses,
+ isFavorite: true,
+ customId: "default",
+ ),
+ );
+ }
+
/// Remove address book contact entry from db if it exists
Future<void> removeContact(String id) async {
await MainDB.instance.deleteContactEntry(id: id);
### 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/shopinbit/src/client.dart
@@ -309,6 +309,31 @@ class ShopInBitClient {
}
}
+ /// URL and auth headers for fetching an attachment via
+ /// `/attachment-proxy/<path>` from an HTTP client that can set headers.
+ Future<ApiResponse<AttachmentRequest>> getAttachmentRequest(
+ String attachmentPath, {
+ String? customerKey,
+ }) async {
+ try {
+ final token = await _tokenManager.getValidToken();
+ final resolved = _resolvePath('/attachment-proxy/$attachmentPath');
+ return ApiResponse(
+ value: (
+ uri: Uri.parse('$baseUrl$resolved'),
+ headers: {
+ 'Authorization': 'Bearer $token',
+ if (customerKey != null) 'External-Customer-Key': customerKey,
+ },
+ ),
+ );
+ } on ApiException catch (e) {
+ return ApiResponse(exception: e);
+ } catch (e) {
+ return ApiResponse(exception: ApiException.network(e));
+ }
+ }
+
/// Download an attachment from `/attachment-proxy/<path>`.
Future<ApiResponse<Response>> getAttachment(
String attachmentPath, {
@@ -1055,6 +1080,8 @@ const kAllowedAttachmentExtensions = [
typedef ResolvedAttachment = ({String mimeType, AttachmentCategory category});
+typedef AttachmentRequest = ({Uri uri, Map<String, String> headers});
+
/// Path + content type, materialized into multipart bytes inside
/// [_multipartRequest]: validation stays separate from encoding, and the
/// encoded bytes can be resent on 401 without re-reading files from disk.
@@ -1075,8 +1102,7 @@ ResolvedAttachment? resolveAttachmentType(String fileName) {
"gif" => (mimeType: "image/gif", category: .image),
"pdf" => (mimeType: "application/pdf", category: .document),
"docx" => (
- mimeType:
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
category: .document,
),
"xlsx" => (
### 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/amount_field_relocalization.dart
@@ -57,23 +57,36 @@ void relocalizeAmountController(
/// parsers, then invokes [onRelocalized] so the caller can re-run any
/// parsing/validation that cached state from the old text.
///
+/// [updateControllers] can wrap the assignments to suppress input listeners.
+/// Use it when the caller stores a canonical amount: a display change must not
+/// be interpreted as another edit of that amount.
+///
/// Must be called from a widget's build method with `ref.listen`.
void listenForAmountRelocalization(
ProviderListen<String> listen, {
required List<TextEditingController> controllers,
VoidCallback? onRelocalized,
+ void Function(VoidCallback update)? updateControllers,
}) {
listen(localeServiceChangeNotifierProvider.select((value) => value.locale), (
previous,
next,
) {
if (previous == null || previous == next) return;
- for (final controller in controllers) {
- relocalizeAmountController(
- controller,
- sourceLocale: previous,
- targetLocale: next,
- );
+ void update() {
+ for (final controller in controllers) {
+ relocalizeAmountController(
+ controller,
+ sourceLocale: previous,
+ targetLocale: next,
+ );
+ }
+ }
+
+ if (updateControllers == null) {
+ update();
+ } else {
+ updateControllers(update);
}
onRelocalized?.call();
});
### lib/utilities/amount/amount_formatter.dart
@@ -69,13 +69,4 @@ class AmountFormatter {
String formatEditable(Amount amount) {
return unit.formatEditable(amount: amount, locale: locale);
}
-
- Amount? tryParseEditable(String string, {Contract? tokenContract}) {
- return unit.tryParse(
- string,
- locale: locale,
- coin: coin,
- tokenContract: tokenContract,
- );
- }
}
### lib/utilities/amount/amount_parser.dart
@@ -0,0 +1,24 @@
+import '../../models/isar/models/contract.dart';
+import '../../wallets/crypto_currency/crypto_currency.dart';
+import 'amount.dart';
+import 'amount_unit.dart';
+
+/// Parses editable text using the locale and unit associated with that text.
+///
+/// Parsing deliberately has no provider or cached formatting preferences.
+/// Display updates must preserve the canonical amount instead of parsing their
+/// own output. Only input changes should call this API.
+abstract final class AmountParser {
+ static Amount? tryParseEditable(
+ String text, {
+ required String locale,
+ required AmountUnit unit,
+ required CryptoCurrency coin,
+ Contract? tokenContract,
+ }) => unit.tryParse(
+ text,
+ locale: locale,
+ coin: coin,
+ tokenContract: tokenContract,
+ );
+}
### 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/utilities/camera_preview_frame.dart
@@ -0,0 +1,94 @@
+import 'dart:typed_data';
+
+import 'package:image/image.dart' as img;
+
+/// Why a frame captured from a camera preview can't be scanned.
+enum BlankPreviewFrame {
+ /// Nothing was drawn: the preview texture has no camera frame yet, or the
+ /// camera has been closed.
+ transparent,
+
+ /// Every visible pixel is black or close to it, as with a closed privacy
+ /// shutter.
+ black,
+}
+
+// Sensor noise keeps a covered webcam from being exactly 0.
+const _blackLevel = 16;
+
+/// Returns why [rgba] can't be scanned, or null if it has picture content.
+///
+/// [rgba] is tightly packed 8-bit RGBA, as from
+/// `ui.Image.toByteData(format: ui.ImageByteFormat.rawRgba)`.
+BlankPreviewFrame? blankPreviewFrame(Uint8List rgba) {
+ var anyVisible = false;
+ for (var i = 0; i + 3 < rgba.length; i += 4) {
+ if (rgba[i + 3] == 0) continue;
+ anyVisible = true;
+ if (rgba[i] > _blackLevel ||
+ rgba[i + 1] > _blackLevel ||
+ rgba[i + 2] > _blackLevel) {
+ return null;
+ }
+ }
+ return anyVisible ? BlankPreviewFrame.black : BlankPreviewFrame.transparent;
+}
+
+/// Builds an image from an RGBA capture of a horizontally mirrored camera
+/// preview, flipped back so a QR code in it reads the right way round.
+///
+/// [rgba] is tightly packed 8-bit RGBA of [width] x [height] pixels.
+img.Image imageFromMirroredPreviewRgba(
+ Uint8List rgba, {
+ required int width,
+ required int height,
+}) {
+ if (width <= 0 || height <= 0) {
+ throw ArgumentError("Invalid frame size ${width}x$height");
+ }
+ final byteLength = width * height * 4;
+ if (rgba.length < byteLength) {
+ throw ArgumentError.value(
+ rgba.length,
+ "rgba",
+ "Too short for a ${width}x$height RGBA frame",
+ );
+ }
+
+ // sublist copies into a fresh buffer, so the 32-bit view is aligned even
+ // if the caller's bytes start at an odd offset.
+ final src = rgba.sublist(0, byteLength).buffer.asUint32List();
+ final flipped = Uint32List(width * height);
+ for (var y = 0; y < height; y++) {
+ final row = y * width;
+ final last = row + width - 1;
+ for (var x = 0; x < width; x++) {
+ flipped[row + x] = src[last - x];
+ }
+ }
+
+ return img.Image.fromBytes(
+ width: width,
+ height: height,
+ bytes: flipped.buffer,
+ numChannels: 4,
+ order: img.ChannelOrder.rgba,
+ );
+}
+
+/// A 64-bit FNV-1a hash of [rgba], for telling a new camera frame from a
+/// repeat of the last one.
+///
+/// Frames from a live sensor never repeat byte for byte, so two captures
+/// with the same fingerprint mean the preview has stopped updating. This is
+/// a full pass over the buffer; an indexed loop keeps it to a few
+/// milliseconds for a 1280 px frame.
+int previewFrameFingerprint(Uint8List rgba) {
+ var hash = 0xcbf29ce484222325;
+ final length = rgba.length;
+ for (var i = 0; i < length; i++) {
+ hash ^= rgba[i];
+ hash *= 0x100000001b3;
+ }
+ return hash;
+}
### lib/utilities/constants.dart
@@ -40,7 +40,7 @@ abstract class Constants {
// Enable Logger.print statements
static const bool disableLogger = false;
- static const int currentDataVersion = 17;
+ static const int currentDataVersion = 18;
static const int rescanV1 = 1;
### lib/utilities/native_library_check.dart
@@ -0,0 +1,263 @@
+import 'dart:ffi';
+import 'dart:io';
+
+import 'package:path/path.dart' as p;
+
+import '../app_config.dart';
+import '../wallets/crypto_currency/crypto_currency.dart';
+import 'logger.dart';
+
+enum NativeLibraryProblem { missing, blockedByAntivirus, loadFailed }
+
+typedef NativeLibraryCheckResult = ({
+ NativeLibraryProblem problem,
+ String path,
+ String error,
+});
+
+/// One library that failed the startup check.
+typedef NativeLibraryFailure = ({
+ String displayName,
+ NativeLibraryCheckResult result,
+});
+
+/// A native library the desktop builds bundle and open through dart:ffi.
+class NativeLibrary {
+ const NativeLibrary({
+ required this.displayName,
+ required this.windows,
+ required this.linux,
+ required this.macos,
+ this.isBundled = _always,
+ });
+
+ /// What stops working without it, worded to start a sentence: "Monero
+ /// wallets".
+ final String displayName;
+
+ /// The name each loader passes to DynamicLibrary.open on that platform.
+ final String windows;
+ final String linux;
+ final String macos;
+
+ /// Whether this build ships the library. Whitelabel builds leave coins out,
+ /// and their libraries with them.
+ final bool Function() isBundled;
+
+ String? fileName(String os) => switch (os) {
+ "windows" => windows,
+ "linux" => linux,
+ "macos" => macos,
+ _ => null,
+ };
+}
+
+bool _always() => true;
+bool _hasMonero() => AppConfig.coins.whereType<Monero>().isNotEmpty;
+bool _hasWownero() => AppConfig.coins.whereType<Wownero>().isNotEmpty;
+bool _hasSalvium() => AppConfig.coins.whereType<Salvium>().isNotEmpty;
+
+/// coinlib's secp256k1, named as in its secp256k1_io.dart. Every non
+/// cryptonote wallet needs it.
+const secp256k1NativeLibrary = NativeLibrary(
+ displayName: "Most wallets",
+ windows: "secp256k1.dll",
+ linux: "libsecp256k1.so",
+ macos: "secp256k1.framework/secp256k1",
+);
+
+/// Checked at startup in this order. The cryptonote names are the ones
+/// cs_monero, cs_wownero and cs_salvium pass to DynamicLibrary.open; their
+/// getters are private, so a rename there has to be mirrored here.
+const nativeLibraries = [
+ NativeLibrary(
+ displayName: "Monero wallets",
+ windows: "monero_libwallet2_api_c.dll",
+ linux: "monero_libwallet2_api_c.so",
+ macos: "MoneroWallet.framework/MoneroWallet",
+ isBundled: _hasMonero,
+ ),
+ NativeLibrary(
+ displayName: "Wownero wallets",
+ windows: "wownero_libwallet2_api_c.dll",
+ linux: "wownero_libwallet2_api_c.so",
+ macos: "WowneroWallet.framework/WowneroWallet",
+ isBundled: _hasWownero,
+ ),
+ NativeLibrary(
+ displayName: "Salvium wallets",
+ windows: "salvium_libwallet2_api_c.dll",
+ linux: "salvium_libwallet2_api_c.so",
+ macos: "SalviumWallet.framework/SalviumWallet",
+ isBundled: _hasSalvium,
+ ),
+ secp256k1NativeLibrary,
+];
+
+/// Where the app bundles [fileName] on [os], given the running executable.
+String nativeLibraryPath(String fileName, String os, String executable) {
+ final path = os == "windows" ? p.windows : p.posix;
+ final dir = path.dirname(executable);
+ return switch (os) {
+ "linux" => path.join(dir, "lib", fileName),
+ "macos" => path.normalize(path.join(dir, "..", "Frameworks", fileName)),
+ _ => path.join(dir, fileName),
+ };
+}
+
+/// Loads [fileName] and returns null, or why it failed to load.
+NativeLibraryCheckResult? checkNativeLibrary(
+ String fileName, {
+ required String os,
+ required String executable,
+ void Function(String) open = _open,
+ bool Function(String) exists = _exists,
+}) {
+ try {
+ open(fileName);
+ return null;
+ } catch (e) {
+ final error = e is ArgumentError ? "${e.message}" : "$e";
+ final path = nativeLibraryPath(fileName, os, executable);
+ final NativeLibraryProblem problem;
+ if (!exists(path)) {
+ problem = NativeLibraryProblem.missing;
+ } else if (RegExp(r"error code: 22[56]\b").hasMatch(error)) {
+ // ERROR_VIRUS_INFECTED or ERROR_VIRUS_DELETED
+ problem = NativeLibraryProblem.blockedByAntivirus;
+ } else {
+ problem = NativeLibraryProblem.loadFailed;
+ }
+ return (problem: problem, path: path, error: error);
+ }
+}
+
+void _open(String name) => DynamicLibrary.open(name);
+bool _exists(String path) => File(path).existsSync();
+
+String nativeLibraryErrorMessage(
+ String displayName,
+ NativeLibraryCheckResult result,
+) {
+ const app = AppConfig.appName;
+ final reason = switch (result.problem) {
+ NativeLibraryProblem.missing =>
+ "a required file is missing. Antivirus software may have quarantined "
+ "it. Restore it from quarantine or reinstall $app, then try again.",
+ NativeLibraryProblem.blockedByAntivirus =>
+ "antivirus software blocked a required file. Allow it in your "
+ "antivirus settings or restore it from quarantine, then try again.",
+ NativeLibraryProblem.loadFailed =>
+ "a required library failed to load. Reinstalling $app may fix this.",
+ };
+ return "$displayName can't be used because $reason\n\n"
+ "File: ${result.path}\nError: ${result.error}";
+}
+
+bool _isDesktop(String os) => os == "windows" || os == "linux" || os == "macos";
+
+final _failures = <NativeLibraryFailure>[];
+String? _coinlibError;
+
+/// Starts coinlib's secp256k1 load for main().
+///
+/// coinlib throws synchronously when the file won't open, which would end
+/// main() long before the home screen could say which file is broken. On
+/// desktop the error is kept for [checkNativeLibrariesOnStartup] to report
+/// and the app carries on; wallets that need coinlib fail their own init.
+/// On mobile the library can't go missing on its own, so the error
+/// propagates as it always has. Logging isn't initialised yet, so the check
+/// is what logs it.
+Future<void> loadCoinlibOrRecordFailure(Future<void> Function() load) async {
+ try {
+ await load();
+ } catch (e) {
+ if (!_isDesktop(Platform.operatingSystem)) rethrow;
+ _coinlibError = "$e";
+ }
+}
+
+/// Tries to open every bundled library in [nativeLibraries], in order, and
+/// remembers the ones that fail for the home screen to report once.
+///
+/// Desktop only; elsewhere it does nothing. It runs on the main isolate
+/// before any wallet loads, so it competes with nothing a user is waiting
+/// on, and a wallet's later open of the same file is a cache hit. Never
+/// throws: a broken check is logged and counts as a pass, because the check
+/// must not be the thing that keeps the app from starting.
+void checkNativeLibrariesOnStartup({
+ List<NativeLibrary> libraries = nativeLibraries,
+ String? os,
+ String? executable,
+ void Function(String) open = _open,
+ bool Function(String) exists = _exists,
+}) {
+ final coinlibError = _coinlibError;
+ _coinlibError = null;
+ try {
+ os ??= Platform.operatingSystem;
+ if (!_isDesktop(os)) return;
+ executable ??= Platform.resolvedExecutable;
+ } catch (e, s) {
+ Logging.instance.w(
+ "Native library check did not run",
+ error: e,
+ stackTrace: s,
+ );
+ return;
+ }
+
+ for (final library in libraries) {
+ final fileName = library.fileName(os);
+ if (fileName == null) continue;
+ final isSecp256k1 = identical(library, secp256k1NativeLibrary);
+ NativeLibraryCheckResult? result;
+ try {
+ if (!library.isBundled()) continue;
+ result = checkNativeLibrary(
+ fileName,
+ os: os,
+ executable: executable,
+ open: open,
+ exists: exists,
+ );
+ if (result == null && isSecp256k1 && coinlibError != null) {
+ // The file opens but coinlib still failed, so report what it said.
+ result = (
+ problem: NativeLibraryProblem.loadFailed,
+ path: nativeLibraryPath(fileName, os, executable),
+ error: coinlibError,
+ );
+ }
+ } catch (e, s) {
+ // One entry's trouble must not hide the others. coinlib's own error
+ // is still worth reporting even if the check of its file blew up.
+ Logging.instance.w(
+ "Native library check for ${library.displayName} did not run",
+ error: e,
+ stackTrace: s,
+ );
+ if (isSecp256k1 && coinlibError != null) {
+ result = (
+ problem: NativeLibraryProblem.loadFailed,
+ path: fileName,
+ error: coinlibError,
+ );
+ }
+ }
+ if (result != null) {
+ _failures.add((displayName: library.displayName, result: result));
+ Logging.instance.e(
+ nativeLibraryErrorMessage(library.displayName, result),
+ );
+ }
+ }
+}
+
+/// The failures the startup check found, cleared so the warning shows once
+/// per launch.
+List<NativeLibraryFailure> takeNativeLibraryFailures() {
+ final failures = List<NativeLibraryFailure>.unmodifiable(_failures);
+ _failures.clear();
+ return failures;
+}
### lib/utilities/qr_image_decoder.dart
@@ -0,0 +1,89 @@
+import 'dart:math' as math;
+import 'dart:typed_data';
+
+import 'package:image/image.dart' as img;
+import 'package:zxing2/qrcode.dart';
+
+/// Decodes a QR code from encoded image bytes (PNG, JPEG, or anything else
+/// the image package can read). Returns null if the bytes can't be decoded as
+/// an image or no QR code is found.
+String? decodeQrFromImageBytes(Uint8List bytes) {
+ final img.Image? image;
+ try {
+ image = img.decodeImage(bytes);
+ } catch (_) {
+ return null;
+ }
+ return image == null ? null : decodeQrFromImage(image);
+}
+
+/// Decodes a QR code from [image], whatever its bit depth, channel count or
+/// palette. Returns null if no QR code is found.
+///
+/// If [maxDimension] is set, larger images are scaled down to fit it first.
+/// Some webcams hand back full sensor-size photos (3264x2448 from a USB
+/// webcam on Windows), which took 2-3 s per frame to scan on an older laptop.
+String? decodeQrFromImage(img.Image image, {int? maxDimension}) {
+ if (maxDimension != null &&
+ math.max(image.width, image.height) > maxDimension) {
+ image = image.width >= image.height
+ ? img.copyResize(
+ image,
+ width: maxDimension,
+ interpolation: img.Interpolation.average,
+ )
+ : img.copyResize(
+ image,
+ height: maxDimension,
+ interpolation: img.Interpolation.average,
+ );
+ }
+
+ final LuminanceSource source;
+ try {
+ source = RGBLuminanceSource(image.width, image.height, _argbPixels(image));
+ } catch (_) {
+ return null;
+ }
+
+ // HybridBinarizer thresholds locally and copes with uneven lighting in a
+ // webcam frame far better. Keep the global one as a fallback.
+ for (final Binarizer binarizer in [
+ HybridBinarizer(source),
+ GlobalHistogramBinarizer(source),
+ ]) {
+ try {
+ final result = QRCodeReader().decode(BinaryBitmap(binarizer));
+ if (result.text.isNotEmpty) {
+ return result.text;
+ }
+ } catch (_) {
+ // No QR code found with this binarizer.
+ }
+ }
+ return null;
+}
+
+/// Packs [image] into the 0xAARRGGBB ints RGBLuminanceSource expects.
+///
+/// convert() keeps the source format unless told otherwise, so a 1-bit PNG
+/// (Python qrcode's default) stays bit-packed and a 16-bit one keeps 2 bytes
+/// per channel. Force 8-bit RGBA, which also resolves palettes. Transparent
+/// pixels are composited onto white so a dark-on-transparent code still has
+/// a light background.
+Int32List _argbPixels(img.Image image) {
+ final rgba = image.convert(format: img.Format.uint8, numChannels: 4);
+ final bytes = rgba.getBytes(order: img.ChannelOrder.rgba);
+ final pixels = Int32List(image.width * image.height);
+ for (var i = 0, j = 0; i < pixels.length; i++, j += 4) {
+ final a = bytes[j + 3];
+ int r = bytes[j], g = bytes[j + 1], b = bytes[j + 2];
+ if (a != 255) {
+ r = (r * a + 255 * (255 - a)) ~/ 255;
+ g = (g * a + 255 * (255 - a)) ~/ 255;
+ b = (b * a + 255 * (255 - a)) ~/ 255;
+ }
+ pixels[i] = 0xFF000000 | (r << 16) | (g << 8) | b;
+ }
+ return pixels;
+}
### lib/utilities/test_eth_node_connection.dart
@@ -1,12 +1,19 @@
-import 'package:http/http.dart';
-import 'package:web3dart/web3dart.dart' as web3;
+import '../services/tor_service.dart';
+import '../wallets/wallet/impl/ethereum_wallet.dart';
+import 'prefs.dart';
-Future<bool> testEthNodeConnection(String host) async {
- final web3.Web3Client client = web3.Web3Client(host, Client());
+Future<bool> testEthNodeConnection(
+ String host, {
+ required Prefs prefs,
+ required TorService torService,
+}) async {
+ final client = EthereumWallet.createWeb3Client(host, prefs, torService);
try {
await client.getBlockNumber();
return true;
} catch (_) {
return false;
+ } finally {
+ await client.dispose();
}
}
### lib/utilities/test_node_connection.dart
@@ -235,7 +235,11 @@ Future<bool> testNodeConnection({
case Ethereum():
try {
- testPassed = await testEthNodeConnection(formData.host!);
+ testPassed = await testEthNodeConnection(
+ formData.host!,
+ prefs: read(prefsChangeNotifierProvider),
+ torService: read(pTorService),
+ );
} catch (_) {
testPassed = false;
}
### lib/utilities/test_stellar_node_connection.dart
@@ -1,5 +1,7 @@
import 'dart:convert';
+import 'dart:io';
+import 'package:socks5_proxy/socks.dart';
import 'package:stellar_flutter_sdk/stellar_flutter_sdk.dart';
import '../app_config.dart';
@@ -28,7 +30,15 @@ Future<bool> testStellarNodeConnection(String host, int port) async {
if (response.code == 200) {
//Get chain height for sdk
- final StellarSDK stellarSdk = StellarSDK(host);
+ HttpClient? httpClient;
+ if (AppConfig.hasFeature(AppFeature.tor) && Prefs.instance.useTor) {
+ final proxyInfo = TorService.sharedInstance.getProxyInfo();
+ httpClient = HttpClient();
+ SocksTCPClient.assignToHttpClient(httpClient, [
+ ProxySettings(proxyInfo.host, proxyInfo.port),
+ ]);
+ }
+ final StellarSDK stellarSdk = StellarSDK(host, httpClient: httpClient);
final height = await stellarSdk.ledgers
.order(RequestBuilderOrder.DESC)
.limit(1)
### lib/wallets/crypto_currency/coins/ethereum.dart
@@ -47,6 +47,9 @@ class Ethereum extends Bip39Currency {
@override
bool get hasTokenSupport => true;
+ @override
+ bool get torSupport => true;
+
@override
NodeModel defaultNode({required bool isPrimary}) => NodeModel(
host: "https://eth2.stackwallet.com",
### lib/wallets/crypto_currency/coins/fact0rn.dart
@@ -48,7 +48,7 @@ class Fact0rn extends Bip39HDCurrency with ElectrumXCurrencyInterface {
String get ticker => _ticker;
@override
- bool get torSupport => false;
+ bool get torSupport => true;
@override
List<DerivePathType> get supportedDerivationPathTypes => [
@@ -184,7 +184,7 @@ class Fact0rn extends Bip39HDCurrency with ElectrumXCurrencyInterface {
coinName: identifier,
isFailover: true,
isDown: false,
- torEnabled: false,
+ torEnabled: true,
clearnetEnabled: true,
isPrimary: isPrimary,
);
### lib/wallets/crypto_currency/intermediate/nano_currency.dart
@@ -18,6 +18,9 @@ abstract class NanoCurrency extends Bip39Currency {
@override
bool get hasBuySupport => false;
+ @override
+ bool get torSupport => true;
+
@override
int get defaultSeedPhraseLength => 24;
### 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/ethereum_wallet.dart
@@ -1,16 +1,21 @@
import 'dart:async';
import 'dart:convert';
+import 'dart:io';
import 'package:decimal/decimal.dart';
import 'package:ethereum_addresses/ethereum_addresses.dart';
import 'package:flutter/foundation.dart';
-import 'package:http/http.dart';
+import 'package:http/http.dart' as http;
+import 'package:http/io_client.dart';
import 'package:isar_community/isar.dart';
+import 'package:socks5_proxy/socks.dart';
import 'package:wallet/wallet.dart' as eth_wallet;
import 'package:web3dart/json_rpc.dart' show RPCError;
import 'package:web3dart/web3dart.dart' as web3;
+import '../../../app_config.dart';
import '../../../dto/ethereum/eth_tx_dto.dart';
+import '../../../exceptions/wallet/node_tor_mismatch_config_exception.dart';
import '../../../models/balance.dart';
import '../../../models/isar/models/blockchain_data/address.dart';
import '../../../models/isar/models/blockchain_data/transaction.dart';
@@ -21,9 +26,12 @@ import '../../../models/paymint/fee_object_model.dart';
import '../../../services/ethereum/ethereum_api.dart';
import '../../../services/event_bus/events/global/updated_in_background_event.dart';
import '../../../services/event_bus/global_event_bus.dart';
+import '../../../services/tor_service.dart';
import '../../../utilities/amount/amount.dart';
import '../../../utilities/eth_commons.dart';
import '../../../utilities/logger.dart';
+import '../../../utilities/prefs.dart';
+import '../../../utilities/tor_plain_net_option_enum.dart';
import '../../crypto_currency/crypto_currency.dart';
import '../../models/tx_data.dart';
import '../intermediate/bip39_wallet.dart';
@@ -85,8 +93,6 @@ Future<List<TransactionV2>> findReplacedPendingEthereumTransactions({
return replacedTransactions;
}
-// Eth can not use tor with web3dart
-
@visibleForTesting
({BigInt maxFeePerGas, BigInt maxPriorityFeePerGas}) resolveEip1559FeeCaps({
required BigInt baseFee,
@@ -144,12 +150,54 @@ class EthereumWallet extends Bip39Wallet with PrivateKeyInterface {
web3.Web3Client getEthClient() {
final node = getCurrentNode();
- // Eth can not use tor with web3dart as Client does not support proxies
- final client = Client();
+ final netOption = TorPlainNetworkOption.fromNodeData(
+ node.torEnabled,
+ node.clearnetEnabled,
+ );
- return web3.Web3Client(node.host, client);
+ if (prefs.useTor) {
+ if (netOption == TorPlainNetworkOption.clear) {
+ throw NodeTorMismatchConfigException(
+ message: "TOR enabled but node set to clearnet only",
+ );
+ }
+ } else {
+ if (netOption == TorPlainNetworkOption.tor) {
+ throw NodeTorMismatchConfigException(
+ message: "TOR off but node set to TOR only",
+ );
+ }
+ }
+
+ return createWeb3Client(node.host, prefs, TorService.sharedInstance);
+ }
+
+ // static helper function for building a web3 client, proxied over tor if
+ // enabled. The returned client refuses to send once the tor preference no
+ // longer matches the transport it was built with; see _TorPreferenceClient.
+ static web3.Web3Client createWeb3Client(
+ String url,
+ Prefs prefs,
+ TorService torService,
+ ) {
+ final httpClient = HttpClient();
+
+ if (_shouldProxy(prefs)) {
+ final proxyInfo = torService.getProxyInfo();
+ SocksTCPClient.assignToHttpClient(httpClient, [
+ ProxySettings(proxyInfo.host, proxyInfo.port),
+ ]);
+ }
+
+ return web3.Web3Client(
+ url,
+ _TorPreferenceClient(IOClient(httpClient), prefs),
+ );
}
+ static bool _shouldProxy(Prefs prefs) =>
+ AppConfig.hasFeature(AppFeature.tor) && prefs.useTor;
+
Amount estimateEthFee(BigInt feeRate, int gasLimit, int decimals) {
final gweiAmount = feeRate.toDecimal() / (Decimal.ten.pow(9).toDecimal());
final fee =
@@ -292,8 +340,8 @@ class EthereumWallet extends Bip39Wallet with PrivateKeyInterface {
@override
Future<bool> pingCheck() async {
- final web3.Web3Client client = getEthClient();
try {
+ final client = getEthClient();
await client.getBlockNumber();
return true;
} catch (_) {
@@ -732,3 +780,32 @@ class EthereumWallet extends Bip39Wallet with PrivateKeyInterface {
await super.exit();
}
}
+
+// The proxy is bound to the HttpClient when it is built, but some operations
+// (updateTransactions, the token wallet's tx loop) build one client and reuse
+// it for many RPCs. If the tor preference flips meanwhile, the remaining RPCs
+// would still use the old transport. Fail those instead of sending: the
+// operation errors out and the next one builds a client under the current
+// preference. Nothing is retried here, so a broadcast is never replayed.
+class _TorPreferenceClient extends http.BaseClient {
+ _TorPreferenceClient(this._inner, this._prefs)
+ : _proxied = EthereumWallet._shouldProxy(_prefs);
+
+ final http.Client _inner;
+ final Prefs _prefs;
+ final bool _proxied;
+
+ @override
+ Future<http.StreamedResponse> send(http.BaseRequest request) async {
+ if (EthereumWallet._shouldProxy(_prefs) != _proxied) {
+ throw StateError(
+ 'Tor preference changed since this client was created; '
+ 'the request was not sent',
+ );
+ }
+ return _inner.send(request);
+ }
+
+ @override
+ void close() => _inner.close();
+}
### 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
@@ -394,6 +394,10 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
highestPercentCached = 0;
await csMonero.rescanBlockchain(wallet!);
+ // Reset again once the worker has accepted the rescan. A progress
+ // reading from before it can land in between and pin the guard near
+ // 100%, which hides every later reading until the rescan passes it.
+ highestPercentCached = 0;
await csMonero.startSyncing(wallet!);
unawaited(save());
});
@@ -731,6 +735,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!);
@@ -881,10 +886,6 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
final _syncStatus = syncStatus;
if (_syncStatus != null) {
- if (_syncStatus.progress() == 1 && refreshMutex.isLocked) {
- refreshMutex.release();
- }
-
WalletSyncStatus? status;
xmrAndWowSyncSpecificFunctionThatShouldBeGottenRidOfInTheFuture(true);
@@ -1119,51 +1120,40 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
Logging.instance.t(
"$runtimeType refresh() refreshMutex.acquire() waiting...",
);
- await refreshMutex.acquire();
- Logging.instance.t(
- "$runtimeType refresh() refreshMutex.acquire() acquired!",
- );
-
- Logging.instance.t("$runtimeType refresh() final node = getCurrentNode();");
- final node = getCurrentNode();
-
- Logging.instance.i(
- "$runtimeType refresh() await _torNodeMismatchGuard(node)",
- );
- if (await _torNodeMismatchGuard(node)) {
- throw Exception("TOR – clearnet mismatch");
- }
+ await refreshMutex.protect(() async {
+ Logging.instance.t(
+ "$runtimeType refresh() final node = getCurrentNode();",
+ );
+ final node = getCurrentNode();
- Logging.instance.t(
- "$runtimeType refresh() it csMonero.startSyncing(wallet!);",
- );
- await csMonero.startSyncing(wallet!);
- Logging.instance.t(
- "$runtimeType refresh() _setSyncStatus(lib_monero_compat.StartingSyncStatus());",
- );
- _setSyncStatus(lib_monero_compat.StartingSyncStatus());
+ Logging.instance.i(
+ "$runtimeType refresh() await _torNodeMismatchGuard(node)",
+ );
+ if (await _torNodeMismatchGuard(node)) {
+ throw Exception("TOR – clearnet mismatch");
+ }
- Logging.instance.t("$runtimeType refresh() await updateTransactions();");
- await updateTransactions();
- Logging.instance.t("$runtimeType refresh() await updateBalance();");
- await updateBalance();
+ Logging.instance.t(
+ "$runtimeType refresh() it csMonero.startSyncing(wallet!);",
+ );
+ await csMonero.startSyncing(wallet!);
+ Logging.instance.t(
+ "$runtimeType refresh() _setSyncStatus(lib_monero_compat.StartingSyncStatus());",
+ );
+ _setSyncStatus(lib_monero_compat.StartingSyncStatus());
- Logging.instance.t(
- "$runtimeType refresh() await checkReceivingAddressForTransactions();",
- );
- if (info.otherData[WalletInfoKeys.reuseAddress] != true) {
- await checkReceivingAddressForTransactions();
- }
+ Logging.instance.t("$runtimeType refresh() await updateTransactions();");
+ await updateTransactions();
+ Logging.instance.t("$runtimeType refresh() await updateBalance();");
+ await updateBalance();
- Logging.instance.t(
- "$runtimeType refresh() refreshMutex.isLocked=${refreshMutex.isLocked} pre release.",
- );
- if (refreshMutex.isLocked) {
- refreshMutex.release();
Logging.instance.t(
- "$runtimeType refresh() refreshMutex.isLocked manually released.",
+ "$runtimeType refresh() await checkReceivingAddressForTransactions();",
);
- }
+ if (info.otherData[WalletInfoKeys.reuseAddress] != true) {
+ await checkReceivingAddressForTransactions();
+ }
+ });
Logging.instance.t(
"$runtimeType refresh() wallet != null && await csMonero.isSynced(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!);
@@ -862,10 +863,6 @@ abstract class LibSalviumWallet<T extends CryptonoteCurrency>
final _syncStatus = syncStatus;
if (_syncStatus != null) {
- if (_syncStatus.progress() == 1 && refreshMutex.isLocked) {
- refreshMutex.release();
- }
-
WalletSyncStatus? status;
xmrAndWowSyncSpecificFunctionThatShouldBeGottenRidOfInTheFuture(true);
@@ -1099,21 +1096,17 @@ abstract class LibSalviumWallet<T extends CryptonoteCurrency>
// this acquire should be almost instant due to above check.
// Slight possibility of race but should be irrelevant
- await refreshMutex.acquire();
-
- csSalvium.startSyncing(wallet!);
- _setSyncStatus(StartingSyncStatus());
-
- await updateTransactions();
- await updateBalance();
+ await refreshMutex.protect(() async {
+ csSalvium.startSyncing(wallet!);
+ _setSyncStatus(StartingSyncStatus());
- if (info.otherData[WalletInfoKeys.reuseAddress] != true) {
- await checkReceivingAddressForTransactions();
- }
+ await updateTransactions();
+ await updateBalance();
- if (refreshMutex.isLocked) {
- refreshMutex.release();
- }
+ if (info.otherData[WalletInfoKeys.reuseAddress] != true) {
+ await checkReceivingAddressForTransactions();
+ }
+ });
final synced = wallet != null && await csSalvium.isSynced(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!);
@@ -898,10 +899,6 @@ abstract class LibWowneroWallet<T extends CryptonoteCurrency>
final _syncStatus = syncStatus;
if (_syncStatus != null) {
- if (_syncStatus.progress() == 1 && refreshMutex.isLocked) {
- refreshMutex.release();
- }
-
WalletSyncStatus? status;
xmrAndWowSyncSpecificFunctionThatShouldBeGottenRidOfInTheFuture(true);
@@ -1136,21 +1133,17 @@ abstract class LibWowneroWallet<T extends CryptonoteCurrency>
// this acquire should be almost instant due to above check.
// Slight possibility of race but should be irrelevant
- await refreshMutex.acquire();
-
- csWownero.startSyncing(wallet!);
- _setSyncStatus(lib_monero_compat.StartingSyncStatus());
-
- await updateTransactions();
- await updateBalance();
+ await refreshMutex.protect(() async {
+ csWownero.startSyncing(wallet!);
+ _setSyncStatus(lib_monero_compat.StartingSyncStatus());
- if (info.otherData[WalletInfoKeys.reuseAddress] != true) {
- await checkReceivingAddressForTransactions();
- }
+ await updateTransactions();
+ await updateBalance();
- if (refreshMutex.isLocked) {
- refreshMutex.release();
- }
+ if (info.otherData[WalletInfoKeys.reuseAddress] != true) {
+ await checkReceivingAddressForTransactions();
+ }
+ });
final synced = wallet != null && await csWownero.isSynced(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(
### lib/widgets/desktop/qr_code_scanner_dialog.dart
@@ -1,21 +1,26 @@
import 'dart:async';
-import 'dart:convert';
import 'dart:io';
+import 'dart:math';
+import 'dart:typed_data';
+import 'dart:ui' as ui;
import 'package:camera_linux/camera_linux.dart';
-import 'package:camera_macos/camera_macos_arguments.dart';
+import 'package:camera_macos/camera_macos_arguments.dart' hide CameraImageData;
import 'package:camera_macos/camera_macos_device.dart';
import 'package:camera_macos/camera_macos_platform_interface.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:camera_windows/camera_windows.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
import 'package:image/image.dart' as img;
-import 'package:zxing2/qrcode.dart';
import '../../notifications/show_flush_bar.dart';
+import '../../themes/stack_colors.dart';
import '../../utilities/assets.dart';
+import '../../utilities/camera_preview_frame.dart';
import '../../utilities/logger.dart';
+import '../../utilities/qr_image_decoder.dart';
import '../../utilities/text_styles.dart';
import 'desktop_dialog.dart';
import 'desktop_dialog_close_button.dart';
@@ -30,16 +35,44 @@ class QrCodeScannerDialog extends StatefulWidget {
}
class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
- final CameraLinux? _cameraLinuxPlugin =
- Platform.isLinux ? CameraLinux() : null;
- final CameraWindows? _cameraWindowsPlugin =
- Platform.isWindows ? CameraWindows() : null;
+ // Created in _initializeCamera. camera_linux implements the camera platform
+ // interface; its image stream delivers JPEG frames and the scan loop takes
+ // the newest one.
+ CameraLinux? _cameraLinuxPlugin;
+ StreamSubscription<CameraImageData>? _linuxFrameSub;
+ StreamSubscription<CameraErrorEvent>? _linuxErrorSub;
+ Uint8List? _latestLinuxFrame;
+ final CameraWindows? _cameraWindowsPlugin = Platform.isWindows
+ ? CameraWindows()
+ : null;
bool _isCameraOpen = false;
Image? _image;
bool _isScanning = false;
int _cameraId = -1;
String? _macOSDeviceId;
- final int _imageDelayInMs = Platform.isLinux ? 500 : 250;
+ final int _imageDelayInMs = 250;
+ int _consecutiveFailures = 0;
+ // Time since the last usable frame, to notice a camera that opened but
+ // stopped (or never started) returning images.
+ final Stopwatch _sinceLastFrame = Stopwatch();
+ static const _frameTimeout = Duration(seconds: 10);
+ String? _cameraError;
+ String? _initError;
+
+ // On Windows we scan what the preview shows rather than calling
+ // takePicture(), which always saves a JPEG to the user's Pictures folder.
+ final GlobalKey _windowsPreviewKey = GlobalKey();
+ Size? _windowsPreviewSize;
+ bool _loggedBlankWindowsFrame = false;
+ bool _hasWindowsFrame = false;
+ // camera_windows keeps showing the last frame after the capture engine
+ // fails, and toImage() keeps returning it. The fingerprint tells a new
+ // frame from a repeat; the error event tells us the camera is gone at once.
+ int? _lastWindowsFrameFingerprint;
+ bool _loggedRepeatedWindowsFrame = false;
+ bool _cameraLost = false;
+ StreamSubscription<CameraErrorEvent>? _windowsErrorSub;
+ bool _cameraStopped = false;
@override
void initState() {
@@ -52,37 +85,139 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
_isCameraOpen = true;
});
unawaited(_captureAndScanImage());
+ } else if (mounted) {
+ setState(() {
+ _cameraError =
+ "Unable to open the camera"
+ "${_initError == null ? "" : " ($_initError)"}. You can "
+ "still use \"Select file\" to scan a QR code image.";
+ });
}
});
});
}
Future<bool> _initializeCamera() async {
try {
- if (Platform.isLinux && _cameraLinuxPlugin != null) {
- await _cameraLinuxPlugin.initializeCamera();
- Logging.instance.d("Linux Camera initialized");
- } else if (Platform.isWindows && _cameraWindowsPlugin != null) {
- final List<CameraDescription> cameras =
- await _cameraWindowsPlugin.availableCameras();
+ if (Platform.isLinux) {
+ final plugin = _cameraLinuxPlugin = CameraLinux();
+ final List<CameraDescription> cameras = await plugin.availableCameras();
if (cameras.isEmpty) {
throw CameraException('No cameras available', 'No cameras found.');
}
- final CameraDescription camera = cameras[0]; // Could be user-selected.
- _cameraId = await _cameraWindowsPlugin.createCameraWithSettings(
- camera,
+ Logging.instance.d(
+ "Linux cameras: ${cameras.map((c) => c.name).toList()}",
+ );
+ // 640x480. low is 320x240 on Linux, too small for QR codes.
+ _cameraId = await plugin.createCameraWithSettings(
+ cameras.first,
const MediaSettings(
- resolutionPreset: ResolutionPreset.low,
- fps: 4,
- videoBitrate: 200000,
+ resolutionPreset: ResolutionPreset.medium,
enableAudio: false,
),
);
- await _cameraWindowsPlugin.initializeCamera(_cameraId);
- // await _cameraWindowsPlugin!.onCameraInitialized(_cameraId).first;
- // TODO [prio=low]: Make this work. ^^^
+ // Throws a CameraException with the driver's reason when the device
+ // can't be opened. A camera that opens but never delivers a frame is
+ // caught by the frame timeout in the scan loop.
+ await plugin.initializeCamera(_cameraId);
+ if (!mounted) {
+ await plugin.dispose(_cameraId);
+ return false;
+ }
+ _linuxErrorSub = plugin
+ .onCameraError(_cameraId)
+ .listen((e) => _onCameraLost(e.description));
+ // A capture failure is reported on the frame stream as well as
+ // through onCameraError, so it needs a handler here too or it escapes
+ // as an uncaught error. _onCameraLost ignores the second report.
+ _linuxFrameSub = plugin
+ .onStreamedFrameAvailable(_cameraId)
+ .listen(
+ (frame) => _latestLinuxFrame = frame.planes.first.bytes,
+ onError: (Object e) => _onCameraLost(
+ e is CameraException ? (e.description ?? e.code) : "$e",
+ ),
+ );
+ Logging.instance.d("Linux camera initialized with ID: $_cameraId");
+ } else if (Platform.isWindows && _cameraWindowsPlugin != null) {
+ final List<CameraDescription> cameras = await _cameraWindowsPlugin
+ .availableCameras();
+ if (cameras.isEmpty) {
+ throw CameraException('No cameras available', 'No cameras found.');
+ }
+ Logging.instance.d(
+ "Windows cameras: ${cameras.map((c) => c.name).toList()}",
+ );
+ // Try anything that looks like an IR camera last.
+ final irName = RegExp(r'\bIR\b|infrared', caseSensitive: false);
+ final ordered = [
+ ...cameras.where((c) => !irName.hasMatch(c.name)),
+ ...cameras.where((c) => irName.hasMatch(c.name)),
+ ];
+
+ // initializeCamera() starts the preview, and camera_windows picks the
+ // preview mode as the largest one with height <= the preset cap
+ // (low = 240, medium = 480, max = none) at >= 15 fps. If no mode fits,
+ // it fails with "Failed to initialize video preview". We scan the
+ // preview, so this also sets the scan resolution. fps and
+ // videoBitrate only apply to video recording, so leave them out.
+ CameraException? lastError;
+ bool opened = false;
+ for (final camera in ordered) {
+ for (final preset in [
+ ResolutionPreset.medium,
+ ResolutionPreset.max,
+ ]) {
+ if (!mounted) return false;
+ try {
+ _cameraId = await _cameraWindowsPlugin.createCameraWithSettings(
+ camera,
+ MediaSettings(resolutionPreset: preset, enableAudio: false),
+ );
+ // The plugin reports the preview size through this event,
+ // which it adds before initializeCamera() returns.
+ final initialized = _cameraWindowsPlugin
+ .onCameraInitialized(_cameraId)
+ .first;
+ await _cameraWindowsPlugin.initializeCamera(_cameraId);
+ final event = await initialized;
+ _windowsPreviewSize = Size(
+ event.previewWidth,
+ event.previewHeight,
+ );
+ opened = true;
+ break;
+ } on CameraException catch (e) {
+ lastError = e;
+ Logging.instance.w(
+ "Windows camera ${camera.name} failed with $preset",
+ error: e,
+ );
+ if (_cameraId >= 0) {
+ await _cameraWindowsPlugin.dispose(_cameraId);
+ _cameraId = -1;
+ }
+ }
+ }
+ if (opened) break;
+ }
+ if (!opened) {
+ throw lastError ??
+ CameraException('camera_error', 'No usable camera found.');
+ }
+ if (!mounted) {
+ // Closed while the camera was opening; PopScope already ran.
+ await _cameraWindowsPlugin.dispose(_cameraId);
+ return false;
+ }
+ // The plugin's only closing event comes from our own dispose(), so
+ // the error event is the one that matters.
+ _windowsErrorSub = _cameraWindowsPlugin
+ .onCameraError(_cameraId)
+ .listen((e) => _onCameraLost(e.description));
Logging.instance.d(
- "Windows Camera initialized with ID: $_cameraId",
+ "Windows Camera initialized with ID: $_cameraId, "
+ "preview $_windowsPreviewSize",
);
} else if (Platform.isMacOS) {
final List<CameraMacOSDevice> videoDevices = await CameraMacOS.instance
@@ -91,16 +226,20 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
throw Exception('No cameras available');
}
_macOSDeviceId = videoDevices.first.deviceId;
- await CameraMacOS.instance
- .initialize(cameraMacOSMode: CameraMacOSMode.photo);
-
- Logging.instance.d(
- "macOS Camera initialized with ID: $_macOSDeviceId",
+ await CameraMacOS.instance.initialize(
+ cameraMacOSMode: CameraMacOSMode.photo,
);
+
+ Logging.instance.d("macOS Camera initialized with ID: $_macOSDeviceId");
}
return true;
} catch (e, s) {
+ _initError = switch (e) {
+ CameraException() => e.description ?? e.code,
+ TimeoutException() => e.message ?? "$e",
+ _ => "$e",
+ };
Logging.instance.e(
"Failed to initialize camera",
error: e,
@@ -110,14 +249,61 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
}
}
+ /// Shows an error once no new frame has arrived for [_frameTimeout].
+ void _checkFrameTimeout() {
+ if (_sinceLastFrame.elapsed >= _frameTimeout &&
+ _cameraError == null &&
+ mounted) {
+ setState(() {
+ _cameraError =
+ "The camera preview has stopped updating. You can still "
+ "use \"Select file\" to scan a QR code image.";
+ });
+ }
+ }
+
+ /// The plugin reported a capture error (Windows: the capture engine failed
+ /// and keeps showing the last frame; Linux: the device went away). Neither
+ /// restarts the stream, so stop scanning and say so now rather than waiting
+ /// for the frame timeout.
+ void _onCameraLost(String description) {
+ // An engine can report one failure several times, and an event already
+ // queued can still arrive after the dialog started closing.
+ if (_cameraLost || !_isScanning) return;
+ _cameraLost = true;
+ _isScanning = false;
+ Logging.instance.w("Camera error: $description");
+ // FormatMessage text ends in ".\r\n", and unknown errors come through
+ // empty.
+ final detail = description.trim().replaceFirst(RegExp(r"\.$"), "");
+ if (!mounted) return;
+ setState(() {
+ _cameraError =
+ "The camera stopped working"
+ "${detail.isEmpty ? "" : " ($detail)"}. Close and reopen the "
+ "scanner to try again, or use \"Select file\" to scan a QR code "
+ "image.";
+ });
+ }
+
Future<void> _stopCamera() async {
_isScanning = false;
+ // Runs from PopScope and from dispose(); the second call has nothing to
+ // do.
+ if (_cameraStopped) return;
+ _cameraStopped = true;
try {
if (Platform.isLinux && _cameraLinuxPlugin != null) {
- _cameraLinuxPlugin.stopCamera();
- Logging.instance.d("Linux Camera stopped");
+ await _linuxFrameSub?.cancel();
+ _linuxFrameSub = null;
+ await _linuxErrorSub?.cancel();
+ _linuxErrorSub = null;
+ await _cameraLinuxPlugin!.dispose(_cameraId);
+ Logging.instance.d("Linux camera stopped with ID: $_cameraId");
} else if (Platform.isWindows && _cameraWindowsPlugin != null) {
+ await _windowsErrorSub?.cancel();
+ _windowsErrorSub = null;
// if (_cameraId >= 0) {
await _cameraWindowsPlugin.dispose(_cameraId);
Logging.instance.d("Windows Camera stopped with ID: $_cameraId");
@@ -135,69 +321,168 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
// }
}
} catch (e, s) {
- Logging.instance.e(
- "Failed to stop camera",
- error: e,
- stackTrace: s,
+ Logging.instance.e("Failed to stop camera", error: e, stackTrace: s);
+ }
+ }
+
+ @override
+ void dispose() {
+ // PopScope normally gets here first; this covers a route removed without
+ // a pop.
+ unawaited(_stopCamera());
+ super.dispose();
+ }
+
+ /// Grabs the frame the Windows preview is showing, in memory. Returns null
+ /// when there is nothing to scan yet, or nothing new since the last call.
+ Future<img.Image?> _captureWindowsPreviewFrame() async {
+ final boundary = _windowsPreviewKey.currentContext?.findRenderObject();
+ // Not laid out or painted yet, e.g. just after the camera opened.
+ // debugNeedsPaint is always false in release builds, where toImage()
+ // would throw instead and the capture loop retries after a delay.
+ if (boundary is! RenderRepaintBoundary ||
+ !boundary.hasSize ||
+ boundary.size.isEmpty ||
+ boundary.debugNeedsPaint) {
+ return null;
+ }
+
+ // toImage() redraws the texture at whatever scale we ask for, so match
+ // the camera's own resolution instead of the on-screen size.
+ final preview = _windowsPreviewSize;
+ double pixelRatio = 1;
+ if (preview != null && preview.width > 0 && preview.height > 0) {
+ final fit = min(
+ 1.0,
+ _cameraFrameMaxDimension / max(preview.width, preview.height),
);
+ // toImage() rounds each side up, and the laid-out box is rarely exactly
+ // the camera's aspect ratio, so take the smaller ratio and stay a hair
+ // under it. Otherwise a 640x480 camera can come back as 640x481.
+ pixelRatio =
+ min(
+ preview.width * fit / boundary.size.width,
+ preview.height * fit / boundary.size.height,
+ ) *
+ (1 - 1e-9);
+ }
+
+ final ui.Image frame = await boundary.toImage(pixelRatio: pixelRatio);
+ final int width = frame.width;
+ final int height = frame.height;
+ final ByteData? bytes;
+ try {
+ bytes = await frame.toByteData(format: ui.ImageByteFormat.rawRgba);
+ } finally {
+ frame.dispose();
}
+ // The dialog closed while we were waiting on the raster thread.
+ if (!_isScanning || !mounted || bytes == null) return null;
+
+ final rgba = bytes.buffer.asUint8List(
+ bytes.offsetInBytes,
+ bytes.lengthInBytes,
+ );
+ final blank = blankPreviewFrame(rgba);
+ if (blank != null) {
+ if (!_loggedBlankWindowsFrame) {
+ _loggedBlankWindowsFrame = true;
+ Logging.instance.w(
+ "Windows camera preview frame is ${blank.name}, "
+ "waiting for a usable one",
+ );
+ }
+ return null;
+ }
+ _loggedBlankWindowsFrame = false;
+
+ // A repeat of the last capture means the preview has stopped updating,
+ // so treat it like no frame and let the frame timeout notice.
+ final fingerprint = previewFrameFingerprint(rgba);
+ if (fingerprint == _lastWindowsFrameFingerprint) {
+ if (!_loggedRepeatedWindowsFrame) {
+ _loggedRepeatedWindowsFrame = true;
+ Logging.instance.w(
+ "Windows camera preview frame has not changed, waiting for a new one",
+ );
+ }
+ return null;
+ }
+ _lastWindowsFrameFingerprint = fingerprint;
+ _loggedRepeatedWindowsFrame = false;
+
+ // camera_windows mirrors the preview, so flip it back for zxing.
+ return imageFromMirroredPreviewRgba(rgba, width: width, height: height);
}
Future<void> _captureAndScanImage() async {
_isScanning = true;
+ _sinceLastFrame.start();
while (_isScanning) {
try {
- String? base64Image;
+ Uint8List? imageBytes;
+ img.Image? windowsFrame;
if (Platform.isLinux && _cameraLinuxPlugin != null) {
- base64Image = await _cameraLinuxPlugin.captureImage();
+ // The newest frame from the image stream, or nothing new yet.
+ imageBytes = _latestLinuxFrame;
+ _latestLinuxFrame = null;
} else if (Platform.isWindows) {
- final XFile xfile =
- await _cameraWindowsPlugin!.takePicture(_cameraId);
- final bytes = await xfile.readAsBytes();
- base64Image = base64Encode(bytes);
- // We could use a Uint8List to optimize for Windows and macOS.
+ windowsFrame = await _captureWindowsPreviewFrame();
} else if (Platform.isMacOS) {
final macOSimg = await CameraMacOS.instance.takePicture();
if (macOSimg == null) {
Logging.instance.w("Failed to capture image");
await Future<void>.delayed(Duration(milliseconds: _imageDelayInMs));
+ _checkFrameTimeout();
continue;
}
final img.Image? image = img.decodeImage(macOSimg.bytes!);
if (image == null) {
Logging.instance.w("Failed to capture image");
await Future<void>.delayed(Duration(milliseconds: _imageDelayInMs));
+ _checkFrameTimeout();
continue;
}
- base64Image = base64Encode(img.encodePng(image));
+ imageBytes = img.encodePng(image);
}
- if (base64Image == null || base64Image.isEmpty) {
+ if (windowsFrame == null &&
+ (imageBytes == null || imageBytes.isEmpty)) {
// Logging.instance
// .log("Failed to capture image", level: LogLevel.Error);
// Spammy.
await Future<void>.delayed(Duration(milliseconds: _imageDelayInMs));
+ _checkFrameTimeout();
continue;
}
- final img.Image? image = img.decodeImage(base64Decode(base64Image));
+ final img.Image? image = windowsFrame ?? img.decodeImage(imageBytes!);
// TODO [prio=low]: Optimize this process. Docs say:
// > WARNING Since this will check the image data against all known
// > decoders, it is much slower than using an explicit decoder
if (image == null) {
Logging.instance.w("Failed to decode image");
await Future<void>.delayed(Duration(milliseconds: _imageDelayInMs));
+ _checkFrameTimeout();
continue;
}
+ _consecutiveFailures = 0;
+ _sinceLastFrame.reset();
if (mounted) {
setState(() {
- _image = Image.memory(
- base64Decode(base64Image!),
- fit: BoxFit.cover,
- );
+ _cameraError = null;
+ // Windows already shows the live preview.
+ if (windowsFrame == null) {
+ _image = Image.memory(imageBytes!, fit: BoxFit.cover);
+ } else {
+ _hasWindowsFrame = true;
+ }
});
}
- final String? scanResult = await _scanImage(image);
+ final String? scanResult = await _scanImage(
+ image,
+ maxDimension: _cameraFrameMaxDimension,
+ );
if (scanResult != null && scanResult.isNotEmpty) {
await _stopCamera();
@@ -214,43 +499,85 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
}
await Future<void>.delayed(Duration(milliseconds: _imageDelayInMs));
- } catch (e) {
- // Logging.instance.log("Failed to capture and scan image", error: e, stackTrace: s,);
- // Spammy.
-
- // if (mounted) {
- // widget.onSnackbar(
- // "Error capturing or scanning the image. Please try again.");
- // }
+ } catch (e, s) {
+ _consecutiveFailures++;
+ // Log the first failure and every 20th after it, so a capture that
+ // fails on every iteration shows up in the logs without flooding them.
+ if (_consecutiveFailures == 1 || _consecutiveFailures % 20 == 0) {
+ Logging.instance.e(
+ "Failed to capture image ($_consecutiveFailures in a row)",
+ error: e,
+ stackTrace: s,
+ );
+ }
+ _checkFrameTimeout();
+ // Without this a failing capture spins the loop with no delay.
+ await Future<void>.delayed(Duration(milliseconds: _imageDelayInMs));
}
}
}
- Future<String?> _scanImage(img.Image image) async {
- try {
- final LuminanceSource source = RGBLuminanceSource(
- image.width,
- image.height,
- image
- .convert(numChannels: 4)
- .getBytes(order: img.ChannelOrder.abgr)
- .buffer
- .asInt32List(),
- );
- final BinaryBitmap bitmap =
- BinaryBitmap(GlobalHistogramBinarizer(source));
+ // Camera frames bigger than this are scaled down before scanning, and
+ // Windows preview captures are taken at no more than this. Files picked
+ // with "Select file" are scanned at full size.
+ static const _cameraFrameMaxDimension = 1280;
- final QRCodeReader reader = QRCodeReader();
- final qrDecode = reader.decode(bitmap);
- if (qrDecode.text.isEmpty) {
- return null;
- }
- return qrDecode.text;
- } catch (e) {
- // Logging.instance.log("Failed to decode QR code", error: e, stackTrace: s,);
- // Spammy.
- return null;
+ Future<String?> _scanImage(img.Image image, {int? maxDimension}) async =>
+ decodeQrFromImage(image, maxDimension: maxDimension);
+
+ Widget _buildCameraView(BuildContext context) {
+ if (Platform.isWindows && _isCameraOpen) {
+ return _buildWindowsPreview(context);
}
+ if (_cameraError != null) {
+ return _buildCameraError(context);
+ }
+ if (_isCameraOpen && _image != null) {
+ return _image!;
+ }
+ return const Center(child: CircularProgressIndicator());
+ }
+
+ Widget _buildCameraError(BuildContext context) {
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 32),
+ child: Text(
+ _cameraError!,
+ textAlign: TextAlign.center,
+ style: STextStyles.desktopTextSmall(context),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildWindowsPreview(BuildContext context) {
+ final size = _windowsPreviewSize;
+ return Stack(
+ fit: StackFit.expand,
+ children: [
+ Center(
+ child: AspectRatio(
+ aspectRatio: size != null && size.width > 0 && size.height > 0
+ ? size.width / size.height
+ : 4 / 3,
+ child: RepaintBoundary(
+ key: _windowsPreviewKey,
+ child: _cameraWindowsPlugin!.buildPreview(_cameraId),
+ ),
+ ),
+ ),
+ // Cover the preview rather than replace it, so it keeps painting and
+ // scanning picks up again once frames come back.
+ if (_cameraError != null)
+ ColoredBox(
+ color: Theme.of(context).extension<StackColors>()!.popupBG,
+ child: _buildCameraError(context),
+ )
+ else if (!_hasWindowsFrame)
+ const Center(child: CircularProgressIndicator()),
+ ],
+ );
}
@override
@@ -278,18 +605,7 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
const DesktopDialogCloseButton(),
],
),
- Expanded(
- child: _isCameraOpen
- ? _image != null
- ? _image!
- : const Center(
- child: CircularProgressIndicator(),
- )
- : const Center(
- child:
- CircularProgressIndicator(), // Show progress indicator immediately
- ),
- ),
+ Expanded(child: _buildCameraView(context)),
Padding(
padding: const EdgeInsets.all(16),
child: Row(
@@ -330,8 +646,9 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
}
try {
- final img.Image? image =
- img.decodeImage(File(filePath).readAsBytesSync());
+ final img.Image? image = img.decodeImage(
+ File(filePath).readAsBytesSync(),
+ );
if (image == null) {
await showFloatingFlushBar(
type: FlushBarType.info,
@@ -364,8 +681,7 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
if (context.mounted) {
await showFloatingFlushBar(
type: FlushBarType.info,
- message:
- "Error processing the image. Please try again.",
+ message: "Error processing the image. Please try again.",
iconAsset: Assets.svg.file,
context: context,
);
### lib/widgets/icon_widgets/eth_token_icon.dart
@@ -16,6 +16,7 @@ import 'package:flutter_svg/svg.dart';
import 'package:isar_community/isar.dart';
import '../../models/isar/exchange_cache/currency.dart';
+import '../../networking/tor_aware_network_image.dart';
import '../../services/exchange/change_now/change_now_exchange.dart';
import '../../services/exchange/exchange_data_loading_service.dart';
import '../../themes/coin_icon_provider.dart';
@@ -87,8 +88,8 @@ class _EthTokenIconState extends ConsumerState<EthTokenIcon> {
height: widget.size,
);
} else {
- return SvgPicture.network(
- imageUrl!,
+ return SvgPicture(
+ TorAwareSvgNetworkLoader(imageUrl!),
width: widget.size,
height: widget.size,
placeholderBuilder: (_) => const LoadingIndicator(),
### lib/widgets/icon_widgets/sol_token_icon.dart
@@ -15,6 +15,7 @@ import 'package:flutter_svg/svg.dart';
import 'package:isar_community/isar.dart';
import '../../models/isar/exchange_cache/currency.dart';
+import '../../networking/tor_aware_network_image.dart';
import '../../services/exchange/change_now/change_now_exchange.dart';
import '../../services/exchange/exchange_data_loading_service.dart';
import '../../themes/coin_icon_provider.dart';
@@ -84,8 +85,8 @@ class _SolTokenIconState extends ConsumerState<SolTokenIcon> {
);
} else {
// Display token icon from network.
- return SvgPicture.network(
- imageUrl!,
+ return SvgPicture(
+ TorAwareSvgNetworkLoader(imageUrl!),
width: widget.size,
height: widget.size,
placeholderBuilder: (_) => const LoadingIndicator(),
### lib/widgets/onetime_popups/native_library_warning_dialog.dart
@@ -0,0 +1,36 @@
+import 'package:flutter/material.dart';
+
+import '../../utilities/native_library_check.dart';
+import '../../utilities/util.dart';
+import '../stack_dialog.dart';
+
+String nativeLibraryWarningTitle(List<NativeLibraryFailure> failures) =>
+ failures.length == 1
+ ? "A required file could not be loaded"
+ : "Some required files could not be loaded";
+
+String nativeLibraryWarningMessage(List<NativeLibraryFailure> failures) => [
+ for (final f in failures) nativeLibraryErrorMessage(f.displayName, f.result),
+].join("\n\n");
+
+/// Shows what the startup check found, once, the first time a home view
+/// appears after launch. Only the message changes hands: wallets open as
+/// they always have, so a broken library never locks anyone out of a seed
+/// they can still reach through wallet settings.
+Future<void> showNativeLibraryWarningIfRequired(BuildContext context) {
+ // Taken only once there is a live context to show them in, so a home
+ // view replaced within its first frame leaves them for the next one.
+ if (!context.mounted) return Future.value();
+ final failures = takeNativeLibraryFailures();
+ if (failures.isEmpty) return Future.value();
+
+ return showDialog<void>(
+ context: context,
+ builder: (_) => StackOkDialog(
+ title: nativeLibraryWarningTitle(failures),
+ message: nativeLibraryWarningMessage(failures),
+ desktopPopRootNavigator: true,
+ maxWidth: Util.isDesktop ? 500 : null,
+ ),
+ );
+}
### lib/widgets/textfields/exchange_textfield.dart
@@ -14,6 +14,7 @@ import 'package:flutter_svg/svg.dart';
import '../../app_config.dart';
import '../../models/exchange/aggregate_currency.dart';
+import '../../networking/tor_aware_network_image.dart';
import '../../pages/buy_view/sub_widgets/crypto_selection_view.dart';
import '../../providers/global/locale_provider.dart';
import '../../themes/stack_colors.dart';
@@ -181,8 +182,10 @@ class _ExchangeTextFieldState extends ConsumerState<ExchangeTextField> {
} else if (widget.currency != null &&
widget.currency!.image.isNotEmpty) {
return Center(
- child: SvgPicture.network(
- widget.currency!.image,
+ child: SvgPicture(
+ TorAwareSvgNetworkLoader(
+ widget.currency!.image,
+ ),
height: 18,
placeholderBuilder: (_) => Container(
width: 18,
### lib/widgets/wallet_info_row/sub_widgets/wallet_info_row_coin_icon.dart
@@ -16,6 +16,7 @@ import 'package:flutter_svg/svg.dart';
import 'package:isar_community/isar.dart';
import '../../../models/isar/exchange_cache/currency.dart';
+import '../../../networking/tor_aware_network_image.dart';
import '../../../services/exchange/change_now/change_now_exchange.dart';
import '../../../services/exchange/exchange_data_loading_service.dart';
import '../../../themes/coin_icon_provider.dart';
@@ -48,18 +49,14 @@ class _WalletInfoCoinIconState extends ConsumerState<WalletInfoCoinIcon> {
ExchangeDataLoadingService.instance.isar.then((isar) async {
if (widget.contractAddress != null) {
- final currency =
- await isar.currencies
- .where()
- .exchangeNameEqualTo(ChangeNowExchange.exchangeName)
- .filter()
- .tokenContractEqualTo(
- widget.contractAddress!,
- caseSensitive: false,
- )
- .and()
- .imageIsNotEmpty()
- .findFirst();
+ final currency = await isar.currencies
+ .where()
+ .exchangeNameEqualTo(ChangeNowExchange.exchangeName)
+ .filter()
+ .tokenContractEqualTo(widget.contractAddress!, caseSensitive: false)
+ .and()
+ .imageIsNotEmpty()
+ .findFirst();
if (mounted) {
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -87,14 +84,17 @@ class _WalletInfoCoinIconState extends ConsumerState<WalletInfoCoinIcon> {
),
child: Padding(
padding: EdgeInsets.all(widget.size / 5),
- child:
- imageUrl != null && imageUrl!.isNotEmpty
- ? SvgPicture.network(imageUrl!, width: 20, height: 20)
- : SvgPicture.file(
- File(ref.watch(coinIconProvider(widget.coin))),
- width: 20,
- height: 20,
- ),
+ child: imageUrl != null && imageUrl!.isNotEmpty
+ ? SvgPicture(
+ TorAwareSvgNetworkLoader(imageUrl!),
+ width: 20,
+ height: 20,
+ )
+ : SvgPicture.file(
+ File(ref.watch(coinIconProvider(widget.coin))),
+ width: 20,
+ height: 20,
+ ),
),
);
}
### pubspec.lock
@@ -42,7 +42,7 @@ packages:
source: hosted
version: "4.0.9"
args:
- dependency: transitive
+ dependency: "direct dev"
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
@@ -227,11 +227,11 @@ packages:
dependency: "direct main"
description:
path: "."
- ref: ecb412474c5d240347b04ac1eb9f019802ff7034
- resolved-ref: ecb412474c5d240347b04ac1eb9f019802ff7034
+ ref: "82e2d82188cc4676a02559118af110c8161b4eed"
+ resolved-ref: "82e2d82188cc4676a02559118af110c8161b4eed"
url: "https://github.com/cypherstack/camera-linux"
source: git
- version: "0.0.8"
+ version: "0.1.0"
camera_macos:
dependency: "direct main"
description:
@@ -244,19 +244,18 @@ packages:
dependency: "direct main"
description:
name: camera_platform_interface
- sha256: "98cfc9357e04bad617671b4c1f78a597f25f08003089dd94050709ae54effc63"
+ sha256: b3083b183ef1daa408d5f0c98c8c7ac0325b490695fb4557ff4210fcf04c5984
url: "https://pub.dev"
source: hosted
- version: "2.12.0"
+ version: "2.15.0"
camera_windows:
dependency: "direct main"
description:
- path: "packages/camera/camera_windows"
- ref: HEAD
- resolved-ref: "9bfbfd643ba4e6865ec34124e42a1cc502c400c0"
- url: "https://github.com/cypherstack/packages.git"
- source: git
- version: "0.2.4"
+ name: camera_windows
+ sha256: "05c322203f66fa68953378398542865606543f294395fbbb055b4ea8f089e39b"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.3.0+1"
cbor:
dependency: "direct main"
description:
@@ -1655,8 +1654,8 @@ packages:
dependency: "direct main"
description:
path: "."
- ref: e60766bc420861b9e8c804627d84cbd570b04ff6
- resolved-ref: e60766bc420861b9e8c804627d84cbd570b04ff6
+ ref: 21f95309522dd48face32c0c4a3ca2ac8df092fb
+ resolved-ref: 21f95309522dd48face32c0c4a3ca2ac8df092fb
url: "https://github.com/cypherstack/mobile_app_privacy"
source: git
version: "0.0.5"
@@ -2342,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
@@ -243,12 +243,9 @@ dependencies:
camera_linux:
git:
url: https://github.com/cypherstack/camera-linux
- ref: ecb412474c5d240347b04ac1eb9f019802ff7034
+ ref: 82e2d82188cc4676a02559118af110c8161b4eed
zxing2: ^0.2.3
- camera_windows:
- git: # TODO [prio=low]: Revert to official after https://github.com/flutter/packages/pull/7067.
- url: https://github.com/cypherstack/packages.git
- path: packages/camera/camera_windows
+ camera_windows: ^0.3.0+1
camera_platform_interface: ^2.8.0
camera_macos: ^0.1.1
blockchain_utils: ^3.3.0
@@ -275,12 +272,14 @@ dependencies:
mobile_app_privacy:
git:
url: https://github.com/cypherstack/mobile_app_privacy
- ref: e60766bc420861b9e8c804627d84cbd570b04ff6
+ ref: 21f95309522dd48face32c0c4a3ca2ac8df092fb
# required for web3dart to use EthereumAddress class...
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/db_version_migration_test.dart
@@ -6,9 +6,11 @@ import 'package:stackwallet/db/db_version_migration.dart';
import 'package:stackwallet/db/hive/db.dart';
import 'package:stackwallet/db/isar/main_db.dart';
import 'package:stackwallet/models/isar/models/ethereum/eth_contract.dart';
+import 'package:stackwallet/models/node_model.dart';
import 'package:stackwallet/utilities/constants.dart';
import 'package:stackwallet/utilities/default_eth_tokens.dart';
import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
import 'hive/hive_ce_test_utils.dart';
@@ -34,8 +36,8 @@ void main() {
DbVersionMigrator().migrate(version, secureStore: FakeSecureStorage());
await migrate(16);
- expect(Constants.currentDataVersion, 17);
- expect(info.get('hive_data_version'), 17);
+ expect(Constants.currentDataVersion, 18);
+ expect(info.get('hive_data_version'), 18);
expect(await db.getEthContracts().isEmpty(), isTrue);
final custom = DefaultTokens.usdc.copyWith(name: 'Custom token');
@@ -58,4 +60,62 @@ void main() {
await migrate(info.get('hive_data_version') as int);
expect(await db.getEthContracts().count(), 1);
});
+
+ test('v18 lets the default Fact0rn node use Tor', () async {
+ await setUpHiveCeTest();
+ addTearDown(tearDownHiveCeTest);
+ final adapter = NodeModelAdapter();
+ if (!DB.instance.hive.isAdapterRegistered(adapter.typeId)) {
+ DB.instance.hive.registerAdapter(adapter);
+ }
+ final info = await DB.instance.hive.openBox<dynamic>(DB.boxNameDBInfo);
+ final nodes = await DB.instance.hive.openBox<NodeModel>(
+ DB.boxNameNodeModels,
+ );
+ NodeModel clearOnly(CryptoCurrency coin) => coin
+ .defaultNode(isPrimary: true)
+ .copyWith(loginName: null, trusted: null, torEnabled: false);
+ final fact0rn = clearOnly(Fact0rn(CryptoCurrencyNetwork.main));
+ final bitcoin = clearOnly(Bitcoin(CryptoCurrencyNetwork.main));
+ await nodes.put(fact0rn.id, fact0rn);
+ await nodes.put(bitcoin.id, bitcoin);
+
+ await DbVersionMigrator().migrate(17, secureStore: FakeSecureStorage());
+
+ expect(info.get('hive_data_version'), 18);
+ expect(nodes.get(fact0rn.id)!.torEnabled, isTrue);
+ expect(nodes.get(fact0rn.id)!.clearnetEnabled, isTrue);
+ expect(nodes.get(fact0rn.id)!.isPrimary, isTrue);
+ expect(nodes.get(bitcoin.id)!.torEnabled, isFalse);
+ });
+
+ test('v18 leaves an edited Fact0rn default node alone', () async {
+ await setUpHiveCeTest();
+ addTearDown(tearDownHiveCeTest);
+ final adapter = NodeModelAdapter();
+ if (!DB.instance.hive.isAdapterRegistered(adapter.typeId)) {
+ DB.instance.hive.registerAdapter(adapter);
+ }
+ await DB.instance.hive.openBox<dynamic>(DB.boxNameDBInfo);
+ final nodes = await DB.instance.hive.openBox<NodeModel>(
+ DB.boxNameNodeModels,
+ );
+ final shipped = Fact0rn(CryptoCurrencyNetwork.main)
+ .defaultNode(isPrimary: true)
+ .copyWith(loginName: null, trusted: null, torEnabled: false);
+ final edited = [
+ shipped.copyWith(loginName: null, trusted: null, isFailover: false),
+ shipped.copyWith(loginName: null, trusted: null, host: "example.com"),
+ shipped.copyWith(loginName: null, trusted: null, port: 50001),
+ shipped.copyWith(loginName: null, trusted: null, useSSL: false),
+ shipped.copyWith(loginName: null, trusted: null, name: "Mine"),
+ shipped.copyWith(loginName: "user", trusted: null),
+ ];
+
+ for (final node in edited) {
+ await nodes.put(node.id, node);
+ await DbVersionMigrator().migrate(17, secureStore: FakeSecureStorage());
+ expect(nodes.get(node.id)!.torEnabled, isFalse, reason: "$node");
+ }
+ });
}
### test/networking/tor_aware_network_image_test.dart
@@ -0,0 +1,57 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/networking/tor_aware_network_image.dart';
+
+void main() {
+ late HttpServer server;
+ late List<HttpRequest> requests;
+
+ setUp(() async {
+ requests = [];
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((request) {
+ requests.add(request);
+ request.response.add([1]);
+ request.response.close();
+ });
+ });
+
+ tearDown(() => server.close(force: true));
+
+ String url(String path) => "http://127.0.0.1:${server.port}$path";
+
+ test("network image sends headers but keys the cache on the url", () async {
+ await fetchTorAwareBytes(
+ url("/a.png"),
+ headers: {"Authorization": "Bearer abc"},
+ );
+ expect(requests.single.headers.value("Authorization"), "Bearer abc");
+
+ expect(
+ TorAwareNetworkImage(
+ url("/a.png"),
+ headers: const {"Authorization": "a"},
+ ),
+ TorAwareNetworkImage(
+ url("/a.png"),
+ headers: const {"Authorization": "b"},
+ ),
+ );
+ });
+
+ test("network image cache is scoped by cacheScope", () {
+ expect(
+ TorAwareNetworkImage(url("/a.png"), cacheScope: "customer-a"),
+ TorAwareNetworkImage(url("/a.png"), cacheScope: "customer-a"),
+ );
+ expect(
+ TorAwareNetworkImage(url("/a.png"), cacheScope: "customer-a"),
+ isNot(TorAwareNetworkImage(url("/a.png"), cacheScope: "customer-b")),
+ );
+ expect(
+ TorAwareNetworkImage(url("/a.png"), cacheScope: "customer-a"),
+ isNot(TorAwareNetworkImage(url("/a.png"))),
+ );
+ });
+}
### 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
@@ -0,0 +1,246 @@
+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/balance.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/pages/send_view/send_view.dart';
+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';
+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/wallet_info_provider.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;
+ AmountUnit selectedUnit = AmountUnit.normal;
+ @override
+ AmountUnit amountUnit(CryptoCurrency coin) => selectedUnit;
+ @override
+ int maxDecimals(CryptoCurrency coin) => coin.fractionDigits;
+ void changeUnit(AmountUnit next) {
+ selectedUnit = next;
+ notifyListeners();
+ }
+}
+
+void main() {
+ const walletId = 'provider-audit-wallet';
+ void setupLayout(WidgetTester tester, bool desktop) {
+ final oldPlatform = Util.layoutPlatform;
+ final oldThemesDir = 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 = oldThemesDir;
+ tester.view.resetPhysicalSize();
+ tester.view.resetDevicePixelRatio();
+ });
+ }
+
+ Future<void> pump(
+ WidgetTester tester,
+ ProviderContainer container,
+ Widget child,
+ ) async {
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ await tester.pumpWidget(
+ UncontrolledProviderScope(
+ container: container,
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: Util.isDesktop
+ ? Scaffold(body: SingleChildScrollView(child: child))
+ : child,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ }
+
+ for (final desktop in [false, true]) {
+ testWidgets('normal send preserves amount on locale change ($desktop)', (
+ tester,
+ ) async {
+ setupLayout(tester, desktop);
+ final wallet = TestWallet(FakeNative());
+ final coin = wallet.cryptoCurrency;
+ final info = WalletInfo(
+ walletId: walletId,
+ name: 'Audit wallet',
+ mainAddressType: AddressType.xelis,
+ coinName: coin.identifier,
+ );
+ final locale = _Locale();
+ final prefs = _Prefs();
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ final container = ProviderContainer(
+ overrides: [
+ pWallets.overrideWithValue(ConfirmationWallets(wallet)),
+ pWalletInfo(walletId).overrideWithValue(info),
+ pWalletCoin(walletId).overrideWithValue(coin),
+ pWalletName(walletId).overrideWithValue(info.name),
+ 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(
+ File('test/sample_data/light/assets/dummy.svg').absolute.path,
+ ),
+ ],
+ );
+ addTearDown(container.dispose);
+ await pump(
+ tester,
+ container,
+ desktop
+ ? const DesktopSend(walletId: walletId)
+ : SendView(walletId: walletId, coin: coin),
+ );
+ final field = find.byKey(const Key('amountInputFieldCryptoTextFieldKey'));
+ await tester.enterText(field, '1.25');
+ await tester.pump(const Duration(milliseconds: 600));
+ final expected = container.read(pSendAmount);
+ expect(
+ expected,
+ Amount(
+ rawValue: BigInt.from(125000000),
+ fractionDigits: coin.fractionDigits,
+ ),
+ );
+ locale.change('de_DE');
+ await tester.pump(const Duration(milliseconds: 600));
+ final actual = container.read(pSendAmount);
+ final text = tester.widget<TextField>(field).controller!.text;
+ expect(text, '1,25');
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ expect(
+ actual,
+ expected,
+ reason: 'Locale change must preserve the canonical send amount',
+ );
+ });
+ testWidgets('Salvium stake keeps amount and unit consistent ($desktop)', (
+ tester,
+ ) async {
+ setupLayout(tester, desktop);
+ final coin = Salvium(CryptoCurrencyNetwork.main);
+ final prefs = _Prefs();
+ final container = ProviderContainer(
+ overrides: [
+ pWalletCoin(walletId).overrideWithValue(coin),
+ themeProvider.overrideWithProvider(
+ StateProvider(
+ (ref) => StackTheme.fromJson(json: lightThemeJsonMap),
+ ),
+ ),
+ prefsChangeNotifierProvider.overrideWithValue(prefs),
+ localeServiceChangeNotifierProvider.overrideWithValue(_Locale()),
+ ],
+ );
+ addTearDown(container.dispose);
+ await pump(
+ tester,
+ container,
+ const SalviumCreateStakeView(walletId: walletId),
+ );
+ final field = find.byType(TextField).first;
+ await tester.enterText(field, '1.25');
+ await tester.pump();
+ prefs.changeUnit(AmountUnit.milli);
+ await tester.pump();
+ final text = tester.widget<TextField>(field).controller!.text;
+ final preview = find.widgetWithText(PrimaryButton, 'Preview');
+ expect(tester.widget<PrimaryButton>(preview).enabled, true);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ expect(text, '1250', reason: '1.25 SAL must display as 1250 mSAL');
+ });
+ testWidgets('Salvium stake preserves amount on locale change ($desktop)', (
+ tester,
+ ) async {
+ setupLayout(tester, desktop);
+ final coin = Salvium(CryptoCurrencyNetwork.main);
+ final locale = _Locale();
+ final container = ProviderContainer(
+ overrides: [
+ pWalletCoin(walletId).overrideWithValue(coin),
+ themeProvider.overrideWithProvider(
+ StateProvider(
+ (ref) => StackTheme.fromJson(json: lightThemeJsonMap),
+ ),
+ ),
+ prefsChangeNotifierProvider.overrideWithValue(_Prefs()),
+ localeServiceChangeNotifierProvider.overrideWithValue(locale),
+ ],
+ );
+ addTearDown(container.dispose);
+ await pump(
+ tester,
+ container,
+ const SalviumCreateStakeView(walletId: walletId),
+ );
+ final field = find.byType(TextField).first;
+ await tester.enterText(field, '1.25');
+ await tester.pump();
+ final preview = find.widgetWithText(PrimaryButton, 'Preview');
+ expect(tester.widget<PrimaryButton>(preview).enabled, true);
+ locale.change('de_DE');
+ await tester.pump();
+ final enabled = tester.widget<PrimaryButton>(preview).enabled;
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ expect(
+ enabled,
+ true,
+ reason: 'Relocalizing the stake must preserve the valid amount',
+ );
+ });
+ }
+}
### test/pages/send_view/amount_input_transition_test.dart
@@ -0,0 +1,262 @@
+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/stack_theme.dart';
+import 'package:stackwallet/pages/send_view/send_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';
+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/wallet_info_provider.dart';
+import 'package:stackwallet/wallets/models/tx_data.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;
+ AmountUnit selectedUnit = AmountUnit.normal;
+ @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);
+}
+
+class _ValidXelis extends Xelis {
+ _ValidXelis() : super(CryptoCurrencyNetwork.test);
+ @override
+ bool validateAddress(String address) => address.isNotEmpty;
+}
+
+class _CaptureWallet extends TestWallet {
+ _CaptureWallet() : super(FakeNative());
+ final _coin = _ValidXelis();
+ @override
+ Xelis get cryptoCurrency => _coin;
+ late WalletInfo testInfo;
+ TxData? captured;
+ @override
+ WalletInfo get info => testInfo;
+ @override
+ Future<TxData> prepareSend({required TxData txData, String? assetId}) async {
+ captured = txData;
+ throw StateError('captured test transaction');
+ }
+}
+
+void main() {
+ const walletId = 'review-wallet';
+ Future<ProviderContainer> mount(
+ WidgetTester tester,
+ bool desktop,
+ _CaptureWallet wallet,
+ _Prefs prefs,
+ _Locale locale,
+ ) 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 = wallet.cryptoCurrency;
+ final info = WalletInfo(
+ walletId: walletId,
+ name: 'Test wallet',
+ mainAddressType: AddressType.xelis,
+ coinName: coin.identifier,
+ );
+ wallet.testInfo = info;
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ final amount = Amount(
+ rawValue: BigInt.from(1000000000),
+ fractionDigits: coin.fractionDigits,
+ );
+ final zero = Amount.zeroWith(fractionDigits: coin.fractionDigits);
+ final balance = Balance(
+ total: amount,
+ spendable: amount,
+ blockedTotal: zero,
+ pendingSpendable: zero,
+ );
+ final container = ProviderContainer(
+ overrides: [
+ pWallets.overrideWithValue(ConfirmationWallets(wallet)),
+ pWalletInfo(walletId).overrideWithValue(info),
+ pWalletCoin(walletId).overrideWithValue(coin),
+ pWalletName(walletId).overrideWithValue(info.name),
+ pWalletBalance(walletId).overrideWithValue(balance),
+ 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);
+ final child = desktop
+ ? const DesktopSend(walletId: walletId)
+ : SendView(walletId: walletId, coin: coin);
+ await tester.pumpWidget(
+ UncontrolledProviderScope(
+ container: container,
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: desktop
+ ? Scaffold(body: SingleChildScrollView(child: child))
+ : child,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ });
+ return container;
+ }
+
+ for (final desktop in [false, true]) {
+ for (final unitFirst in [false, true]) {
+ testWidgets(
+ 'same frame locale and unit desktop=$desktop unitFirst=$unitFirst',
+ (tester) async {
+ final prefs = _Prefs();
+ final locale = _Locale();
+ final container = await mount(
+ tester,
+ desktop,
+ _CaptureWallet(),
+ prefs,
+ locale,
+ );
+ final field = find.byKey(
+ const Key('amountInputFieldCryptoTextFieldKey'),
+ );
+ await tester.enterText(field, '1.2501');
+ await tester.pump(const Duration(milliseconds: 600));
+ final expected = container.read(pSendAmount);
+ if (unitFirst) {
+ prefs.changeUnit(AmountUnit.milli);
+ locale.change('de_DE');
+ } else {
+ locale.change('de_DE');
+ prefs.changeUnit(AmountUnit.milli);
+ }
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(container.read(pSendAmount), expected);
+ expect(tester.widget<TextField>(field).controller!.text, '1250,1');
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ },
+ );
+ }
+ testWidgets('fiat input clears send all desktop=$desktop', (tester) async {
+ final prefs = _Prefs();
+ final locale = _Locale();
+ final wallet = _CaptureWallet();
+ final container = await mount(tester, desktop, wallet, prefs, locale);
+ final sendAll = find.textContaining('Send all', findRichText: true);
+ if (sendAll.evaluate().isEmpty) {
+ expect(find.textContaining('Send all'), findsOneWidget);
+ }
+ final sendAllActual = sendAll.evaluate().isEmpty
+ ? find.textContaining('Send all')
+ : sendAll;
+ await tester.ensureVisible(sendAllActual);
+ await tester.tap(sendAllActual);
+ await tester.pump();
+ expect(container.read(pSendAmount)!.decimal, Decimal.fromInt(10));
+ final fiat = find.byKey(const Key('amountInputFieldFiatTextFieldKey'));
+ expect(fiat, findsOneWidget);
+ await tester.enterText(fiat, '1');
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(container.read(pSendAmount)!.decimal, Decimal.one);
+ final address = find.byKey(const Key('sendViewAddressFieldKey'));
+ await tester.enterText(address, 'some-address');
+ await tester.pump();
+ // Trigger the current preview callback without relying on scroll position.
+ if (desktop) {
+ final preview = tester.widget<PrimaryButton>(
+ find.widgetWithText(PrimaryButton, 'Preview send'),
+ );
+ expect(preview.enabled, true);
+ 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(wallet.captured, isNotNull);
+ expect(wallet.captured!.recipients!.single.amount.decimal, Decimal.one);
+ expect(
+ wallet.captured!.xelisSendAll,
+ false,
+ reason: 'Editing the fiat amount must cancel send-all intent',
+ );
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ });
+ }
+}
### 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/frost_ms/recipient_test.dart
@@ -30,6 +30,18 @@ class _TestMonero extends Monero {
bool validateAddress(String address) => address.startsWith("address");
}
+class _TestLocaleService extends LocaleService {
+ String _locale = "en_US";
+
+ @override
+ String get locale => _locale;
+
+ void setLocale(String locale) {
+ _locale = locale;
+ notifyListeners();
+ }
+}
+
/// The mobile camera scanner, returning [rawContent].
class _FakeScanner implements BarcodeScannerInterface {
_FakeScanner(this.rawContent);
@@ -59,6 +71,7 @@ void main() {
late List<PaymentUriData> multiRecipientUris;
late _FakeScanner scanner;
late List<String> messages;
+ late _TestLocaleService localeService;
/// Lays widgets out for desktop or mobile on any host platform.
void useLayout({required bool desktop}) {
@@ -85,24 +98,17 @@ void main() {
clipboard = FakeClipboard();
multiRecipientUris = [];
messages = [];
+ localeService = _TestLocaleService();
container = ProviderContainer(
overrides: [
pAmountUnit.overrideWithProvider(
(_) => Provider((ref) => ref.watch(unit)),
),
- pAmountFormatter.overrideWithProvider(
- (coin) => Provider(
- (ref) => AmountFormatter(
- unit: ref.watch(pAmountUnit(coin)),
- locale: "en_US",
- coin: coin,
- maxDecimals: coin.fractionDigits,
- ),
- ),
- ),
- localeServiceChangeNotifierProvider.overrideWithProvider(
- ChangeNotifierProvider((_) => LocaleService()),
+ // Use the production formatter so locale/provider ordering is tested.
+ pMaxDecimals.overrideWithProvider(
+ (coin) => Provider((_) => coin.fractionDigits),
),
+ localeServiceChangeNotifierProvider.overrideWithValue(localeService),
pClipboard.overrideWithValue(clipboard),
pBarcodeScanner.overrideWithValue(scanner),
],
@@ -267,6 +273,52 @@ void main() {
expect(recipient()!.label, isNull);
});
+ for (final desktop in [false, true]) {
+ testWidgets("keeps the recipient amount across locale changes "
+ "on ${desktop ? 'desktop' : 'mobile'}", (tester) async {
+ useLayout(desktop: desktop);
+ await pumpRecipient(
+ tester,
+ initial: (
+ address: "address0",
+ amount: xmr("1.000000000001"),
+ label: "Alice",
+ ),
+ );
+
+ localeService.setLocale("de_DE");
+ await tester.pump();
+ await tester.pump();
+ expect(text(tester, amountField()), "1,000000000001");
+ expect(
+ recipient(),
+ (address: "address0", amount: xmr("1.000000000001"), label: "Alice"),
+ reason:
+ "Changing locale must preserve the stored amount, "
+ "not just its text",
+ );
+
+ await tester.enterText(amountField(), "2,000000000001");
+ await tester.pump();
+ expect(recipient()?.amount, xmr("2.000000000001"));
+
+ localeService.setLocale("en_US");
+ await tester.pump();
+ await tester.pump();
+ expect(text(tester, amountField()), "2.000000000001");
+ expect(recipient()?.amount, xmr("2.000000000001"));
+ expect(recipient()?.label, "Alice");
+
+ await tester.enterText(addressField(), "address1");
+ await tester.pump();
+ expect(recipient(), (
+ address: "address1",
+ amount: xmr("2.000000000001"),
+ label: null,
+ ));
+ });
+ }
+
testWidgets("fills the address, amount, and name from a pasted request", (
tester,
) async {
### 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/recipient_amount_context_test.dart
@@ -0,0 +1,117 @@
+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/send_view/frost_ms/recipient.dart';
+import 'package:stackwallet/providers/global/locale_provider.dart';
+import 'package:stackwallet/services/locale_service.dart';
+import 'package:stackwallet/themes/stack_colors.dart';
+import 'package:stackwallet/utilities/amount/amount.dart';
+import 'package:stackwallet/utilities/amount/amount_formatter.dart';
+import 'package:stackwallet/utilities/amount/amount_unit.dart';
+import 'package:stackwallet/utilities/util.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import '../../sample_data/theme_json.dart';
+
+class _TestMonero extends Monero {
+ _TestMonero() : super(CryptoCurrencyNetwork.main);
+ @override
+ bool validateAddress(String address) => address.startsWith("address");
+}
+
+class _Locale extends LocaleService {
+ String _locale = "en_US";
+ @override
+ String get locale => _locale;
+ void setLocale(String l) {
+ _locale = l;
+ notifyListeners();
+ }
+}
+
+void main() {
+ final coin = _TestMonero();
+ const RecipientId id = (walletId: "wallet", index: 1);
+ Amount xmr(String v) =>
+ Amount.tryParseCanonicalAmount(v, fractionDigits: coin.fractionDigits)!;
+
+ for (final unitFirst in [false, true]) {
+ testWidgets('recipient same-frame unit+locale unitFirst=$unitFirst', (
+ tester,
+ ) async {
+ final prev = Util.layoutPlatform;
+ Util.layoutPlatform = platform.FakePlatform(operatingSystem: "android");
+ addTearDown(() => Util.layoutPlatform = prev);
+ final unit = StateProvider((_) => AmountUnit.normal);
+ final locale = _Locale();
+ final container = ProviderContainer(
+ overrides: [
+ pAmountUnit.overrideWithProvider(
+ (_) => Provider((ref) => ref.watch(unit)),
+ ),
+ pMaxDecimals.overrideWithProvider(
+ (coin) => Provider((_) => coin.fractionDigits),
+ ),
+ localeServiceChangeNotifierProvider.overrideWithValue(locale),
+ ],
+ );
+ addTearDown(container.dispose);
+ container.read(pRecipient(id).notifier).state = (
+ address: "address0",
+ amount: xmr("1.2501"),
+ label: null,
+ );
+ await tester.pumpWidget(
+ UncontrolledProviderScope(
+ container: container,
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [
+ StackColors.fromStackColorTheme(
+ StackTheme.fromJson(json: lightThemeJsonMap),
+ ),
+ ],
+ ),
+ home: Scaffold(
+ body: SingleChildScrollView(
+ child: Recipient(
+ walletId: id.walletId,
+ index: id.index,
+ displayNumber: 1,
+ coin: coin,
+ remove: () {},
+ addAnotherRecipientTapped: () {},
+ sendAllTapped: () => "",
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ final amountField = find.byKey(
+ const Key("amountInputFieldCryptoTextFieldKey"),
+ );
+ final addressField = find.byKey(const Key("sendViewAddressFieldKey"));
+ String text() => tester.widget<TextField>(amountField).controller!.text;
+ expect(text(), "1.2501");
+
+ if (unitFirst) {
+ container.read(unit.notifier).state = AmountUnit.milli;
+ locale.setLocale("de_DE");
+ } else {
+ locale.setLocale("de_DE");
+ container.read(unit.notifier).state = AmountUnit.milli;
+ }
+ await tester.pump();
+ await tester.pump();
+ expect(text(), "1250,1");
+ expect(container.read(pRecipient(id))?.amount, xmr("1.2501"));
+
+ await tester.enterText(addressField, "address1");
+ await tester.pump();
+ expect(container.read(pRecipient(id))?.amount, xmr("1.2501"));
+ });
+ }
+}
### 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/send_view/token_amount_display_updates_test.dart
@@ -0,0 +1,271 @@
+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/token_send_view.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/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/models/tx_data.dart';
+import 'package:stackwallet/wallets/wallet/impl/sub_wallets/eth_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 {
+ AmountUnit value = AmountUnit.normal;
+ @override
+ bool get enableCoinControl => false;
+ @override
+ bool get externalCalls => false;
+ @override
+ AmountUnit amountUnit(CryptoCurrency coin) => value;
+ @override
+ int maxDecimals(CryptoCurrency coin) => coin.fractionDigits;
+ void change(AmountUnit next) {
+ value = next;
+ notifyListeners();
+ }
+}
+
+class _Price extends PriceService {
+ _Price() : super('USD');
+ @override
+ ({Decimal value, double change24h})? getTokenPrice(String contractAddress) =>
+ (value: Decimal.one, change24h: 0);
+}
+
+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);
+ TxData? captured;
+ @override
+ Future<TxData> prepareSend({required TxData txData, String? assetId}) async {
+ captured = txData;
+ throw StateError('capture');
+ }
+}
+
+void main() {
+ const walletId = 'token-r2';
+ for (final desktop in [false, true]) {
+ for (final decimals in [6, 8, 18]) {
+ for (final unitFirst in [false, true]) {
+ testWidgets(
+ 'token input transitions desktop=$desktop decimals=$decimals unitFirst=$unitFirst',
+ (tester) 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 = Ethereum(CryptoCurrencyNetwork.main);
+ final contract = DefaultTokens.rsFiro.copyWith(decimals: decimals);
+ final info = WalletInfo(
+ walletId: walletId,
+ name: 'Token test',
+ mainAddressType: AddressType.ethereum,
+ coinName: coin.identifier,
+ );
+ final wallet = _ParentWallet(info);
+ final tokenWallet = _TokenWallet(contract, info);
+ final prefs = _Prefs();
+ final locale = _Locale();
+ final zero = Amount.zeroWith(fractionDigits: decimals);
+ final balance = Balance(
+ total: zero,
+ spendable: zero,
+ blockedTotal: zero,
+ pendingSpendable: zero,
+ );
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+ final container = ProviderContainer(
+ overrides: [
+ pWallets.overrideWithValue(ConfirmationWallets(wallet)),
+ pCurrentTokenWallet.overrideWithValue(tokenWallet),
+ pWalletInfo(walletId).overrideWithValue(info),
+ pWalletCoin(walletId).overrideWithValue(coin),
+ pWalletName(walletId).overrideWithValue(info.name),
+ pTokenBalance((
+ walletId: walletId,
+ contractAddress: contract.address,
+ )).overrideWithValue(balance),
+ 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);
+ final child = desktop
+ ? const DesktopTokenSend(walletId: walletId)
+ : TokenSendView(
+ walletId: walletId,
+ coin: coin,
+ tokenContract: contract,
+ );
+ 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);
+ final field = find.byKey(
+ const Key('amountInputFieldCryptoTextFieldKey'),
+ );
+ await tester.enterText(field, '1.250001');
+ await tester.pump(const Duration(milliseconds: 600));
+ if (unitFirst) {
+ prefs.change(AmountUnit.milli);
+ locale.change('de_DE');
+ } else {
+ locale.change('de_DE');
+ prefs.change(AmountUnit.milli);
+ }
+ await tester.pump(const Duration(milliseconds: 600));
+ expect(
+ tester.widget<TextField>(field).controller!.text,
+ '1250,001',
+ );
+ final address = find.byKey(
+ Key(
+ desktop
+ ? 'sendViewAddressFieldKey'
+ : 'tokenSendViewAddressFieldKey',
+ ),
+ );
+ await tester.enterText(
+ address,
+ '0x2744ea5ac9b11cb5e3cd63d3a88e858336aeddc2',
+ );
+ await tester.pump();
+ if (desktop) {
+ final preview = tester.widget<PrimaryButton>(
+ find.widgetWithText(PrimaryButton, 'Preview send'),
+ );
+ expect(preview.enabled, true);
+ 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.tryParseCanonicalAmount(
+ '1.250001',
+ fractionDigits: decimals,
+ ),
+ );
+ expect(amount.fractionDigits, decimals);
+ await tester.pumpWidget(const SizedBox.shrink());
+ await tester.pumpAndSettle();
+ },
+ );
+ }
+ }
+ }
+}
### 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/pages/wallet_view/transaction_views/transaction_search_filter_view_test.dart
@@ -1,24 +1,17 @@
import "package:flutter_test/flutter_test.dart";
import "package:stackwallet/pages/wallet_view/transaction_views/transaction_search_filter_view.dart";
-import "package:stackwallet/utilities/amount/amount_formatter.dart";
import "package:stackwallet/utilities/amount/amount_unit.dart";
import "package:stackwallet/wallets/crypto_currency/crypto_currency.dart";
void main() {
- AmountFormatter formatter(String locale) => AmountFormatter(
- unit: AmountUnit.normal,
- locale: locale,
- coin: Bitcoin(CryptoCurrencyNetwork.main),
- maxDecimals: 8,
- );
-
test("transaction filter distinguishes empty from malformed amounts", () {
for (final text in ["", "."]) {
expect(
parseTransactionFilterAmountInput(
text: text,
locale: "en_US",
- formatter: formatter("en_US"),
+ unit: AmountUnit.normal,
+ coin: Bitcoin(CryptoCurrencyNetwork.main),
),
(isValid: true, amount: null),
reason: text,
@@ -28,7 +21,8 @@ void main() {
final trailingSeparator = parseTransactionFilterAmountInput(
text: "1.",
locale: "en_US",
- formatter: formatter("en_US"),
+ unit: AmountUnit.normal,
+ coin: Bitcoin(CryptoCurrencyNetwork.main),
);
expect(trailingSeparator.isValid, isTrue);
expect(trailingSeparator.amount?.raw, BigInt.from(100000000));
@@ -38,7 +32,8 @@ void main() {
parseTransactionFilterAmountInput(
text: text,
locale: "en_US",
- formatter: formatter("en_US"),
+ unit: AmountUnit.normal,
+ coin: Bitcoin(CryptoCurrencyNetwork.main),
).isValid,
isFalse,
reason: text,
@@ -51,15 +46,17 @@ void main() {
parseTransactionFilterAmountInput(
text: ",",
locale: "de_DE",
- formatter: formatter("de_DE"),
+ unit: AmountUnit.normal,
+ coin: Bitcoin(CryptoCurrencyNetwork.main),
),
(isValid: true, amount: null),
);
expect(
parseTransactionFilterAmountInput(
text: "1,,",
locale: "de_DE",
- formatter: formatter("de_DE"),
+ unit: AmountUnit.normal,
+ coin: Bitcoin(CryptoCurrencyNetwork.main),
).isValid,
isFalse,
);
### 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/address_book_service_test.dart
@@ -0,0 +1,145 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
+import 'package:stackwallet/models/isar/models/contact_entry.dart';
+import 'package:stackwallet/services/address_book_service.dart';
+import 'package:stackwallet/wallets/crypto_currency/coins/firo.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/spark_interface.dart';
+
+class _TestAddressBookService extends AddressBookService {
+ final writes = <ContactEntry>[];
+
+ @override
+ Future<bool> editContact(ContactEntry editedContact) async {
+ writes.add(editedContact);
+ return true;
+ }
+}
+
+class _TestWallet extends Mock implements Wallet {
+ _TestWallet({required this.info, required this.loadAddress});
+
+ @override
+ final WalletInfo info;
+
+ final Future<Address?> Function() loadAddress;
+
+ @override
+ Future<Address?> getCurrentReceivingAddress() => loadAddress();
+}
+
+class _TestSparkWallet extends Mock
+ implements Wallet<Firo>, SparkInterface<Firo> {
+ _TestSparkWallet({required this.info});
+
+ @override
+ final WalletInfo info;
+
+ @override
+ bool get isViewOnly => false;
+
+ @override
+ Future<Address?> getCurrentReceivingSparkAddress() async => null;
+
+ @override
+ Future<Address> generateNextSparkAddress({required bool saveToDB}) =>
+ throw Exception("spark address generation failed");
+}
+
+WalletInfo _walletInfo(String id) => WalletInfo(
+ walletId: id,
+ name: id,
+ mainAddressType: AddressType.p2wpkh,
+ coinName: "bitcoin",
+ cachedReceivingAddress: "cached-$id",
+);
+
+Address _address(String walletId) => Address(
+ walletId: walletId,
+ value: "address-$walletId",
+ publicKey: const [],
+ derivationIndex: 0,
+ derivationPath: null,
+ type: AddressType.p2wpkh,
+ subType: AddressSubType.receiving,
+);
+
+void main() {
+ test("uses the cached address for a wallet that fails", () async {
+ final service = _TestAddressBookService();
+ final goodWallet = _TestWallet(
+ info: _walletInfo("good"),
+ loadAddress: () async => _address("good"),
+ );
+ final failingWallet = _TestWallet(
+ info: _walletInfo("failing"),
+ loadAddress: () async => throw Exception("temporary failure"),
+ );
+
+ await service.updateMyStackContact([goodWallet, failingWallet]);
+
+ expect(service.writes, hasLength(1));
+ expect(service.writes.single.addresses.map((e) => e.address), [
+ "address-good",
+ "cached-failing",
+ ]);
+ });
+
+ test("leaves out a Spark wallet whose Spark address fails", () async {
+ final service = _TestAddressBookService();
+ final goodWallet = _TestWallet(
+ info: _walletInfo("good"),
+ loadAddress: () async => _address("good"),
+ );
+ final sparkWallet = _TestSparkWallet(
+ info: WalletInfo(
+ walletId: "firo",
+ name: "firo",
+ mainAddressType: AddressType.p2pkh,
+ coinName: "firo",
+ cachedReceivingAddress: "transparent-firo",
+ ),
+ );
+
+ await service.updateMyStackContact([goodWallet, sparkWallet]);
+
+ expect(service.writes, hasLength(1));
+ expect(service.writes.single.addresses.map((e) => e.address), [
+ "address-good",
+ ]);
+ });
+
+ test("serializes My Stack updates in call order", () async {
+ final service = _TestAddressBookService();
+ final firstStarted = Completer<void>();
+ final firstAddress = Completer<Address?>();
+ final firstWallet = _TestWallet(
+ info: _walletInfo("first"),
+ loadAddress: () {
+ firstStarted.complete();
+ return firstAddress.future;
+ },
+ );
+ final secondWallet = _TestWallet(
+ info: _walletInfo("second"),
+ loadAddress: () async => _address("second"),
+ );
+
+ final firstUpdate = service.updateMyStackContact([firstWallet]);
+ await firstStarted.future;
+ final secondUpdate = service.updateMyStackContact([secondWallet]);
+ await Future<void>.delayed(Duration.zero);
+
+ expect(service.writes, isEmpty);
+
+ firstAddress.complete(_address("first"));
+ await Future.wait([firstUpdate, secondUpdate]);
+
+ expect(service.writes, hasLength(2));
+ expect(service.writes.last.addresses.single.address, "address-second");
+ });
+}
### 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/amount/amount_unit_test.dart
@@ -4,6 +4,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:stackwallet/models/isar/models/solana/sol_contract.dart';
import 'package:stackwallet/utilities/amount/amount.dart';
import 'package:stackwallet/utilities/amount/amount_formatter.dart';
+import 'package:stackwallet/utilities/amount/amount_parser.dart';
import 'package:stackwallet/utilities/amount/amount_input_formatter.dart';
import 'package:stackwallet/utilities/amount/amount_unit.dart';
import 'package:stackwallet/utilities/util.dart';
@@ -217,7 +218,15 @@ void main() {
maxDecimals: 8,
);
- expect(formatter.tryParseEditable("5")?.decimal, Decimal.fromInt(5));
+ expect(
+ AmountParser.tryParseEditable(
+ "5",
+ locale: formatter.locale,
+ unit: formatter.unit,
+ coin: formatter.coin,
+ )?.decimal,
+ Decimal.fromInt(5),
+ );
for (final value in [
"+5",
@@ -226,15 +235,32 @@ void main() {
for (final codePoint in [0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x20])
"1${String.fromCharCode(codePoint)}234",
]) {
- expect(formatter.tryParseEditable(value), isNull, reason: value);
+ expect(
+ AmountParser.tryParseEditable(
+ value,
+ locale: formatter.locale,
+ unit: formatter.unit,
+ coin: formatter.coin,
+ ),
+ isNull,
+ reason: value,
+ );
expect(
Amount.tryParseFiatString(value, locale: "en_US"),
isNull,
reason: value,
);
}
- expect(formatter.tryParseEditable("0.000000001"), isNull);
+ expect(
+ AmountParser.tryParseEditable(
+ "0.000000001",
+ locale: formatter.locale,
+ unit: formatter.unit,
+ coin: formatter.coin,
+ ),
+ isNull,
+ );
expect(Amount.tryParseFiatString("1.001", locale: "en_US"), isNull);
expect(
@@ -790,7 +816,12 @@ void main() {
);
final text = formatter.formatEditable(amount);
expect(
- formatter.tryParseEditable(text),
+ AmountParser.tryParseEditable(
+ text,
+ locale: formatter.locale,
+ unit: formatter.unit,
+ coin: formatter.coin,
+ ),
amount,
reason: "$locale $unit $text",
);
### test/utilities/camera_preview_capture_test.dart
@@ -0,0 +1,150 @@
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:image/image.dart' as img;
+import 'package:stackwallet/utilities/camera_preview_frame.dart';
+import 'package:zxing2/qrcode.dart';
+
+const _text = "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq";
+
+/// Paints a QR code with a red marker in its top-left corner, so a capture
+/// shows whether it was flipped.
+class _QrPainter extends CustomPainter {
+ _QrPainter(this.modules);
+
+ /// True for dark modules, row by row.
+ final List<List<bool>> modules;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ canvas.drawRect(Offset.zero & size, Paint()..color = Colors.white);
+ const border = 4;
+ final module = size.width / (modules.length + 2 * border);
+ final black = Paint()
+ ..color = Colors.black
+ // Hairline seams between anti-aliased modules throw off zxing.
+ ..isAntiAlias = false;
+ for (var y = 0; y < modules.length; y++) {
+ for (var x = 0; x < modules[y].length; x++) {
+ if (modules[y][x]) {
+ canvas.drawRect(
+ Rect.fromLTWH(
+ (x + border) * module,
+ (y + border) * module,
+ module,
+ module,
+ ),
+ black,
+ );
+ }
+ }
+ }
+ canvas.drawRect(
+ Rect.fromLTWH(0, 0, module * 2, module * 2),
+ Paint()..color = const Color(0xFFFF0000),
+ );
+ }
+
+ @override
+ bool shouldRepaint(_QrPainter oldDelegate) => false;
+}
+
+void main() {
+ testWidgets("reads a QR code back from a mirrored preview capture", (
+ tester,
+ ) async {
+ final matrix = Encoder.encode(_text, ErrorCorrectionLevel.m).matrix!;
+ final modules = [
+ for (var y = 0; y < matrix.height; y++)
+ [for (var x = 0; x < matrix.width; x++) matrix.get(x, y) == 1],
+ ];
+ // Whole logical pixels per module.
+ final side = (modules.length + 8) * 4.0;
+ final key = GlobalKey();
+ await tester.pumpWidget(
+ Center(
+ child: RepaintBoundary(
+ key: key,
+ child: SizedBox(
+ width: side,
+ height: side,
+ // Mirrored like the camera_windows preview.
+ child: Transform.flip(
+ flipX: true,
+ child: CustomPaint(painter: _QrPainter(modules)),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ final boundary =
+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final (width, height, rgba) = (await tester.runAsync(() async {
+ final frame = await boundary.toImage(pixelRatio: 2);
+ try {
+ final bytes = await frame.toByteData(
+ format: ui.ImageByteFormat.rawRgba,
+ );
+ return (frame.width, frame.height, bytes!.buffer.asUint8List());
+ } finally {
+ frame.dispose();
+ }
+ }))!;
+
+ expect((width, height), (side * 2, side * 2));
+ expect(blankPreviewFrame(rgba), isNull);
+
+ final image = imageFromMirroredPreviewRgba(
+ rgba,
+ width: width,
+ height: height,
+ );
+
+ // The marker is back in the top-left once flipped.
+ final marker = image.getPixel(4, 4);
+ expect([marker.r, marker.g, marker.b], [255, 0, 0]);
+ final opposite = image.getPixel(width - 5, 4);
+ expect([opposite.r, opposite.g, opposite.b], [255, 255, 255]);
+
+ final source = RGBLuminanceSource(
+ width,
+ height,
+ image.getBytes(order: img.ChannelOrder.abgr).buffer.asInt32List(),
+ );
+ final result = QRCodeReader().decode(BinaryBitmap(HybridBinarizer(source)));
+ expect(result.text, _text);
+ });
+
+ testWidgets("sees a capture with nothing painted as transparent", (
+ tester,
+ ) async {
+ final key = GlobalKey();
+ await tester.pumpWidget(
+ Center(
+ child: RepaintBoundary(
+ key: key,
+ child: const SizedBox(width: 50, height: 40),
+ ),
+ ),
+ );
+
+ final boundary =
+ key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final rgba = (await tester.runAsync(() async {
+ final frame = await boundary.toImage();
+ try {
+ final bytes = await frame.toByteData(
+ format: ui.ImageByteFormat.rawRgba,
+ );
+ return bytes!.buffer.asUint8List();
+ } finally {
+ frame.dispose();
+ }
+ }))!;
+
+ expect(blankPreviewFrame(rgba), BlankPreviewFrame.transparent);
+ });
+}
### test/utilities/camera_preview_frame_test.dart
@@ -0,0 +1,169 @@
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:image/image.dart' as img;
+import 'package:stackwallet/utilities/camera_preview_frame.dart';
+
+/// Packs one RGBA pixel per entry, in row order.
+Uint8List _rgba(List<List<int>> pixels) =>
+ Uint8List.fromList([for (final p in pixels) ...p]);
+
+void main() {
+ group("imageFromMirroredPreviewRgba", () {
+ test("flips each row back", () {
+ // 3x2, every pixel distinct.
+ final rgba = _rgba([
+ [1, 2, 3, 255], [4, 5, 6, 255], [7, 8, 9, 255], //
+ [10, 11, 12, 255], [13, 14, 15, 255], [16, 17, 18, 255],
+ ]);
+
+ final image = imageFromMirroredPreviewRgba(rgba, width: 3, height: 2);
+
+ expect(image.width, 3);
+ expect(image.height, 2);
+ expect(image.numChannels, 4);
+ List<num> rgbaAt(int x, int y) {
+ final p = image.getPixel(x, y);
+ return [p.r, p.g, p.b, p.a];
+ }
+
+ expect(rgbaAt(0, 0), [7, 8, 9, 255]);
+ expect(rgbaAt(1, 0), [4, 5, 6, 255]);
+ expect(rgbaAt(2, 0), [1, 2, 3, 255]);
+ expect(rgbaAt(0, 1), [16, 17, 18, 255]);
+ expect(rgbaAt(2, 1), [10, 11, 12, 255]);
+ });
+
+ test("undoes a mirrored capture of a whole image", () {
+ final original = img.Image(width: 40, height: 30, numChannels: 4);
+ for (final p in original) {
+ p
+ ..r = (p.x * 6) % 256
+ ..g = (p.y * 8) % 256
+ ..b = (p.x + p.y) % 256
+ ..a = 255;
+ }
+ final mirrored = img.flipHorizontal(original.clone());
+ final rgba = mirrored.getBytes(order: img.ChannelOrder.rgba);
+
+ final image = imageFromMirroredPreviewRgba(rgba, width: 40, height: 30);
+
+ expect(
+ image.getBytes(order: img.ChannelOrder.rgba),
+ original.getBytes(order: img.ChannelOrder.rgba),
+ );
+ });
+
+ test("accepts bytes at an unaligned offset", () {
+ final backing = Uint8List(1 + 2 * 4);
+ backing.setAll(1, [1, 2, 3, 255, 4, 5, 6, 255]);
+ final view = Uint8List.view(backing.buffer, 1, 8);
+
+ final image = imageFromMirroredPreviewRgba(view, width: 2, height: 1);
+
+ expect(image.getPixel(0, 0).r, 4);
+ expect(image.getPixel(1, 0).r, 1);
+ });
+
+ test("rejects a buffer that is too short", () {
+ expect(
+ () => imageFromMirroredPreviewRgba(Uint8List(15), width: 2, height: 2),
+ throwsArgumentError,
+ );
+ expect(
+ () => imageFromMirroredPreviewRgba(Uint8List(0), width: 0, height: 0),
+ throwsArgumentError,
+ );
+ });
+ });
+
+ group("blankPreviewFrame", () {
+ test("reports a frame with nothing drawn as transparent", () {
+ expect(
+ blankPreviewFrame(Uint8List(4 * 16)),
+ BlankPreviewFrame.transparent,
+ );
+ expect(blankPreviewFrame(Uint8List(0)), BlankPreviewFrame.transparent);
+ });
+
+ test("reports black and near-black frames as black", () {
+ expect(
+ blankPreviewFrame(_rgba(List.filled(16, [0, 0, 0, 255]))),
+ BlankPreviewFrame.black,
+ );
+ expect(
+ blankPreviewFrame(
+ _rgba([
+ [3, 9, 1, 255],
+ [16, 12, 0, 255],
+ [0, 0, 0, 0],
+ ]),
+ ),
+ BlankPreviewFrame.black,
+ );
+ });
+
+ test("accepts a frame with any picture content", () {
+ expect(
+ blankPreviewFrame(
+ _rgba([
+ [0, 0, 0, 0],
+ [0, 0, 0, 255],
+ [0, 0, 200, 255],
+ ]),
+ ),
+ isNull,
+ );
+ });
+
+ test("ignores color in fully transparent pixels", () {
+ expect(
+ blankPreviewFrame(
+ _rgba([
+ [255, 255, 255, 0],
+ [0, 0, 0, 0],
+ ]),
+ ),
+ BlankPreviewFrame.transparent,
+ );
+ });
+ });
+
+ group("previewFrameFingerprint", () {
+ test("is the same for identical frames", () {
+ final a = Uint8List.fromList(
+ List.generate(4 * 64, (i) => (i * 7) & 0xff),
+ );
+ final b = Uint8List.fromList(a);
+ expect(previewFrameFingerprint(a), previewFrameFingerprint(b));
+ });
+
+ test("changes when one byte changes", () {
+ final a = Uint8List.fromList(
+ List.generate(4 * 64, (i) => (i * 7) & 0xff),
+ );
+ final b = Uint8List.fromList(a);
+ b[b.length ~/ 2] ^= 1;
+ expect(previewFrameFingerprint(a), isNot(previewFrameFingerprint(b)));
+ });
+
+ test("changes when a pixel is moved", () {
+ // Same bytes, different order: a plain sum would miss this.
+ final a = _rgba([
+ [1, 2, 3, 255],
+ [4, 5, 6, 255],
+ ]);
+ final b = _rgba([
+ [4, 5, 6, 255],
+ [1, 2, 3, 255],
+ ]);
+ expect(previewFrameFingerprint(a), isNot(previewFrameFingerprint(b)));
+ });
+
+ test("distinguishes frames of different lengths", () {
+ final a = Uint8List(16);
+ final b = Uint8List(20);
+ expect(previewFrameFingerprint(a), isNot(previewFrameFingerprint(b)));
+ });
+ });
+}
### 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/utilities/native_library_check_test.dart
@@ -0,0 +1,239 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/native_library_check.dart';
+
+const _exe = r"C:\Program Files\Stack Wallet\stack_wallet.exe";
+const _dll = "monero_libwallet2_api_c.dll";
+const _path = r"C:\Program Files\Stack Wallet\monero_libwallet2_api_c.dll";
+
+// Messages from a tester's Windows log.
+const _blocked =
+ "Failed to load dynamic library '$_dll': Operation did not complete "
+ "successfully because the file contains a virus or potentially unwanted "
+ "software.\n (error code: 225)";
+const _notFound =
+ "Failed to load dynamic library '$_dll': The specified module could not "
+ "be found.\n (error code: 126)";
+
+final _monero = nativeLibraries[0];
+final _salvium = nativeLibraries[2];
+
+NativeLibraryCheckResult? _check(String? error, {required bool exists}) =>
+ checkNativeLibrary(
+ _dll,
+ os: "windows",
+ executable: _exe,
+ open: (_) {
+ if (error != null) throw ArgumentError(error);
+ },
+ exists: (path) {
+ expect(path, _path);
+ return exists;
+ },
+ );
+
+/// Runs the startup check over the whole table on Windows with [failing]
+/// files refusing to open, and returns what it recorded.
+List<NativeLibraryFailure> _startup(
+ Set<String> failing, {
+ List<NativeLibrary> libraries = nativeLibraries,
+}) {
+ checkNativeLibrariesOnStartup(
+ libraries: libraries,
+ os: "windows",
+ executable: _exe,
+ open: (name) {
+ if (failing.contains(name)) throw ArgumentError(_notFound);
+ },
+ exists: (path) => !failing.contains(path.split(r"\").last),
+ );
+ return takeNativeLibraryFailures();
+}
+
+void main() {
+ late Directory logDir;
+
+ setUpAll(() async {
+ logDir = await Directory.systemTemp.createTemp("native_lib_check_test");
+ await Logging.instance.initialize(logDir.path, level: Level.off);
+ });
+
+ tearDownAll(() => logDir.delete(recursive: true));
+
+ tearDown(takeNativeLibraryFailures);
+
+ test("file names", () {
+ expect(_monero.fileName("windows"), _dll);
+ expect(_salvium.fileName("linux"), "salvium_libwallet2_api_c.so");
+ expect(
+ nativeLibraries[1].fileName("macos"),
+ "WowneroWallet.framework/WowneroWallet",
+ );
+ expect(_monero.fileName("android"), isNull);
+ expect(secp256k1NativeLibrary.fileName("windows"), "secp256k1.dll");
+ expect(secp256k1NativeLibrary.fileName("linux"), "libsecp256k1.so");
+ expect(
+ secp256k1NativeLibrary.fileName("macos"),
+ "secp256k1.framework/secp256k1",
+ );
+ expect(nativeLibraries.last, same(secp256k1NativeLibrary));
+ });
+
+ test("bundle paths", () {
+ expect(nativeLibraryPath(_dll, "windows", _exe), _path);
+ expect(
+ nativeLibraryPath("a.so", "linux", "/opt/sw/stack_wallet"),
+ "/opt/sw/lib/a.so",
+ );
+ expect(
+ nativeLibraryPath("M.framework/M", "macos", "/A/S.app/Contents/MacOS/S"),
+ "/A/S.app/Contents/Frameworks/M.framework/M",
+ );
+ expect(
+ nativeLibraryPath("libsecp256k1.so", "linux", "/opt/sw/stack_wallet"),
+ "/opt/sw/lib/libsecp256k1.so",
+ );
+ });
+
+ test("loads", () {
+ expect(_check(null, exists: true), isNull);
+ });
+
+ test("quarantined away", () {
+ expect(
+ _check(_notFound, exists: false)!.problem,
+ NativeLibraryProblem.missing,
+ );
+ });
+
+ test("blocked by antivirus", () {
+ expect(
+ _check(_blocked, exists: true)!.problem,
+ NativeLibraryProblem.blockedByAntivirus,
+ );
+ });
+
+ test("other failure", () {
+ final result = _check(_notFound, exists: true)!;
+ expect(result.problem, NativeLibraryProblem.loadFailed);
+ final message = nativeLibraryErrorMessage("Monero wallets", result);
+ expect(message, startsWith("Monero wallets can't be used"));
+ expect(message, contains(_path));
+ expect(message, contains("error code: 126"));
+ });
+
+ group("startup check", () {
+ test("records nothing when everything loads", () {
+ expect(_startup({}), isEmpty);
+ });
+
+ test("records failures in table order", () {
+ final failures = _startup({"secp256k1.dll", _dll});
+ expect(failures.map((f) => f.displayName), [
+ "Monero wallets",
+ "Most wallets",
+ ]);
+ expect(failures.first.result.problem, NativeLibraryProblem.missing);
+ expect(failures.first.result.path, _path);
+ });
+
+ test("failures are handed over once", () {
+ _startup({_dll});
+ expect(takeNativeLibraryFailures(), isEmpty);
+ });
+
+ test("skips libraries this build does not ship", () {
+ final failures = _startup(
+ {_dll},
+ libraries: [
+ NativeLibrary(
+ displayName: "Monero wallets",
+ windows: _dll,
+ linux: "x.so",
+ macos: "X.framework/X",
+ isBundled: () => false,
+ ),
+ ],
+ );
+ expect(failures, isEmpty);
+ });
+
+ test("does nothing on mobile", () {
+ checkNativeLibrariesOnStartup(
+ os: "android",
+ executable: "/data/app/stack_wallet",
+ open: (_) => throw ArgumentError(_notFound),
+ exists: (_) => false,
+ );
+ expect(takeNativeLibraryFailures(), isEmpty);
+ });
+
+ test("a check that blows up counts as a pass", () {
+ checkNativeLibrariesOnStartup(
+ os: "windows",
+ executable: _exe,
+ open: (_) => throw ArgumentError(_notFound),
+ exists: (_) => throw StateError("no file system"),
+ );
+ expect(takeNativeLibraryFailures(), isEmpty);
+ });
+
+ test("one entry blowing up does not hide the others", () async {
+ await loadCoinlibOrRecordFailure(() async => throw ArgumentError("x"));
+ checkNativeLibrariesOnStartup(
+ os: "windows",
+ executable: _exe,
+ open: (name) {
+ if (name != "salvium_libwallet2_api_c.dll") {
+ throw ArgumentError(_notFound);
+ }
+ },
+ // The Monero entry's file system check dies; Wownero's file is
+ // present but won't load; secp256k1's check dies too.
+ exists: (path) {
+ if (path.contains("monero") || path.contains("secp")) {
+ throw StateError("no file system");
+ }
+ return true;
+ },
+ );
+ final failures = takeNativeLibraryFailures();
+ expect(failures.map((f) => f.displayName), [
+ "Wownero wallets",
+ "Most wallets",
+ ]);
+ expect(failures.first.result.problem, NativeLibraryProblem.loadFailed);
+ expect(failures.last.result.error, contains("x"));
+ });
+
+ test("a coinlib error is reported against secp256k1", () async {
+ await loadCoinlibOrRecordFailure(
+ () async => throw StateError("secp256k1_context_create not found"),
+ );
+ final failures = _startup({});
+ expect(failures.map((f) => f.displayName), ["Most wallets"]);
+ expect(failures.single.result.problem, NativeLibraryProblem.loadFailed);
+ expect(failures.single.result.error, contains("secp256k1_context"));
+ expect(
+ failures.single.result.path,
+ r"C:\Program Files\Stack Wallet\secp256k1.dll",
+ );
+ });
+
+ test("a missing secp256k1 is reported once", () async {
+ await loadCoinlibOrRecordFailure(() async => throw ArgumentError(""));
+ final failures = _startup({"secp256k1.dll"});
+ expect(failures.map((f) => f.displayName), ["Most wallets"]);
+ expect(failures.single.result.problem, NativeLibraryProblem.missing);
+ });
+
+ test("a coinlib error is forgotten after one check", () async {
+ await loadCoinlibOrRecordFailure(() async => throw ArgumentError(""));
+ _startup({});
+ expect(_startup({}), isEmpty);
+ });
+ });
+}
### test/utilities/qr_image_decoder_test.dart
@@ -0,0 +1,113 @@
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:image/image.dart' as img;
+import 'package:stackwallet/utilities/qr_image_decoder.dart';
+import 'package:zxing2/qrcode.dart';
+
+const _address = "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq";
+
+/// Renders [text] as a black-on-white QR code in 8-bit RGB.
+img.Image _qrImage(String text, {int scale = 8, int border = 4}) {
+ final matrix = Encoder.encode(text, ErrorCorrectionLevel.m).matrix!;
+ final size = (matrix.width + 2 * border) * scale;
+ final image = img.Image(width: size, height: size);
+ img.fill(image, color: img.ColorRgb8(255, 255, 255));
+ for (var y = 0; y < matrix.height; y++) {
+ for (var x = 0; x < matrix.width; x++) {
+ if (matrix.get(x, y) == 1) {
+ img.fillRect(
+ image,
+ x1: (x + border) * scale,
+ y1: (y + border) * scale,
+ x2: (x + border + 1) * scale - 1,
+ y2: (y + border + 1) * scale - 1,
+ color: img.ColorRgb8(0, 0, 0),
+ );
+ }
+ }
+ }
+ return image;
+}
+
+Uint8List _png(img.Image image) => Uint8List.fromList(img.encodePng(image));
+
+void main() {
+ final rgb = _qrImage(_address);
+
+ final variants = <String, img.Image>{
+ "1-bit grayscale": rgb.convert(format: img.Format.uint1, numChannels: 1),
+ "1-bit palette": rgb.convert(
+ format: img.Format.uint1,
+ numChannels: 1,
+ withPalette: true,
+ ),
+ "8-bit grayscale": rgb.convert(numChannels: 1),
+ "8-bit palette": img.quantize(rgb, numberOfColors: 2),
+ "16-bit grayscale": rgb.convert(format: img.Format.uint16, numChannels: 1),
+ "8-bit RGB": rgb,
+ "8-bit RGBA": rgb.convert(numChannels: 4),
+ };
+
+ for (final entry in variants.entries) {
+ test("decodes a ${entry.key} PNG", () {
+ final bytes = _png(entry.value);
+ final decoded = img.decodePng(bytes)!;
+ expect(decoded.width, rgb.width);
+ expect(decodeQrFromImageBytes(bytes), _address);
+ });
+ }
+
+ test("decodes a 1-bit PNG with a 1-bit format after decoding", () {
+ final decoded = img.decodePng(
+ _png(rgb.convert(format: img.Format.uint1, numChannels: 1)),
+ )!;
+ // This is the case the old code got wrong: convert(numChannels: 4) kept
+ // the 1-bit format and handed bit-packed bytes to RGBLuminanceSource.
+ expect(decoded.format, img.Format.uint1);
+ expect(decodeQrFromImage(decoded), _address);
+ });
+
+ test("decodes a large camera-sized frame scaled down to maxDimension", () {
+ // A QR code held up to a 3264x2448 webcam, filling about a third of the
+ // frame's height.
+ final frame = img.Image(width: 3264, height: 2448);
+ img.fill(frame, color: img.ColorRgb8(200, 200, 200));
+ final code = _qrImage(_address, scale: 18);
+ img.compositeImage(frame, code, dstX: 1200, dstY: 700);
+ final jpeg = img.decodeJpg(img.encodeJpg(frame, quality: 85))!;
+ expect(decodeQrFromImage(jpeg, maxDimension: 1280), _address);
+ });
+
+ test("leaves images within maxDimension alone", () {
+ expect(decodeQrFromImage(rgb, maxDimension: 1280), _address);
+ });
+
+ test("decodes a JPEG", () {
+ final bytes = Uint8List.fromList(img.encodeJpg(rgb, quality: 85));
+ expect(decodeQrFromImageBytes(bytes), _address);
+ });
+
+ test("decodes a black-on-transparent RGBA PNG", () {
+ final image = img.Image(
+ width: rgb.width,
+ height: rgb.height,
+ numChannels: 4,
+ );
+ for (final p in rgb) {
+ final dark = p.r < 128;
+ image.setPixelRgba(p.x, p.y, 0, 0, 0, dark ? 255 : 0);
+ }
+ expect(decodeQrFromImageBytes(_png(image)), _address);
+ });
+
+ test("returns null for an image without a QR code", () {
+ final blank = img.Image(width: 64, height: 64);
+ img.fill(blank, color: img.ColorRgb8(255, 255, 255));
+ expect(decodeQrFromImageBytes(_png(blank)), isNull);
+ });
+
+ test("returns null for bytes that are not an image", () {
+ expect(decodeQrFromImageBytes(Uint8List.fromList([1, 2, 3, 4])), isNull);
+ });
+}
### 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/ethereum_tor_proxy_test.dart
@@ -0,0 +1,258 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/wallets/wallet/impl/ethereum_wallet.dart';
+
+class _MockPrefs extends Mock implements Prefs {
+ _MockPrefs(this.useTor);
+
+ @override
+ bool useTor;
+}
+
+class _FakeTorService extends Fake implements TorService {
+ _FakeTorService(this.proxyInfo);
+
+ final ({InternetAddress host, int port}) proxyInfo;
+ int proxyInfoReads = 0;
+
+ @override
+ ({InternetAddress host, int port}) getProxyInfo() {
+ proxyInfoReads++;
+ return proxyInfo;
+ }
+}
+
+const _rpcBody = '{"jsonrpc":"2.0","id":0,"result":"0x2a"}';
+
+String _rpcHttpResponse() =>
+ 'HTTP/1.1 200 OK\r\n'
+ 'Content-Type: application/json\r\n'
+ 'Content-Length: ${_rpcBody.length}\r\n'
+ 'Connection: close\r\n\r\n'
+ '$_rpcBody';
+
+// Minimal SOCKS5 server that records the CONNECT target and answers the
+// tunnelled HTTP request with a canned JSON-RPC eth_blockNumber result.
+class _FakeSocksServer {
+ late final ServerSocket _server;
+ int connections = 0;
+ int? addressType;
+ String? target;
+ int? port;
+ final request = StringBuffer();
+
+ int get listeningPort => _server.port;
+
+ Future<void> start() async {
+ _server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ _server.listen((socket) {
+ connections++;
+ var stage = 0;
+ socket.listen((Uint8List bytes) {
+ switch (stage) {
+ case 0:
+ socket.add([0x05, 0x00]);
+ stage = 1;
+ case 1:
+ addressType = bytes[3];
+ if (addressType == 0x03) {
+ target = String.fromCharCodes(bytes.sublist(5, 5 + bytes[4]));
+ } else {
+ target = bytes.sublist(4, bytes.length - 2).join('.');
+ }
+ port = (bytes[bytes.length - 2] << 8) | bytes[bytes.length - 1];
+ socket.add([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]);
+ stage = 2;
+ case 2:
+ request.write(utf8.decode(bytes, allowMalformed: true));
+ socket.write(_rpcHttpResponse());
+ socket.close();
+ stage = 3;
+ default:
+ request.write(utf8.decode(bytes, allowMalformed: true));
+ }
+ });
+ });
+ }
+
+ Future<void> stop() => _server.close();
+}
+
+// Local node that answers every RPC with the canned result and counts them.
+class _FakeNode {
+ late final HttpServer _server;
+ int requests = 0;
+
+ String get url => 'http://127.0.0.1:${_server.port}';
+
+ Future<void> start() async {
+ _server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ _server.listen((req) async {
+ requests++;
+ await utf8.decoder.bind(req).join();
+ req.response
+ ..headers.contentType = ContentType.json
+ ..write(_rpcBody);
+ await req.response.close();
+ });
+ }
+
+ Future<void> stop() => _server.close(force: true);
+}
+
+final _torPreferenceChanged = throwsA(
+ isA<StateError>().having(
+ (e) => e.message,
+ 'message',
+ contains('Tor preference changed'),
+ ),
+);
+
+void main() {
+ late _FakeSocksServer socks;
+
+ setUp(() async {
+ socks = _FakeSocksServer();
+ await socks.start();
+ });
+
+ tearDown(() => socks.stop());
+
+ test('web3 client sends RPC through the Tor SOCKS5 proxy', () async {
+ final torService = _FakeTorService((
+ host: InternetAddress.loopbackIPv4,
+ port: socks.listeningPort,
+ ));
+ final client = EthereumWallet.createWeb3Client(
+ 'http://eth.example.invalid:8545',
+ _MockPrefs(true),
+ torService,
+ );
+
+ final height = await client.getBlockNumber();
+ await client.dispose();
+
+ expect(height, 42);
+ expect(torService.proxyInfoReads, 1);
+ // Hostname goes to the proxy, so there is no local DNS lookup.
+ expect(socks.addressType, 0x03);
+ expect(socks.target, 'eth.example.invalid');
+ expect(socks.port, 8545);
+ expect(socks.request.toString(), contains('eth_blockNumber'));
+ });
+
+ test('web3 client connects directly when Tor is off', () async {
+ final node = _FakeNode();
+ await node.start();
+
+ final torService = _FakeTorService((
+ host: InternetAddress.loopbackIPv4,
+ port: socks.listeningPort,
+ ));
+ final client = EthereumWallet.createWeb3Client(
+ node.url,
+ _MockPrefs(false),
+ torService,
+ );
+
+ final height = await client.getBlockNumber();
+ await client.dispose();
+ await node.stop();
+
+ expect(height, 42);
+ expect(node.requests, 1);
+ expect(torService.proxyInfoReads, 0);
+ expect(socks.target, isNull);
+ });
+
+ group('tor preference changed after the client was built', () {
+ late _FakeNode node;
+ late _FakeTorService torService;
+
+ setUp(() async {
+ node = _FakeNode();
+ await node.start();
+ torService = _FakeTorService((
+ host: InternetAddress.loopbackIPv4,
+ port: socks.listeningPort,
+ ));
+ });
+
+ tearDown(() => node.stop());
+
+ test('client built with Tor off refuses to send once Tor is on', () async {
+ final prefs = _MockPrefs(false);
+ final client = EthereumWallet.createWeb3Client(
+ node.url,
+ prefs,
+ torService,
+ );
+
+ expect(await client.getBlockNumber(), 42);
+ expect(node.requests, 1);
+
+ prefs.useTor = true;
+
+ await expectLater(client.getBlockNumber(), _torPreferenceChanged);
+ await client.dispose();
+
+ // Nothing went out directly and nothing was rerouted via the proxy.
+ expect(node.requests, 1);
+ expect(socks.connections, 0);
+ expect(torService.proxyInfoReads, 0);
+ });
+
+ test('client built with Tor on refuses to send once Tor is off', () async {
+ final prefs = _MockPrefs(true);
+ final client = EthereumWallet.createWeb3Client(
+ node.url,
+ prefs,
+ torService,
+ );
+
+ expect(await client.getBlockNumber(), 42);
+ expect(socks.connections, 1);
+ expect(socks.request.toString(), contains('eth_blockNumber'));
+
+ prefs.useTor = false;
+
+ await expectLater(client.getBlockNumber(), _torPreferenceChanged);
+ await client.dispose();
+
+ // No new proxy connection and nothing went to the node directly.
+ expect(socks.connections, 1);
+ expect(node.requests, 0);
+ expect(torService.proxyInfoReads, 1);
+ });
+
+ test('unchanged preference keeps a reused client working', () async {
+ final direct = EthereumWallet.createWeb3Client(
+ node.url,
+ _MockPrefs(false),
+ torService,
+ );
+ expect(await direct.getBlockNumber(), 42);
+ expect(await direct.getBlockNumber(), 42);
+ await direct.dispose();
+ expect(node.requests, 2);
+ expect(socks.connections, 0);
+
+ final proxied = EthereumWallet.createWeb3Client(
+ node.url,
+ _MockPrefs(true),
+ torService,
+ );
+ expect(await proxied.getBlockNumber(), 42);
+ expect(await proxied.getBlockNumber(), 42);
+ await proxied.dispose();
+ expect(node.requests, 2);
+ expect(socks.connections, 2);
+ });
+ });
+}
### 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);
+ });
+}
### test/widgets/onetime_popups/native_library_warning_dialog_test.dart
@@ -0,0 +1,65 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/utilities/native_library_check.dart';
+import 'package:stackwallet/widgets/onetime_popups/native_library_warning_dialog.dart';
+
+const _monero = (
+ displayName: "Monero wallets",
+ result: (
+ problem: NativeLibraryProblem.missing,
+ path: r"C:\Program Files\Stack Wallet\monero_libwallet2_api_c.dll",
+ error: "The specified module could not be found.\n (error code: 126)",
+ ),
+);
+
+const _secp = (
+ displayName: "Most wallets",
+ result: (
+ problem: NativeLibraryProblem.blockedByAntivirus,
+ path: r"C:\Program Files\Stack Wallet\secp256k1.dll",
+ error:
+ "the file contains a virus or potentially unwanted software.\n "
+ "(error code: 225)",
+ ),
+);
+
+void main() {
+ test("one failure", () {
+ expect(
+ nativeLibraryWarningTitle([_monero]),
+ "A required file could not be loaded",
+ );
+ final message = nativeLibraryWarningMessage([_monero]);
+ expect(
+ message,
+ nativeLibraryErrorMessage("Monero wallets", _monero.result),
+ );
+ expect(
+ message,
+ startsWith(
+ "Monero wallets can't be used because a required file is missing.",
+ ),
+ );
+ expect(message, endsWith("(error code: 126)"));
+ });
+
+ test("several failures", () {
+ expect(
+ nativeLibraryWarningTitle([_monero, _secp]),
+ "Some required files could not be loaded",
+ );
+ final message = nativeLibraryWarningMessage([_monero, _secp]);
+ expect(
+ message,
+ "${nativeLibraryErrorMessage("Monero wallets", _monero.result)}\n\n"
+ "${nativeLibraryErrorMessage("Most wallets", _secp.result)}",
+ );
+ expect(
+ message,
+ contains("Most wallets can't be used because antivirus software blocked"),
+ );
+ expect(
+ message.indexOf("Monero"),
+ lessThan(message.indexOf("Most wallets")),
+ );
+ });
+}Why this scored 45/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.