Skip to content

Implement wasm macro on DotrainOrderGui deposit methods#1456

Merged
hardyjosh merged 6 commits intomainfrom
2025-04-12-wasm-macro-deposit-methods
Mar 26, 2025
Merged

Implement wasm macro on DotrainOrderGui deposit methods#1456
hardyjosh merged 6 commits intomainfrom
2025-04-12-wasm-macro-deposit-methods

Conversation

@findolor
Copy link
Copy Markdown
Collaborator

@findolor findolor commented Mar 12, 2025

Caution

Do not merge before #1452

Motivation

Solution

Checks

By submitting this for review, I'm confirming I've done the following:

  • made this PR as small as possible
  • unit-tested any new functionality
  • linked any relevant issues or PRs
  • included screenshots (if this involves a front-end change)

fix #1402

Summary by CodeRabbit

  • New Features

    • Enhanced deposit validation to ensure only valid tokens are processed, resulting in clearer and more informative error notifications during deposit operations.
    • Improved error handling in the DepositInput component for better user experience when retrieving deposits.
  • Bug Fixes

    • Improved error handling in deposit interactions, ensuring smoother and more reliable deposit management throughout the user interface.
    • Consistent error handling across the test suite for deposit-related functionalities.

@findolor findolor added the rust Related to rust crates label Mar 12, 2025
@findolor findolor requested a review from hardyjosh March 12, 2025 06:10
@findolor findolor self-assigned this Mar 12, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 12, 2025

Walkthrough

This pull request introduces modifications to the DotrainOrderGui implementation, adding a new method check_deposits for validating deposits and updating several existing methods to use the #[wasm_export] attribute with revised return types. The test suite is updated to utilize the extractWasmEncodedData utility for error handling and data extraction, while the DepositInput component tests now instantiate a real DotrainOrderGui class with mocked methods. Enhanced error handling is also implemented in the Svelte component.

Changes

File(s) Change Summary
crates/js_api/src/gui/deposits.rs Added new method check_deposits for validating deposits; replaced #[wasm_bindgen] with #[wasm_export] on methods (e.g., getDeposits, saveDeposit, removeDeposit, getDepositPresets, getMissingDeposits, hasAnyDeposit); updated return types to include unchecked_return_type and changed error handling (e.g., hasAnyDeposit now returns a Result<bool, GuiError>).
packages/orderbook/test/js_api/gui.test.ts,
packages/ui-components/src/__tests__/DepositInput.test.ts
Updated tests to use the new extractWasmEncodedData utility for processing results from GUI methods and to instantiate a real DotrainOrderGui instance with prototype-level method mocks instead of relying on a manually constructed mock object.
packages/ui-components/src/lib/components/deployment/DepositInput.svelte Enhanced error handling in component functions (setCurrentDeposit, handlePresetClick, and handleInput) by checking asynchronous results from methods like getDeposits and throwing errors based on the encountered issue.

Sequence Diagram(s)

sequenceDiagram
    participant JS as JavaScript Client
    participant Gui as DotrainOrderGui
    participant Validator as Deposit Validator

    JS->>Gui: call check_deposits()
    Gui->>Validator: Validate each deposit (check token selected & existence)
    Validator-->>Gui: Return validation result or error
    Gui-->>JS: Return Ok or GuiError
Loading
sequenceDiagram
    participant Test as Test Suite
    participant Extractor as extractWasmEncodedData
    participant Gui as DotrainOrderGui

    Test->>Gui: call getDeposits() / other methods
    Gui-->>Test: Return raw result (value/error)
    Test->>Extractor: Process raw result
    Extractor-->>Test: Return extracted data or error details
Loading

Assessment against linked issues

Objective Addressed Explanation
Macro for exporting DotrainOrderGui methods (#1402)

Possibly related PRs

Suggested reviewers

  • hardyjosh

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c3f468d and c21b80b.

📒 Files selected for processing (1)
  • packages/ui-components/src/lib/components/deployment/DepositInput.svelte (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Deploy-Preview
  • GitHub Check: test
  • GitHub Check: standard-tests (ubuntu-latest, ob-rs-test, true)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-legal)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-static)
  • GitHub Check: standard-tests (ubuntu-latest, test-js-bindings)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-artifacts, true)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-artifacts)
  • GitHub Check: test
  • GitHub Check: build-tauri (ubuntu-22.04, true)
  • GitHub Check: git-clean
  • GitHub Check: test
🔇 Additional comments (4)
packages/ui-components/src/lib/components/deployment/DepositInput.svelte (4)

25-31: Good refactoring of common error checking logic.

Extracting the common deposit retrieval and error checking logic into a dedicated function improves maintainability and reduces code duplication. This function properly throws errors when necessary, which can then be caught by the calling functions.


33-41: Successfully simplified the setCurrentDeposit function.

The function now appropriately uses the extracted getCurrentDeposit method and includes proper error handling with a meaningful error message. The conversion from async to synchronous is appropriate since the function no longer contains asynchronous operations.


65-69: Improved error handling in handlePresetClick.

This change addresses a previous review comment by implementing proper error handling with a try-catch block. The error message is specific to the preset click operation, which enhances debuggability.


80-84: Improved error handling in handleInput.

This change addresses a previous review comment by implementing proper error handling with a try-catch block. The error message is specific to the input handling operation, which improves error clarity for users.


🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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
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

🔭 Outside diff range comments (1)
packages/ui-components/src/lib/components/deployment/DepositInput.svelte (1)

54-66: 🛠️ Refactor suggestion

Missing error handling in handlePresetClick function

Similar to handleInput, the handlePresetClick function throws an error but doesn't have a try/catch block to handle it. This could cause unhandled exceptions in the UI.

function handlePresetClick(preset: string) {
  if (deposit.token?.key) {
    inputValue = preset;
    gui?.saveDeposit(deposit.token?.key, preset);
    gui = gui;
+   try {
      const deposits = gui.getDeposits();
      if (deposits.error) {
        throw new Error(deposits.error.msg);
      }
      currentDeposit = deposits.value.find((d) => d.token === deposit.token?.key);
+   } catch (e) {
+     error = e instanceof Error ? e.message : 'Error getting deposits';
+   }
  }
}
🧹 Nitpick comments (4)
packages/ui-components/src/lib/components/deployment/DepositInput.svelte (1)

60-64: Consider extracting error handling pattern to a utility function

The error handling pattern is repeated multiple times in this file (and across other files). Consider creating a utility function to handle this common pattern to reduce duplication and improve maintainability.

+ // Add this to a utils file
+ function handleResult<T>(result: { error?: { msg: string }, value?: T }): T {
+   if (result.error) {
+     throw new Error(result.error.msg);
+   }
+   return result.value as T;
+ }

// Then use it like:
- const deposits = gui.getDeposits();
- if (deposits.error) {
-   throw new Error(deposits.error.msg);
- }
- currentDeposit = deposits.value.find((d) => d.token === deposit.token?.key);
+ const deposits = handleResult(gui.getDeposits());
+ currentDeposit = deposits.find((d) => d.token === deposit.token?.key);
crates/js_api/src/gui/deposits.rs (2)

12-33: Consider adding deposit context in error messages.

The check_deposits method appropriately checks for missing or unselected tokens. However, to aid in debugging, you might consider including more context—such as deposit index or deposit name—in the error message. This additional detail can be especially helpful when multiple deposits fail validation.


83-113: Validate amount format if necessary.

The save_deposit method conditionally removes or updates deposits based on the provided amount string. Consider validating numeric formats if the deposit amount must be strictly numeric. Otherwise, code logic looks straightforward and consistent with project conventions.

crates/js_api/src/gui/mod.rs (1)

166-193: Potential parallelization for retrieving many tokens.

get_all_token_infos processes each token key sequentially. Consider fetching token info concurrently if performance becomes a concern, especially with substantial token lists.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1dfe8cb and d7e7c14.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • tauri-app/src-tauri/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (22)
  • Cargo.toml (2 hunks)
  • crates/common/src/dotrain_order/mod.rs (2 hunks)
  • crates/js_api/src/gui/deposits.rs (5 hunks)
  • crates/js_api/src/gui/mod.rs (8 hunks)
  • packages/orderbook/test/js_api/gui.test.ts (38 hunks)
  • packages/ui-components/src/__tests__/DeploymentsSection.test.ts (3 hunks)
  • packages/ui-components/src/__tests__/DepositInput.test.ts (2 hunks)
  • packages/ui-components/src/__tests__/StrategyPage.test.ts (10 hunks)
  • packages/ui-components/src/__tests__/TokenIOInput.test.ts (4 hunks)
  • packages/ui-components/src/lib/components/deployment/ComposedRainlangModal.svelte (1 hunks)
  • packages/ui-components/src/lib/components/deployment/DeploymentSteps.svelte (6 hunks)
  • packages/ui-components/src/lib/components/deployment/DeploymentsSection.svelte (1 hunks)
  • packages/ui-components/src/lib/components/deployment/DepositInput.svelte (4 hunks)
  • packages/ui-components/src/lib/components/deployment/SelectToken.svelte (2 hunks)
  • packages/ui-components/src/lib/components/deployment/StrategyPage.svelte (1 hunks)
  • packages/ui-components/src/lib/components/deployment/TokenIOInput.svelte (1 hunks)
  • packages/ui-components/test-setup.ts (2 hunks)
  • packages/webapp/src/__tests__/handleGuiInitialization.test.ts (1 hunks)
  • packages/webapp/src/lib/services/handleGuiInitialization.ts (3 hunks)
  • packages/webapp/src/routes/deploy/+layout.ts (1 hunks)
  • packages/webapp/src/routes/deploy/[strategyName]/[deploymentKey]/+layout.ts (1 hunks)
  • packages/webapp/test-setup.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-legal)
  • GitHub Check: standard-tests (ubuntu-latest, test-js-bindings)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-artifacts, true)
  • GitHub Check: test
  • GitHub Check: build-tauri (ubuntu-22.04, true)
  • GitHub Check: standard-tests (ubuntu-latest, ob-rs-test, true)
  • GitHub Check: git-clean
  • GitHub Check: test
  • GitHub Check: Deploy-Preview
  • GitHub Check: test
🔇 Additional comments (75)
packages/webapp/test-setup.ts (1)

11-20: Good update to the test mocks to align with the WASM implementation changes

The mocks correctly mirror the structure of the actual DotrainOrderGui class, adding both a static method deserializeState and an instance method chooseDeployment. This will ensure the tests remain valid with the updated error handling pattern across the application.

packages/webapp/src/routes/deploy/[strategyName]/[deploymentKey]/+layout.ts (1)

12-16: Improved error handling implementation

The updated code properly handles potential errors from the getDeploymentDetail method by checking for the presence of error in the result object before destructuring the value. This change makes the code more robust by explicitly handling error conditions rather than assuming the call will always succeed.

packages/ui-components/src/lib/components/deployment/DeploymentsSection.svelte (1)

13-17: Proper error handling pattern implemented

The updated code correctly checks for errors in the result object before accessing the value, which is consistent with the WASM export pattern now used in the DotrainOrderGui implementation. This ensures that errors are properly propagated and handled rather than causing runtime exceptions.

packages/ui-components/src/lib/components/deployment/DepositInput.svelte (2)

27-31: Error handling added to getDeposits method

The code now properly checks for errors in the deposits result before accessing the value. This is a good improvement that aligns with the WASM export pattern.


41-45: Proper error handling for getTokenInfo

Adding error checking before accessing the result value is the correct approach for handling the WASM export pattern. This change improves the robustness of the component.

packages/webapp/src/routes/deploy/+layout.ts (1)

13-17: Enhanced error handling for strategy details retrieval

The code now properly handles errors returned from DotrainOrderGui.getStrategyDetails() by checking for the presence of an error in the result object and throwing it explicitly, rather than relying on the function to throw errors directly. This makes the error handling more explicit and consistent with other parts of the codebase.

packages/ui-components/src/lib/components/deployment/SelectToken.svelte (2)

22-26: Improved error handling for token information retrieval

The code now properly checks for errors in the result returned from gui.getTokenInfo() before proceeding, which ensures that any issues are properly propagated as exceptions.


38-42: Consistent error handling for token information retrieval

The same error handling pattern is applied here as in the previous token info retrieval, maintaining consistency throughout the component.

packages/ui-components/src/lib/components/deployment/StrategyPage.svelte (1)

30-34: Enhanced error handling for strategy details

The code now properly handles errors returned from DotrainOrderGui.getStrategyDetails() by explicitly checking for the presence of an error in the result object and throwing it with a meaningful message. This is consistent with the error handling improvements made across the codebase.

crates/common/src/dotrain_order/mod.rs (2)

12-12: Streamlined imports with additional functionality

The import has been modified to include default_document along with YamlError and YamlParsable, which is needed for the new dummy() method implementation.


126-135: Added convenience method for creating default DotrainOrder instances

A new dummy() method has been added to create default instances of DotrainOrder, which is useful for testing and initialization purposes. The implementation correctly sets up a minimal valid instance with an empty dotrain string and a default document in the yaml structure.

packages/ui-components/src/lib/components/deployment/TokenIOInput.svelte (1)

32-37: Improved error handling with structured response format

The code has been refactored to handle responses using a structured error pattern. This is a good enhancement that makes error handling more explicit and consistent.

Note that the optional chaining operator (?.) in line 32 on vault.token?.key is still used while it was removed from the gui object, suggesting gui is now expected to be defined at this point.

packages/ui-components/src/lib/components/deployment/ComposedRainlangModal.svelte (1)

14-19:

Details

❓ Verification inconclusive

Enhanced error handling with structured result

The implementation now correctly handles the structured result object returned by getComposedRainlang(). This follows the same pattern as other components in the codebase, ensuring consistent error handling.

Note that this implementation throws an error rather than setting an error state variable like some other components do. Consider whether this is intentional or if it should follow the same pattern as other components by displaying errors to the user rather than throwing them.

Confirm whether this error handling approach is consistent with the application's error handling strategy:


🌐 Web query:

What is the best practice for handling errors in Svelte components - throwing errors vs displaying error messages?

💡 Result:

When handling errors in Svelte components, best practices depend on error type and context. Here's a structured approach:


Expected vs. Unexpected Errors

  1. Expected Errors (e.g., validation failures, API timeouts):

    • Throw structured errors using SvelteKit’s error helper:
      import { error } from '@sveltejs/kit';
      throw error(404, 'Resource not found');
      • SvelteKit automatically renders the nearest +error.svelte page with $page.error containing your message[2][8].
    • Avoid try...catch in actions for expected validation errors. Instead, use fail for form submissions to maintain response flow[6]:
      import { fail } from '@sveltejs/kit';
      return fail(400, { message: 'Invalid email' });
  2. Unexpected Errors (e.g., runtime bugs, unhandled exceptions):

    • Use error boundaries to isolate component crashes:
      <svelte:boundary onerror={(error, reset) => logError(error)}>
        <ComponentThatMightCrash />
      </svelte:boundary>
      • Prevents app-wide crashes and allows recovery via reset[4].
    • Log errors globally via handleError hook for monitoring:
      export function handleError({ error }) {
        console.error(error);
        return { message: 'Internal Error' }; // Generic user-facing message
      }

Best Practices

Approach Use Case Example
error helper HTTP/expected errors throw error(404, 'Page not found')
fail method Form validation errors return fail(400, { email: 'Invalid format' })
Error boundaries Component rendering errors <svelte:boundary onerror={...}>
Global listeners Uncaught exceptions/promise rejections window.onerror = (msg, source) => { ... }

Key Recommendations

  • Avoid exposing sensitive details: Unexpected errors show a generic message (e.g., "Internal Error") by default[12].
  • Type safety: Define App.PageError to standardize error structures[8].
  • Proactive monitoring: Use tools like Zipy for error tracking and session replay[1][3][10].

Example Flow

  1. Validation failure → Return fail with user-facing message.
  2. API error → Throw error with status code.
  3. Component crash → Catch with <svelte:boundary> and log.
  4. Global error → Log via handleError and display fallback UI.

By combining Svelte’s built-in tools with structured error boundaries, you balance user experience and debuggability.

Citations:


Confirm Consistent Error Handling Across Components
The updated implementation in packages/ui-components/src/lib/components/deployment/ComposedRainlangModal.svelte now handles the structured result from getComposedRainlang() correctly by throwing an error when one is returned. This approach aligns with Svelte’s best practices for handling certain error types—specifically, throwing structured errors (e.g., via SvelteKit’s error helper) for cases where a standardized error page is appropriate. However, note that other components display error messages inline by updating an error state instead of throwing errors.

Please verify whether this modal’s error handling should continue throwing errors (to potentially leverage global error boundaries and SvelteKit’s mechanisms) or if it should be modified to display error messages inline for a more user-friendly experience.

  • File: packages/ui-components/src/lib/components/deployment/ComposedRainlangModal.svelte (Lines 14-19)
  • Diff Snippet Remains:
    		let result = await gui.getComposedRainlang();
    		if (result.error) {
    			throw new Error(result.error.msg);
    		}
    		rainlangText = result.value;
    		open = true;
packages/ui-components/src/__tests__/DeploymentsSection.test.ts (3)

2-2: Added Mock type import for improved type safety

Good addition of the type Mock import from Vitest to ensure type safety when working with mocks.


19-19: Updated mock to match new result structure

The mock implementation has been updated to return a structured result with a value property, matching the new API contract. This ensures that tests align with the actual implementation.


37-39: Error case mock updated to use structured result pattern

The error case mock has been updated to return an object with an error property instead of rejecting with an error. This aligns with the new error handling pattern implemented across the application.

Cargo.toml (2)

80-80: Fixed formatting in path declaration

Minor formatting improvement to the path declaration for rain_orderbook_math.


56-56:

Details

❓ Verification inconclusive

Updated wasm-bindgen-utils to use specific Git commit

The dependency has been changed from a version string to a Git repository reference with a specific commit hash. This ensures consistency and removes potential issues with version incompatibilities.

Make sure this specific commit has been thoroughly tested with your application, as pinning to a specific commit can make future upgrades more challenging.


🏁 Script executed:

#!/bin/bash
# Check if this is the latest commit in the repo
gh repo view rainlanguage/rain.wasm --json defaultBranchRef --jq '.defaultBranchRef.name' > branch.txt
DEFAULT_BRANCH=$(cat branch.txt)
COMMIT_HASH="939b59f7b52798e04a988cef435030d78eb11e91"
LATEST_COMMIT=$(gh api repos/rainlanguage/rain.wasm/commits/$DEFAULT_BRANCH --jq '.sha')

echo "Checking if commit $COMMIT_HASH is the latest in $DEFAULT_BRANCH branch..."
echo "Latest commit: $LATEST_COMMIT"

if [ "$COMMIT_HASH" = "$LATEST_COMMIT" ]; then
  echo "✅ The specified commit is the latest on the default branch."
else
  echo "⚠️ The specified commit is NOT the latest on the default branch."
  echo "Checking when this commit was created..."
  COMMIT_DATE=$(gh api repos/rainlanguage/rain.wasm/commits/$COMMIT_HASH --jq '.commit.author.date')
  echo "Commit date: $COMMIT_DATE"
  
  echo "Checking for newer commits since then..."
  NEWER_COMMITS=$(gh api repos/rainlanguage/rain.wasm/commits --query="since=$COMMIT_DATE" --jq 'length')
  echo "Number of newer commits: $NEWER_COMMITS"
fi

Length of output: 2795


Action: Verify the chosen commit for wasm-bindgen-utils is intentional

It appears that the wasm-bindgen-utils dependency in Cargo.toml at line 56 now points to commit
939b59f7b52798e04a988cef435030d78eb11e91, which is not the latest commit on the default main branch (the latest is c8e1105dd5b524d57a8fdbc6545f493043e06d7c).
If you have deliberately pinned to this older commit, please ensure it has been thoroughly tested with your application. If not, consider whether upgrading to the latest commit might be beneficial to avoid potential issues arising from outdated functionality.

  • File: Cargo.toml (line 56)
  • Diff snippet:
    wasm-bindgen-utils = { git = "https://github.com/rainlanguage/rain.wasm", rev = "939b59f7b52798e04a988cef435030d78eb11e91" }
packages/webapp/src/lib/services/handleGuiInitialization.ts (4)

1-1: Good addition of the WasmEncodedResult type import.

The explicit import of the WasmEncodedResult type improves type safety and readability by making it clear what kind of result structure we're dealing with.


10-11: Improved initialization with explicit type declaration.

The change from initializing gui as null to creating a new instance directly is a good improvement. Adding the typed result variable enhances type safety for the error handling that follows.


21-24: Proper error handling implementation.

The code now correctly checks for errors in the result object and throws a meaningful error message. This is an important improvement for robustness.


27-30: Consistent error handling pattern.

The error handling pattern is consistently applied across different code paths, which is good for maintainability and debugging.

packages/ui-components/src/__tests__/TokenIOInput.test.ts (7)

5-5: Adding DotrainOrderGui import for actual instance testing.

Good practice to import the actual class being tested rather than relying on mocks.


7-7: Type declaration changed to local scope.

Changed from exported type to locally scoped type, which is appropriate since this type is only used within this test file.


10-10: Using actual DotrainOrderGui instance in tests.

This change makes the tests more realistic by testing against an actual instance of the class rather than a mock object.


22-27: Updated mock structure with value property.

The addition of the value property in the mock response aligns with the new WASM result pattern, making the tests consistent with the implementation.


29-51: Well-structured test setup with prototype mocking.

The test setup is now more maintainable with clear mock implementations on the DotrainOrderGui prototype. The organization with clearing mocks first, then instantiating the class, and finally setting up mocks is a good practice.


53-64: Updated mock props to use the DotrainOrderGui instance.

Props are correctly updated to use the actual instance, maintaining consistency throughout the test.


88-88: Updated method expectations for new instance-based approach.

Test expectations are properly updated to check calls on the instance methods rather than static methods.

Also applies to: 95-95, 125-125

packages/ui-components/src/__tests__/DepositInput.test.ts (7)

6-6: Added DotrainOrderGui import for instance-based testing.

Consistent with the changes in other test files, importing the actual class enhances test realism.


12-12: Using DotrainOrderGui instance in tests.

Consistent with other test files, using an actual instance makes tests more realistic.


20-29: Improved test setup with instance and prototype mocking.

The test setup now follows the same pattern as other test files, with clear initialization and mock implementations on the prototype.


33-38: Updated mock return structure with value property.

The mock response now includes a value property, consistent with the WASM result pattern used throughout the codebase.


43-43: Updated component props to use DotrainOrderGui instance.

All component renderings now consistently use the instance rather than a mock object.

Also applies to: 58-58, 72-72


63-63: Updated expectations to check instance methods.

Test assertions now correctly verify calls on the instance methods.

Also applies to: 80-80


67-67: Consistent mocking approach using prototype.

The mock for isDepositPreset follows the same pattern as other mocks, using the prototype approach.

packages/ui-components/src/lib/components/deployment/DeploymentSteps.svelte (5)

8-8: Updated imports to include TokenInfo type.

Good practice to explicitly import the types being used, improving code readability and maintainability.


15-15: Simplified import by using type prefix.

Using the type prefix in the import improves clarity about what's being imported.


51-51: Improved type specificity for allTokenInfos.

Changed from a generic AllTokenInfos to the more specific TokenInfo[], which enhances type safety.


78-82: Robust error handling for getCurrentDeployment.

The code now properly checks for errors in the result object and throws appropriate exceptions with meaningful messages. This is implemented consistently across all calls to getCurrentDeployment.

Also applies to: 93-97, 105-109


140-144: Consistent error handling for getAllTokenInfos.

The same error handling pattern is applied to getAllTokenInfos calls, maintaining consistency throughout the codebase and improving robustness.

Also applies to: 211-215

packages/ui-components/src/__tests__/StrategyPage.test.ts (3)

4-4: Updated import to support improved mocking approach.

The addition of type Mock from vitest enhances type safety when mocking the DotrainOrderGui methods.


22-29: Adjusted test structure to match new result handling pattern.

The mockStrategyDetails object has been updated to include properties under a value field, which reflects an improved API design pattern for handling results. This structured approach separates successful results from error conditions more clearly.


83-87: Enhanced error handling with structured error objects.

The error handling has been improved to use a structured result with an error object containing a message instead of rejecting with an error. This approach provides more consistent error handling and makes tests more predictable.

packages/orderbook/test/js_api/gui.test.ts (5)

17-18: Updated imports to support structured result handling.

Adding the WasmEncodedResult type import supports the new structured approach to result handling in the API.


354-364: Well-designed utility function for handling structured results.

The new extractWasmEncodedData function provides a centralized and consistent way to handle the structured result pattern. It properly checks for errors and extracts values from the WasmEncodedResult<T> type, improving code readability and maintaining consistent error handling throughout the tests.


367-369: Consistent implementation of the new result handling pattern.

This code segment exemplifies the new pattern used throughout the file - calling the method to get a WasmEncodedResult, then extracting the value using the utility function. This pattern is more robust for error handling while keeping the tests readable.


557-559: Direct testing of error cases without exceptions.

Instead of expecting exceptions, the code now directly checks for error messages in the result object. This approach is more explicit and allows for more precise testing of error conditions.


1228-1230: Added method for removing field values.

The addition of the removeFieldValue method enhances the API's functionality by providing a way to clear field values. The test verifies that the method correctly empties the field values array.

packages/webapp/src/__tests__/handleGuiInitialization.test.ts (4)

1-4: Enhanced imports for more accurate testing.

Updated imports to include type Mock and WasmEncodedResult types, enabling more precise mocking and better type safety in tests.


7-14: Improved testing approach using actual class instance.

Switching from a completely mocked object to a real DotrainOrderGui instance with mocked methods provides more realistic testing. This approach better tests the actual integration between components and catches potential issues with method signatures or behavior.


32-36: Properly typed mock responses for consistent error handling.

Using WasmEncodedResult<void> as the return type for mocked methods ensures type consistency with the actual implementation. This approach maintains the structured result pattern throughout the codebase.


62-70: Comprehensive error handling test.

The test properly verifies error handling behavior by mocking a rejection and checking that the handler returns the expected error message. This ensures robustness in error scenarios.

packages/ui-components/test-setup.ts (2)

15-19: Improved readability of mock store configuration.

The page object has been reformatted for better readability, making it easier to understand the structure of the mocked data.


56-72: Comprehensive mock setup for DotrainOrderGui.

Added a complete mock for DotrainOrderGui that includes both static and instance methods. This centralized mock setup ensures consistency across tests and simplifies individual test files by providing pre-mocked methods.

The comments explaining the TypeScript annotations are helpful for future maintainers.

crates/js_api/src/gui/deposits.rs (5)

47-81: Looks good; ensure all edge cases are tested.

The get_deposits method correctly transforms and returns deposit details, including preset validation. Ensure there is adequate test coverage for scenarios like invalid presets, empty strings, and missing tokens to confirm robust error handling.


115-120: Straightforward removal logic.
No issues found in remove_deposit. Removal is properly followed by a state update callback.


122-126: Return of presets is clear.

get_deposit_presets gracefully returns either the stored presets or an empty vector. This is a clear and concise approach.


128-141: Appropriate missing-deposits check.

get_missing_deposits properly identifies deposits that are not yet defined. No concerns here.


143-146: Consistent boolean check.

has_any_deposit returning a Result<bool, GuiError> is consistent with the rest of the API, although it does not appear to require error handling internally. This is fine for uniformity.

crates/js_api/src/gui/mod.rs (15)

21-24: Import changes acknowledged.

