Skip to content

fix(wasm-ops): fix example app login by improving JS call error handling#185

Merged
CharlVS merged 3 commits intodevfrom
bugfix/wasm-js-error-parsing
Aug 13, 2025
Merged

fix(wasm-ops): fix example app login by improving JS call error handling#185
CharlVS merged 3 commits intodevfrom
bugfix/wasm-js-error-parsing

Conversation

@takenagain
Copy link
Copy Markdown
Contributor

@takenagain takenagain commented Aug 12, 2025

Fixes the login error when running the example app via Wasm compilation (flutter run -d chrome --wasm) by improving JS call error handling and type checking.

Komodo wallet did not suffer the same issue, likely because it configures auth listeners after successful login (in AuthBloc)

Before (current dev)

Screen.Recording.2025-08-12.at.13.23.28.mov
Console log snippet
main.dart.mjs:59 Stopping KDF...
main.dart.mjs:59 Error stopping KDF: Type 'JSValue' is not a subtype of type 'Future<Object?>' in type cast
main.dart.mjs:59 KDF stop result: StopStatus.errorStopping
main.dart.mjs:59 [3] KDF: 12 11:56:24, mm2_core::mm_ctx:603] INFO MmCtx (2384139199) has been dropped
main.dart.mjs:59 [3] KDF: 12 11:56:24, mm2_db::indexed_db::db_driver:94] INFO 'MAIN::KOMODEFI::wallets' database has been closed
main.dart.mjs:59 Couldn't get KDF version: Exception: Unknown error for method version: 1
Request: {userpass: eZrd4OB1cIC0JSVk225CiUGid90afp@1, method: version}
main.dart.mjs:59 KDF is not running.
main.dart.mjs:59 Starting KDF main...
main.dart.mjs:59 Unknown error starting KDF: [_TypeError] Type 'JSValue' is not a subtype of type 'Future<dynamic>?' in type cast
main.dart.mjs:59 KDF main result: KdfStartupResult.invalidParams
main.dart.mjs:59 [3] KDF: 12 11:56:24, mm2_main::lp_native_dex:435] INFO Version: 2.5.1-beta_6172ba8 DT 2025-08-05T18:24:17.373329738+00:00
main.dart.mjs:59 Couldn't get KDF version: Exception: Unknown error for method version: 1
Request: {userpass: eZrd4OB1cIC0JSVk225CiUGid90afp@1, method: version}
main.dart.mjs:59 KDF is not running.
main.dart.mjs:59 Starting KDF main...
main.dart.mjs:59 Unknown error starting KDF: [_TypeError] Type 'JSValue' is not a subtype of type 'Future<dynamic>?' in type cast
main.dart.mjs:59 KDF main result: KdfStartupResult.invalidParams
main.dart.mjs:59 KDF main status: MainStatus.noRpc
kdflib.js:990 mm2_wasm_lib:119] MM2 is already running
imports.wbg.__wbg_error_524f506f44df1645 @ kdflib.js:990
$func26506 @ kdflib_bg.wasm:0x1c53d9c
$func917 @ kdflib_bg.wasm:0x949ca8
$func9903 @ kdflib_bg.wasm:0x18623ce
$__wbindgen_export_8 @ kdflib_bg.wasm:0x1c2b947
__wbg_adapter_53 @ kdflib.js:494
real @ kdflib.js:163
setTimeout
_1449 @ main.dart.mjs:559
$_JSEventLoop._setTimeout @ main.dart.wasm:0x1a7311
$_OneShotTimer._schedule @ timer_patch.dart:128
$new _Timer (constructor body) @ timer_patch.dart:115
$new _OneShotTimer (constructor body) @ timer_patch.dart:124
$_OneShotTimer @ timer_patch.dart:124
$Timer._createTimer @ timer_patch.dart:88
$_RootZone.createTimer @ zone.dart:1873
$new Timer @ timer.dart:46
$new Future.delayed @ future.dart:413
$KomodoDefiFramework.kdfStop inner @ komodo_defi_framework.dart:130
$_awaitHelper closure at org-dartlang-sdk:///dart-sdk/lib/_internal/wasm/lib/async_patch.dart:104:5 @ async_patch.dart:105
$closure wrapper at org-dartlang-sdk:///dart-sdk/lib/_internal/wasm/lib/async_patch.dart:104:5 trampoline @ main.dart.wasm:0x183d45
$_RootZone.runUnary @ zone.dart:1849
$_FutureListener.handleValue (body) @ future_impl.dart:224
$_FutureListener.handleValue (checked entry) @ future_impl.dart:223
$_Future._propagateToListeners closure handleValueCallback at org-dartlang-sdk:///dart-sdk/lib/async/future_impl.dart:949:33 @ future_impl.dart:951
$_Future._propagateToListeners @ future_impl.dart:980
$_Future._completeWithValue (body) @ future_impl.dart:723
$_Future._completeWithValue (unchecked entry) @ future_impl.dart:718
$_Future._asyncCompleteWithValue closure at org-dartlang-sdk:///dart-sdk/lib/async/future_impl.dart:806:29 @ future_impl.dart:807
$closure wrapper at org-dartlang-sdk:///dart-sdk/lib/async/future_impl.dart:806:29 trampoline @ main.dart.wasm:0x18127a
$_microtaskLoop @ schedule_microtask.dart:40
$_startMicrotaskLoop @ schedule_microtask.dart:49
$_startMicrotaskLoop tear-off trampoline @ main.dart.wasm:0x1815c8
$_invokeCallback @ timer_patch.dart:71
(anonymous) @ main.dart.mjs:565
main.dart.mjs:59 [3] KDF: 12 11:56:24, mm2_db::indexed_db::db_driver::builder:72] INFO Open 'MAIN::KOMODEFI::wallets' database with tables: {"mnemonics"}
kdflib.js:865 Uncaught (in promise) StartupError {__wbg_ptr: 5246424}
(anonymous) @ kdflib.js:865
handleError @ kdflib.js:105
imports.wbg.__wbg_call_7cccdd69e0791ae2 @ kdflib.js:864
$func21775 @ kdflib_bg.wasm:0x1b7c1ea
$func917 @ kdflib_bg.wasm:0x94a913
$func9903 @ kdflib_bg.wasm:0x18623ce
$__wbindgen_export_8 @ kdflib_bg.wasm:0x1c2b947
__wbg_adapter_53 @ kdflib.js:494
real @ kdflib.js:163
setTimeout
_1449 @ main.dart.mjs:559
$_JSEventLoop._setTimeout @ main.dart.wasm:0x1a7311
$_OneShotTimer._schedule @ timer_patch.dart:128
$new _Timer (constructor body) @ timer_patch.dart:115
$new _OneShotTimer (constructor body) @ timer_patch.dart:124
$_OneShotTimer @ timer_patch.dart:124
$Timer._createTimer @ timer_patch.dart:88
$_RootZone.createTimer @ zone.dart:1873
$new Timer @ timer.dart:46
$new Future.delayed @ future.dart:413
$KomodoDefiFramework.kdfStop inner @ komodo_defi_framework.dart:130
$_awaitHelper closure at org-dartlang-sdk:///dart-sdk/lib/_internal/wasm/lib/async_patch.dart:104:5 @ async_patch.dart:105
$closure wrapper at org-dartlang-sdk:///dart-sdk/lib/_internal/wasm/lib/async_patch.dart:104:5 trampoline @ main.dart.wasm:0x183d45
$_RootZone.runUnary @ zone.dart:1849
$_FutureListener.handleValue (body) @ future_impl.dart:224
$_FutureListener.handleValue (checked entry) @ future_impl.dart:223
$_Future._propagateToListeners closure handleValueCallback at org-dartlang-sdk:///dart-sdk/lib/async/future_impl.dart:949:33 @ future_impl.dart:951
$_Future._propagateToListeners @ future_impl.dart:980
$_Future._completeWithValue (body) @ future_impl.dart:723
$_Future._completeWithValue (unchecked entry) @ future_impl.dart:718
$_Future._asyncCompleteWithValue closure at org-dartlang-sdk:///dart-sdk/lib/async/future_impl.dart:806:29 @ future_impl.dart:807
$closure wrapper at org-dartlang-sdk:///dart-sdk/lib/async/future_impl.dart:806:29 trampoline @ main.dart.wasm:0x18127a
$_microtaskLoop @ schedule_microtask.dart:40
$_startMicrotaskLoop @ schedule_microtask.dart:49
$_startMicrotaskLoop tear-off trampoline @ main.dart.wasm:0x1815c8
$_invokeCallback @ timer_patch.dart:71
(anonymous) @ main.dart.mjs:565
main.dart.mjs:59 KDF main status: MainStatus.noRpc

