Merge pull request #1483 from cypherstack/fix/eth-add-token-new-wallet
What changed, and why it matters
This commit fixes a UI crash in Stack Wallet that could occur when adding an Ethereum token right after creating a new Ethereum wallet. The problem was a timing mismatch: the new wallet's basic info was saved to the database before the wallet setup flow finished, so the token-add screen tried to show and use a wallet that wasn't fully registered yet. The fix filters the list to only wallets that are fully registered and adds a test to confirm the crash scenario no longer happens.
No immediate security action required; this is a reliability/bug-fix change. Reviewers may want to confirm that other wallet-picker flows perform similar registered-wallet checks and that the temporary trigger provider is eventually removed once the legacy Hive migration is complete.
Security signals we found
Crash/DoS in wallet picker UI due to inconsistent wallet registration state
Race condition between database persistence and in-memory provider registration
UI state derived from one provider (all wallet info) without checking another provider (registered wallets)
New regression test covers unregistered-wallet edge case
Evidence from the diff
In select_wallet_for_token_view.dart, the widget previously watched pAllWalletsInfo and built rows for every Ethereum wallet info entry. Because Wallet.create persists WalletInfo before the verification step adds the wallet to the global pWallets provider, the picker could reference a walletId that pWalletTokenAddresses and other global wallet state could not resolve, leading to a crash. The patch introduces a registeredWalletIds set from pWallets and filters ethWalletInfos to only those whose walletId is registered. It also watches newEthWalletTriggerTempUntilHiveCompletelyDeleted to rebuild once registration completes. A new widget test reproduces the unregistered-wallet scenario and verifies the picker skips it and rebuilds correctly after registration.
Changed components
lib/pages/add_wallet_views/select_wallet_for_token_view.dartEthereum token add flow wallet picker UIWallet registration state providers (pWallets, pAllWalletsInfo, pWalletTokenAddresses)Inspect captured patch +171 / −55
### lib/pages/add_wallet_views/select_wallet_for_token_view.dart
@@ -10,6 +10,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
+
import '../../models/add_wallet_list_entity/sub_classes/coin_entity.dart';
import '../../models/add_wallet_list_entity/sub_classes/eth_token_entity.dart';
import 'add_token_view/edit_wallet_tokens_view.dart';
@@ -18,6 +19,7 @@ import 'verify_recovery_phrase_view/verify_recovery_phrase_view.dart';
import '../../themes/stack_colors.dart';
import '../../utilities/text_styles.dart';
import '../../utilities/util.dart';
+import '../../providers/global/wallets_provider.dart';
import '../../wallets/isar/providers/all_wallets_info_provider.dart';
import '../../wallets/isar/providers/wallet_info_provider.dart';
import '../../widgets/background.dart';
@@ -30,16 +32,15 @@ import '../../widgets/eth_wallet_radio.dart';
import '../../widgets/rounded_container.dart';
import '../../widgets/rounded_white_container.dart';
import '../../widgets/wallet_info_row/wallet_info_row.dart';
+
import 'package:tuple/tuple.dart';
-final newEthWalletTriggerTempUntilHiveCompletelyDeleted =
- StateProvider((ref) => false);
+final newEthWalletTriggerTempUntilHiveCompletelyDeleted = StateProvider(
+ (ref) => false,
+);
class SelectWalletForTokenView extends ConsumerStatefulWidget {
- const SelectWalletForTokenView({
- super.key,
- required this.entity,
- });
+ const SelectWalletForTokenView({super.key, required this.entity});
static const String routeName = "/selectWalletForTokenView";
@@ -59,10 +60,7 @@ class _SelectWalletForTokenViewState
void _onContinue() {
Navigator.of(context).pushNamed(
EditWalletTokensView.routeName,
- arguments: Tuple2(
- _selectedWalletId!,
- [widget.entity.token.address],
- ),
+ arguments: Tuple2(_selectedWalletId!, [widget.entity.token.address]),
);
}
@@ -76,16 +74,26 @@ class _SelectWalletForTokenViewState
@override
Widget build(BuildContext context) {
+ // The wallet info is written to the db when a new wallet is created, but
+ // the wallet is only added to pWallets once its flow completes. Rebuild
+ // when that happens and skip wallets that are not registered yet.
+ ref.watch(newEthWalletTriggerTempUntilHiveCompletelyDeleted);
+ final registeredWalletIds = ref
+ .read(pWallets)
+ .wallets
+ .map((e) => e.walletId)
+ .toSet();
+
final ethWalletInfos = ref
.watch(pAllWalletsInfo)
.where((e) => e.coin == widget.entity.cryptoCurrency)
+ .where((e) => registeredWalletIds.contains(e.walletId))
.toList();
final _hasEthWallets = ethWalletInfos.isNotEmpty;
-
final List<String> ethWalletIds = [];
- for (final walletId in ethWalletInfos.map((e) => e.walletId).toList()) {
+ for (final walletId in ethWalletInfos.map((e) => e.walletId)) {
final walletContracts = ref.read(pWalletTokenAddresses(walletId));
if (!walletContracts.contains(widget.entity.token.address)) {
ethWalletIds.add(walletId);
@@ -101,8 +109,9 @@ class _SelectWalletForTokenViewState
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: () {
@@ -111,10 +120,7 @@ class _SelectWalletForTokenViewState
),
),
body: SafeArea(
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: child,
- ),
+ child: Padding(padding: const EdgeInsets.all(16), child: child),
// child: LayoutBuilder(
// builder: (ctx, constraints) {
@@ -139,48 +145,36 @@ class _SelectWalletForTokenViewState
isCompactHeight: false,
leading: AppBarBackButton(),
),
- body: SizedBox(
- width: 500,
- child: child,
- ),
+ body: SizedBox(width: 500, child: child),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- if (isDesktop)
- const SizedBox(
- height: 24,
- ),
+ if (isDesktop) const SizedBox(height: 24),
Text(
"Select Ethereum wallet",
textAlign: TextAlign.center,
style: isDesktop
? STextStyles.desktopH2(context)
: STextStyles.pageTitleH1(context),
),
- SizedBox(
- height: isDesktop ? 16 : 8,
- ),
+ SizedBox(height: isDesktop ? 16 : 8),
Text(
"You are adding an ETH token.",
textAlign: TextAlign.center,
style: isDesktop
? STextStyles.desktopSubtitleH2(context)
: STextStyles.subtitle(context),
),
- const SizedBox(
- height: 8,
- ),
+ const SizedBox(height: 8),
Text(
"You must choose an Ethereum wallet in order to use ${widget.entity.name}",
textAlign: TextAlign.center,
style: isDesktop
? STextStyles.desktopSubtitleH2(context)
: STextStyles.subtitle(context),
),
- SizedBox(
- height: isDesktop ? 60 : 16,
- ),
+ SizedBox(height: isDesktop ? 60 : 16),
ethWalletIds.isEmpty
? RoundedWhiteContainer(
padding: EdgeInsets.all(isDesktop ? 16 : 12),
@@ -208,9 +202,8 @@ class _SelectWalletForTokenViewState
child: ListView.separated(
itemCount: ethWalletIds.length,
shrinkWrap: true,
- separatorBuilder: (_, __) => SizedBox(
- height: isDesktop ? 12 : 6,
- ),
+ separatorBuilder: (_, __) =>
+ SizedBox(height: isDesktop ? 12 : 6),
itemBuilder: (_, index) {
return RoundedContainer(
padding: EdgeInsets.all(isDesktop ? 16 : 8),
@@ -221,33 +214,25 @@ class _SelectWalletForTokenViewState
},
color: isDesktop
? Theme.of(context)
- .extension<StackColors>()!
- .popupBG
+ .extension<StackColors>()!
+ .popupBG
: _selectedWalletId == ethWalletIds[index]
- ? Theme.of(context)
- .extension<StackColors>()!
- .highlight
- : Colors.transparent,
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .highlight
+ : Colors.transparent,
child: isDesktop
? EthWalletRadio(
walletId: ethWalletIds[index],
selectedWalletId: _selectedWalletId,
)
- : WalletInfoRow(
- walletId: ethWalletIds[index],
- ),
+ : WalletInfoRow(walletId: ethWalletIds[index]),
);
},
),
),
- if (ethWalletIds.isEmpty || isDesktop)
- const SizedBox(
- height: 16,
- ),
- if (isDesktop)
- const SizedBox(
- height: 16,
- ),
+ if (ethWalletIds.isEmpty || isDesktop) const SizedBox(height: 16),
+ if (isDesktop) const SizedBox(height: 16),
ethWalletIds.isEmpty
? PrimaryButton(
label: "Add new Ethereum wallet",
### test/pages/add_wallet_views/select_wallet_for_token_view_test.dart
@@ -0,0 +1,131 @@
+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/add_wallet_list_entity/sub_classes/eth_token_entity.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/pages/add_wallet_views/select_wallet_for_token_view.dart';
+import 'package:stackwallet/providers/global/wallets_provider.dart';
+import 'package:stackwallet/services/wallets.dart';
+import 'package:stackwallet/themes/stack_colors.dart';
+import 'package:stackwallet/themes/theme_service.dart';
+import 'package:stackwallet/utilities/default_eth_tokens.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/all_wallets_info_provider.dart';
+import 'package:stackwallet/wallets/isar/providers/wallet_info_provider.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+
+import '../../sample_data/theme_json.dart';
+
+void main() {
+ late platform.Platform originalPlatform;
+
+ setUp(() => originalPlatform = Util.layoutPlatform);
+ tearDown(() => Util.layoutPlatform = originalPlatform);
+
+ final token = DefaultTokens.usdc;
+
+ // Wallet.create saves the info to the db before the verify step adds the
+ // wallet to pWallets, so the picker can see a wallet it can't look up yet.
+ Future<WalletInfo> pumpWithUnregisteredWallet(
+ WidgetTester tester,
+ _FakeWallets wallets, {
+ List<String> walletTokens = const [],
+ }) async {
+ final info = WalletInfo.createNew(
+ coin: Ethereum(CryptoCurrencyNetwork.main),
+ name: "new eth wallet",
+ );
+ final theme = StackTheme.fromJson(json: lightThemeJsonMap);
+
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [
+ pThemeService.overrideWithValue(_TestThemeService(theme)),
+ pAllWalletsInfo.overrideWithValue([info]),
+ pWallets.overrideWithValue(wallets),
+ pWalletTokenAddresses.overrideWithProvider(
+ (walletId) => Provider((_) => walletTokens),
+ ),
+ ],
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [StackColors.fromStackColorTheme(theme)],
+ ),
+ home: SelectWalletForTokenView(entity: EthTokenEntity(token)),
+ ),
+ ),
+ );
+ await tester.pump();
+ return info;
+ }
+
+ for (final os in ["android", "linux"]) {
+ testWidgets("$os picker skips a wallet that isn't registered yet", (
+ tester,
+ ) async {
+ Util.layoutPlatform = platform.FakePlatform(operatingSystem: os);
+ await pumpWithUnregisteredWallet(tester, _FakeWallets());
+
+ expect(tester.takeException(), isNull);
+ expect(find.text("You do not have any Ethereum wallets"), findsOneWidget);
+ expect(find.text("Add new Ethereum wallet"), findsOneWidget);
+ });
+ }
+
+ testWidgets("picker rebuilds when the new wallet is registered", (
+ tester,
+ ) async {
+ Util.layoutPlatform = platform.FakePlatform(operatingSystem: "android");
+ final wallets = _FakeWallets();
+ // The wallet already holds the token, so once it is registered the
+ // picker shows the "already have" message instead of building a row.
+ final info = await pumpWithUnregisteredWallet(
+ tester,
+ wallets,
+ walletTokens: [token.address],
+ );
+ expect(find.text("You do not have any Ethereum wallets"), findsOneWidget);
+
+ wallets.registered.add(_FakeWallet(info.walletId));
+ final container = ProviderScope.containerOf(
+ tester.element(find.byType(SelectWalletForTokenView)),
+ );
+ final trigger = container.read(
+ newEthWalletTriggerTempUntilHiveCompletelyDeleted.notifier,
+ );
+ trigger.state = !trigger.state;
+ await tester.pump();
+
+ expect(tester.takeException(), isNull);
+ expect(
+ find.text("All current Ethereum wallets already have ${token.name}"),
+ findsOneWidget,
+ );
+ });
+}
+
+class _TestThemeService extends Fake implements ThemeService {
+ _TestThemeService(this.theme);
+
+ final StackTheme theme;
+
+ @override
+ StackTheme? getTheme({required String themeId}) => theme;
+}
+
+class _FakeWallets extends Fake implements Wallets {
+ final List<Wallet> registered = [];
+
+ @override
+ List<Wallet> get wallets => registered;
+}
+
+class _FakeWallet extends Fake implements Wallet {
+ _FakeWallet(this.walletId);
+
+ @override
+ final String walletId;
+}Why this scored 22/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.