The updated imports for HashMap and the wasm_export macro look fine.


51-51: No concerns regarding this change.

The additional blank line or spacing is inconsequential and does not introduce any issues.


54-63: Constructor implementation.

Providing a default constructor with DotrainOrder::dummy() is valid for quick instantiation. Ensure that any fields requiring actual data are updated during further initialization steps.


68-74: Deployment keys retrieval looks correct.

The get_deployment_keys method properly parses deployment keys and returns them as a vector of strings. Code is straightforward and properly handles errors.


76-82: Deployment selection logic is solid.

choose_deployment checks for valid deployments before storing them, preventing users from selecting invalid deployments.


90-94: Assignment of state fields.

Storing dotrain_order, deployment_name, and an optional callback in this block appears consistent with the rest of the code. No issues found.


97-105: Retrieving GUI config.

The get_gui_config method properly fetches and returns the GUI configuration from the YAML structure. Error handling is well-defined.


107-110: Deployment retrieval.

get_current_deployment delegates to get_gui_config and validates the user’s selected deployment. Implementation looks correct.


126-164: Async token info retrieval.

get_token_info method checks for local token metadata and fetches missing fields on-chain if needed. This approach is well-structured; just be mindful of performance if large numbers of tokens are fetched repeatedly.


195-204: Strategy details retrieval.

get_strategy_details fetches metadata as expected. Implementation is straightforward.


207-217: Deployment details mapping.

get_deployment_details returns a HashMap of name-and-description data, aligning with the updated approach. No issues found.


219-232: Deployment detail access.

get_deployment_detail uses get_deployment_details to extract a single entry, returning an error if it isn’t found. This flow is correct.


234-245: Dotrain text generation.

generate_dotrain_text constructs a combined YAML body. Implementation appears robust and meets the straightforward requirement.


246-255: Composing rainlang.

get_composed_rainlang finalizes scenario bindings and composes the deployment to a Rainlang representation. No concerns regarding this logic.


342-350: WasmEncodedError conversion.

Converting GuiError into WasmEncodedError by embedding the error message is a suitable approach for propagating error details to JavaScript.

Comment thread packages/ui-components/src/lib/components/deployment/DepositInput.svelte 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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d7e7c14 and 25e18ff.

📒 Files selected for processing (1)
  • packages/orderbook/test/js_api/gui.test.ts (6 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/orderbook/test/js_api/gui.test.ts (2)
crates/js_api/src/gui/deposits.rs (1)
  • deposits (49-80)
crates/settings/src/gui.rs (3)
  • presets (130-140)
  • presets (499-516)
  • presets (701-714)
🪛 Biome (1.9.4)
packages/orderbook/test/js_api/gui.test.ts

[error] 585-585: This let declares a variable that is only assigned once.

'deposits' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)


[error] 589-589: This let declares a variable that is only assigned once.

'depositsAfterRemove' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: standard-tests (ubuntu-latest, test-js-bindings)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-legal)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-static)
  • GitHub Check: standard-tests (ubuntu-latest, ob-rs-test, true)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-artifacts, true)
  • GitHub Check: Deploy-Preview
  • GitHub Check: build-tauri (ubuntu-22.04, true)
  • GitHub Check: test
  • GitHub Check: git-clean
  • GitHub Check: test
  • GitHub Check: test
🔇 Additional comments (8)
packages/orderbook/test/js_api/gui.test.ts (8)

554-561: Good implementation of the new extractWasmEncodedData utility.

The code now correctly uses the extractWasmEncodedData utility function to handle results from hasAnyDeposit(), which simplifies error handling and aligns with the changes in the underlying implementation. This reflects the updated method signature in the Rust code where return types now use Result<bool, GuiError>.


569-571: LGTM: Consistent extraction of deposit data.

The usage of extractWasmEncodedData for processing the deposits result is consistent with the new error handling approach.


579-581: Proper error handling testing for non-existent tokens.

The error handling approach correctly tests the specific error message for a deposit token that doesn't exist in the GUI config, which is appropriate for this test case.


592-595: Good inline usage of extractWasmEncodedData.

The code correctly uses the utility function inline when only needing to access properties of the returned value, which keeps the code concise.


602-609: LGTM: Proper handling of deposit presets.

The code correctly extracts and validates the deposit presets using the new utility function.


612-614: Proper error testing for invalid token preset.

The test correctly verifies the expected error message when retrieving presets for a token that doesn't exist in the GUI config.


902-910: Consistent extraction in deserialization test.

This change ensures consistent use of the data extraction pattern throughout the test suite, including after state deserialization.


930-933: LGTM: Consistent extraction after clearState.

The code correctly uses the extraction utility to verify deposits are cleared.

Comment thread packages/orderbook/test/js_api/gui.test.ts
Comment thread packages/orderbook/test/js_api/gui.test.ts
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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 25e18ff and d1a4e2a.

📒 Files selected for processing (2)
  • packages/orderbook/test/js_api/gui.test.ts (6 hunks)
  • packages/ui-components/src/lib/components/deployment/DepositInput.svelte (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/orderbook/test/js_api/gui.test.ts (2)
crates/js_api/src/gui/deposits.rs (1)
  • deposits (49-80)
crates/settings/src/gui.rs (3)
  • presets (130-140)
  • presets (499-516)
  • presets (701-714)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-artifacts, true)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-test)
  • GitHub Check: Deploy-Preview
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: build-tauri (ubuntu-22.04, true)
  • GitHub Check: git-clean
🔇 Additional comments (15)
packages/ui-components/src/lib/components/deployment/DepositInput.svelte (2)

27-31: Improved error handling for deposit retrieval.

The enhanced error handling now properly checks for errors from getDeposits() and throws a meaningful error with the appropriate message.


75-83: Complete error handling implementation in handleInput.

Good implementation of try-catch block to handle potential errors when retrieving deposits.

packages/orderbook/test/js_api/gui.test.ts (13)

555-556: Updated hasAnyDeposit call to use extractWasmEncodedData.

The test now properly handles the new return type from the wasm-exported method.


558-559: Updated getDeposits call to use extractWasmEncodedData.

The test now properly unwraps the result from the wasm-exported method.


561-561: Consistent use of extractWasmEncodedData for hasAnyDeposit.

Good consistency in handling wasm-exported method results.


570-572: Updated getDeposits call to use extractWasmEncodedData in update deposit test.

Now properly handles the WasmEncodedResult return type.


580-581: Improved error handling test for getDepositPresets.

The test now correctly checks the error message in the result object instead of expecting a thrown exception.


585-586: Updated getDeposits call in remove deposit test.

Consistently using the extractWasmEncodedData pattern.


589-590: Updated getDeposits call after removal.

Using extractWasmEncodedData to handle the result consistently.


593-595: Consistent use of extractWasmEncodedData for getDeposits.

Maintaining the pattern throughout the test file for deposit operations.


602-603: Updated getDepositPresets call to use extractWasmEncodedData.

Now properly unwraps the structured result from the wasm-exported method.


612-614: Updated error test for getDepositPresets.

Now properly checks the error in the returned result object.


903-911: Updated getDeposits call in deserializeState test.

Consistently using the extractWasmEncodedData pattern for accessing the deposit data.


931-932: Updated getDeposits call in clearState test.

Maintains consistency in handling WasmEncodedResult returns.


354-364: Well-implemented utility function for extracting data from WasmEncodedResult.

This utility centralizes error handling for wasm-exported methods, making the tests more maintainable and consistent.

The function appropriately:

  1. Checks for errors in the result
  2. Uses a custom error message if provided
  3. Handles undefined values
  4. Returns the extracted value

Comment thread packages/ui-components/src/lib/components/deployment/DepositInput.svelte 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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d1a4e2a and c3f468d.

📒 Files selected for processing (1)
  • packages/ui-components/src/lib/components/deployment/DepositInput.svelte (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: build-tauri (ubuntu-22.04, true)
  • GitHub Check: Deploy-Preview
  • GitHub Check: test
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-test)
  • GitHub Check: standard-tests (ubuntu-latest, test-js-bindings)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-legal)
  • GitHub Check: standard-tests (ubuntu-latest, ob-rs-test, true)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-artifacts, true)
  • GitHub Check: test
  • GitHub Check: test
  • GitHub Check: git-clean
🔇 Additional comments (3)
packages/ui-components/src/lib/components/deployment/DepositInput.svelte (3)

27-31: Great improvement to error handling in setCurrentDeposit!

The error handling has been significantly improved by checking for errors in the deposits response and throwing appropriate errors. The error message in the catch block now properly extracts the message from the Error object.

Also applies to: 33-33, 35-35


61-69: Nice addition of consistent error handling for handlePresetClick.

This addresses the previous review comment by adding proper error handling when getting deposits. The pattern matches the approach used in other functions, making the error handling consistent throughout the component.


80-88: Good implementation of error handling for handleInput.

This successfully addresses the previous review comment by adding proper try-catch error handling for the getDeposits call. The error handling is now aligned with the rest of the component.

Comment thread packages/ui-components/src/lib/components/deployment/DepositInput.svelte Outdated
@hardyjosh hardyjosh enabled auto-merge March 26, 2025 08:21
@hardyjosh hardyjosh merged commit b2c4348 into main Mar 26, 2025
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

rust Related to rust crates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add macro to deposit DotrainOrderGui methods

2 participants