After

Screen.Recording.2025-08-12.at.13.26.03.mov
Console logs snippet
main.dart.mjs:59 mm2_main called: 0
main.dart.mjs:59 KDF main result: KdfStartupResult.ok
main.dart.mjs:59 KDF main status: MainStatus.rpcIsUp
main.dart.mjs:59 Starting KDF main...
kdflib.js:990 mm2_wasm_lib:119] MM2 is already running
imports.wbg.__wbg_error_524f506f44df1645 @ kdflib.js:990
main.dart.mjs:59 Handling JSAny error: [JSValue] [object Object]
main.dart.mjs:59 KDF main result: KdfStartupResult.alreadyRunning
main.dart.mjs:59 KDF main status: MainStatus.rpcIsUp
main.dart.mjs:59 Starting KDF main...
kdflib.js:990 mm2_wasm_lib:119] MM2 is already running
imports.wbg.__wbg_error_524f506f44df1645 @ kdflib.js:990
main.dart.mjs:59 Handling JSAny error: [JSValue] [object Object]
main.dart.mjs:59 KDF main result: KdfStartupResult.alreadyRunning
main.dart.mjs:59 KDF main status: MainStatus.rpcIsUp

Summary by CodeRabbit

  • New Features

    • More robust JavaScript interop with automatic parsing of responses and promises.
    • Clearer error messages and detection of “already running” states.
  • Bug Fixes

    • More accurate stop status mapping across varied response formats.
    • Improved JSON handling and numeric normalization to reduce parsing errors.
  • Refactor

    • Centralized interop and error handling; removed legacy parsing paths for consistency and reliability.
  • Tests

    • Added unit tests validating stop-result mapping behavior.

@takenagain takenagain self-assigned this Aug 12, 2025
Copilot AI review requested due to automatic review settings August 12, 2025 11:29
@takenagain takenagain added the bug Something isn't working label Aug 12, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 12, 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 new JS interop utilities and error/result mappers, integrates them into KDF WASM operations for startup/stop flows, updates JSON type normalization and error messages, and adds unit tests for stop-result mapping. Legacy parsing in KDF operations is removed in favor of centralized helpers.

Changes

Cohort / File(s) Summary of Changes
JS interop utilities
packages/komodo_defi_framework/lib/src/js/js_error_utils.dart, packages/komodo_defi_framework/lib/src/js/js_interop_utils.dart, packages/komodo_defi_framework/lib/src/js/js_result_mappers.dart
New helpers for extracting numeric codes/messages from dartified JS errors, parsing/normalizing JS interop JSON and promises, and mapping mm2_stop results to StopStatus.
KDF WASM operations
packages/komodo_defi_framework/lib/src/operations/kdf_operations_wasm.dart
Replaces ad-hoc interop with new utilities for mm2_main, mm2_stop, error handling, and RPC parsing; removes legacy deep-conversion and response parsing. Adds conditional debug logging.
Types JSON utils
packages/komodo_defi_types/lib/src/utils/json_type_utils.dart
Adds numeric normalization (num→int/double) and clearer errors when parsing JSON strings to JsonMap/JsonList. Formatting tweaks.
Tests
packages/komodo_defi_framework/test/js/js_result_mappers_test.dart
New unit tests validating mapJsStopResult across numeric, string, map, and null inputs.

