Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

SQS-375 | Unit test createFormattedLimitOrder #492

Merged
merged 10 commits into from
Sep 9, 2024
Merged

Conversation

deividaspetraitis
Copy link
Collaborator

@deividaspetraitis deividaspetraitis commented Aug 28, 2024

This PR introduces unit tests for Orderbook usecase createFormattedLimitOrder method. The aim of the tests are to cover edge cases as well as successful scenario. As a side effect pull request introduces OrderbookRepositoryMock.

❯ go test ./orderbook/usecase -run "TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder" -v
=== RUN   TestOrderbookUsecaseTestSuite
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/tick_not_found
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_quantity
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_placed_quantity
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_getting_spot_price_scaling_factor
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_bid_effective_total_amount_swapped
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_bid_unrealized_cancels
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_etas
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_converting_tick_to_price
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_placed_at
=== RUN   TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/successful_order_processing
--- PASS: TestOrderbookUsecaseTestSuite (0.03s)
    --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder (0.03s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/tick_not_found (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_quantity (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_placed_quantity (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_getting_spot_price_scaling_factor (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_bid_effective_total_amount_swapped (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_bid_unrealized_cancels (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_etas (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_converting_tick_to_price (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/error_parsing_placed_at (0.00s)
        --- PASS: TestOrderbookUsecaseTestSuite/TestCreateFormattedLimitOrder/successful_order_processing (0.00s)
PASS
ok      github.com/osmosis-labs/sqs/orderbook/usecase   0.090s

Summary by CodeRabbit

  • New Features

    • Introduced a mock implementation for the OrderBookRepository to enhance testing capabilities.
    • Added a public interface for creating formatted limit orders in the order book domain.
    • Implemented a comprehensive test suite for the OrderbookUsecase functionality, covering various scenarios for order creation.
    • Defined custom error types for improved error handling and reporting within the order book system.
    • Enhanced the OrderBookClient interface with new methods for fetching unrealized cancels and ticks in chunks.
    • Updated the LimitOrder struct to use higher precision decimal types for key fields.
    • Added a new endpoint to retrieve active orders associated with a specified Osmo wallet address.
  • Bug Fixes

    • Added validation for placedQuantity in order creation to prevent invalid orders.
    • Adjusted return types for better performance and type handling in order book use case functions.

Introduces unit tests for Orderbook usecase createFormattedLimitOrder
method.
Copy link
Contributor

coderabbitai bot commented Aug 28, 2024

Walkthrough

The changes introduce a mock implementation of the OrderBookRepository interface to enhance testing capabilities in the order book domain. New methods for fetching unrealized cancels and ticks in chunks are added to the OrderBookClient interface, along with custom error types for improved error handling. The constructor function's return type is modified to return a concrete implementation instead of an interface. Additionally, a comprehensive test suite for the order book use case is established, validating various scenarios for order creation and processing.

Changes

File Change Summary
domain/mocks/..., domain/orderbook/..., orderbook/usecase/... Introduced mock implementations for OrderbookRepository, OrderBookUsecase, and enhanced OrderbookGRPCClientMock with new callback functions for flexible testing.
orderbook/types/errors.go, domain/errors.go Defined custom error types for various error scenarios in the order book system and added new error variables for validation failures.
domain/orderbook/grpcclient/orderbook_grpc_client.go Added FetchTickUnrealizedCancels and FetchTicks methods to the OrderBookClient interface for improved data retrieval.
orderbook/usecase/export_test.go, orderbook/usecase/orderbook_usecase.go, orderbook/usecase/orderbook_usecase_test.go Added CreateFormattedLimitOrder function, modified New function to return a concrete type, and established a test suite for OrderbookUsecase.
domain/orderbook/order.go Updated LimitOrder struct fields to use osmosmath.Dec for improved precision in monetary values.
docs/docs.go, docs/swagger.json, docs/swagger.yaml Enhanced API documentation by adding a new endpoint for active orders and refining existing response schemas.
passthrough/delivery/http/passthrough_handler.go, passthrough/delivery/http/passthrough_handler_test.go Improved error handling in HTTP handlers and added a test suite for the new GetActiveOrders method.
router/usecase/routertesting/suite.go Introduced ErrorIsAs method to enhance error assertions in tests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant OrderbookUseCase
    participant OrderbookRepositoryMock

    Client->>OrderbookUseCase: CreateFormattedLimitOrder(params)
    OrderbookUseCase->>OrderbookRepositoryMock: StoreTicks(poolID, ticksMap)
    OrderbookRepositoryMock-->>OrderbookUseCase: Ticks stored
    OrderbookUseCase-->>Client: Return LimitOrder
Loading

🐇 In the meadow, I hop with glee,
New mocks and tests, oh what a spree!
Orderbooks dance, with limits in tow,
Code flows like rivers, watch it all grow!
With each little change, our dreams take flight,
Hooray for the code, it shines so bright! 🌟

Tip

New features

Walkthrough comment now includes:

  • Possibly related PRs: A list of potentially related PRs to help you recall past context.
  • Suggested labels: CodeRabbit can now suggest labels by learning from your past PRs. You can also provide custom labeling instructions in the UI or configuration file.

Notes:

  • Please share any feedback in the discussion post on our Discord.
  • Possibly related PRs, automatic label suggestions based on past PRs, learnings, and possibly related issues require data opt-in (enabled by default).

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 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.

@deividaspetraitis deividaspetraitis added the A:backport/v26.x backport patches to v26.x branch label Aug 28, 2024
@deividaspetraitis deividaspetraitis self-assigned this Aug 28, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4133a71 and 21f98e1.

Files selected for processing (4)
  • domain/mocks/orderbook_repository_mock.go (1 hunks)
  • orderbook/usecase/export_test.go (1 hunks)
  • orderbook/usecase/orderbook_usecase.go (1 hunks)
  • orderbook/usecase/orderbook_usecase_test.go (1 hunks)
Additional comments not posted (16)
orderbook/usecase/export_test.go (1)

7-15: LGTM!

The function correctly forwards the call to createFormattedLimitOrder.

The code changes are approved.

domain/mocks/orderbook_repository_mock.go (4)

17-23: LGTM!

The method is correctly implemented.

The code changes are approved.


26-31: LGTM!

The method is correctly implemented.

The code changes are approved.


34-39: LGTM!

The method is correctly implemented.

The code changes are approved.


42-47: LGTM!

The method is correctly implemented.

The code changes are approved.

orderbook/usecase/orderbook_usecase_test.go (10)

37-52: LGTM!

The test case is correctly implemented.

The code changes are approved.


53-67: LGTM!

The test case is correctly implemented.

The code changes are approved.


69-84: LGTM!

The test case is correctly implemented.

The code changes are approved.


86-104: LGTM!

The test case is correctly implemented.

The code changes are approved.


106-123: LGTM!

The test case is correctly implemented.

The code changes are approved.


126-146: LGTM!

The test case is correctly implemented.

The code changes are approved.


149-171: LGTM!

The test case is correctly implemented.

The code changes are approved.


173-196: LGTM!

The test case is correctly implemented.

The code changes are approved.


199-225: LGTM!

The test case is correctly implemented.

The code changes are approved.


227-279: LGTM!

The test case is correctly implemented.

The code changes are approved.

orderbook/usecase/orderbook_usecase.go (1)

48-50: Verify the impact of changing the return type.

The return type of the New function has been changed from mvc.OrderBookUsecase to *orderbookUseCaseImpl. This change can improve performance but may affect other parts of the codebase that expect the interface type.

Run the following script to verify the usage of the New function and ensure that all occurrences are compatible with the new return type:

Verification successful

No direct issues found with the return type change.

The change in the return type of the New function from mvc.OrderBookUsecase to *orderbookUseCaseImpl does not appear to cause any direct issues in the app/sidecar_query_server.go file. However, ensure that any functions receiving orderBookUseCase do not expect an interface type elsewhere in the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the `New` function and ensure compatibility with the new return type.

# Test: Search for the function usage. Expect: No incompatible occurrences.
rg --type go -A 5 $'orderbookusecase.New'

Length of output: 931


Script:

#!/bin/bash
# Description: Check if `orderBookUseCase` is used as an `mvc.OrderBookUsecase` in `app/sidecar_query_server.go`.

# Test: Search for type assertions or interface implementations related to `orderBookUseCase`.
rg --type go 'orderBookUseCase' -A 10 app/sidecar_query_server.go

Length of output: 1049

Copy link
Member

@p0mvn p0mvn left a comment

Choose a reason for hiding this comment

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

Nice work. Left some comments - please take a look.

Mostly, recommendations around overflows and reducing code duplication

orderbook/usecase/orderbook_usecase_test.go Outdated Show resolved Hide resolved
orderbook/usecase/orderbook_usecase_test.go Outdated Show resolved Hide resolved
orderbook/usecase/orderbook_usecase_test.go Outdated Show resolved Hide resolved
orderbook/usecase/orderbook_usecase_test.go Outdated Show resolved Hide resolved
orderbook/usecase/orderbook_usecase_test.go Show resolved Hide resolved
orderbook/usecase/orderbook_usecase_test.go Show resolved Hide resolved
orderbook/usecase/orderbook_usecase_test.go Outdated Show resolved Hide resolved
orderbook/usecase/orderbook_usecase_test.go Outdated Show resolved Hide resolved
Implements requested improvements
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 21f98e1 and e4ce755.

Files selected for processing (2)
  • orderbook/usecase/orderbook_usecase.go (2 hunks)
  • orderbook/usecase/orderbook_usecase_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • orderbook/usecase/orderbook_usecase_test.go
Additional comments not posted (2)
orderbook/usecase/orderbook_usecase.go (2)

285-287: Added validation for placedQuantity.

The addition of a validation check to ensure that placedQuantity is neither zero nor negative enhances the robustness of the order creation process.

The code changes are approved.


48-48: Return type change in New function.

The change from returning an interface to a concrete type could improve performance by reducing interface overhead. However, ensure that all consumers of this function are updated to handle the new return type.

The code changes are approved.

Run the following script to verify the impact on consumers:

Verification successful

Return type change successfully integrated.

The change in the return type of the New function in orderbook/usecase/orderbook_usecase.go has been successfully integrated into the codebase. The consumers of this function have been updated to handle the new return type without issues.

  • The New function is used in app/sidecar_query_server.go and aligns with the new return type.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all consumers of the `New` function are updated to handle the new return type.

# Test: Search for the function usage. Expect: Only occurrences of the new return type.
rg --type go -A 5 $'New'

Length of output: 347556

Implements requested improvements: Define error messages as types
Implements requested improvements: Define error messages as types
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e4ce755 and 99e5abc.

Files selected for processing (3)
  • orderbook/types/errors.go (1 hunks)
  • orderbook/usecase/orderbook_usecase.go (6 hunks)
  • orderbook/usecase/orderbook_usecase_test.go (1 hunks)
Files skipped from review due to trivial changes (1)
  • orderbook/usecase/orderbook_usecase_test.go
Additional comments not posted (3)
orderbook/types/errors.go (1)

1-133: LGTM!

The errors.go file is well-structured and follows the Go conventions for defining custom error types. It covers a comprehensive set of error scenarios related to the orderbook package, providing meaningful error messages with relevant details.

The custom error types are defined consistently, each with its own struct and Error() method implementation. The error messages include the problematic values and the underlying error (if any), which helps in debugging and understanding the error context.

Overall, the file is clean, organized, and serves its purpose effectively.

orderbook/usecase/orderbook_usecase.go (2)

294-295: LGTM!

The validation check for placedQuantity is a good addition to prevent the submission of invalid orders.


266-269: LGTM!

The improved error handling enhances the clarity and specificity of error reporting by replacing generic error messages with specific error types from the types package.

Also applies to: 277-280, 288-291, 300-303, 312-316, 324-327, 332-335, 340-343, 348-351, 358-361, 374-374, 380-380, 386-386, 403-406

* SQS-377 | Unit test ProcessPool

Introduces unit tests for Orderbook usecase ProcessPool
method.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 99e5abc and 14b01e5.

Files selected for processing (6)
  • domain/mocks/orderbook_grpc_client_mock.go (2 hunks)
  • domain/orderbook/grpcclient/orderbook_grpc_client.go (7 hunks)
  • orderbook/types/errors.go (1 hunks)
  • orderbook/usecase/export_test.go (1 hunks)
  • orderbook/usecase/orderbook_usecase.go (14 hunks)
  • orderbook/usecase/orderbook_usecase_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • orderbook/types/errors.go
Additional comments not posted (12)
orderbook/usecase/export_test.go (1)

8-16: LGTM!

Exporting the unexported createFormattedLimitOrder function for testing purposes is a good practice. The function signature matches the unexported function and the implementation simply calls the unexported function and returns the result, which is the expected behavior.

domain/mocks/orderbook_grpc_client_mock.go (4)

18-18: LGTM!

The code changes are approved.


20-20: LGTM!

The code changes are approved.


47-53: LGTM!

The code changes are approved.


63-69: LGTM!

The code changes are approved.

domain/orderbook/grpcclient/orderbook_grpc_client.go (2)

25-30: LGTM!

The new method FetchTickUnrealizedCancels is well-documented and implemented. It follows the documented behavior of fetching unrealized cancels in chunks, handling errors, and checking for mismatches in the number of unrealized cancels fetched.

Also applies to: 88-113


35-40: LGTM!

The new method FetchTicks is well-documented and implemented. It follows the documented behavior of fetching ticks in chunks, handling errors, and checking for mismatches in the number of ticks fetched.

Also applies to: 124-149

orderbook/usecase/orderbook_usecase.go (3)

298-299: LGTM: Added validation check for placedQuantity.

The added validation check ensures that the placedQuantity is greater than zero, preventing the submission of invalid orders. This strengthens the order creation process and helps maintain data integrity.


270-273: LGTM: Improved error handling using specific error types.

The error handling for various parsing operations has been improved by replacing generic error messages with specific error types from the types package. This enhances the clarity and specificity of error reporting, making it easier to diagnose and handle different types of errors.

Also applies to: 281-284, 292-295, 304-307, 316-320, 328-331, 336-339, 344-347, 352-355, 362-365, 378-378, 384-384, 390-390, 407-410


49-49: Verify the impact of the return type change.

The return type of the New function has been modified from the interface type mvc.OrderBookUsecase to a pointer to the concrete type *OrderbookUseCaseImpl. This change indicates a shift towards a more specific implementation and may improve performance by reducing interface overhead. However, it's important to ensure that all consumers of this function are adapted to handle the concrete type instead of the interface.

Run the following script to verify the usage of the New function:

Verification successful

Return type change successfully integrated.

The return type of the New function has been changed to a pointer to the concrete type *OrderbookUseCaseImpl. The usages in orderbook/usecase/orderbook_usecase_test.go and app/sidecar_query_server.go indicate that the consumers have been adapted to handle this concrete type directly, with no type assertions or interface assignments observed. This confirms that the change has been successfully integrated into the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all usages of the `New` function are adapted to the concrete type.

# Test: Search for the function usage. Expect: No type assertions or interface assignments.
rg --type go -A 5 $'orderbookusecase\.New'

Length of output: 1401

orderbook/usecase/orderbook_usecase_test.go (2)

35-222: LGTM!

The TestProcessPool test suite covers a comprehensive set of scenarios, including error cases and successful processing. The use of table-driven tests and mocks enhances maintainability and readability. The test cases are well-structured and cover the important aspects of the ProcessPool method.


223-528: LGTM!

The TestCreateFormattedLimitOrder test suite is comprehensive and covers various scenarios for the CreateFormattedLimitOrder method. The test cases handle different error conditions, such as tick not found, parsing errors, and overflow checks. They also verify the correctness of the formatted limit order in the successful case.

The use of table-driven tests and mocks improves the maintainability and readability of the code. The test cases are well-structured and cover the important aspects of the CreateFormattedLimitOrder method.

Implements requested improvements: Parse quantity as osmomath.Dec
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 14b01e5 and 2b33f77.

Files selected for processing (4)
  • domain/orderbook/order.go (2 hunks)
  • orderbook/types/errors.go (1 hunks)
  • orderbook/usecase/orderbook_usecase.go (13 hunks)
  • orderbook/usecase/orderbook_usecase_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • orderbook/types/errors.go
  • orderbook/usecase/orderbook_usecase_test.go
Additional comments not posted (16)
domain/orderbook/order.go (7)

80-80: LGTM!

The change to osmomath.Dec for the Quantity field is approved as it enhances the precision of numerical representations in the order book.


83-83: LGTM!

The change to osmomath.Dec for the PlacedQuantity field is approved as it enhances the precision of numerical representations in the order book.


85-85: LGTM!

The change to osmomath.Dec for the Price field is approved as it enhances the precision of numerical representations in the order book.


86-86: LGTM!

The change to osmomath.Dec for the PercentClaimed field is approved as it enhances the precision of numerical representations in the order book.


87-87: LGTM!

The change to osmomath.Dec for the TotalFilled field is approved as it enhances the precision of numerical representations in the order book.


88-88: LGTM!

The change to osmomath.Dec for the PercentFilled field is approved as it enhances the precision of numerical representations in the order book.


91-91: LGTM!

The change to osmomath.Dec for the Output field is approved as it enhances the precision of numerical representations in the order book.

orderbook/usecase/orderbook_usecase.go (9)

17-17: LGTM!

The code change is approved.


24-24: LGTM!

The code change is approved.


32-32: LGTM!

The code change is approved.


48-48: LGTM!

The code change is approved.


59-59: LGTM!

The code change is approved.


Line range hint 64-87: LGTM!

The code changes are approved.


137-137: LGTM!

The code changes are approved.


200-200: LGTM!

The code changes are approved.


Line range hint 259-431: LGTM!

The code changes are approved.

Copy link
Member

@p0mvn p0mvn left a comment

Choose a reason for hiding this comment

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

One blocking comment remaining:

  • The concern around ETAs overflow

orderbook/usecase/orderbook_usecase.go Outdated Show resolved Hide resolved
orderbook/usecase/orderbook_usecase.go Show resolved Hide resolved
orderbook/usecase/orderbook_usecase_test.go Outdated Show resolved Hide resolved
Implements requested improvements: Parse ETA`s as osmomath.Dec
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2b33f77 and 45552e9.

Files selected for processing (2)
  • orderbook/usecase/orderbook_usecase.go (13 hunks)
  • orderbook/usecase/orderbook_usecase_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • orderbook/usecase/orderbook_usecase_test.go
Additional comments not posted (20)
orderbook/usecase/orderbook_usecase.go (20)

17-17: LGTM!

The import statement for the types package is valid and necessary.


24-24: LGTM!

The struct name change to OrderbookUseCaseImpl follows the Go naming convention.


32-32: LGTM!

The interface assertion is correctly updated to match the struct name change.


48-48: LGTM!

The return type change to *OrderbookUseCaseImpl is valid and may have performance benefits by reducing interface overhead.


49-49: LGTM!

The struct initialization is correctly updated to match the struct name change.


58-58: LGTM!

The method declaration is correctly updated to match the struct name change.


63-63: LGTM!

The method declaration is correctly updated to match the struct name change.


65-67: LGTM!

The error handling block for the nil pool case is valid and necessary to prevent potential nil pointer dereferences and provide a specific error type.


71-71: LGTM!

The error handling block for the nil CosmWasmPoolModel case is valid and necessary to prevent potential nil pointer dereferences and provide a specific error type.


76-76: LGTM!

The error handling block for the non-orderbook pool case is valid and necessary to ensure that the pool is an orderbook pool and provide a specific error type.


87-87: LGTM!

The error handling block for the failed type assertion case is valid and necessary to ensure that the underlying pool is of the expected type and provide a specific error type.


99-99: LGTM!

The error handling block for the error case while fetching ticks is valid and necessary to handle potential errors and provide a specific error type with relevant information.


105-105: LGTM!

The error handling block for the error case while fetching unrealized cancels is valid and necessary to handle potential errors and provide a specific error type with relevant information.


114-114: LGTM!

The error handling block for the tick ID mismatch case is valid and necessary to ensure the consistency of tick IDs and provide a specific error type with relevant information.


119-119: LGTM!

The error handling block for the tick ID mismatch case is valid and necessary to ensure the consistency of tick IDs and provide a specific error type with relevant information.


137-137: LGTM!

The method declaration is correctly updated to match the struct name change.


200-200: LGTM!

The method declaration is correctly updated to match the struct name change.


258-260: LGTM!

The variable declaration for zeroDec is valid and the comment provides a clear explanation of its purpose. Defining the zero decimal value in a global space avoids creating a new instance every time, which can improve performance.


263-263: LGTM!

The method declaration is correctly updated to match the struct name change.


273-276: LGTM!

The error handling block for the case where the tick for the order is not found is valid and necessary to handle the scenario and provide a specific error type with relevant information.

Copy link
Member

@p0mvn p0mvn left a comment

Choose a reason for hiding this comment

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

LGTM

Could we address this one dangling comment pre-merge?
#492 (comment)

* SQS-377 | Unit test ProcessPool

Introduces unit tests for Orderbook usecase ProcessPool
method.

* SQS-378 | WIP

* SQS-377 | Unit test ProcessPool

Adds requested improvements

* SQS-377 | Unit test ProcessPool

Add cosmwasmpool import

* SQS-378 | Test GetActiveOrders

Formatting

* SQS-378 | Test GetActiveOrders

Adds several more test cases

* SQS-378 | Test GetActiveOrders

Implements tests for GetActiveOrders orderbook usecase method

* SQS-378 | Test GetActiveOrders

* SQS-378 | Test GetActiveOrders

Implements requested changes

* SQS-378 | Test GetActiveOrders

Cleanup

* SQS-379 | unit tests for processOrderBookActiveOrders (#499)

* SQS-379 | processOrderBookActiveOrders

Implements tests for processOrderBookActiveOrders orderbook usecase method.
As a side effect introduces some helper methods and refactors some test
cases.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Outside diff range, codebase verification and nitpick comments (1)
Makefile (1)

38-38: Unrecognized --pd option in swag init command

The --pd option used in the swag init command within the Makefile is not recognized as a standard option in Swaggo's documentation, and there is no custom implementation found in the codebase. Please verify if this option is intended or correct it if it is a typo. The .swaggo file for overrides is correctly specified and exists.

Analysis chain

Verify the --pd option and the overrides file path.

The --pd option in the swag init command is not recognized in standard Swaggo documentation. Please confirm if this is a custom option specific to your project. Additionally, ensure that the .swaggo file exists at the specified path and is correctly formatted to be used as an overrides file.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the existence of the .swaggo file and its content.
cat ./.swaggo

Length of output: 207


Script:

#!/bin/bash
# Search for any custom implementation or alias of the `swag` command that includes the `--pd` option.
rg 'swag.*--pd'

Length of output: 98

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 45552e9 and be65040.

Files selected for processing (21)
  • .swaggo (1 hunks)
  • Makefile (1 hunks)
  • docs/docs.go (6 hunks)
  • docs/swagger.json (6 hunks)
  • docs/swagger.yaml (5 hunks)
  • domain/errors.go (1 hunks)
  • domain/mocks/orderbook_grpc_client_mock.go (2 hunks)
  • domain/mocks/orderbook_usecase_mock.go (1 hunks)
  • domain/mocks/pools_usecase_mock.go (2 hunks)
  • domain/pools.go (1 hunks)
  • orderbook/types/errors.go (1 hunks)
  • orderbook/types/get_orders_request.go (1 hunks)
  • orderbook/usecase/export_test.go (1 hunks)
  • orderbook/usecase/orderbook_usecase.go (16 hunks)
  • orderbook/usecase/orderbook_usecase_test.go (1 hunks)
  • orderbook/usecase/orderbooktesting/parsing/active_orders_response.json (1 hunks)
  • orderbook/usecase/orderbooktesting/suite.go (1 hunks)
  • passthrough/delivery/http/passthrough_handler.go (3 hunks)
  • passthrough/delivery/http/passthrough_handler_test.go (1 hunks)
  • pools/delivery/http/pools_handler.go (1 hunks)
  • router/usecase/routertesting/suite.go (2 hunks)
Files skipped from review due to trivial changes (2)
  • .swaggo
  • pools/delivery/http/pools_handler.go
Files skipped from review as they are similar to previous changes (4)
  • domain/mocks/orderbook_grpc_client_mock.go
  • orderbook/usecase/export_test.go
  • orderbook/usecase/orderbook_usecase.go
  • orderbook/usecase/orderbook_usecase_test.go
Additional comments not posted (28)
orderbook/usecase/orderbooktesting/parsing/active_orders_response.json (1)

1-53: Well-formed JSON structure for testing.

The JSON structure is comprehensive and well-formed, suitable for testing the active orders response. It includes detailed fields that are essential for thorough testing of the orderbook functionality.

orderbook/types/get_orders_request.go (2)

14-37: Clear and robust validation logic.

The addition of specific error messages for different types of validation failures enhances the clarity and robustness of the API. The validation logic for the UserOsmoAddress is concise and effectively uses the sdk.AccAddressFromBech32 function to ensure the address's validity.


20-20: Verify impact of removing pagination parameters.

The removal of Limit and Cursor fields simplifies the request structure. However, verify the impact on client-side implementations and ensure that this change is clearly communicated to API consumers.

passthrough/delivery/http/passthrough_handler_test.go (2)

22-28: Well-structured test suite initialization.

The test suite is properly initialized using the suite.Run function, which is a standard practice for running tests in Go using the testify/suite package. This ensures that all methods defined with the Test prefix are run as part of the test suite.


30-117: Comprehensive test cases for GetActiveOrders.

The test cases cover a variety of scenarios including validation errors, successful retrieval of active orders, and handling of internal server errors. This comprehensive coverage is crucial for ensuring the robustness of the GetActiveOrders method.

  • Validation Error Handling: The test correctly anticipates a BadRequest status when no query parameters are provided, which aligns with the expected behavior for missing required fields.
  • Successful Data Retrieval: The test for successful retrieval of active orders mocks the expected behavior and uses a file to compare the expected JSON response, which is a good practice for ensuring the response structure is maintained.
  • Error Handling: The test for internal server errors properly mocks a failure scenario in the use case, ensuring the handler correctly handles and responds with an InternalServerError.

Overall, the tests are well-structured and effectively use mocking to isolate the handler's functionality, which is key in unit testing.

passthrough/delivery/http/passthrough_handler.go (1)

Line range hint 64-101: Well-documented and robust implementation of GetActiveOrders.

The method GetActiveOrders is well-documented with clear annotations that describe the API endpoint, expected responses, and parameters. This documentation is crucial for API usability and clarity.

  • Error Handling: The method uses domain.ResponseError for error responses, which centralizes error handling and ensures consistency across different parts of the application. This is a significant improvement in maintaining code quality and reducing redundancy.
  • Request Validation: The method includes request validation logic, which is essential for ensuring that the incoming requests meet the expected criteria before processing.
  • Trace Handling: The use of OpenTelemetry for tracing and error recording is a good practice, especially for debugging and monitoring the application in production environments.

Overall, the method is implemented with a clear focus on error handling, request validation, and documentation, which are all best practices in API development.

domain/pools.go (1)

70-85: Robust validation logic in CanonicalOrderBooksResult.Validate.

The addition of the Validate method to the CanonicalOrderBooksResult struct enhances the robustness of the data handling by ensuring that all critical fields are checked before the object is used further in the application. This method checks for empty strings and zero values, which are common sources of bugs in data processing.

  • Field Validations: Each field is appropriately validated against specific criteria, such as non-empty strings and non-zero values. This is crucial for preventing invalid data from propagating through the system.
  • Error Handling: The method returns custom errors for each type of validation failure, which aids in debugging and maintaining the system by providing clear error messages.

This method is a good example of defensive programming and helps ensure the integrity of the data within the application.

orderbook/types/errors.go (1)

9-220: Approved: Comprehensive and well-defined custom error types for orderbook operations.

The new file errors.go introduces a variety of custom error types that enhance the error handling capabilities within the orderbook domain. Each error type is well-defined and implements the error interface consistently, providing clear and informative error messages that are specific to various failure scenarios encountered in orderbook operations.

This approach not only improves the maintainability of the code by segregating error handling but also aids in debugging and error tracking during runtime.

orderbook/usecase/orderbooktesting/suite.go (1)

15-208: Approved: Well-structured test suite helper for the orderbook use case.

The file suite.go introduces a comprehensive test suite helper for the orderbook use case, featuring various helper methods and default objects. These additions significantly simplify the setup and execution of unit tests by providing reusable components and clear, concise helper methods.

This structure not only enhances the readability and maintainability of the test code but also promotes consistency and efficiency in test implementation.

domain/errors.go (4)

21-21: Approved: Clear error message for empty base denomination.

The addition of ErrBaseDenomNotValid with the message "base denom is empty" is clear and effectively communicates the specific validation failure.


22-22: Approved: Clear error message for empty quote denomination.

The addition of ErrQuoteDenomNotValid with the message "quote denom is empty" is appropriate and clearly indicates the validation failure when the quote denomination is not provided.


23-23: Approved: Clear error message for invalid pool ID.

The addition of ErrPoolIDNotValid with the message "pool ID is zero" effectively communicates the validation failure when a pool ID is not properly specified.


24-24: Approved: Clear error message for empty contract address.

The addition of ErrContractAddressNotValid with the message "contract address is empty" is clear and effectively communicates the specific validation failure when a contract address is not provided.

router/usecase/routertesting/suite.go (1)

462-470: Approved: Robust error handling method added.

The addition of the ErrorIsAs method in the RouterTestHelper struct enhances error assertions by effectively using errors.Is and errors.As to check for exact and compatible error conditions, respectively.

docs/swagger.yaml (8)

13-17: Approved: Addition of domain.ResponseError definition.

This new structure standardizes error responses across the API, enhancing clarity and consistency in error handling.


38-44: Approved: Addition of github_com_cosmos_cosmos-sdk_types.Coin definition.

This definition is essential for clearly representing monetary values within the API, ensuring structured data handling for amounts and denominations.


45-49: Approved: Addition of github_com_osmosis-labs_sqs_domain_orderbook.Asset definition.

This definition standardizes the representation of assets within the API, which is crucial for financial and trading applications.


50-90: Approved: Comprehensive addition of github_com_osmosis-labs_sqs_domain_orderbook.LimitOrder definition.

This definition is critical for the API's trading functionality, providing a clear and structured representation of limit orders with detailed properties.


91-104: Approved: Addition of github_com_osmosis-labs_sqs_domain_orderbook.OrderStatus enum.

This enum is essential for clearly tracking and managing the status of orders within the API.


105-135: Approved: Addition of various github_com_osmosis-labs_sqs_domain_passthrough definitions.

These definitions are crucial for representing detailed financial data within the API, enhancing the portfolio management features.


136-144: Approved: Addition of github_com_osmosis-labs_sqs_orderbook_types.GetActiveOrdersResponse definition.

This definition is important for structuring responses related to active orders, ensuring clarity and accessibility of the data.


181-207: Approved: Addition of new endpoints /passthrough/active-orders and /passthrough/portfolio-assets/{address}.

These endpoints are crucial for the API's functionality, allowing users to retrieve detailed financial data related to orders and assets.

Also applies to: 225-229

docs/swagger.json (3)

9-45: Comprehensive addition of the /passthrough/active-orders endpoint.

The addition of the /passthrough/active-orders endpoint is well-documented with a clear description, parameters, and response schemas. The use of $ref for schema references ensures consistency and reusability of the defined models. This is a good practice as it helps maintain the schema definitions in one place, making the API easier to update and maintain.


67-73: Ensure consistency in schema references.

The schema references for PortfolioAssetsResult and CanonicalOrderBooksResult are used correctly to ensure type safety and clarity in the API documentation. This approach helps in maintaining a clean and manageable codebase by avoiding redundancy and enhancing readability.

Also applies to: 145-145


Line range hint 468-702: Review of new definitions added to the Swagger configuration.

The new definitions such as ResponseError, LimitOrder, OrderStatus, and others are well-structured and provide a clear and detailed schema for the API. Each definition is equipped with appropriate properties and types, enhancing the API's robustness and usability.

  • ResponseError: Properly defined with a message property.
  • LimitOrder and OrderStatus: These definitions are crucial for the new /passthrough/active-orders endpoint and are detailed with relevant properties.

It's important to ensure that these new definitions are consistently used across the API wherever applicable to maintain uniformity.

docs/docs.go (3)

18-54: Well-documented addition of the /passthrough/active-orders endpoint in Go documentation.

The Go documentation for the new endpoint /passthrough/active-orders mirrors the Swagger JSON configuration accurately. The detailed description, parameters, and response schemas are consistent and correctly implemented in the Go template string. This ensures that the generated Swagger documentation will be accurate and informative.


76-82: Consistent implementation of schema references in Go documentation.

The schema references for PortfolioAssetsResult and CanonicalOrderBooksResult are implemented consistently in the Go documentation as seen in the Swagger JSON. This consistency is crucial for maintaining the integrity and accuracy of the API documentation across different implementations.

Also applies to: 154-154


Line range hint 477-711: Review of new definitions added to the Go documentation.

The new definitions such as ResponseError, LimitOrder, OrderStatus, and others are correctly implemented in the Go documentation. The structure and properties match those defined in the Swagger JSON configuration, ensuring consistency across the documentation sources.

  • ResponseError: Defined with a message property, aligning with the Swagger JSON.
  • LimitOrder and OrderStatus: Detailed with appropriate properties and types, crucial for the new endpoint documentation.

These definitions are essential for ensuring that the generated Swagger documentation is robust and user-friendly.

Comment on lines +13 to +39
// OrderbookUsecaseMock is a mock implementation of the RouterUsecase interface
type OrderbookUsecaseMock struct {
ProcessPoolFunc func(ctx context.Context, pool sqsdomain.PoolI) error
GetAllTicksFunc func(poolID uint64) (map[int64]orderbookdomain.OrderbookTick, bool)
GetActiveOrdersFunc func(ctx context.Context, address string) ([]orderbookdomain.LimitOrder, bool, error)
}

func (m *OrderbookUsecaseMock) ProcessPool(ctx context.Context, pool sqsdomain.PoolI) error {
if m.ProcessPoolFunc != nil {
return m.ProcessPoolFunc(ctx, pool)
}
panic("unimplemented")
}

func (m *OrderbookUsecaseMock) GetAllTicks(poolID uint64) (map[int64]orderbookdomain.OrderbookTick, bool) {
if m.GetAllTicksFunc != nil {
return m.GetAllTicksFunc(poolID)
}
panic("unimplemented")
}

func (m *OrderbookUsecaseMock) GetActiveOrders(ctx context.Context, address string) ([]orderbookdomain.LimitOrder, bool, error) {
if m.GetActiveOrdersFunc != nil {
return m.GetActiveOrdersFunc(ctx, address)
}
panic("unimplemented")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider enhancing panic messages for clarity.

The mock implementation uses a common pattern of function pointers for flexible testing. However, consider enhancing the panic messages to include the name of the unimplemented method for easier debugging.

For example:

- panic("unimplemented")
+ panic("ProcessPool method is unimplemented")

Committable suggestion was skipped due to low confidence.

Comment on lines +22 to +31
GetAllPoolsFunc func() ([]sqsdomain.PoolI, error)
GetPoolsFunc func(opts ...domain.PoolsOption) ([]sqsdomain.PoolI, error)
StorePoolsFunc func(pools []sqsdomain.PoolI) error
GetRoutesFromCandidatesFunc func(candidateRoutes sqsdomain.CandidateRoutes, tokenInDenom, tokenOutDenom string) ([]route.RouteImpl, error)
GetTickModelMapFunc func(poolIDs []uint64) (map[uint64]*sqsdomain.TickModel, error)
GetPoolFunc func(poolID uint64) (sqsdomain.PoolI, error)
GetPoolSpotPriceFunc func(ctx context.Context, poolID uint64, takerFee osmomath.Dec, quoteAsset, baseAsset string) (osmomath.BigDec, error)
GetCosmWasmPoolConfigFunc func() domain.CosmWasmPoolRouterConfig
CalcExitCFMMPoolFunc func(poolID uint64, exitingShares osmomath.Int) (sdk.Coins, error)
GetAllCanonicalOrderbookPoolIDsFunc func() ([]domain.CanonicalOrderBooksResult, error)
Copy link
Contributor

Choose a reason for hiding this comment

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

Approved: Addition of GetAllCanonicalOrderbookPoolIDsFunc enhances mock flexibility.

The addition of GetAllCanonicalOrderbookPoolIDsFunc to PoolsUsecaseMock is consistent with the existing structure of the mock and enhances its flexibility by allowing specific behavior to be injected for testing. This change is well-integrated and follows the established pattern of optional function implementations within the mock.

Consider adding documentation for GetAllCanonicalOrderbookPoolIDsFunc to explain its purpose and usage, which will aid future developers in understanding the mock's capabilities.

Would you like me to help draft the documentation for this new function?

Also applies to: 44-46

Requested changes: cover test cases with different addresses
Copy link

sonarcloud bot commented Sep 9, 2024

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between be65040 and 4e1e945.

Files selected for processing (1)
  • orderbook/usecase/orderbook_usecase_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • orderbook/usecase/orderbook_usecase_test.go

@deividaspetraitis deividaspetraitis merged commit ec649ca into v25.x Sep 9, 2024
10 checks passed
@deividaspetraitis deividaspetraitis deleted the SQS-375 branch September 9, 2024 11:23
mergify bot pushed a commit that referenced this pull request Sep 9, 2024
* SQS-375 | Unit test createFormattedLimitOrder

Introduces unit tests for Orderbook usecase createFormattedLimitOrder
method.

* SQS-377 | Unit test ProcessPool

Introduces unit tests for Orderbook usecase ProcessPool
method.

* SQS-378 | Test GetActiveOrders

Implements tests for GetActiveOrders orderbook usecase method

* SQS-379 | processOrderBookActiveOrders

Implements tests for processOrderBookActiveOrders orderbook usecase method.
As a side effect introduces some helper methods and refactors some test
cases.

(cherry picked from commit ec649ca)
deividaspetraitis added a commit that referenced this pull request Sep 9, 2024
* SQS-375 | Unit test createFormattedLimitOrder (#492)

* SQS-375 | Unit test createFormattedLimitOrder

Introduces unit tests for Orderbook usecase createFormattedLimitOrder
method.

* SQS-377 | Unit test ProcessPool

Introduces unit tests for Orderbook usecase ProcessPool
method.

* SQS-378 | Test GetActiveOrders

Implements tests for GetActiveOrders orderbook usecase method

* SQS-379 | processOrderBookActiveOrders

Implements tests for processOrderBookActiveOrders orderbook usecase method.
As a side effect introduces some helper methods and refactors some test
cases.

(cherry picked from commit ec649ca)

* SQS-375 | Unit test createFormattedLimitOrder

Backport

---------

Co-authored-by: Deividas Petraitis <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A:backport/v26.x backport patches to v26.x branch
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants