Skip to content

Add vault related data structures and functions #1950

Merged
hardyjosh merged 7 commits intomainfrom
2025-06-24-raindex-client-vaults
Jul 2, 2025
Merged

Add vault related data structures and functions #1950
hardyjosh merged 7 commits intomainfrom
2025-06-24-raindex-client-vaults

Conversation

@findolor
Copy link
Copy Markdown
Collaborator

@findolor findolor commented Jun 24, 2025

Caution

CHAINED PR
Do not merge before #1947

Motivation

See issue: #1747

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 #1747

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive vault management: querying vaults, balance changes, deposit/withdrawal/approval calldata generation, and allowance checks.
    • Added blockchain transaction data support with accessible fields.
    • Enhanced error handling with new user-friendly messages.
    • Added TypeScript template literal types for addresses and hex strings in the WASM API.
  • Bug Fixes

    • Improved deterministic ordering in multi-subgraph queries.
  • Tests

    • Added extensive integration tests for vault and order functionality in the JavaScript API, covering data retrieval and transaction preparation.
    • Updated test utilities for dynamic configuration and improved test reliability.

@findolor findolor requested review from 0xgleb and hardyjosh June 24, 2025 13:21
@findolor findolor self-assigned this Jun 24, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 24, 2025

Walkthrough

This change introduces a comprehensive vault management system to the RaindexClient module, adding new data structures, methods, and error handling for vaults, tokens, balance changes, and allowances. It migrates and extends vault-related functionality, updates tests for dynamic configuration, and provides new TypeScript bindings and integration tests for the JavaScript API.

Changes

File(s) Change Summary
crates/common/src/raindex_client/vaults.rs New module implementing vault-related data structures, async methods for querying/manipulating vaults, tokens, balance changes, allowances, and conversion logic. Adds WASM bindings and unit tests.
crates/common/src/raindex_client/mod.rs, crates/common/src/raindex_client/orders.rs Enhanced RaindexClient with new error variants, deterministic ordering for multi-subgraph queries, RPC URL retrieval, and public transactions module. Refactored test utilities for dynamic configuration. Orders module updated to use new client methods and test helpers.
crates/common/src/raindex_client/transactions.rs New module defining RaindexTransaction struct, conversion from subgraph transaction, and WASM bindings for transaction data.
crates/js_api/src/lib.rs Added TypeScript custom section for Address and Hex template literal types in WASM bindings.
packages/orderbook/test/js_api/raindexClient.test.ts New integration test suite for RaindexClient JS API, covering vaults, orders, calldata generation, allowance logic, and error handling using a mock server.
packages/orderbook/test/js_api/vault.test.ts Simplified import statement by removing unused imports.

Sequence Diagram(s)

sequenceDiagram
    participant JS as JS API
    participant WASM as WASM Bindings
    participant Client as RaindexClient
    participant Subgraph as Subgraph
    participant RPC as RPC Endpoint

    JS->>WASM: Call get_vaults(chain_id, filters, page)
    WASM->>Client: get_vaults(chain_id, filters, page)
    Client->>Subgraph: Query vaults with filters
    Subgraph-->>Client: Return vault data
    Client->>WASM: Return vault list
    WASM->>JS: Return vault list

    JS->>WASM: Call get_deposit_calldata(vault, amount)
    WASM->>Client: get_deposit_calldata(vault, amount)
    Client->>Client: Validate amount
    Client->>Client: Generate calldata
    Client->>WASM: Return calldata
    WASM->>JS: Return calldata

    JS->>WASM: Call get_allowance(vault)
    WASM->>Client: get_allowance(vault)
    Client->>RPC: Query ERC20 allowance
    RPC-->>Client: Return allowance value
    Client->>WASM: Return allowance
    WASM->>JS: Return allowance
Loading

Assessment against linked issues

Objective Addressed Explanation
Migrate/add vault-related functions to OrderbookClient class (#1747)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation

Suggested labels

rust

Suggested reviewers

  • 0xgleb
  • hardyjosh

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-02T13_52_38_699Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

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

♻️ Duplicate comments (1)
crates/common/src/raindex_client/vaults.rs (1)

547-547: Arc instance creation pattern.

Same issue as in orders.rs - creating new Arc<RwLock instances.

Also applies to: 622-622

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 576b1f2 and 146541e.

⛔ 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 (26)
  • crates/common/Cargo.toml (1 hunks)
  • crates/common/src/add_order.rs (1 hunks)
  • crates/common/src/deposit.rs (1 hunks)
  • crates/common/src/dotrain_add_order_lsp.rs (1 hunks)
  • crates/common/src/dotrain_order/mod.rs (1 hunks)
  • crates/common/src/erc20.rs (1 hunks)
  • crates/common/src/lib.rs (1 hunks)
  • crates/common/src/meta.rs (5 hunks)
  • crates/common/src/raindex_client/mod.rs (1 hunks)
  • crates/common/src/raindex_client/orders.rs (1 hunks)
  • crates/common/src/raindex_client/transactions.rs (1 hunks)
  • crates/common/src/raindex_client/vaults.rs (1 hunks)
  • crates/common/src/remove_order.rs (1 hunks)
  • crates/common/src/transaction.rs (1 hunks)
  • crates/common/src/types/order_detail_extended.rs (1 hunks)
  • crates/common/src/withdraw.rs (1 hunks)
  • crates/js_api/src/lib.rs (1 hunks)
  • crates/js_api/src/yaml/mod.rs (1 hunks)
  • crates/settings/src/yaml/mod.rs (3 hunks)
  • crates/settings/src/yaml/orderbook.rs (3 hunks)
  • crates/subgraph/src/performance/vol.rs (1 hunks)
  • flake.nix (1 hunks)
  • packages/orderbook/test/js_api/order.test.ts (1 hunks)
  • packages/orderbook/test/js_api/orderbookYaml.test.ts (1 hunks)
  • packages/orderbook/test/js_api/raindexClient.test.ts (1 hunks)
  • packages/orderbook/test/js_api/vault.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (14)
crates/common/src/erc20.rs (1)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
crates/common/src/dotrain_add_order_lsp.rs (2)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1715
File: crates/js_api/src/common/mod.rs:111-118
Timestamp: 2025-04-30T09:28:36.960Z
Learning: In the rain.orderbook repository, the WASM tests are already properly configured with conditional compilation using `#[cfg(target_family = "wasm")]` and `#[cfg(not(target_family = "wasm"))]`, and don't require additional `wasm_bindgen_test_configure!(run_in_browser)` directives.
crates/common/src/withdraw.rs (2)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1715
File: crates/js_api/src/common/mod.rs:111-118
Timestamp: 2025-04-30T09:28:36.960Z
Learning: In the rain.orderbook repository, the WASM tests are already properly configured with conditional compilation using `#[cfg(target_family = "wasm")]` and `#[cfg(not(target_family = "wasm"))]`, and don't require additional `wasm_bindgen_test_configure!(run_in_browser)` directives.
crates/common/src/remove_order.rs (2)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1715
File: crates/js_api/src/common/mod.rs:111-118
Timestamp: 2025-04-30T09:28:36.960Z
Learning: In the rain.orderbook repository, the WASM tests are already properly configured with conditional compilation using `#[cfg(target_family = "wasm")]` and `#[cfg(not(target_family = "wasm"))]`, and don't require additional `wasm_bindgen_test_configure!(run_in_browser)` directives.
crates/common/src/transaction.rs (1)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
crates/common/src/dotrain_order/mod.rs (2)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1715
File: crates/js_api/src/common/mod.rs:111-118
Timestamp: 2025-04-30T09:28:36.960Z
Learning: In the rain.orderbook repository, the WASM tests are already properly configured with conditional compilation using `#[cfg(target_family = "wasm")]` and `#[cfg(not(target_family = "wasm"))]`, and don't require additional `wasm_bindgen_test_configure!(run_in_browser)` directives.
crates/common/src/deposit.rs (1)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
flake.nix (1)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1715
File: crates/js_api/src/common/mod.rs:111-118
Timestamp: 2025-04-30T09:28:36.960Z
Learning: In the rain.orderbook repository, the WASM tests are already properly configured with conditional compilation using `#[cfg(target_family = "wasm")]` and `#[cfg(not(target_family = "wasm"))]`, and don't require additional `wasm_bindgen_test_configure!(run_in_browser)` directives.
packages/orderbook/test/js_api/order.test.ts (1)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1907
File: packages/orderbook/test/common/test.test.ts:75-77
Timestamp: 2025-06-04T10:21:01.388Z
Learning: The DotrainOrder.create API in packages/orderbook/test/common/test.test.ts is internal and not used directly in consumer applications, so API changes here don't require external breaking change documentation.
crates/common/src/add_order.rs (2)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1715
File: crates/js_api/src/common/mod.rs:111-118
Timestamp: 2025-04-30T09:28:36.960Z
Learning: In the rain.orderbook repository, the WASM tests are already properly configured with conditional compilation using `#[cfg(target_family = "wasm")]` and `#[cfg(not(target_family = "wasm"))]`, and don't require additional `wasm_bindgen_test_configure!(run_in_browser)` directives.
crates/js_api/src/lib.rs (3)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1710
File: crates/quote/Cargo.toml:30-30
Timestamp: 2025-05-14T04:49:14.621Z
Learning: In the rain.orderbook repository, wasm-bindgen-utils is intentionally used as an unconditional dependency because non-wasm targets (like tests) sometimes need to use it.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1715
File: crates/js_api/src/common/mod.rs:111-118
Timestamp: 2025-04-30T09:28:36.960Z
Learning: In the rain.orderbook repository, the WASM tests are already properly configured with conditional compilation using `#[cfg(target_family = "wasm")]` and `#[cfg(not(target_family = "wasm"))]`, and don't require additional `wasm_bindgen_test_configure!(run_in_browser)` directives.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
crates/common/Cargo.toml (3)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1744
File: crates/subgraph/src/orderbook_client.rs:44-46
Timestamp: 2025-05-14T05:13:59.713Z
Learning: In the rain.orderbook project, WASM dependencies are intentionally made available in non-WASM targets to facilitate testing of WASM-related functionality, so conditional compilation guards like `#[cfg(target_family = "wasm")]` should not be added to imports or implementations that may be needed for tests.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1715
File: crates/js_api/src/common/mod.rs:111-118
Timestamp: 2025-04-30T09:28:36.960Z
Learning: In the rain.orderbook repository, the WASM tests are already properly configured with conditional compilation using `#[cfg(target_family = "wasm")]` and `#[cfg(not(target_family = "wasm"))]`, and don't require additional `wasm_bindgen_test_configure!(run_in_browser)` directives.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1710
File: crates/quote/Cargo.toml:30-30
Timestamp: 2025-05-14T04:49:14.621Z
Learning: In the rain.orderbook repository, wasm-bindgen-utils is intentionally used as an unconditional dependency because non-wasm targets (like tests) sometimes need to use it.
crates/settings/src/yaml/mod.rs (1)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1938
File: crates/settings/src/yaml/mod.rs:176-178
Timestamp: 2025-06-18T19:23:33.747Z
Learning: In crates/settings/src/yaml/mod.rs, the YamlError enum has two distinct error variants: `KeyNotFound(String)` for when a specific YAML key is not found in a hash/map, and `NotFound(String)` for when other types of entities (like networks, orderbooks, etc.) are not found in the configuration. These serve different purposes and should not be consolidated.
crates/settings/src/yaml/orderbook.rs (2)
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1938
File: crates/settings/src/yaml/orderbook.rs:180-199
Timestamp: 2025-06-18T18:24:32.049Z
Learning: In crates/settings/src/yaml/orderbook.rs, the user prefers to avoid refactoring duplicate search logic between get_orderbook_by_address and get_orderbook_by_network_key when there are only 2 functions, indicating they would consider it if more similar functions are added in the future.
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1938
File: crates/settings/src/yaml/orderbook.rs:185-199
Timestamp: 2025-06-18T19:24:40.518Z
Learning: In crates/settings/src/yaml/orderbook.rs, the user prefers not to refactor get_orderbook_by_network_key to handle multiple orderbooks per network key since their current architecture maintains a one-to-one mapping between orderbooks and networks. They would consider the refactoring if the system evolves to support multiple orderbooks per network in the future.
🪛 Biome (1.9.4)
packages/orderbook/test/js_api/raindexClient.test.ts

[error] 1-1: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: standard-tests (ubuntu-latest, test-js-bindings)
  • GitHub Check: standard-tests (ubuntu-latest, ob-rs-test, true)
  • GitHub Check: Deploy-Preview
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-test)
  • 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-rs-static)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-legal)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-sol-test)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-wasm-artifacts)
  • GitHub Check: standard-tests (ubuntu-latest, rainix-rs-artifacts, true)
  • GitHub Check: test
  • GitHub Check: git-clean
  • GitHub Check: test
🔇 Additional comments (35)
crates/settings/src/yaml/mod.rs (3)

176-178: LGTM! Well-implemented error variant addition.

The new NotFound variant follows the established pattern and maintains the important distinction from KeyNotFound as noted in the learning context.


251-251: Proper PartialEq implementation for the new variant.

The equality comparison for NotFound is implemented consistently with other string-based variants.


283-288: Clear and user-friendly error message formatting.

The error message format is helpful and follows the established pattern of providing context-rich feedback to users.

packages/orderbook/test/js_api/vault.test.ts (1)

12-12: Good cleanup of unused imports.

Removing SgVaultWithSubgraphName and SgDeposit reduces unnecessary dependencies while maintaining test functionality.

crates/common/src/withdraw.rs (1)

58-58: Proper test environment separation for WASM builds.

This change correctly restricts test compilation to non-WASM targets, aligning with the project's strategy for separating native and WASM test environments.

crates/common/src/lib.rs (1)

10-10: Proper addition of the new raindex_client module.

The module is correctly exposed in the public API to provide the vault and orderbook querying functionality.

packages/orderbook/test/js_api/order.test.ts (1)

13-13: Good cleanup of unused imports.

Removing SgOrderWithSubgraphName and OrderWithSortedVaults streamlines the imports while maintaining test functionality.

crates/common/src/remove_order.rs (1)

78-78: LGTM! Test compilation properly restricted to non-WASM targets.

This change aligns with the coordinated effort to separate test environments by target platform, ensuring WASM builds exclude tests that depend on non-WASM specific functionality.

crates/common/src/dotrain_add_order_lsp.rs (1)

123-123: LGTM! Consistent test compilation restriction applied.

This change matches the pattern across the crates/common directory, properly excluding WASM targets from test compilation.

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

628-628: LGTM! Test environment segregation properly implemented.

The conditional compilation change correctly restricts test compilation to non-WASM targets, maintaining consistency with the broader refactoring effort.

crates/common/src/deposit.rs (1)

148-148: LGTM! Test compilation correctly configured for target separation.

This change maintains the established pattern of excluding WASM targets from test compilation, ensuring compatibility with the project's test infrastructure.

crates/common/src/transaction.rs (1)

103-103: LGTM! Test compilation configuration completed consistently.

This final change completes the coordinated effort to properly segregate test environments across the crates/common directory, ensuring WASM builds exclude incompatible test dependencies.

crates/common/src/erc20.rs (1)

201-201: LGTM: Appropriate platform-specific test scoping.

The conditional compilation change correctly restricts these tests to non-WASM targets, which aligns with the broader strategy of separating test environments for different platforms while maintaining WASM-compatible functionality in the main codebase.

crates/common/src/add_order.rs (1)

363-363: LGTM: Consistent platform-specific test configuration.

This change maintains consistency with other files in the crates/common/src directory by properly scoping tests to non-WASM targets, supporting the overall strategy for WASM-compatible development.

packages/orderbook/test/js_api/orderbookYaml.test.ts (1)

118-122: LGTM: Improved error messaging for better UX.

The updated test assertions correctly reflect the improved error message format that provides more descriptive feedback ("orderbook with address: ... not found" vs generic key errors). This enhances the user experience by making error messages more actionable and context-specific.

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

231-236: LGTM: Consistent error message improvements across the stack.

The test assertions correctly reflect the enhanced error messaging that provides descriptive context ("orderbook with address: ... not found") instead of generic key errors. This maintains consistency between the Rust backend and JavaScript frontend error handling.

flake.nix (1)

223-223: LGTM: Appropriate inclusion of enhanced crate in WASM test suite.

Adding rain_orderbook_common to the WASM test pipeline is correct given the new WASM-compatible functionality (like raindex_client) introduced in this crate. This ensures the WASM bindings and client features are properly tested in the WebAssembly environment.

crates/common/src/types/order_detail_extended.rs (1)

25-25: LGTM! Metadata decoding updated correctly.

The change correctly adapts to the trait implementation shift from SgRainMetaV1 to String by accessing the inner value meta.0 before calling try_decode_rainlangsource().

crates/js_api/src/lib.rs (1)

24-30: TypeScript types look good for blockchain context.

The Address and Hex template literal types with "0x" prefix are appropriate for blockchain applications. Both types are currently identical - consider if more specific typing (e.g., length constraints for addresses) would be beneficial in the future.

crates/common/Cargo.toml (1)

51-55: Excellent dependency scoping for target platforms.

The separation of WASM-specific (wasm-bindgen-test) and non-WASM-specific (httpmock, rain_orderbook_test_fixtures) dev dependencies ensures clean builds and appropriate test tooling for each target platform.

crates/common/src/meta.rs (2)

24-27: Clean trait refactoring to target String directly.

Moving the TryDecodeRainlangSource implementation from SgRainMetaV1 to String simplifies the interface and makes the trait more reusable. The updated decode call correctly operates on the string directly.


73-73: Test updates correctly handle wrapper type.

All tests properly extract the inner string (meta.0) before calling try_decode_rainlangsource(), maintaining compatibility with the trait implementation change.

Also applies to: 80-80, 90-90, 100-100

crates/common/src/raindex_client/transactions.rs (2)

10-17: Well-structured transaction representation.

The struct design with proper types (Address, U256) and WASM bindings is clean and appropriate for blockchain transaction data.


52-62: Robust conversion implementation with proper error handling.

The TryFrom<SgTransaction> implementation correctly handles string parsing with appropriate error propagation for address and numeric conversions.

crates/subgraph/src/performance/vol.rs (1)

25-32: LGTM! Simplified WASM trait derivation aligns with project-wide WASM support.

The unconditional Tsify derivation and impl_wasm_traits! macro usage is consistent with the crate's design where WASM dependencies are always available (as evidenced by the unconditional import of wasm_bindgen_utils at line 9).

crates/settings/src/yaml/orderbook.rs (2)

112-123: LGTM! Network lookup by chain ID is implemented correctly.

The method efficiently searches through all networks and returns a descriptive error message when not found.


185-199: LGTM! Orderbook lookup by network key follows the established pattern.

The implementation is consistent with existing lookup methods. As per your previous feedback, I understand you prefer to avoid refactoring the duplicate search logic while there are only a few lookup methods.

packages/orderbook/test/js_api/raindexClient.test.ts (2)

85-94: LGTM! Well-designed error handling helper.

The extractWasmEncodedData function provides clean error handling and logging for WASM results throughout the tests.


1-1: Use the node: protocol for Node.js builtin imports.

This makes it explicit that the imported module is a Node.js builtin.

-import assert from 'assert';
+import assert from 'node:assert';
⛔ Skipped due to learnings
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1474
File: packages/orderbook/test/js_api/orderbookYaml.test.ts:1-1
Timestamp: 2025-03-31T13:51:32.841Z
Learning: The project maintainers prefer not to use the node: protocol (e.g., 'node:assert') for Node.js built-in modules in import statements, opting instead for the direct import format (e.g., 'assert').
crates/common/src/raindex_client/mod.rs (2)

51-92: LGTM! Well-documented public API with clear examples.

The RaindexClient struct and constructor are properly documented with helpful JavaScript examples for WASM users.


159-197: LGTM! Comprehensive error enum with good coverage.

The RaindexError enum covers all potential failure modes with appropriate error variants.

crates/common/src/raindex_client/orders.rs (2)

476-1615: Excellent test coverage!

The tests are comprehensive, well-structured, and cover various scenarios including edge cases. Good use of mocking for external dependencies.


99-125: Optimize the vaults() method to reduce iterations and allocations.

The current implementation iterates through the vaults multiple times and creates several intermediate collections. This can be optimized to a single pass.

Apply this diff to optimize the method:

 pub fn vaults(&self) -> Vec<RaindexVault> {
-    let mut vaults: Vec<RaindexVault> = Vec::new();
-
-    let input_ids: HashSet<String> = self.inputs.iter().map(|v| v.id()).collect();
-    let output_ids: HashSet<String> = self.outputs.iter().map(|v| v.id()).collect();
-
-    // First add inputs (excluding input_outputs)
-    for vault in &self.inputs {
-        if !output_ids.contains(&vault.id()) {
-            vaults.push(vault.clone());
-        }
-    }
-    // Then add outputs (excluding input_outputs)
-    for vault in &self.outputs {
-        if !input_ids.contains(&vault.id()) {
-            vaults.push(vault.clone());
-        }
-    }
-    // Finally add input_outputs (only once for vaults that are both input and output)
-    for vault in &self.inputs {
-        if output_ids.contains(&vault.id()) {
-            let input_output_vault = vault.with_vault_type(RaindexVaultType::InputOutput);
-            vaults.push(input_output_vault);
-        }
-    }
-    vaults
+    let mut vaults: Vec<RaindexVault> = Vec::new();
+    let mut seen_ids: HashSet<String> = HashSet::new();
+
+    // Build a set of output IDs for quick lookup
+    let output_ids: HashSet<String> = self.outputs.iter().map(|v| v.id()).collect();
+
+    // Process inputs
+    for vault in &self.inputs {
+        let vault_id = vault.id();
+        if output_ids.contains(&vault_id) {
+            // This vault is both input and output
+            vaults.push(vault.with_vault_type(RaindexVaultType::InputOutput));
+        } else {
+            // This vault is input only
+            vaults.push(vault.clone());
+        }
+        seen_ids.insert(vault_id);
+    }
+
+    // Process outputs that haven't been seen as inputs
+    for vault in &self.outputs {
+        if !seen_ids.contains(&vault.id()) {
+            vaults.push(vault.clone());
+        }
+    }
+
+    vaults
 }
⛔ Skipped due to learnings
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1947
File: crates/common/src/raindex_client/orders.rs:98-125
Timestamp: 2025-06-24T08:46:03.368Z
Learning: In the vault merging logic in crates/common/src/raindex_client/orders.rs, optimization isn't necessary because the maximum list items are usually around 5 items. For such small datasets, the simple three-loop approach is preferred over HashMap-based optimization due to clarity and minimal performance impact.
crates/common/src/raindex_client/vaults.rs (2)

358-378: Well-implemented approval logic with proper validation.

The approval calldata generation correctly checks existing allowance and prevents unnecessary approvals. This is a good security practice.


709-1192: Comprehensive test coverage with good error case handling.

The tests thoroughly cover all functionality including error cases, edge conditions, and integration scenarios.

Comment on lines +34 to +38
#[cfg(not(target_family = "wasm"))]
#[wasm_bindgen(getter = blockNumber)]
pub fn block_number(&self) -> String {
self.block_number.to_string()
}
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot Jun 24, 2025

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove wasm_bindgen attributes from non-WASM methods.

The non-WASM versions of block_number() and timestamp() methods shouldn't have #[wasm_bindgen] attributes since they're only compiled for non-WASM targets. This creates confusion and potential compilation issues.

Apply this diff to remove unnecessary attributes:

 #[cfg(not(target_family = "wasm"))]
-#[wasm_bindgen(getter = blockNumber)]
 pub fn block_number(&self) -> String {
 #[cfg(not(target_family = "wasm"))]
-#[wasm_bindgen(getter)]
 pub fn timestamp(&self) -> String {

Also applies to: 45-49

🤖 Prompt for AI Agents
In crates/common/src/raindex_client/transactions.rs around lines 34 to 38 and 45
to 49, remove the #[wasm_bindgen] attributes from the block_number() and
timestamp() methods that are conditionally compiled for non-WASM targets. These
attributes should only be present on WASM-targeted methods to avoid confusion
and compilation issues. Simply delete the #[wasm_bindgen(getter = ...)] lines
from the non-WASM versions of these methods.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

this gives us compiler errors if we remove the attributes

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.

@findolor Thank you for clarifying! You're absolutely right. When #[wasm_bindgen] is applied to an impl block, all methods within that block need the wasm_bindgen attributes, even if they're conditionally compiled for different targets. This is due to how the wasm_bindgen macro expansion works - it processes the entire impl block and expects consistent attribute usage.

I appreciate you testing this and providing the feedback. This is valuable information for understanding wasm_bindgen's requirements.

🐰✨ ears perk up with curiosity Thanks for sharing this insight!


✏️ Learnings added
Learnt from: findolor
PR: rainlanguage/rain.orderbook#1950
File: crates/common/src/raindex_client/transactions.rs:34-38
Timestamp: 2025-06-24T13:30:02.947Z
Learning: When using #[wasm_bindgen] on an impl block, all methods within that block must have wasm_bindgen attributes, even if they are conditionally compiled for non-WASM targets using #[cfg(not(target_family = "wasm"))]. Removing these attributes causes compiler errors because the wasm_bindgen macro expansion processes the entire impl block and expects consistent attribute usage across all methods.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@findolor should we create an issue for this in rain.wasm?

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.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment thread crates/common/src/raindex_client/mod.rs Outdated
Comment thread crates/common/src/raindex_client/mod.rs Outdated
Comment thread crates/common/src/raindex_client/orders.rs Outdated
Comment thread crates/common/src/raindex_client/orders.rs
Comment on lines +74 to +76
BigInt::from_str(&self.vault_id.to_string())
.map_err(|e| RaindexError::JsError(e.to_string().into()))
}
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.

🧹 Nitpick (assertive)

Extract BigInt conversion logic into helper methods.

The BigInt conversion with error handling is repeated throughout the file. Consider creating helper methods to reduce duplication.

Add helper methods:

#[cfg(target_family = "wasm")]
impl RaindexVault {
    fn u256_to_bigint(value: &U256) -> Result<BigInt, RaindexError> {
        BigInt::from_str(&value.to_string())
            .map_err(|e| RaindexError::JsError(e.to_string().into()))
    }
}

Then use it:

 #[cfg(target_family = "wasm")]
 #[wasm_bindgen(getter = vaultId)]
 pub fn vault_id(&self) -> Result<BigInt, RaindexError> {
-    BigInt::from_str(&self.vault_id.to_string())
-        .map_err(|e| RaindexError::JsError(e.to_string().into()))
+    Self::u256_to_bigint(&self.vault_id)
 }

Also applies to: 84-86, 139-145, 430-433, 441-444

🤖 Prompt for AI Agents
In crates/common/src/raindex_client/vaults.rs around lines 74 to 76 and also at
lines 84-86, 139-145, 430-433, and 441-444, the BigInt conversion from U256 with
error handling is duplicated. To fix this, create a helper method inside the
RaindexVault impl block (conditioned on wasm target) that takes a U256 reference
and returns a Result<BigInt, RaindexError> by converting the U256 to string and
parsing it to BigInt with proper error mapping. Then replace all repeated
conversion code with calls to this helper method to reduce duplication and
improve maintainability.

Comment thread crates/common/src/raindex_client/vaults.rs
Comment thread crates/common/src/raindex_client/mod.rs
Comment on lines +34 to +38
#[cfg(not(target_family = "wasm"))]
#[wasm_bindgen(getter = blockNumber)]
pub fn block_number(&self) -> String {
self.block_number.to_string()
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@findolor should we create an issue for this in rain.wasm?

#[wasm_export(js_name = "getDepositCalldata", unchecked_return_type = "Hex")]
pub async fn get_deposit_calldata(
&self,
deposit_amount: String,
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.

why is this a string?

#[wasm_export(js_name = "getWithdrawCalldata", unchecked_return_type = "Hex")]
pub async fn get_withdraw_calldata(
&self,
withdraw_amount: String,
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.

why is this a string?

#[wasm_export(js_name = "getApprovalCalldata", unchecked_return_type = "Hex")]
pub async fn get_approval_calldata(
&self,
deposit_amount: String,
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.

string?

#[serde(rename_all = "camelCase")]
#[wasm_bindgen]
pub struct RaindexVaultBalanceChange {
__typename: String,
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.

shouldn't this be an enum? __typename as a string is an artifact of graphql

#[wasm_bindgen]
pub struct RaindexVaultBalanceChange {
__typename: String,
amount: U256,
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.

we should also have a formatted version ready for display, instead of having to do parseUnits on the front end

#[cfg(target_family = "wasm")]
#[wasm_bindgen(getter = newVaultBalance)]
pub fn new_vault_balance(&self) -> Result<BigInt, RaindexError> {
BigInt::from_str(&self.new_vault_balance.to_string())
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.

this is repeated a lot - can we move elsewhere?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

this is improved in the follow-up PR and no longer repeated

self.amount.to_string()
}
#[cfg(target_family = "wasm")]
#[wasm_bindgen(getter = newVaultBalance)]
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.

is a getter the right approach if it's a Result?

would it be better to do all these fallible operations when originally creating the type so we don't have to do it later?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

i'll check if we can do that

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

this is also improved in the followup PR but we are not doing the operation in the constructor. I think I can create an issue for this and implement it on top of the latest changes

This was referenced Sep 6, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Feb 9, 2026
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Adding vault related functions to OrderbookClient class

3 participants