Skip to content

fix: crash when KomodoDefiSdk is disposed during periodic fetch#3117

Merged
CharlVS merged 4 commits intodevfrom
patch-fix-crach-on-exit
Sep 11, 2025
Merged

fix: crash when KomodoDefiSdk is disposed during periodic fetch#3117
CharlVS merged 4 commits intodevfrom
patch-fix-crach-on-exit

Conversation

@DeckerSU
Copy link
Copy Markdown
Contributor

@DeckerSU DeckerSU commented Aug 29, 2025

Added a _closed flag to TradingEntitiesBloc to prevent periodic updates from running after the SDK has been disposed. The timer callback and fetch now check _closed before accessing _kdfSdk.

This prevents StateError (Bad state: KomodoDefiSdk has been disposed) from crashing the app after sign-out or SDK disposal.

On Linux, after exit we saw an exception and crash like this:

[ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: Bad state: KomodoDefiSdk has been disposed
#0      KomodoDefiSdk._assertNotDisposed (package:komodo_defi_sdk/src/komodo_defi_sdk.dart:217)
#1      KomodoDefiSdk._assertSdkInitialized (package:komodo_defi_sdk/src/komodo_defi_sdk.dart:205)
#2      KomodoDefiSdk.auth (package:komodo_defi_sdk/src/komodo_defi_sdk.dart:163)
#3      TradingEntitiesBloc.fetch (package:web_dex/blocs/trading_entities_bloc.dart:64)
#4      TradingEntitiesBloc.runUpdate.<anonymous closure> (package:web_dex/blocs/trading_entities_bloc.dart:83)
#5      _rootRunUnary (dart:async/zone.dart:1538)
#6      _CustomZone.runUnary (dart:async/zone.dart:1429)
#7      _CustomZone.runUnaryGuarded (dart:async/zone.dart:1329)
#8      _CustomZone.bindUnaryCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1367)
#9      _rootRunUnary (dart:async/zone.dart:1546)
#10     _CustomZone.runUnary (dart:async/zone.dart:1429)
#11     _CustomZone.bindUnaryCallback.<anonymous closure> (dart:async/zone.dart:1350)
#12     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:423)
#13     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:454)
#14     _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:193)

Error getting version: ConnectionError
embedder.cc (2572): 'FlutterEngineRemoveView' returned 'kInvalidArguments'. Remove view info was invalid. The implicit view cannot be removed.

** (KomodoWallet:51255): CRITICAL **: 20:45:45.951: FlOpenGLManager *fl_engine_get_opengl_manager(FlEngine *): assertion 'FL_IS_ENGINE(self)' failed
Segmentation fault (core dumped)

This PR should fix this behavior.

TODO: maybe we should also consider timer?.cancel() logic here.

Summary by CodeRabbit

  • Bug Fixes
    • Resolved intermittent errors when closing or navigating away from trading-related views, reducing rare crashes.
    • Background updates now stop cleanly after a view is closed, preventing redundant work and error logs.
    • Improved handling of update failures to ensure the app remains responsive and stable during periodic data refreshes.

Added a `_closed` flag to TradingEntitiesBloc to prevent periodic updates from
running after the SDK has been disposed. The timer callback and `fetch` now
check `_closed` before accessing `_kdfSdk`.

This prevents `StateError (Bad state: KomodoDefiSdk has been disposed)` from
crashing the app after sign-out or SDK disposal.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 29, 2025

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.

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.

Walkthrough

Introduces a private _closed flag to TradingEntitiesBloc, adds early-return guards in fetch() and the Timer.periodic loop, wraps fetch logic in try/catch/finally within runUpdate, sets _closed on StateError containing 'disposed', logs other errors, and ensures updateInProgress is reset in finally. No public API changes.

Changes

Cohort / File(s) Summary
Trading entities bloc lifecycle & error handling
lib/blocs/trading_entities_bloc.dart
Added _closed flag; early exits in fetch() and periodic loop; wrapped periodic fetch() in try/catch/finally; set _closed on 'disposed' StateError; log other errors; ensure updateInProgress resets in finally.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant T as Timer.periodic
  participant B as TradingEntitiesBloc
  participant F as fetch()

  T->>B: tick()
  alt B._closed == true
    B-->>T: return (stop work)
  else Not closed
    B->>B: set updateInProgress = true
    B->>F: fetch()
    alt fetch succeeds
      F-->>B: data
      B->>B: finally: updateInProgress = false
    else fetch throws
      F-->>B: error
      alt StateError contains "disposed"
        B->>B: _closed = true
      else Other error
        B->>B: log "TradingEntitiesBloc.fetch"
      end
      B->>B: finally: updateInProgress = false
    end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I hop through loops that tick and chime,
Then softly pause at shutdown time.
A whisper: “disposed” — I close my eyes,
No more fetches, no surprise.
Errors logged, flags set just right —
A tidy burrow for the night. 🐇✨

✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch patch-fix-crach-on-exit

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.

@github-actions
Copy link
Copy Markdown

github-actions bot commented Aug 29, 2025

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

https://walletrc--pull-3117-merge-j3jo4mw1.web.app

(expires Thu, 18 Sep 2025 14:08:58 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: f66a4ff03faa546f12f0ae5a841bd9eff2714dcc

@CharlVS CharlVS requested a review from Copilot September 1, 2025 10:32
@CharlVS
Copy link
Copy Markdown
Collaborator

CharlVS commented Sep 1, 2025

@cursor review

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Sep 1, 2025

@CharlVS I'll review the changes in this PR for you.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes a crash that occurs when the KomodoDefiSdk is disposed while a periodic timer is still attempting to fetch trading data. The fix adds a _closed flag to prevent operations after disposal.

  • Added a _closed boolean flag to track when the bloc should stop operations
  • Enhanced the periodic timer callback with proper error handling and disposal detection
  • Added early return checks in both fetch() and the timer callback to prevent accessing disposed SDK

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment on lines 85 to +89
updateInProgress = true;
await fetch();
updateInProgress = false;
try {
await fetch();
} catch (e) {
if (e is StateError && e.message.contains('disposed')) {
Copy link

Copilot AI Sep 1, 2025

Choose a reason for hiding this comment

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

The error message check is fragile and could miss disposal errors with different wording. Consider checking the error type more specifically or using a more robust method to detect SDK disposal state.

Suggested change
updateInProgress = true;
await fetch();
updateInProgress = false;
try {
await fetch();
} catch (e) {
if (e is StateError && e.message.contains('disposed')) {
// Check SDK disposal state before running fetch
if (_kdfSdk is Disposable && (_kdfSdk as dynamic).isDisposed == true) {
_closed = true;
return;
}
updateInProgress = true;
try {
await fetch();
} catch (e) {
if (e is StateError) {

Copilot uses AI. Check for mistakes.
Comment on lines +39 to 40
bool _closed = false;

Copy link

Copilot AI Sep 1, 2025

Choose a reason for hiding this comment

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

The _closed flag lacks a proper disposal mechanism. Consider adding a dispose() method that sets _closed = true and cancels the timer to ensure clean resource cleanup.

Suggested change
bool _closed = false;
/// Dispose resources and mark bloc as closed.
void dispose() {
_closed = true;
timer?.cancel();
_authModeListener?.cancel();
_myOrdersController.close();
_swapsController.close();
}

Copilot uses AI. Check for mistakes.
cursor[bot]

This comment was marked as outdated.

Copy link
Copy Markdown
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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/blocs/trading_entities_bloc.dart (1)

169-172: Await order cancellations; current implementation returns early and can drop errors
Without await, the cancellations run unobserved and exceptions are lost.

   Future<void> cancelAllOrders() async {
     final futures = myOrders.map((o) => cancelOrder(o.uuid));
-    Future.wait(futures);
+    await Future.wait(futures);
   }
🧹 Nitpick comments (7)
lib/blocs/trading_entities_bloc.dart (7)

86-99: Log stack trace and correct log context; keep finally semantics
Include the stack trace for diagnosis and tag the log with the caller context (runUpdate).

-      } catch (e) {
+      } catch (e, st) {
         if (e is StateError && e.message.contains('disposed')) {
           _closed = true;
           timer?.cancel();
           timer = null;
           return;
         } else {
-          await log(
-            'fetch error: $e',
-            path: 'TradingEntitiesBloc.fetch',
-          );
+          await log(
+            'fetch error: $e\n$st',
+            path: 'TradingEntitiesBloc.runUpdate',
+          );
         }
       } finally {
         updateInProgress = false;
       }

65-70: Guard is good; optionally handle disposed directly in fetch()
This prevents one extra throw path after disposal when isSignedIn() touches the disposed SDK. Optional duplication of the catch, but keeps fetch() safe if called outside runUpdate().

   Future<void> fetch() async {
     if (_closed) return;
-    if (!await _kdfSdk.auth.isSignedIn()) return;
-
-    myOrders = await _myOrdersService.getOrders() ?? [];
-    swaps = await getRecentSwaps(MyRecentSwapsRequest()) ?? [];
+    try {
+      if (!await _kdfSdk.auth.isSignedIn()) return;
+      myOrders = await _myOrdersService.getOrders() ?? [];
+      swaps = await getRecentSwaps(MyRecentSwapsRequest()) ?? [];
+    } on StateError catch (e) {
+      if (e.message.contains('disposed')) {
+        _closed = true;
+        timer?.cancel();
+        timer = null;
+        return;
+      }
+      rethrow;
+    }
   }

109-120: Avoid materializing lists; short-circuit with any()
Reduces allocations and improves readability.

   bool isCoinBusy(String coin) {
-    return (_swaps
-                .where((swap) => !swap.isCompleted)
-                .where((swap) => swap.sellCoin == coin || swap.buyCoin == coin)
-                .toList()
-                .length +
-            _myOrders
-                .where((order) => order.base == coin || order.rel == coin)
-                .toList()
-                .length) >
-        0;
+    final hasActiveSwap = _swaps.any(
+      (s) => !s.isCompleted && (s.sellCoin == coin || s.buyCoin == coin),
+    );
+    if (hasActiveSwap) return true;
+    return _myOrders.any((o) => o.base == coin || o.rel == coin);
   }

159-167: Protect against divide-by-zero in progress calculation
If order.baseAmount is zero, the UI may get Infinity/NaN.

   double getProgressFillSwap(MyOrder order) {
@@
-    return swapFill / order.baseAmount.toDouble();
+    final base = order.baseAmount.toDouble();
+    if (base == 0) return 0;
+    return swapFill / base;
   }

41-50: Do not mutate caller-provided lists in setters
Clone before sort to avoid side-effects on the input list.

   set myOrders(List<MyOrder> orderList) {
-    orderList.sort((first, second) => second.createdAt - first.createdAt);
-    _myOrders = orderList;
+    final sorted =
+        [...orderList]..sort((a, b) => b.createdAt - a.createdAt);
+    _myOrders = sorted;
     _inMyOrders.add(_myOrders);
   }

57-62: Same cloning suggestion for swaps setter
Avoids mutating swapList passed by callers.

   set swaps(List<Swap> swapList) {
-    swapList.sort((first, second) =>
-        (second.myInfo?.startedAt ?? 0) - (first.myInfo?.startedAt ?? 0));
-    _swaps = swapList;
+    final sorted = [...swapList]
+      ..sort((a, b) => (b.myInfo?.startedAt ?? 0) - (a.myInfo?.startedAt ?? 0));
+    _swaps = sorted;
     _inSwaps.add(_swaps);
   }

39-39: Nit: consider renaming to _isClosed
Improves readability at call sites (if (_isClosed) return;).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5e83be8 and 5ba4fb6.

📒 Files selected for processing (1)
  • lib/blocs/trading_entities_bloc.dart (3 hunks)
⏰ 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). (12)
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Build Desktop (linux)
  • GitHub Check: Build Desktop (windows)
  • GitHub Check: Build Desktop (macos)
  • GitHub Check: build_and_preview
  • GitHub Check: validate_code_guidelines
  • GitHub Check: Test web-app-linux-profile
  • GitHub Check: unit_tests
  • GitHub Check: Test web-app-macos
  • GitHub Check: Build Mobile (Android)
  • GitHub Check: Build Mobile (iOS)

List<MyOrder> _myOrders = [];
List<Swap> _swaps = [];
Timer? timer;
bool _closed = false;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Stop the timer and mark closed during disposal to prevent leaks and stray ticks

Right now the periodic timer keeps firing after close and holds references. Cancel it when _closed flips to true and in dispose(). Also mark _closed in dispose() and close the controllers.

   Timer? timer;
   bool _closed = false;
@@
   @override
   void dispose() {
-    _authModeListener?.cancel();
+    _closed = true;
+    timer?.cancel();
+    timer = null;
+    _authModeListener?.cancel();
+    // Best-effort; returns Future<void>, but dispose() is sync.
+    _myOrdersController.close();
+    _swapsController.close();
   }
@@
     timer = Timer.periodic(const Duration(seconds: 1), (_) async {
-      if (_closed) return;
+      if (_closed) {
+        timer?.cancel();
+        timer = null;
+        return;
+      }
@@
-      } catch (e) {
-        if (e is StateError && e.message.contains('disposed')) {
-          _closed = true;
-        } else {
+      } catch (e) {
+        if (e is StateError && e.message.contains('disposed')) {
+          _closed = true;
+          timer?.cancel();
+          timer = null;
+          return;
+        } else {
           await log(
             'fetch error: $e',
             path: 'TradingEntitiesBloc.fetch',
           );
         }
       } finally {

Also applies to: 72-75, 81-81, 89-91

🤖 Prompt for AI Agents
In lib/blocs/trading_entities_bloc.dart around line 39 (and similarly lines
72-75, 81, 89-91), the periodic Timer is never cancelled and _closed is never
set during disposal; update the class so that when you set _closed = true you
also cancel the Timer (if not null and active), and in dispose() set _closed =
true, cancel the Timer, and close any StreamControllers/subjects used by the
bloc; ensure any periodic callbacks check _closed before running and that all
controller.close() calls are invoked in dispose to prevent leaks and stray
ticks.

@CharlVS CharlVS changed the title fix crash when KomodoDefiSdk is disposed during periodic fetch fix: crash when KomodoDefiSdk is disposed during periodic fetch Sep 1, 2025
@CharlVS CharlVS requested review from CharlVS and smk762 September 2, 2025 11:34
@CharlVS CharlVS added the QA Ready for QA Testing label Sep 2, 2025
Copy link
Copy Markdown
Collaborator

@CharlVS CharlVS left a comment

Choose a reason for hiding this comment

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

As discussed in DMs, you said the AI review comments do not apply to the scope of this PR and/or the comments do not need to be addressed.

@CharlVS CharlVS merged commit 4da682b into dev Sep 11, 2025
9 of 16 checks passed
@CharlVS CharlVS deleted the patch-fix-crach-on-exit branch September 11, 2025 14:36
@CharlVS CharlVS mentioned this pull request Oct 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

QA Ready for QA Testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants