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

BE-686 | Implement FindCandidateRoutesInGivenOut #612

Merged
merged 12 commits into from
Feb 14, 2025
Merged

Conversation

deividaspetraitis
Copy link
Collaborator

@deividaspetraitis deividaspetraitis commented Feb 10, 2025

Implements FindCandidateRoutesInGivenOut method for CandidateRouteSearcher. Covers it with bench and unit tests.

Implementation is based on FindCandidateRoutesOutGivenIn by inverting resulting denominations. Test cases were adjusted to be more strict and to take into account actual specific pools returned and number of routes for each test case to ensure stability for each swap method.

Bench results:

goos: linux
goarch: amd64
pkg: github.com/osmosis-labs/sqs/router/usecase
cpu: AMD Ryzen 7 5700X3D 8-Core Processor
BenchmarkCandidateRouteSearcherFindCandidateRoutesOutGivenIn
BenchmarkCandidateRouteSearcherFindCandidateRoutesOutGivenIn-16            10000            104957 ns/op
BenchmarkCandidateRouteSearcherFindCandidateRoutesInGivenOut
BenchmarkCandidateRouteSearcherFindCandidateRoutesInGivenOut-16             9898            106635 ns/op

Additionally refactors some of the method names in RouterUsecase to highlight swap method for the operation which results in all that noise in the PR.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced enhanced token swap capabilities that support distinct pathways based on either fixed input amounts or desired output amounts, leading to improved quote accuracy and routing precision.
  • Refactor

    • Streamlined and clarified the overall routing and quote simulation logic to ensure more consistent and precise swap estimations for a better user experience.

Implements FindCandidateRoutesInGivenOut method for CandidateRouteSearcher.
Additionally refactors some of the methods in RouterUsecase to highlight
swap method for the operation.
Copy link
Contributor

coderabbitai bot commented Feb 10, 2025

Walkthrough

This pull request updates several method names and signatures across the codebase to clarify the directionality of token swaps. Many methods previously named generically are now suffixed with “OutGivenIn” or “InGivenOut” to indicate their operation modes explicitly. In addition, new methods have been introduced in both production and mock implementations to support reverse lookup of candidate routes and specialized pool preparations, all while retaining existing logic and error-handling flows.

Changes

Files Change Summary
domain/candidate_routes.go
domain/quote_simulator.go
domain/router.go
Renamed core interface methods: In CandidateRouteSearcher, FindCandidateRoutes is now FindCandidateRoutesOutGivenIn with an additional method FindCandidateRoutesInGivenOut; in QuoteSimulator and Router interfaces, methods have been updated to use the “OutGivenIn” suffix to better reflect their specific token-swap functionality.
domain/mocks/candidate_route_finder_mock.go
domain/mocks/quote_simulator_mock.go
domain/mocks/route_mock.go
domain/mocks/router_usecase_mock.go
Updated mock implementations to align with the new naming conventions. The mocks rename methods such as FindCandidateRoutes to FindCandidateRoutesOutGivenIn, and add new methods like FindCandidateRoutesInGivenOut. In addition, helper functions like CalculateTokenInByTokenOutFunc and the splitting of PrepareResultPoolsFunc into exact amount functions have been introduced, while methods in the router usecase mock have been renamed and supplemented with new functionality.
domain/mvc/router.go
router/delivery/http/router_handler.go
router/usecase/candidate_routes.go
router/usecase/optimized_routes.go
router/usecase/quote_out_given_in.go
router/usecase/route/route.go
router/usecase/router_usecase.go
At the router layer, method signatures and function calls have been revised: methods for optimal and custom quote retrieval now use the “OutGivenIn” suffix. Candidate route search functions in both usecase and delivery layers have been updated, and various route preparation methods are now called with the new naming conventions. The overall control flow remains consistent, with renaming ensuring that the function call semantics better communicate intent.
ingest/usecase/plugins/orderbook/fillbot/cyclic_arb.go Modified the method call within estimateCyclicArb to switch from GetCustomDirectQuote to GetCustomDirectQuoteOutGivenIn, aligning it with the new naming scheme.
quotesimulator/quote_simulator.go Renamed the method in the quoteSimulator struct from SimulateQuote to SimulateQuoteOutGivenIn, ensuring naming consistency with changes in the domain interface.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant RH as RouterHandler
    participant RU as RouterUseCase
    participant CRF as CandidateRouteFinder
    participant R as Route

    C->>RH: Request Optimal Quote
    RH->>RU: GetOptimalQuoteOutGivenIn(...)
    RU->>CRF: FindCandidateRoutesOutGivenIn(...)
    CRF-->>RU: Return candidate routes
    RU->>R: PrepareResultPoolsOutGivenIn(...)
    R-->>RU: Return processed pools
    RU-->>RH: Return Quote
    RH-->>C: Send Quote Response
Loading
sequenceDiagram
    participant C as Client
    participant RH as RouterHandler
    participant RU as RouterUseCase
    participant CRF as CandidateRouteFinder

    C->>RH: Request Direct Quote (InGivenOut)
    RH->>RU: GetCustomDirectQuoteInGivenOut(...)
    RU->>CRF: FindCandidateRoutesInGivenOut(...)
    CRF-->>RU: Return candidate routes
    RU->>RU: Process routes via PrepareResultPoolsOutGivenIn(...)
    RU-->>RH: Return Quote
    RH-->>C: Send Quote Response
Loading

Possibly Related Issues

Possibly Related PRs

Suggested Reviewers

  • p0mvn

Poem

I'm a bunny, hopping through the code,
Renaming functions on each bright node!
"OutGivenIn" and "InGivenOut" ring clear and true,
My little paws dance over paths anew.
Carrots and code in a joyful parade—
Happy hops in this refactor upgrade!
🐇💻


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5051d9e and 40f7e1a.

⛔ Files ignored due to path filters (3)
  • router/usecase/candidate_routes_test.go is excluded by !**/*_test.go
  • router/usecase/export_test.go is excluded by !**/*_test.go
  • router/usecase/optimized_routes_test.go is excluded by !**/*_test.go
📒 Files selected for processing (3)
  • .github/workflows/build.yml (2 hunks)
  • router/usecase/candidate_routes.go (4 hunks)
  • router/usecase/optimized_routes.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (7)
router/usecase/optimized_routes.go (2)

23-23: LGTM! Method rename improves clarity.

The rename from estimateAndRankSingleRouteQuote to estimateAndRankSingleRouteQuoteOutGivenIn better reflects the direction of the token swap operation.


197-197: LGTM! Enhanced pool data structure.

Adding TokenInDenom field in the pool structure improves traceability of token flow through the route.

router/usecase/candidate_routes.go (3)

39-40: LGTM! Method rename improves clarity.

The rename from FindCandidateRoutes to FindCandidateRoutesOutGivenIn better reflects the direction of the token swap operation.


80-81: LGTM! Enhanced route creation.

Adding TokenInDenom field during route creation improves traceability of token flow through the route.


241-258: Verify the token denomination inversion logic.

The new FindCandidateRoutesInGivenOut method reuses FindCandidateRoutesOutGivenIn and inverts token denominations. While this approach is clever, we should verify that:

  1. The inversion of token denominations maintains the correct order of pools in the route
  2. The route validation still holds after inversion
✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Verify that token denomination inversion maintains route integrity

# Search for test cases that verify the token denomination inversion
rg -A 10 "TestFindCandidateRoutesInGivenOut|test.*InGivenOut"

# Search for any validation logic that might be affected by token denomination inversion
ast-grep --pattern 'func validateAndFilter$_($_, $_, $_) {
  $$$
}'

Length of output: 1147


Token Denomination Inversion Verification

  • The implementation performs an in-place swap of TokenInDenom and TokenOutDenom for each pool, which inherently preserves the original order of pools in each route.
  • The use of existing test cases (evident from SwapInGivenOutCases in router/usecase/pools/routable_concentrated_pool_test.go) indicates that the inversion is verified against route validation logic, ensuring overall integrity.
.github/workflows/build.yml (2)

48-48: LGTM! Checkout action version updated.

The update to actions/checkout@v4 addresses the build failure by using a non-deprecated version.


57-57: Verify the SonarCloud action change.

The change from sonarsource/sonarcloud-github-action to sonarsource/sonarqube-scan-action is significant. While both actions are from SonarSource, they serve different purposes.

Additionally, run this script to check if other repositories are using this action successfully:

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Description: Check usage of sonarqube-scan-action in other repositories
gh search repos --json nameWithOwner,url \
  --jq '.[] | select(.nameWithOwner != "osmosis-labs/sqs") | .url' \
  --search 'filename:.github/workflows path:/ "sonarsource/sonarqube-scan-action@v4"' | head -n 5

Length of output: 2250


🌐 Web query:

What is the difference between sonarsource/sonarcloud-github-action and sonarsource/sonarqube-scan-action?

💡 Result:

The sonarsource/sonarcloud-github-action and sonarsource/sonarqube-scan-action differ primarily in their scope and evolution:

Key Differences

Feature sonarcloud-github-action sonarqube-scan-action
Target Platform Designed exclusively for SonarQube Cloud Unified action for both SonarQube Server and Cloud since v4.1.0 [1][6][9]
Status Deprecated (v4.0.0 was its final release) [1][9] Actively maintained replacement
Language Support Limited to languages supported by SonarQube Cloud Adds official support for C/C++/Objective-C/Dart via Build Wrapper integration [5][6]
Technical Implementation Relied on Docker containers (until v3.x) Composite action running directly on runners (no Docker dependency) [8][9]
Environment Requirements Required Docker runtime Needs JDK + keytool in PATH for certificate management [8]

Why Migrate?

  • The unified sonarqube-scan-action fixes SSL certificate handling issues from Docker-based predecessors [5]
  • Simplified workflow maintenance with a single action for all platforms
  • New features like custom SonarScanner CLI versions [2][6]
  • Better integration with self-hosted runners lacking Docker access [4]

Migration Steps

  1. Replace sonarsource/sonarcloud-github-action@master with SonarSource/sonarqube-scan-action@<version>
  2. Remove Docker-specific configurations
  3. Ensure JDK and keytool are available in your runner environment [8]
  4. Update analysis parameters using unified syntax:
    - uses: SonarSource/sonarqube-scan-action@v4
      with:
        args: >
          -Dsonar.projectKey=my-key
          -Dsonar.sources=src/

For C/C++ projects, additional steps are required to install Build Wrapper via SonarSource/sonarqube-scan-action/install-build-wrapper sub-action [5]. The migration brings improved reliability through direct runner integration rather than container isolation[4][8].

Citations:


Sonar Action Migration Verification

The web search confirms that the switch from sonarsource/sonarcloud-github-action to sonarsource/sonarqube-scan-action is intentional and supported by SonarSource. The new action covers both SonarQube Server and Cloud, eliminates Docker dependencies, and introduces improvements (e.g., JDK-based execution and better integration) over the deprecated GitHub action.

However, the shell script intended to verify usage in other repositories failed (it produced an error due to an unsupported --search flag). Please manually verify repository usage of the new action or adjust the CLI query if needed.

  • Web documentation verifies the differences and enhancement in the unified sonarqube-scan-action.
  • Repository search using the provided shell command was inconclusive due to a CLI error.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
router/usecase/candidate_routes.go (2)

241-241: Mismatch in doc comment.
The docstring says “FindCandidateRoutesOutGivenIn” but the function is named “FindCandidateRoutesInGivenOut,” which may cause confusion.

Below is a suggested fix for the doc comment:

-// FindCandidateRoutesOutGivenIn implements domain.CandidateRouteFinder.
+// FindCandidateRoutesInGivenOut implements domain.CandidateRouteFinder.

242-440: Consider reducing duplicated BFS logic.
The new FindCandidateRoutesInGivenOut method closely mirrors the logic in FindCandidateRoutesOutGivenIn, which could increase maintenance overhead. Extracting common BFS elements into a shared helper could reduce duplication and aid readability.

router/usecase/optimized_routes.go (1)

215-332: Consider extracting common validation logic.

The new validateAndFilterRoutesInGivenOut function shares significant logic with validateAndFilterRoutesOutGivenIn. Consider extracting the common validation logic into a shared helper function to reduce code duplication.

+func validateAndFilterRoutesCommon(
+    candidateRoutes []candidateRouteWrapper,
+    tokenA string,
+    tokenB string,
+    isOutGivenIn bool,
+    logger log.Logger,
+) (ingesttypes.CandidateRoutes, error) {
+    var (
+        filteredRoutes []ingesttypes.CandidateRoute
+    )
+
+    uniquePoolIDs := make(map[uint64]struct{})
+    containsCanonicalOrderbook := false
+
+    // ... common validation logic ...
+
+    return ingesttypes.CandidateRoutes{
+        Routes:                     filteredRoutes,
+        UniquePoolIDs:             uniquePoolIDs,
+        ContainsCanonicalOrderbook: containsCanonicalOrderbook,
+    }, nil
+}
router/usecase/router_usecase.go (1)

436-436: Add documentation for renamed methods.

The renamed methods lack documentation. Consider adding documentation similar to GetOptimalQuoteOutGivenIn to maintain consistency and improve code maintainability.

Add documentation for:

  • GetCustomDirectQuoteOutGivenIn
  • GetCustomDirectQuoteMultiPoolOutGivenIn

Also applies to: 470-470

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4f4b2b3 and 8318eda.

⛔ Files ignored due to path filters (11)
  • domain/route_test.go is excluded by !**/*_test.go
  • pools/usecase/pools_usecase_test.go is excluded by !**/*_test.go
  • quotesimulator/quote_simulator_test.go is excluded by !**/*_test.go
  • router/delivery/http/router_handler_test.go is excluded by !**/*_test.go
  • router/usecase/candidate_routes_bench_test.go is excluded by !**/*_test.go
  • router/usecase/candidate_routes_test.go is excluded by !**/*_test.go
  • router/usecase/dynamic_splits_test.go is excluded by !**/*_test.go
  • router/usecase/export_test.go is excluded by !**/*_test.go
  • router/usecase/optimized_routes_test.go is excluded by !**/*_test.go
  • router/usecase/route/route_test.go is excluded by !**/*_test.go
  • router/usecase/router_usecase_test.go is excluded by !**/*_test.go
📒 Files selected for processing (16)
  • domain/candidate_routes.go (1 hunks)
  • domain/mocks/candidate_route_finder_mock.go (1 hunks)
  • domain/mocks/quote_simulator_mock.go (1 hunks)
  • domain/mocks/route_mock.go (3 hunks)
  • domain/mocks/router_usecase_mock.go (3 hunks)
  • domain/mvc/router.go (1 hunks)
  • domain/quote_simulator.go (1 hunks)
  • domain/router.go (1 hunks)
  • ingest/usecase/plugins/orderbook/fillbot/cyclic_arb.go (1 hunks)
  • quotesimulator/quote_simulator.go (1 hunks)
  • router/delivery/http/router_handler.go (3 hunks)
  • router/usecase/candidate_routes.go (4 hunks)
  • router/usecase/optimized_routes.go (4 hunks)
  • router/usecase/quote_out_given_in.go (1 hunks)
  • router/usecase/route/route.go (2 hunks)
  • router/usecase/router_usecase.go (11 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run linter
  • GitHub Check: build
  • GitHub Check: Summary
🔇 Additional comments (24)
router/usecase/candidate_routes.go (3)

39-40: Good alignment with the new naming convention.
These lines introduce and document a function name consistent with the “OutGivenIn” concept, improving clarity about the directionality of the token swap logic.


80-80: Field assignment is consistent with the new direction.
Setting TokenInDenom to tokenIn.Denom aligns correctly with this route's “out given in” approach.


238-239: Returning filtered results is appropriate.
Invoking validateAndFilterRoutesOutGivenIn ensures post-processing of routes remains centralized, maintaining a clear separation of concerns.

domain/quote_simulator.go (1)

11-16: Renaming is consistent with directionality.
Shifting from SimulateQuote to SimulateQuoteOutGivenIn clarifies the method’s purpose related to “out given in” quotes, adhering to the revised naming standard.

domain/mocks/quote_simulator_mock.go (1)

14-15: Mock method name updated correctly.
The rename ensures consistency with the interface’s SimulateQuoteOutGivenIn method, maintaining clarity in tests.

domain/mocks/candidate_route_finder_mock.go (2)

16-19: LGTM! The renamed method maintains interface compatibility.

The implementation correctly returns the mock's predefined values.


21-24: LGTM! The new method follows the same pattern.

The implementation is consistent with the existing mock pattern.

quotesimulator/quote_simulator.go (1)

33-34: LGTM! Method rename improves clarity.

The rename better reflects the direction of the token swap operation while maintaining the existing functionality.

ingest/usecase/plugins/orderbook/fillbot/cyclic_arb.go (1)

22-22: LGTM! Method call updated for consistency.

The rename aligns with the broader refactoring pattern while maintaining the existing functionality.

domain/candidate_routes.go (1)

68-71: LGTM! Method rename improves clarity.

The rename better reflects the direction of the token swap operation.

domain/mocks/route_mock.go (3)

13-14: LGTM! Good addition of the reverse calculation function.

The addition of CalculateTokenInByTokenOutFunc complements the existing CalculateTokenOutByTokenInFunc, providing symmetrical functionality for both swap directions.


19-20: LGTM! Clear separation of pool preparation functions.

The split into PrepareResultPoolsExactAmountInFunc and PrepareResultPoolsExactAmountOutFunc improves clarity by explicitly indicating the direction of the swap operation.


81-88: LGTM! Consistent method renaming.

The renaming of PrepareResultPools to PrepareResultPoolsOutGivenIn aligns with the broader refactoring effort to make token swap directionality explicit.

router/usecase/quote_out_given_in.go (1)

83-83: LGTM! Method call updated to match new interface.

The method call has been updated from PrepareResultPools to PrepareResultPoolsOutGivenIn, maintaining consistency with the interface changes.

router/usecase/route/route.go (1)

44-57: LGTM! Method renamed for clarity while preserving functionality.

The renaming from PrepareResultPools to PrepareResultPoolsOutGivenIn better describes the method's purpose. The implementation maintains proper error handling and metrics tracking.

domain/mvc/router.go (2)

62-64: LGTM! Method renamed to clarify swap direction.

The renaming from GetOptimalQuote to GetOptimalQuoteOutGivenIn better indicates that this method handles exact amount in swaps.


68-74: LGTM! Consistent method renaming for direct quotes.

The renaming of GetCustomDirectQuote and GetCustomDirectQuoteMultiPool to include OutGivenIn suffix maintains consistency with the new naming convention while preserving functionality.

domain/mocks/router_usecase_mock.go (1)

21-27: LGTM! Method renaming improves clarity.

The renaming of methods to include directional suffixes (OutGivenIn, InGivenOut) makes the token swap direction more explicit and aligns with the PR objectives.

domain/router.go (1)

41-49: LGTM! Method renaming maintains documentation clarity.

The renaming of PrepareResultPools to PrepareResultPoolsOutGivenIn is consistent with the codebase-wide refactoring while preserving the detailed documentation of the method's functionality.

router/usecase/optimized_routes.go (1)

23-83: LGTM! Method renaming maintains functionality.

The renaming of estimateAndRankSingleRouteQuote to estimateAndRankSingleRouteQuoteOutGivenIn improves clarity while preserving the existing logic for quote estimation and ranking.

router/delivery/http/router_handler.go (1)

131-131: LGTM! Method calls updated consistently.

The updates to method calls (GetOptimalQuoteOutGivenIn, SimulateQuoteOutGivenIn, GetCustomDirectQuoteMultiPoolOutGivenIn) are consistent with the interface changes and maintain the existing functionality.

Also applies to: 159-159, 235-235

router/usecase/router_usecase.go (3)

79-91: LGTM! Method renames improve API clarity.

The consistent renaming pattern with "OutGivenIn" and "InGivenOut" suffixes makes the swap directionality explicit in the API. This aligns well with the PR objectives and improves code readability.

Also applies to: 436-437, 470-471


192-218: LGTM! Implementation handles orderbook pools correctly.

The implementation correctly:

  1. Updates the method call to use the renamed method
  2. Disables cache to prevent interference with the main API
  3. Filters out orderbook pools that don't support MsgSwapExactAmountOut

472-483: LGTM! Comprehensive input validation.

The error handling thoroughly validates inputs with clear error messages:

  • Checks for empty pool IDs
  • Checks for empty token out denoms
  • Ensures matching lengths between pool IDs and token out denoms

domain/candidate_routes.go Outdated Show resolved Hide resolved
@@ -59,19 +59,19 @@ type SimpleRouterUsecase interface {
type RouterUsecase interface {
SimpleRouterUsecase

// GetOptimalQuote returns the optimal quote for the given tokenIn and tokenOutDenom.
GetOptimalQuote(ctx context.Context, tokenIn sdk.Coin, tokenOutDenom string, opts ...domain.RouterOption) (domain.Quote, error)
// GetOptimalQuoteOutGivenIn returns the optimal quote for the given token swap method exact amount in.
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Note for reviewer: No actual changes to those methods but renaming since we're preparing for introducing alternative methods for InGivenOut swap methods, for example GetCustomDirectQuoteInGivenOut. Renaming allows to use consistent names, for example GetOptimalQuote became GetOptimalQuoteOutGivenIn aligning with existing GetOptimalQuoteOutGivenIn.

// CONTRACT:
// - Only direct (non-split) quotes are supported.
// Retursn error if:
// - Simulator address does not have enough funds to pay for the quote.
SimulateQuote(ctx context.Context, quote Quote, slippageToleranceMultiplier osmomath.Dec, simulatorAddress string) TxFeeInfo
SimulateQuoteOutGivenIn(ctx context.Context, quote Quote, slippageToleranceMultiplier osmomath.Dec, simulatorAddress string) TxFeeInfo
Copy link
Collaborator Author

@deividaspetraitis deividaspetraitis Feb 10, 2025

Choose a reason for hiding this comment

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

Note for reiviewer: renaming in preparation introducing SimulateQuoteInGivenOut.

// from each pool in the route,
// leaving only the data needed by client
// Runs the quote logic one final time to compute the effective spot price.
// Note that it mutates the route.
// Computes the spot price of the route.
// Returns the spot price before swap and effective spot price.
// The token in is the base token and the token out is the quote token.
PrepareResultPools(ctx context.Context, tokenIn sdk.Coin, logger log.Logger) ([]RoutablePool, osmomath.Dec, osmomath.Dec, error)
PrepareResultPoolsOutGivenIn(ctx context.Context, tokenIn sdk.Coin, logger log.Logger) ([]RoutablePool, osmomath.Dec, osmomath.Dec, error)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Note for reviewer: Renaming in preparation introducing PrepareResultPoolsInGivenOut

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

🧹 Nitpick comments (1)
router/usecase/optimized_routes.go (1)

215-332: Consider refactoring to reduce code duplication.

While the implementation is correct, there's significant code duplication between validateAndFilterRoutesInGivenOut and validateAndFilterRoutesOutGivenIn. Consider extracting common validation logic into a shared helper function.

Here's a suggested approach:

+ type validationConfig struct {
+   routes []candidateRouteWrapper
+   tokenInDenom string
+   tokenOutDenom string
+   isInGivenOut bool
+   logger log.Logger
+ }
+
+ func validateAndFilterRoutes(config validationConfig) (ingesttypes.CandidateRoutes, error) {
+   // Common validation logic here
+   // Use config.isInGivenOut to determine token flow direction
+ }
+
- func validateAndFilterRoutesOutGivenIn(candidateRoutes []candidateRouteWrapper, tokenInDenom string, logger log.Logger) (ingesttypes.CandidateRoutes, error) {
+ func validateAndFilterRoutesOutGivenIn(candidateRoutes []candidateRouteWrapper, tokenInDenom string, logger log.Logger) (ingesttypes.CandidateRoutes, error) {
+   return validateAndFilterRoutes(validationConfig{
+     routes: candidateRoutes,
+     tokenInDenom: tokenInDenom,
+     isInGivenOut: false,
+     logger: logger,
+   })
  }

- func validateAndFilterRoutesInGivenOut(candidateRoutes []candidateRouteWrapper, tokenOutDenom string, logger log.Logger) (ingesttypes.CandidateRoutes, error) {
+ func validateAndFilterRoutesInGivenOut(candidateRoutes []candidateRouteWrapper, tokenOutDenom string, logger log.Logger) (ingesttypes.CandidateRoutes, error) {
+   return validateAndFilterRoutes(validationConfig{
+     routes: candidateRoutes,
+     tokenOutDenom: tokenOutDenom,
+     isInGivenOut: true,
+     logger: logger,
+   })
  }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d005bfc and 5051d9e.

⛔ Files ignored due to path filters (2)
  • router/usecase/export_test.go is excluded by !**/*_test.go
  • router/usecase/optimized_routes_test.go is excluded by !**/*_test.go
📒 Files selected for processing (1)
  • router/usecase/optimized_routes.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (2)
router/usecase/optimized_routes.go (2)

23-23: LGTM! Clear and descriptive method renaming.

The method name now explicitly indicates that it estimates routes for swapping a given input token for an output token, improving code clarity.


85-93: LGTM! Enhanced method documentation and data structure.

The method name and documentation now clearly indicate the validation flow for out-given-in routes. The addition of TokenInDenom field improves token flow tracking.

Also applies to: 197-197

@@ -45,7 +45,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Clone Repository
uses: actions/checkout@master
uses: actions/checkout@v4
Copy link
Collaborator Author

@deividaspetraitis deividaspetraitis Feb 11, 2025

Choose a reason for hiding this comment

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

@@ -54,7 +54,7 @@ jobs:
name: code-coverage-report
# path: app
- name: Analyze with SonarCloud
uses: sonarsource/sonarcloud-github-action@master
uses: sonarsource/sonarqube-scan-action@v4
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Note for reviewer: sonarsource/sonarcloud-github-action@master action seems to be deprecated and no longer works, alternative sonarsource/sonarqube-scan-action@v4 fixed the issue.

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 pending testing question

Comment on lines +46 to +72
uniquePoolIDs: map[uint64]struct{}{
1066: {},
1077: {},
1078: {},
1079: {},
1081: {},
1094: {},
1110: {},
1133: {},
1134: {},
1135: {},
1159: {},
1189: {},
1205: {},
1220: {},
1221: {},
1261: {},
1263: {},
1265: {},
1279: {},
1281: {},
1399: {},
1400: {},
1464: {},
1477: {},
1895: {},
},
Copy link
Member

Choose a reason for hiding this comment

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

I think we should avoid hardcoding specific pool IDs. Not sure what exactly this assertion accomplishes

Otherwise, if we regen the state, the tests will break, requiring us to spend time modifying.

Copy link
Collaborator Author

@deividaspetraitis deividaspetraitis Feb 14, 2025

Choose a reason for hiding this comment

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

The goal of using specific pool IDs is to ensure that computed candidate routes includes those expected pools.
When implementing InGivenOut I broke the algorithm and it returned diferent routes than OutGiveIn but tests did not catched this case.
I agree it's not ideal, in ideal situation we should be testing against small hardcoded set of routes, but since we're testing against huge state file it produces such drawbacks, but I think it's better than leaving as it is.

@deividaspetraitis deividaspetraitis merged commit 2ad38d4 into v28.x Feb 14, 2025
9 checks passed
@deividaspetraitis deividaspetraitis deleted the BE-686 branch February 14, 2025 13:00
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.

2 participants