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-676 | Implement InGivenOut APIs for CL pool #604

Open
wants to merge 8 commits into
base: v28.x
Choose a base branch
from

Conversation

deividaspetraitis
Copy link
Collaborator

@deividaspetraitis deividaspetraitis commented Jan 21, 2025

This PR implements InGivenOut APIs for CL pool, more specifically following methods:

  • CalculateTokenInByTokenOut
  • ChargeTakerFeeExactOut

New APIs were covered with unit tests.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced error reporting for liquidity swap operations with more detailed context.
    • Added ability to calculate input token amount based on desired output in concentrated liquidity pools.
  • Dependency Updates

    • Updated multiple dependencies to latest versions, including OpenTelemetry, gRPC, and various Go libraries.
  • Improvements

    • Refined method naming for fee calculations in concentrated liquidity pools.
    • Improved comments for clarity on method functionalities and error conditions.

@deividaspetraitis deividaspetraitis self-assigned this Jan 21, 2025
@@ -282,6 +283,9 @@ replace (
github.com/osmosis-labs/osmosis/osmoutils => github.com/osmosis-labs/osmosis/osmoutils v0.0.12-0.20240825083448-87db4447a1ff
github.com/osmosis-labs/osmosis/v28 => github.com/osmosis-labs/osmosis/v28 v28.0.2

// Temp replacement
github.com/osmosis-labs/osmosis/v28 v28.0.2 => github.com/osmosis-labs/osmosis/v28 v28.0.0-20250123151709-6bb88cccbfe6
Copy link
Collaborator Author

@deividaspetraitis deividaspetraitis Jan 23, 2025

Choose a reason for hiding this comment

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

Note for reviewer: we need to close osmosis-labs/osmosis#8954 first

// - the current tick is not within the specified current bucket range
// - tick model has no liquidity flag set
// - the current sqrt price is zero
// - rans out of ticks during swap (token out is too high for liquidity in the pool)
func (r *routableConcentratedPoolImpl) CalculateTokenInByTokenOut(ctx context.Context, tokenOut sdk.Coin) (sdk.Coin, error) {
Copy link
Collaborator Author

@deividaspetraitis deividaspetraitis Jan 23, 2025

Choose a reason for hiding this comment

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

Note for reviewer: Would it make sense to move this method to ChainModel in Osmosis repo and let SQS just forward request there? As we are doing for example here:

// CalculateTokenInByTokenOut implements RoutablePool.
func (r *routableBalancerPoolImpl) CalculateTokenInByTokenOut(ctx context.Context, tokenOut sdk.Coin) (sdk.Coin, error) {
	tokenIn, err := r.ChainPool.CalcInAmtGivenOut(sdk.Context{}.WithContext(ctx), sdk.Coins{tokenOut}, r.TokenInDenom, r.GetSpreadFactor())
	if err != nil {
		return sdk.Coin{}, err
	}

	return tokenIn, nil
}

Copy link
Member

Choose a reason for hiding this comment

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

No, chain operates on the chain store. Here, we simulate the store by operating on the custom data representation that is ingested from chain

Copy link
Contributor

coderabbitai bot commented Jan 23, 2025

Walkthrough

This pull request introduces changes across multiple files, focusing on enhancing error handling and pool routing functionality. The primary modifications include updating the ConcentratedNotEnoughLiquidityToCompleteSwapError struct in the domain errors, upgrading various dependencies in the go.mod file, and adding a new method CalculateTokenInByTokenOut in the router's concentrated pool implementation. These changes aim to provide more detailed error reporting and expand the capabilities of token swap calculations.

Changes

File Change Summary
domain/errors.go - Added AmountOut field to ConcentratedNotEnoughLiquidityToCompleteSwapError struct
- Updated Error() method to conditionally format error messages based on input/output amounts
go.mod - Updated multiple dependencies to latest versions
- Added new indirect dependency github.com/cockroachdb/apd/v3
router/usecase/pools/routable_concentrated_pool.go - Added CalculateTokenInByTokenOut method
- Renamed ChargeTakerFee methods to ChargeTakerFeeExactIn and ChargeTakerFeeExactOut
router/usecase/pools/routable_cw_transmuter_pool.go - Added comments to CalculateTokenOutByTokenIn and CalculateTokenInByTokenOut methods for clarity

Possibly related PRs

Suggested reviewers

  • p0mvn

Poem

🐰 Hop, hop, through the code we go,
Liquidity swaps now flow with grace,
Errors speak with context clear,
Dependencies dance without a trace,
A rabbit's leap of coding flair! 🌈


📜 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 39d0d3a and fb3dbab.

📒 Files selected for processing (2)
  • router/usecase/pools/routable_concentrated_pool.go (3 hunks)
  • router/usecase/pools/routable_cw_transmuter_pool.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • router/usecase/pools/routable_cw_transmuter_pool.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (5)
router/usecase/pools/routable_concentrated_pool.go (5)

78-78: LGTM! Improved documentation clarity.

The added comment clarifies how the ChainPool operation is simulated using custom data representation from the chain.


198-314: LGTM! Well-implemented reverse operation.

The implementation correctly mirrors CalculateTokenOutByTokenIn with appropriate adjustments for the reverse operation, including:

  • Proper reversal of isZeroForOne logic
  • Correct token denomination handling
  • Use of ComputeSwapWithinBucketInGivenOut for swap computation

275-276: Fix incorrect comment about token direction.

The comment incorrectly refers to "token in" when describing a scenario about insufficient liquidity for a given amount of token out.


333-336: Handle potential errors from fee calculation.

The error returned by CalcTakerFeeExactIn should not be ignored as it could lead to silent failures.


340-344: Handle potential errors from fee calculation.

Similarly, the error returned by CalcTakerFeeExactOut should not be ignored.

✨ 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: 3

🧹 Nitpick comments (2)
router/usecase/pools/routable_concentrated_pool.go (1)

197-204: Consider refactoring to eliminate duplicate logic between swap calculation methods.

The methods CalculateTokenOutByTokenIn and CalculateTokenInByTokenOut share similar logic structures with slight differences in variable handling and function calls. To adhere to the DRY (Don't Repeat Yourself) principle and improve maintainability, consider abstracting the common logic into shared functions or components. This will reduce code duplication and make future updates easier.

domain/errors.go (1)

146-150: Ensure error message covers cases where both AmountIn and AmountOut are empty.

Currently, if both AmountIn and AmountOut are empty strings, the error message will not provide specific details, which could lead to confusion. Consider adding a default error message or explicitly handling this scenario.

Apply this diff to handle the case when both amounts are empty:

 func (e ConcentratedNotEnoughLiquidityToCompleteSwapError) Error() string {
 	if e.AmountIn != "" {
 		return fmt.Sprintf("not enough liquidity to complete swap in pool (%d) with amount in (%s)", e.PoolId, e.AmountIn)
+	} else if e.AmountOut != "" {
 		return fmt.Sprintf("not enough liquidity to complete swap in pool (%d) with amount out (%s)", e.PoolId, e.AmountOut)
+	} else {
+		return fmt.Sprintf("not enough liquidity to complete swap in pool (%d)", e.PoolId)
 	}
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f4e918c and 39d0d3a.

⛔ Files ignored due to path filters (2)
  • go.sum is excluded by !**/*.sum
  • router/usecase/pools/routable_concentrated_pool_test.go is excluded by !**/*_test.go
📒 Files selected for processing (3)
  • domain/errors.go (1 hunks)
  • go.mod (8 hunks)
  • router/usecase/pools/routable_concentrated_pool.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (2)
router/usecase/pools/routable_concentrated_pool.go (1)

205-312: Consider moving CalculateTokenInByTokenOut to ChainModel in the Osmosis repository.

As previously suggested, it might be beneficial to move this method to the ChainModel in the Osmosis repository and have SQS forward the request. This approach is consistent with how CalculateTokenInByTokenOut is handled in routable_balancer_pool.go. Centralizing this logic can improve maintainability and reduce code duplication across repositories.

go.mod (1)

287-287: Reminder to update the Osmosis dependency after merging PR 8954.

As noted, a temporary replacement has been added for github.com/osmosis-labs/osmosis/v28. Ensure to update the dependency to the official release version once PR 8954 is merged to maintain consistency and stability in the codebase.

Comment on lines +273 to +274
// for a given amount of token in.
return sdk.Coin{}, domain.ConcentratedNotEnoughLiquidityToCompleteSwapError{
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Correct the comment to reflect the accurate context of the swap operation.

The comment indicates "for a given amount of token in," which is misleading in the context of CalculateTokenInByTokenOut. This method calculates the required token in amount for a specified token out, so the comment should be updated accordingly.

Apply this diff to correct the comment:

     // This happens when there is not enough liquidity in the pool to complete the swap
-    // for a given amount of token in.
+    // for a given amount of token out.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// for a given amount of token in.
return sdk.Coin{}, domain.ConcentratedNotEnoughLiquidityToCompleteSwapError{
// This happens when there is not enough liquidity in the pool to complete the swap
// for a given amount of token out.
return sdk.Coin{}, domain.ConcentratedNotEnoughLiquidityToCompleteSwapError{

Comment on lines +331 to 334
// ChargeTakerFeeExactIn implements domain.RoutablePool.
// Charges the taker fee for the given token in and returns the token in after the fee has been charged.
func (r *routableConcentratedPoolImpl) ChargeTakerFeeExactIn(tokenIn sdk.Coin) (tokenInAfterFee sdk.Coin) {
tokenInAfterTakerFee, _ := poolmanager.CalcTakerFeeExactIn(tokenIn, r.GetTakerFee())
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential errors returned by CalcTakerFeeExactIn.

In ChargeTakerFeeExactIn, the error returned by CalcTakerFeeExactIn is being ignored. Ignoring errors can lead to unintended consequences or silent failures. Consider handling the error to ensure robust error management.

Apply this diff to handle the error:

 func (r *routableConcentratedPoolImpl) ChargeTakerFeeExactIn(tokenIn sdk.Coin) (tokenInAfterFee sdk.Coin, err error) {
-	tokenInAfterTakerFee, _ := poolmanager.CalcTakerFeeExactIn(tokenIn, r.GetTakerFee())
+	tokenInAfterTakerFee, err := poolmanager.CalcTakerFeeExactIn(tokenIn, r.GetTakerFee())
+	if err != nil {
+		return sdk.Coin{}, err
+	}
 	return tokenInAfterTakerFee, nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// ChargeTakerFeeExactIn implements domain.RoutablePool.
// Charges the taker fee for the given token in and returns the token in after the fee has been charged.
func (r *routableConcentratedPoolImpl) ChargeTakerFeeExactIn(tokenIn sdk.Coin) (tokenInAfterFee sdk.Coin) {
tokenInAfterTakerFee, _ := poolmanager.CalcTakerFeeExactIn(tokenIn, r.GetTakerFee())
// ChargeTakerFeeExactIn implements domain.RoutablePool.
// Charges the taker fee for the given token in and returns the token in after the fee has been charged.
func (r *routableConcentratedPoolImpl) ChargeTakerFeeExactIn(tokenIn sdk.Coin) (tokenInAfterFee sdk.Coin, err error) {
tokenInAfterTakerFee, err := poolmanager.CalcTakerFeeExactIn(tokenIn, r.GetTakerFee())
if err != nil {
return sdk.Coin{}, err
}
return tokenInAfterTakerFee, nil
}

Comment on lines +338 to +342
// ChargeTakerFeeExactOut implements domain.RoutablePool.
// Charges the taker fee for the given token out and returns the token out after the fee has been charged.
func (r *routableConcentratedPoolImpl) ChargeTakerFeeExactOut(tokenOut sdk.Coin) (tokenOutAfterFee sdk.Coin) {
return sdk.Coin{}
tokenOutAfterTakerFee, _ := poolmanager.CalcTakerFeeExactOut(tokenOut, r.GetTakerFee())
return tokenOutAfterTakerFee
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential errors returned by CalcTakerFeeExactOut.

Similarly, in ChargeTakerFeeExactOut, the error returned by CalcTakerFeeExactOut is being ignored. Proper error handling is crucial for reliable software. Consider modifying the function to handle the error appropriately.

Apply this diff to handle the error:

 func (r *routableConcentratedPoolImpl) ChargeTakerFeeExactOut(tokenOut sdk.Coin) (tokenOutAfterFee sdk.Coin, err error) {
-	tokenOutAfterTakerFee, _ := poolmanager.CalcTakerFeeExactOut(tokenOut, r.GetTakerFee())
+	tokenOutAfterTakerFee, err := poolmanager.CalcTakerFeeExactOut(tokenOut, r.GetTakerFee())
+	if err != nil {
+		return sdk.Coin{}, err
+	}
 	return tokenOutAfterTakerFee, nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// ChargeTakerFeeExactOut implements domain.RoutablePool.
// Charges the taker fee for the given token out and returns the token out after the fee has been charged.
func (r *routableConcentratedPoolImpl) ChargeTakerFeeExactOut(tokenOut sdk.Coin) (tokenOutAfterFee sdk.Coin) {
return sdk.Coin{}
tokenOutAfterTakerFee, _ := poolmanager.CalcTakerFeeExactOut(tokenOut, r.GetTakerFee())
return tokenOutAfterTakerFee
// ChargeTakerFeeExactOut implements domain.RoutablePool.
// Charges the taker fee for the given token out and returns the token out after the fee has been charged.
func (r *routableConcentratedPoolImpl) ChargeTakerFeeExactOut(tokenOut sdk.Coin) (tokenOutAfterFee sdk.Coin, err error) {
tokenOutAfterTakerFee, err := poolmanager.CalcTakerFeeExactOut(tokenOut, r.GetTakerFee())
if err != nil {
return sdk.Coin{}, err
}
return tokenOutAfterTakerFee, nil
}

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! Nice work

Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
10.1% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

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