Sequence Diagram(s)

sequenceDiagram
  participant C as Caller
  participant K as KdfOperationsWasm
  participant JS as JS (mm2_main)
  participant U as Interop Utils

  C->>K: start()
  K->>JS: mm2_main(...)
  JS-->>K: value or Promise
  K->>U: parseJsInteropMaybePromise<int>(jsValue)
  U-->>K: int result
  K-->>C: KdfStartupResult.fromDefaultInt(result)
Loading
sequenceDiagram
  participant C as Caller
  participant K as KdfOperationsWasm
  participant JS as JS (mm2_stop)
  participant U as Interop Utils
  participant M as Result Mapper

  C->>K: stop()
  K->>JS: mm2_stop()
  JS-->>K: value or Promise
  K->>U: parseJsInteropMaybePromise(jsValue, mapper)
  U->>M: mapJsStopResult(dartValue)
  M-->>U: StopStatus
  U-->>K: StopStatus
  alt status is ok or stoppingAlready
    loop until notRunning or timeout
      K->>K: poll kdfMainStatus()
    end
  end
  K-->>C: StopStatus
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • CharlVS

Poem

A hop, a skip, I bridge JS and Dart,
With tidy maps and errors picked apart.
mm2 starts, mm2 stops—so neat!
Promises tamed beneath my feet.
I thump approve: results align—
Carrots for tests, all green and fine! 🥕🐇

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bugfix/wasm-js-error-parsing

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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
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 JS interop error handling in the WASM operations to resolve login issues in the example app. The changes improve robustness when dealing with type conversions and error responses from JavaScript calls.

  • Adds numeric type normalization for int/double conversion in WASM interop scenarios
  • Introduces centralized JS error handling utilities and result mappers
  • Refactors WASM operations to use new error handling patterns for better reliability

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
json_type_utils.dart Adds numeric type normalization and minor formatting fixes
js_result_mappers_test.dart New test file for JS result mapping functions
kdf_operations_wasm.dart Major refactor to use centralized JS error handling utilities
js_result_mappers.dart New utility for mapping JS stop result responses
js_interop_utils.dart New comprehensive JS interop utilities for type conversion
js_error_utils.dart New utilities for extracting error codes and messages from JS values

Comment thread packages/komodo_defi_framework/lib/src/js/js_interop_utils.dart Outdated
Comment thread packages/komodo_defi_framework/lib/src/js/js_error_utils.dart Outdated
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Aug 12, 2025

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

https://komodo-defi-sdk--pr185-bugfix-wasm-js-error-qenfk0bo.web.app

(expires Tue, 19 Aug 2025 12:19:49 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 7f9f5ac39928f333b6e8fcefb7138575e24ed347

cursor[bot]

This comment was marked as outdated.

@takenagain
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 12, 2025

✅ 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

@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: 0

♻️ Duplicate comments (1)
packages/komodo_defi_framework/lib/src/js/js_interop_utils.dart (1)

144-145: Potential TypeError risk from unsafe cast

The direct cast dartValue as T without validation could throw a TypeError at runtime if the actual type doesn't match the expected type T. Consider adding type checking or wrapping in a try-catch to provide more informative error messages.

   // Fallback: attempt a direct cast; this will surface a clear type error
-  return dartValue as T;
+  try {
+    return dartValue as T;
+  } catch (e) {
+    throw FormatException(
+      'Failed to cast dartValue of type ${dartValue.runtimeType} to expected type $T',
+    );
+  }
🧹 Nitpick comments (6)
packages/komodo_defi_types/lib/src/utils/json_type_utils.dart (2)

115-127: Improve error message clarity

The error message mentions "Expected a JSON string to parse" but the actual expectation is that the string should be valid JSON that decodes to a Map. Consider making the error message more specific.

-          throw ArgumentError(
-            'Expected a JSON string to parse, but got an invalid type: '
-            '${value.runtimeType}',
-          );
+          throw ArgumentError(
+            'Failed to parse string as JsonMap. Expected valid JSON string, '
+            'but parsing failed for value of type: ${value.runtimeType}',
+          );

133-143: Inconsistent error message between JsonMap and JsonList parsing

The error message for JsonList parsing mentions "JSON string representing a List" but doesn't clarify that the parsing failed. Consider aligning with the JsonMap error message pattern.

           throw ArgumentError(
-            'Expected a JSON string representing a List, '
-            'but got an invalid type: ${value.runtimeType}',
+            'Failed to parse string as JsonList. Expected valid JSON array string, '
+            'but parsing failed for value of type: ${value.runtimeType}',
           );
packages/komodo_defi_framework/lib/src/js/js_error_utils.dart (1)

52-57: Consider extracting the heuristic patterns to constants

The TODO comment suggests future generalization. Consider extracting the matching patterns as constants now to make future extensions easier.

+const List<String> _alreadyRunningPatterns = [
+  'already running',
+  'already_running',
+];
+
 // TODO: generalise to a log/string-based watcher for other KDF errors
 /// Heuristic matcher for common "already running" messages.
 bool messageIndicatesAlreadyRunning(String message) {
   final lower = message.toLowerCase();
-  return lower.contains('already running') || lower.contains('already_running');
+  return _alreadyRunningPatterns.any((pattern) => lower.contains(pattern));
 }
packages/komodo_defi_framework/lib/src/js/js_result_mappers.dart (1)

30-43: Consider adding logging for unexpected map structures

When processing Map inputs, the function silently defaults to StopStatus.ok for unexpected structures. Consider adding debug logging to help diagnose integration issues.

+import 'package:logging/logging.dart';
+
+final _logger = Logger('JsResultMappers');
+
 StopStatus mapJsStopResult(dynamic result) {
   // ... existing code ...
   
   if (result is Map) {
     final map = result;
     if (map.containsKey('error') && map['error'] != null) {
       return StopStatus.errorStopping;
     }
     final inner = map['result'];
     if (inner is String) return mapJsStopResult(inner);
     if (inner is num) return StopStatus.fromDefaultInt(inner.toInt());

     final code = map['code'];
     if (code is num) return StopStatus.fromDefaultInt(code.toInt());

+    // Log unexpected map structure for debugging
+    _logger.fine('Unexpected map structure in stop result, defaulting to ok: $map');
     return StopStatus.ok;
   }

+  _logger.fine('Unrecognized stop result type ${result.runtimeType}, defaulting to ok');
   return StopStatus.ok;
 }
packages/komodo_defi_framework/lib/src/operations/kdf_operations_wasm.dart (2)

118-120: Consider extracting debug logging to a helper method.

The repeated pattern of checking KdfLoggingConfig.debugLogging before logging could be extracted into a debug-specific logging method to reduce code duplication.

Add a debug logging helper method:

  void _log(String message) => (_logger ?? print).call(message);
+
+ void _debugLog(String message) {
+   if (KdfLoggingConfig.debugLogging) {
+     _log(message);
+   }
+ }

Then replace the conditional logging calls throughout the file:

- if (KdfLoggingConfig.debugLogging) {
-   _log('Handling JSAny error: [${jsError.runtimeType}] $jsError');
- }
+ _debugLog('Handling JSAny error: [${jsError.runtimeType}] $jsError');

178-184: Consider simplifying the type checking logic.

The isInstance method has redundant type checking that could be simplified.

The current implementation checks both obj is T and instanceOfString. Since JavaScript types don't directly map to Dart types via is operator, the first check might be redundant:

  bool isInstance<T extends js_interop.JSAny?>(
    js_interop.JSAny? obj, [
    String? typeString,
  ]) {
-   return obj is T ||
-       obj.instanceOfString(typeString ?? T.runtimeType.toString());
+   return obj.instanceOfString(typeString ?? T.runtimeType.toString());
  }

However, if the obj is T check is intentionally kept for Dart-side type checking, consider adding a comment explaining this dual-checking strategy.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 62b919f and 0e33368.

📒 Files selected for processing (6)
  • packages/komodo_defi_framework/lib/src/js/js_error_utils.dart (1 hunks)
  • packages/komodo_defi_framework/lib/src/js/js_interop_utils.dart (1 hunks)
  • packages/komodo_defi_framework/lib/src/js/js_result_mappers.dart (1 hunks)
  • packages/komodo_defi_framework/lib/src/operations/kdf_operations_wasm.dart (3 hunks)
  • packages/komodo_defi_framework/test/js/js_result_mappers_test.dart (1 hunks)
  • packages/komodo_defi_types/lib/src/utils/json_type_utils.dart (4 hunks)
🔇 Additional comments (10)
packages/komodo_defi_types/lib/src/utils/json_type_utils.dart (1)

158-165: Good addition for WASM interop numeric normalization

The numeric type normalization between int and double is a good addition that will help prevent type mismatches when dealing with JavaScript numeric values in WASM contexts.

packages/komodo_defi_framework/test/js/js_result_mappers_test.dart (1)

5-36: Comprehensive test coverage for mapJsStopResult

The test suite provides good coverage of various input types and edge cases, including numeric codes, string responses with different cases, map structures with various keys, and null handling. The tests align well with the implementation's behavior.

packages/komodo_defi_framework/lib/src/js/js_result_mappers.dart (1)

3-11: Well-documented function with clear input expectations

The documentation clearly describes the various input shapes and their expected mappings, which is helpful for maintainability.

packages/komodo_defi_framework/lib/src/operations/kdf_operations_wasm.dart (7)

10-12: LGTM! Good centralization of JS interop utilities.

The extraction of JS error handling and result mapping into separate utility modules improves maintainability and reusability across the codebase.


102-114: LGTM! Clean refactoring of KDF main execution.

The new implementation properly handles both Promise and direct value returns using the centralized parseJsInteropMaybePromise utility, simplifying the previous Future/dartify flow.


123-132: LGTM! Robust handling of JSNumber errors.

The error handling properly extracts numeric codes from JSNumber types using the centralized utility functions.


138-146: LGTM! Comprehensive JSObject error extraction.

The code properly attempts multiple extraction strategies: dartify first, then numeric code extraction, and finally message extraction with already-running detection.


199-226: LGTM! Well-structured stop operation with proper polling.

The implementation correctly:

  1. Uses the centralized result mapper for stop status
  2. Implements polling with timeout to ensure the node actually stops
  3. Handles various error cases appropriately

The 10-second timeout with 300ms polling intervals provides a good balance between responsiveness and avoiding excessive polling.


233-234: LGTM! Clean replacement of legacy parsing with centralized utility.

The use of parseJsInteropJson simplifies the JSON parsing logic and removes the need for the complex _parseDartResponse, _deepConvertMap, and _deepConvertList methods.


241-289: LGTM! Comprehensive error handling and debugging support.

The _makeJsCall method provides excellent error handling with detailed error messages and optional debug logging for troubleshooting.

@takenagain takenagain requested a review from CharlVS August 12, 2025 12:17
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.

That's hot

@CharlVS CharlVS merged commit 6e487e3 into dev Aug 13, 2025
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants