Skip to content

fix: eliminate crash issues when fragments/dialogs recreated and address network error #1407

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jul 12, 2025

Conversation

HashEngineering
Copy link
Collaborator

@HashEngineering HashEngineering commented Jul 2, 2025

Issue being fixed or feature implemented

A user had this crash that is reported 2 seconds after the app starts.The user was trying to purchase a gift card, but was getting SSL Handshake errors with purchaseGiftCard. Logs report many other connection problems.7 minutes later, the app is restarted by the user. 2 seconds later the crash happenedI am wondering if this PurchaseGiftCardConfirmDialog is being recreated by Android, but this dialog was created from the right place in the app, so the giftCardMerchant value is not initialized. My idea is based on the call stack and that 2 seconds had passed, so it would seem impossible to make an attempt to purchase a card.or is there another explanation?

20:07:14 [main] WalletApplication - WalletApplication.onCreate()

20:07:16 [main] CrashReporter - crashing because of uncaught exception
kotlin.UninitializedPropertyAccessException: lateinit property giftCardMerchant has not been initialized
	at org.dash.wallet.features.exploredash.ui.ctxspend.CTXSpendViewModel.getGiftCardMerchant(CTXSpendViewModel.kt:90)
	at org.dash.wallet.features.exploredash.ui.ctxspend.dialogs.PurchaseGiftCardConfirmDialog.onViewCreated(PurchaseGiftCardConfirmDialog.kt:70)
	at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3147)
	at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:588)
	at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:272)
	at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:114)
	at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1455)
	at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3034)
	at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2952)
	at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:263)
	at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:350)
	at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
	at de.schildbach.wallet.ui.LockScreenActivity.onStart(LockScreenActivity.kt:224)
	at de.schildbach.wallet.ui.main.MainActivity.onStart(MainActivity.kt:197)
	at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1582)
	at android.app.Activity.performStart(Activity.java:9034)
	at android.app.ActivityThread.handleStartActivity(ActivityThread.java:4206)
	at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:225)
	at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:205)
	at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:177)
	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:98)
	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2693)
	at android.os.Handler.dispatchMessage(Handler.java:106)
	at android.os.Looper.loopOnce(Looper.java:230)
	at android.os.Looper.loop(Looper.java:319)
	at android.app.ActivityThread.main(ActivityThread.java:9063)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:588)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)
20:07:16 [DefaultDispatcher-worker-13] ExchangeRatesRepository - exchange rates updated successfully with de.schildbach.wallet.rates.DashRetailClient@534c060
20:07:19 [main] WalletApplication - WalletApplication.onCreate()

The stack trace from this dialog when the user clicks on the "Continue" button on the gift card enter amount screen:

result = {StackTraceElement[16]@43373} 
 0 = {StackTraceElement@43385} "org.dash.wallet.features.exploredash.ui.ctxspend.dialogs.PurchaseGiftCardConfirmDialog.onViewCreated(PurchaseGiftCardConfirmDialog.kt:68)"
 1 = {StackTraceElement@43386} "androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3147)"
 2 = {StackTraceElement@43387} "androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:588)"
 3 = {StackTraceElement@43388} "androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:272)"
 4 = {StackTraceElement@43389} "androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1943)"
 5 = {StackTraceElement@43390} "androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1845)"
 6 = {StackTraceElement@43391} "androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1782)"
 7 = {StackTraceElement@43392} "androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:565)"
 8 = {StackTraceElement@43393} "android.os.Handler.handleCallback(Handler.java:942)"
 9 = {StackTraceElement@43394} "android.os.Handler.dispatchMessage(Handler.java:99)"
 10 = {StackTraceElement@43395} "android.os.Looper.loopOnce(Looper.java:201)"
 11 = {StackTraceElement@43396} "android.os.Looper.loop(Looper.java:288)"
 12 = {StackTraceElement@43397} "android.app.ActivityThread.main(ActivityThread.java:7924)"
 13 = {StackTraceElement@43398} "java.lang.reflect.Method.invoke(Native Method)"
 14 = {StackTraceElement@43399} "com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)"
 15 = {StackTraceElement@43400} "com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)"
Andrei said:
PurchaseGiftCardConfirmDialog expects the merchant to be initialized, but if it's recreated for an app that comes back from background, it might not be.The quick solution would be to check if merchant is initialized in the dialog with a viewModel property
val hasMerchant: Boolean
        get() = ::giftCardMerchant.isInitialized

And then dismiss the dialog before going futher.This somewhat defeats the purpose of lateinit (we might as well be using a nullable here). A proper solution would be to dismiss any dialogs when the app goes into background, similar to how we do it for the lockscreen. But this might be a bit of work to get everything correct.
The problem, of course, is that even if we dismiss the dialog, the user will end up on an empty Buy screen with uninitialized merchant, this can lead to other issues if he starts pressing buttons.The REAL proper solution would be to save the state of the viewModel with SavedStateHandle and restore the state correctly when the app is restored from background. We do this in the Send screen iirk.

Related PR's and Dependencies

none

Screenshots / Videos

How Has This Been Tested?

  • QA (Mobile Team)

Checklist:

  • I have performed a self-review of my own code and added comments where necessary
  • I have added or updated relevant unit/integration/functional/e2e tests

Summary by CodeRabbit

  • New Features

    • Improved state saving and restoration for amount entry and merchant selection, ensuring user input and selections persist across app restarts or navigation.
    • Added the ability to fetch merchant details by ID for enhanced merchant management.
  • Bug Fixes

    • Resolved potential crashes by handling null merchant and transaction states more safely throughout gift card purchase and confirmation flows.
    • Improved error handling for network issues during gift card purchases, providing clearer feedback to users.
  • Refactor

    • Centralized and streamlined merchant setup logic for better reliability and maintainability.
    • Enhanced UI updates to reflect accurate merchant data and prevent inconsistencies.
  • Chores

    • Added null checks and improved LiveData handling to prevent unexpected errors and improve app stability.
    • Wrapped critical state assignments and navigation calls in try-catch blocks to handle edge cases after process death gracefully.
    • Updated fragment lifecycle and navigation handling to clear saved states appropriately and avoid stale data.

@HashEngineering HashEngineering self-assigned this Jul 2, 2025
Copy link
Contributor

coderabbitai bot commented Jul 2, 2025

Walkthrough

These changes add saved state management to ViewModels for amount entry and merchant data, enhance null safety and error handling in merchant and gift card purchase flows, extend data source and DAO interfaces for merchant retrieval by ID, and refactor UI components to better handle nullable merchant states and process death scenarios.

Changes

File(s) Change Summary
common/.../EnterAmountFragment.kt, common/.../EnterAmountViewModel.kt Added saved state persistence for amount and currency; introduced method to set amount from saved state and clear saved state.
features/exploredash/.../ExploreDataSource.kt, .../MerchantAtmDataSource.kt, .../MerchantDao.kt Added getMerchantById method to interface and implementation for merchant retrieval by ID.
features/exploredash/.../CTXSpendRepository.kt Extended CTXSpendException with optional cause and isNetworkError property.
features/exploredash/.../CTXSpendViewModel.kt Refactored for saved state restoration, nullable merchant handling, added merchant fetching and state management methods, improved error handling.
features/exploredash/.../PurchaseGiftCardFragment.kt Refactored merchant setup with suspend functions, improved null safety and UI consistency, restored merchant from saved state.
features/exploredash/.../dialogs/PurchaseGiftCardConfirmDialog.kt Added EnterAmountViewModel integration, null checks for merchant, enhanced error handling, cleared saved state after purchase.
wallet/.../TxResourceMapper.kt Added null check for assetLockPublicKeyId to prevent null pointer exceptions.
features/exploredash/.../SearchFragment.kt Wrapped viewModel.onExitSearch() in try-catch to handle IllegalArgumentException after process death.
integrations/coinbase/.../CoinbaseBuyDashFragment.kt Made fragment property nullable, added safe calls, cleared saved state on navigation and validation success.
integrations/coinbase/.../EnterAmountToTransferFragment.kt Wrapped assignments in try-catch to handle IllegalArgumentException after process death.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PurchaseGiftCardFragment
    participant CTXSpendViewModel
    participant MerchantDao
    participant EnterAmountViewModel

    User->>PurchaseGiftCardFragment: Navigates to purchase gift card
    PurchaseGiftCardFragment->>CTXSpendViewModel: Get saved merchant ID
    alt Merchant ID found
        PurchaseGiftCardFragment->>CTXSpendViewModel: getMerchantById(merchantId)
        CTXSpendViewModel->>MerchantDao: getMerchantById(merchantId)
        MerchantDao-->>CTXSpendViewModel: Merchant?
        CTXSpendViewModel-->>PurchaseGiftCardFragment: Merchant?
        alt Merchant found
            PurchaseGiftCardFragment->>CTXSpendViewModel: Setup merchant
        else Merchant not found
            PurchaseGiftCardFragment->>User: Navigate back
        end
    else No merchant ID
        PurchaseGiftCardFragment->>User: Navigate back
    end
Loading
sequenceDiagram
    participant User
    participant PurchaseGiftCardConfirmDialog
    participant EnterAmountViewModel
    participant CTXSpendViewModel

    User->>PurchaseGiftCardConfirmDialog: Clicks confirm purchase
    PurchaseGiftCardConfirmDialog->>CTXSpendViewModel: Check giftCardMerchant
    alt Merchant is null
        PurchaseGiftCardConfirmDialog->>User: Dismiss dialog
    else Merchant is valid
        PurchaseGiftCardConfirmDialog->>CTXSpendViewModel: Purchase gift card
        alt Success
            PurchaseGiftCardConfirmDialog->>EnterAmountViewModel: clearSavedState()
            PurchaseGiftCardConfirmDialog->>User: Show gift card details
        else CTXSpendException
            alt isNetworkError
                PurchaseGiftCardConfirmDialog->>User: Show network error dialog
            else
                PurchaseGiftCardConfirmDialog->>User: Show error dialog
            end
        end
    end
Loading

Possibly related PRs

  • Fix CTXSpend discount rounding issue #1398: Adds saved state handling and amount tracking in EnterAmountFragment and EnterAmountViewModel, related by component but focused on amount change handling rather than state persistence.

Suggested labels

codex

Suggested reviewers

  • Syn-McJ

Poem

In the warren of code, a stateful delight,
Rabbits hop through fragments, restoring what's right.
Merchants remembered, with nulls held at bay,
Errors now handled, no crashes today!
With each gentle commit, the wallet grows bright—
🐇✨ Safe, robust, and ready for flight!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 98be24c and a9263af.

📒 Files selected for processing (2)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt (10 hunks)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/PurchaseGiftCardFragment.kt (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/PurchaseGiftCardFragment.kt
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountViewModel.kt (1)

139-147: Consider lifecycle-aware observers to prevent memory leaks.

Using observeForever can lead to memory leaks if the ViewModel outlives the observers. Since SavedStateHandle persists across configuration changes, this might be acceptable, but consider documenting why observeForever is safe here.

Add a comment explaining the safety of using observeForever:

+    // Using observeForever is safe here because:
+    // 1. ViewModel and SavedStateHandle have the same lifecycle
+    // 2. These observers are needed for the entire ViewModel lifetime
+    // 3. They will be cleaned up when ViewModel is cleared
     // Save amount changes to SavedStateHandle
     _amount.observeForever { coin ->
         savedStateHandle[KEY_AMOUNT] = coin?.value
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a87db82 and d219cb6.

📒 Files selected for processing (9)
  • common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountFragment.kt (2 hunks)
  • common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountViewModel.kt (5 hunks)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/ExploreDataSource.kt (2 hunks)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/MerchantDao.kt (1 hunks)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/repository/CTXSpendRepository.kt (2 hunks)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt (10 hunks)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/PurchaseGiftCardFragment.kt (8 hunks)
  • features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/dialogs/PurchaseGiftCardConfirmDialog.kt (7 hunks)
  • wallet/src/de/schildbach/wallet/ui/transactions/TxResourceMapper.kt (1 hunks)
🧰 Additional context used
🧠 Learnings (8)
📓 Common learnings
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/SearchFragment.kt:45-46
Timestamp: 2025-05-07T14:18:11.161Z
Learning: In the ExploreViewModel of the dash-wallet application, `appliedFilters` is a StateFlow (not LiveData), so Flow operators like `distinctUntilChangedBy` can be used with it.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1390
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt:129-145
Timestamp: 2025-05-08T18:11:40.249Z
Learning: The hardcoded test data in the purchaseGiftCard() function of CTXSpendViewModel is intentionally left in place for testing the error handling for limit mismatch, and will be fixed later before release.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In Dash Wallet, DataStore operations (like those in DashPayConfig through BaseConfig) already handle background threading internally. Adding another layer of withContext(Dispatchers.IO) around these calls in ViewModels is redundant because the Jetpack DataStore API automatically dispatches its operations to a background thread.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In the Dash Wallet app, DashPayConfig methods like isTransactionMetadataInfoShown() already use withContext(Dispatchers.IO) internally, so wrapping these calls with another withContext(Dispatchers.IO) in ViewModels is redundant.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1386
File: wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt:108-0
Timestamp: 2025-05-06T15:46:59.440Z
Learning: In UI code where frequent updates to a value might trigger expensive operations (like the SendCoinsViewModel's `executeDryrun` method), it's preferable to use a Flow with debounce rather than launching a new coroutine for each update. This prevents race conditions, reduces resource usage, and provides a more reactive architecture.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1391
File: wallet/src/de/schildbach/wallet/ui/payments/PaymentsFragment.kt:111-119
Timestamp: 2025-05-12T09:14:36.656Z
Learning: In the dashpay/dash-wallet project, explicitly unregistering ViewPager2 callbacks is not considered critical since memory leaks haven't been observed in practice with the memory profiler.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1391
File: common/src/main/java/org/dash/wallet/common/ui/segmented_picker/SegmentedPicker.kt:70-83
Timestamp: 2025-05-12T09:17:22.548Z
Learning: The SegmentedPicker component in the Dash Wallet app intentionally uses a mixed state pattern (both internal state and external parameter) to handle animations internally while still respecting external state changes. This design allows the component to manage animation timing independently without requiring the parent component to handle animation logic.
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/MerchantDao.kt (1)
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/ExploreDataSource.kt:106-115
Timestamp: 2025-05-07T14:17:15.912Z
Learning: In the Dash Wallet app, MerchantDao interface methods use an "excludeType" parameter (e.g., `MerchantType.ONLINE`) to exclude merchants of a specific type rather than to include them. For example, in `observePhysicalMerchants()`, passing `MerchantType.ONLINE` as the exclude type parameter filters out online-only merchants, effectively returning physical merchants.
common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountFragment.kt (5)
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In the Dash Wallet app, DashPayConfig methods like isTransactionMetadataInfoShown() already use withContext(Dispatchers.IO) internally, so wrapping these calls with another withContext(Dispatchers.IO) in ViewModels is redundant.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/SearchFragment.kt:45-46
Timestamp: 2025-05-07T14:18:11.161Z
Learning: In the ExploreViewModel of the dash-wallet application, `appliedFilters` is a StateFlow (not LiveData), so Flow operators like `distinctUntilChangedBy` can be used with it.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1386
File: wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt:108-0
Timestamp: 2025-05-06T15:46:59.440Z
Learning: In UI code where frequent updates to a value might trigger expensive operations (like the SendCoinsViewModel's `executeDryrun` method), it's preferable to use a Flow with debounce rather than launching a new coroutine for each update. This prevents race conditions, reduces resource usage, and provides a more reactive architecture.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In Dash Wallet, DataStore operations (like those in DashPayConfig through BaseConfig) already handle background threading internally. Adding another layer of withContext(Dispatchers.IO) around these calls in ViewModels is redundant because the Jetpack DataStore API automatically dispatches its operations to a background thread.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1391
File: integrations/coinbase/src/main/java/org/dash/wallet/integrations/coinbase/ui/convert_currency/ConvertViewFragment.kt:134-155
Timestamp: 2025-05-12T09:15:56.594Z
Learning: The SegmentedPicker composable in Dash Wallet has a safety check for empty options, returning early if options.isEmpty() is true.
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/ExploreDataSource.kt (1)
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/ExploreDataSource.kt:106-115
Timestamp: 2025-05-07T14:17:15.912Z
Learning: In the Dash Wallet app, MerchantDao interface methods use an "excludeType" parameter (e.g., `MerchantType.ONLINE`) to exclude merchants of a specific type rather than to include them. For example, in `observePhysicalMerchants()`, passing `MerchantType.ONLINE` as the exclude type parameter filters out online-only merchants, effectively returning physical merchants.
common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountViewModel.kt (5)
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/SearchFragment.kt:45-46
Timestamp: 2025-05-07T14:18:11.161Z
Learning: In the ExploreViewModel of the dash-wallet application, `appliedFilters` is a StateFlow (not LiveData), so Flow operators like `distinctUntilChangedBy` can be used with it.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In the Dash Wallet app, DashPayConfig methods like isTransactionMetadataInfoShown() already use withContext(Dispatchers.IO) internally, so wrapping these calls with another withContext(Dispatchers.IO) in ViewModels is redundant.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In Dash Wallet, DataStore operations (like those in DashPayConfig through BaseConfig) already handle background threading internally. Adding another layer of withContext(Dispatchers.IO) around these calls in ViewModels is redundant because the Jetpack DataStore API automatically dispatches its operations to a background thread.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1386
File: wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt:108-0
Timestamp: 2025-05-06T15:46:59.440Z
Learning: In UI code where frequent updates to a value might trigger expensive operations (like the SendCoinsViewModel's `executeDryrun` method), it's preferable to use a Flow with debounce rather than launching a new coroutine for each update. This prevents race conditions, reduces resource usage, and provides a more reactive architecture.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1391
File: integrations/coinbase/src/main/java/org/dash/wallet/integrations/coinbase/ui/convert_currency/ConvertViewFragment.kt:134-155
Timestamp: 2025-05-12T09:15:56.594Z
Learning: The SegmentedPicker composable in Dash Wallet has a safety check for empty options, returning early if options.isEmpty() is true.
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/dialogs/PurchaseGiftCardConfirmDialog.kt (7)
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1390
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt:129-145
Timestamp: 2025-05-08T18:11:40.249Z
Learning: The hardcoded test data in the purchaseGiftCard() function of CTXSpendViewModel is intentionally left in place for testing the error handling for limit mismatch, and will be fixed later before release.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In the Dash Wallet app, DashPayConfig methods like isTransactionMetadataInfoShown() already use withContext(Dispatchers.IO) internally, so wrapping these calls with another withContext(Dispatchers.IO) in ViewModels is redundant.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In Dash Wallet, DataStore operations (like those in DashPayConfig through BaseConfig) already handle background threading internally. Adding another layer of withContext(Dispatchers.IO) around these calls in ViewModels is redundant because the Jetpack DataStore API automatically dispatches its operations to a background thread.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/SearchFragment.kt:45-46
Timestamp: 2025-05-07T14:18:11.161Z
Learning: In the ExploreViewModel of the dash-wallet application, `appliedFilters` is a StateFlow (not LiveData), so Flow operators like `distinctUntilChangedBy` can be used with it.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1391
File: integrations/coinbase/src/main/java/org/dash/wallet/integrations/coinbase/ui/convert_currency/ConvertViewFragment.kt:134-155
Timestamp: 2025-05-12T09:15:56.594Z
Learning: The SegmentedPicker composable in Dash Wallet has a safety check for empty options, returning early if options.isEmpty() is true.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1391
File: wallet/src/de/schildbach/wallet/ui/payments/PaymentsFragment.kt:111-119
Timestamp: 2025-05-12T09:14:36.656Z
Learning: In the dashpay/dash-wallet project, explicitly unregistering ViewPager2 callbacks is not considered critical since memory leaks haven't been observed in practice with the memory profiler.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1386
File: wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt:108-0
Timestamp: 2025-05-06T15:46:59.440Z
Learning: In UI code where frequent updates to a value might trigger expensive operations (like the SendCoinsViewModel's `executeDryrun` method), it's preferable to use a Flow with debounce rather than launching a new coroutine for each update. This prevents race conditions, reduces resource usage, and provides a more reactive architecture.
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/PurchaseGiftCardFragment.kt (5)
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1390
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt:129-145
Timestamp: 2025-05-08T18:11:40.249Z
Learning: The hardcoded test data in the purchaseGiftCard() function of CTXSpendViewModel is intentionally left in place for testing the error handling for limit mismatch, and will be fixed later before release.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In the Dash Wallet app, DashPayConfig methods like isTransactionMetadataInfoShown() already use withContext(Dispatchers.IO) internally, so wrapping these calls with another withContext(Dispatchers.IO) in ViewModels is redundant.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/SearchFragment.kt:45-46
Timestamp: 2025-05-07T14:18:11.161Z
Learning: In the ExploreViewModel of the dash-wallet application, `appliedFilters` is a StateFlow (not LiveData), so Flow operators like `distinctUntilChangedBy` can be used with it.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1386
File: wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt:108-0
Timestamp: 2025-05-06T15:46:59.440Z
Learning: In UI code where frequent updates to a value might trigger expensive operations (like the SendCoinsViewModel's `executeDryrun` method), it's preferable to use a Flow with debounce rather than launching a new coroutine for each update. This prevents race conditions, reduces resource usage, and provides a more reactive architecture.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1391
File: integrations/coinbase/src/main/java/org/dash/wallet/integrations/coinbase/ui/convert_currency/ConvertViewFragment.kt:134-155
Timestamp: 2025-05-12T09:15:56.594Z
Learning: The SegmentedPicker composable in Dash Wallet has a safety check for empty options, returning early if options.isEmpty() is true.
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt (6)
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1390
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt:129-145
Timestamp: 2025-05-08T18:11:40.249Z
Learning: The hardcoded test data in the purchaseGiftCard() function of CTXSpendViewModel is intentionally left in place for testing the error handling for limit mismatch, and will be fixed later before release.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In the Dash Wallet app, DashPayConfig methods like isTransactionMetadataInfoShown() already use withContext(Dispatchers.IO) internally, so wrapping these calls with another withContext(Dispatchers.IO) in ViewModels is redundant.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/explore/SearchFragment.kt:45-46
Timestamp: 2025-05-07T14:18:11.161Z
Learning: In the ExploreViewModel of the dash-wallet application, `appliedFilters` is a StateFlow (not LiveData), so Flow operators like `distinctUntilChangedBy` can be used with it.
Learnt from: HashEngineering
PR: dashpay/dash-wallet#1362
File: wallet/src/de/schildbach/wallet/ui/more/SettingsViewModel.kt:107-115
Timestamp: 2025-04-19T07:01:17.535Z
Learning: In Dash Wallet, DataStore operations (like those in DashPayConfig through BaseConfig) already handle background threading internally. Adding another layer of withContext(Dispatchers.IO) around these calls in ViewModels is redundant because the Jetpack DataStore API automatically dispatches its operations to a background thread.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1386
File: wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt:108-0
Timestamp: 2025-05-06T15:46:59.440Z
Learning: In UI code where frequent updates to a value might trigger expensive operations (like the SendCoinsViewModel's `executeDryrun` method), it's preferable to use a Flow with debounce rather than launching a new coroutine for each update. This prevents race conditions, reduces resource usage, and provides a more reactive architecture.
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1389
File: features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/ExploreDataSource.kt:106-115
Timestamp: 2025-05-07T14:17:15.912Z
Learning: In the Dash Wallet app, MerchantDao interface methods use an "excludeType" parameter (e.g., `MerchantType.ONLINE`) to exclude merchants of a specific type rather than to include them. For example, in `observePhysicalMerchants()`, passing `MerchantType.ONLINE` as the exclude type parameter filters out online-only merchants, effectively returning physical merchants.
🪛 detekt (1.23.8)
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt

[warning] 159-159: The caught exception is swallowed. The original exception could be lost.

(detekt.exceptions.SwallowedException)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: check
🔇 Additional comments (19)
features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/MerchantDao.kt (1)

493-494: LGTM! Clean implementation following established patterns.

The new getMerchantById method properly implements merchant lookup by ID with appropriate nullable return type and correct SQL syntax.

features/exploredash/src/main/java/org/dash/wallet/features/exploredash/data/explore/ExploreDataSource.kt (2)

84-84: Interface extension looks good.

The new getMerchantById method signature is consistent with the repository pattern and matches the DAO implementation.


514-516: Proper delegation to DAO layer.

The implementation correctly delegates to the merchantDao.getMerchantById() method, maintaining clean separation of concerns.

features/exploredash/src/main/java/org/dash/wallet/features/exploredash/repository/CTXSpendRepository.kt (3)

37-37: Appropriate import for network error detection.

Adding SSLHandshakeException import supports the new network error detection capability.


42-44: Enhanced exception constructor improves error chaining.

Adding the optional cause parameter enables proper exception chaining while maintaining backward compatibility with existing constructors.


70-71: Useful network error detection property.

The isNetworkError property provides a clean way to identify SSL handshake failures, enabling more specific error handling in the UI layer.

wallet/src/de/schildbach/wallet/ui/transactions/TxResourceMapper.kt (1)

75-84: Good defensive programming to prevent NPE.

The null check for cftx.assetLockPublicKeyId before accessing its bytes property prevents potential crashes and provides appropriate fallback behavior.

features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/dialogs/PurchaseGiftCardConfirmDialog.kt (5)

28-28: Good integration of EnterAmountViewModel for state management.

Adding activity-scoped EnterAmountViewModel enables proper state persistence and cleanup across the purchase flow.

Also applies to: 43-43, 67-67


80-84: Essential null safety check prevents dialog crashes.

The early null check for giftCardMerchant with proper logging and dialog dismissal prevents crashes when merchant data is unavailable during fragment recreation.


108-113: Defensive double-check prevents race conditions.

Re-checking merchant availability before proceeding with confirmation guards against race conditions where merchant data might become null during async operations.


126-133: Enhanced network error handling improves UX.

The specific handling of network errors using ex.isNetworkError provides users with more meaningful error messages for SSL handshake failures and other network issues.


180-180: Proper state cleanup after successful purchase.

Clearing the saved state in EnterAmountViewModel after successful purchase prevents stale input data from affecting subsequent transactions.

common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountFragment.kt (1)

79-82: Good practice: Clearing saved state on navigation back.

Clearing the saved state when navigating back prevents stale data from persisting and improves the user experience.

common/src/main/java/org/dash/wallet/common/ui/enter_amount/EnterAmountViewModel.kt (1)

84-92: Robust error handling for saved state restoration.

Good defensive programming by catching parsing exceptions when restoring fiat amount from saved state. This prevents crashes from corrupted or invalid saved data.

features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/PurchaseGiftCardFragment.kt (2)

90-102: Well-structured state restoration logic.

The merchant setup logic properly handles state restoration by checking saved merchant ID first, then falling back to the currently selected merchant. The error handling with navigation back ensures the UI doesn't get stuck in an invalid state.


214-219: Good null safety handling for merchant access.

The refactored code properly handles the nullable merchant with safe calls and early returns, preventing potential null pointer exceptions.

features/exploredash/src/main/java/org/dash/wallet/features/exploredash/ui/ctxspend/CTXSpendViewModel.kt (3)

86-90: Comprehensive state persistence implementation.

Good implementation of SavedStateHandle for both balance and merchant ID persistence. The observers ensure state is automatically saved when values change.

Also applies to: 142-145


116-121: Smart implementation of nullable merchant with state preservation.

Converting from lateinit to nullable with a custom setter that saves the merchant ID is a robust approach that eliminates potential UninitializedPropertyAccessException while maintaining state persistence.


373-375: Good practice using IO dispatcher for database operations.

Properly using withContext(Dispatchers.IO) for the database query ensures the operation doesn't block the main thread.

@HashEngineering
Copy link
Collaborator Author

@coderabbitai can you review again in light of the PR description

Copy link
Contributor

coderabbitai bot commented Jul 10, 2025

Tip

For best results, initiate chat on the files or code changes.

@HashEngineering Thank you for the clarification! Reviewing the changes in light of the PR description makes the implementation strategy much clearer. The changes are indeed well-focused on the two stated objectives:

Crash Prevention During Fragment/Dialog Recreation

The changes systematically address recreation crashes through:

Saved State Management:

  • EnterAmountViewModel and CTXSpendViewModel now use SavedStateHandle to persist critical state across process death
  • Amount values, currency selection, and merchant data are preserved and restored

Null Safety Improvements:

  • CTXSpendViewModel.giftCardMerchant changed from lateinit var to nullable var with proper null handling
  • CoinbaseBuyDashFragment.fragment made nullable with safe call operators
  • Added comprehensive null checks in PurchaseGiftCardConfirmDialog and PurchaseGiftCardFragment

Process Death Scenario Handling:

  • Try-catch blocks in SearchFragment.onDestroy() and EnterAmountToTransferFragment.onViewCreated() for IllegalArgumentException when navigation graph is no longer on back stack
  • Null check in TxResourceMapper.getTransactionTypeName() for assetLockPublicKeyId

Network Error Handling

Enhanced error management through:

Network Error Detection:

  • CTXSpendException now includes isNetworkError property that detects SSLHandshakeException
  • CTXSpendViewModel.purchaseGiftCard() wraps repository calls in try-catch to properly categorize network errors

Improved User Experience:

  • PurchaseGiftCardConfirmDialog shows dedicated network error dialogs for better user feedback
  • State cleanup after successful operations to prevent stale data issues

The implementation is comprehensive and addresses the root causes mentioned in your PR description. The combination of state persistence, null safety, and proper error handling should significantly improve app stability during fragment recreation and network-related scenarios.

Copy link
Member

@Syn-McJ Syn-McJ left a comment

Choose a reason for hiding this comment

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

Looks good

@HashEngineering HashEngineering merged commit 9e9a304 into master Jul 12, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants