Skip to content

Fix: Prevent state loss in private key retrieval and improve empty keys handling#3375

Merged
DeckerSU merged 6 commits intodevfrom
patch-fix-ios-privkeys-show
Nov 6, 2025
Merged

Fix: Prevent state loss in private key retrieval and improve empty keys handling#3375
DeckerSU merged 6 commits intodevfrom
patch-fix-ios-privkeys-show

Conversation

@DeckerSU
Copy link
Copy Markdown
Contributor

@DeckerSU DeckerSU commented Nov 6, 2025

Summary

This PR fixes an issue where private keys were not displaying correctly on iOS (and potentially other platforms) due to state loss during async callback execution. It also adds proper handling for empty private keys scenarios with improved user feedback.

Problem

Issue 1: State Loss During Async Callback Execution

The private keys were being lost due to state management issues during async operations:

  1. walletPasswordDialogWithLoading shows a dialog and accepts an onPasswordValidated callback
  2. The callback runs asynchronously inside WidgetsBinding.instance.addPostFrameCallback
  3. Inside the callback, _sdkPrivateKeys was being set directly
  4. However, the widget could rebuild or the state could be lost between when the callback sets the value and when the dialog closes
  5. When walletPasswordDialogWithLoading returned and we checked _sdkPrivateKeys, it was already null/empty

The problem was that setting _sdkPrivateKeys inside the callback didn't guarantee the state would persist when the dialog closed and the widget rebuilt.

Issue 2: Missing Empty Keys Handling

When assets are still being activated and getEnabledCoins returns an empty value, the app was not showing any error message to the user. The user had no feedback about why private keys were not available. Now the app displays a user-friendly message suggesting them to try again later.

Solution

Fix 1: Defer State Update Until After Dialog Closes

The fix defers setting _sdkPrivateKeys until after the dialog closes:

  • Store fetched keys in a local variable (fetchedKeys) during the async callback
  • Only assign to _sdkPrivateKeys after the dialog closes and we confirm the operation succeeded
  • This ensures state is preserved when the widget rebuilds

Fix 2: Proper Empty Keys Handling

Added proper handling for empty private keys when assets are still being activated:

  • Check if privateKeys is empty immediately after fetching from SDK
  • Set a flag (isEmptyKeys) to distinguish between empty keys and actual errors
  • Show appropriate error message:
    • privateKeysEmptyError: "No private keys found. Assets may need to be activated. Please try again later." (when keys are empty)
    • privateKeyRetrievalFailed: Generic error message (for actual errors/exceptions)
  • Previously, when getEnabledCoins returned empty during asset activation, no error was shown to the user. Now users receive clear feedback suggesting them to try again later.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 6, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch patch-fix-ios-privkeys-show

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines 294 to 299
} catch (e) {
// Clear sensitive data on any error
_clearPrivateKeyData();

// Log error for debugging
debugPrint('Failed to retrieve private keys: ${e.toString()}');
fetchedKeys?.clear();
fetchedKeys = null;

return false; // Failure
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Clear cached keys after retrieval failure

The new flow moves private key assignment out of the password callback, but the catch block now only clears the local fetchedKeys variable and never calls _clearPrivateKeyData(). If a previous retrieval succeeded and a subsequent attempt fails (for example due to RPC/network error), _sdkPrivateKeys continues to hold the old keys in memory even though the operation failed. The prior implementation explicitly cleared _sdkPrivateKeyData on error to minimize exposure of sensitive data. Restoring that clear keeps the private key cache from persisting after a failed fetch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in 43e8022 ,

@github-actions
Copy link
Copy Markdown

github-actions bot commented Nov 6, 2025

Visit the preview URL for this PR (updated for commit c296597):

https://walletrc--pull-3375-merge-739micho.web.app

(expires Thu, 13 Nov 2025 14:21:59 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: f66a4ff03faa546f12f0ae5a841bd9eff2714dcc

@DeckerSU
Copy link
Copy Markdown
Contributor Author

DeckerSU commented Nov 6, 2025

@codex Is it enough to do:

_sdkPrivateKeys = fetchedKeys;

or better:

setState(() {
  _sdkPrivateKeys = fetchedKeys;
});

?

@GLEECBTC GLEECBTC deleted a comment from cursor bot Nov 6, 2025
@CharlVS
Copy link
Copy Markdown
Collaborator

CharlVS commented Nov 6, 2025

@cursor Is it enough to do:

_sdkPrivateKeys = fetchedKeys;

or better:

setState(() {
  _sdkPrivateKeys = fetchedKeys;
});

?

@cursor
Copy link
Copy Markdown

cursor bot commented Nov 6, 2025

Based on examining the code, you should use setState() to properly update the state variable.

Here's why:

The Context

Looking at the code flow in security_settings_page.dart:

    if (success && fetchedKeys != null) {
      // Set the keys AFTER dialog closes to ensure state is preserved
      _sdkPrivateKeys = fetchedKeys;
      // Clear the local reference to minimize the number of places holding sensitive data
      // Note: fetchedKeys is a reference to the same Map object, so we only set it to null
      // to remove the extra reference, not clear() which would clear the data used by _sdkPrivateKeys
      fetchedKeys = null;
      
      // Private keys are ready, show the private keys screen
      // ignore: use_build_context_synchronously
      context.read<SecuritySettingsBloc>().add(const ShowPrivateKeysEvent());

The variable _sdkPrivateKeys is used in the widget tree (line 190) and affects UI rendering:

        return PrivateKeyShow(
          privateKeys: _sdkPrivateKeys ?? <AssetId, List<PrivateKey>>{},
          blockedAssetIds: blockedAssets,
        );

Why setState() is Better

Use this:

setState(() {
  _sdkPrivateKeys = fetchedKeys;
});

Reasons:

  1. Flutter Best Practice: Any state variable that affects rendering must be updated via setState() to notify the framework that the widget needs rebuilding

  2. Explicit State Management: While the BLoC event on line 309 will trigger a rebuild, using setState() makes the state change explicit and doesn't rely on side effects

  3. Robustness: If the BLoC event is delayed, skipped, or the step doesn't actually change, the UI could be out of sync without setState()

  4. Consistency: This is a StatefulWidget state variable - using setState() follows the standard Flutter pattern and makes the code easier to maintain

So the answer is: wrap it in setState() for proper state management.


Open in Cursor Open in Web

Learn more about Cursor Agents

@CharlVS CharlVS self-requested a review November 6, 2025 11:58
@cursor
Copy link
Copy Markdown

cursor bot commented Nov 6, 2025

Cursor Agent can help with this pull request. Just @cursor in comments and I'll start working on changes in this branch.
Learn more about Cursor Agents

@DeckerSU
Copy link
Copy Markdown
Contributor Author

DeckerSU commented Nov 6, 2025

I've carefully tested all the changes in this PR across all platforms. The latest web deployment is available at walletrc--pull-3375-merge-739micho.web.app and works fine.

With @ca333’s approval to merge and @CharlVS’s approval of the PR, I’m going to merge it and prepare the release binaries. Others in the internal chat have also confirmed that this PR resolves all issues and that the TestFlight build on iOS works well.

p.s. Thanks, everyone, for your hard work and dedication to this release.

@DeckerSU DeckerSU merged commit 5780096 into dev Nov 6, 2025
7 of 13 checks passed
@DeckerSU DeckerSU deleted the patch-fix-ios-privkeys-show branch November 6, 2025 19:23
@smk762 smk762 mentioned this pull request Nov 23, 2025
5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants