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

fix(rfq-relayer): respond with failure if quote amount is zero [SLT-459] #3391

Merged
merged 5 commits into from
Nov 20, 2024

Conversation

dwasse
Copy link
Collaborator

@dwasse dwasse commented Nov 13, 2024

Summary by CodeRabbit

  • New Features
    • Enhanced quote request handling for large origin amounts, improving fallback mechanisms when no active quotes are available.
  • Bug Fixes
    • Improved error handling and response generation for quote requests, ensuring accurate feedback when no quotes are found.
  • Refactor
    • Streamlined response construction and logic for determining quote types, enhancing code readability and modularity.

Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes in this pull request enhance the RFQ API by introducing a new test case in rfq_test.go that validates the fallback mechanism when no active quotes are available. The test checks the system's response to a large origin amount request, ensuring it handles failures correctly. Additionally, modifications in server.go improve the PutRFQRequest method by adding logic to determine quote types and refactoring response construction into a new helper function, getQuoteResponse, which utilizes big.Int for better handling of large integers.

Changes

File Path Change Summary
services/rfq/api/rest/rfq_test.go Added a new test case in TestActiveRFQFallbackToPassive to handle large origin amounts and verify responses.
services/rfq/api/rest/server.go Enhanced PutRFQRequest method to determine quote types; added getQuoteResponse function for response handling; updated function signature.

Possibly related PRs

Suggested labels

size/s

Suggested reviewers

  • aureliusbtc
  • trajan0x
  • ChiTimesChi

🐇 In the meadow, where quotes do play,
A large request came out to sway.
With tests so bright, they check the flow,
Ensuring all quotes, both high and low.
Hooray for changes, let’s hop and cheer,
For RFQs are better, let’s spread the cheer! 🥕

Warning

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

🔧 golangci-lint

level=warning msg="[config_reader] The configuration option run.skip-files is deprecated, please use issues.exclude-files."
level=warning msg="[config_reader] The configuration option run.skip-dirs is deprecated, please use issues.exclude-dirs."
level=warning msg="[config_reader] The configuration option run.skip-dirs-use-default is deprecated, please use issues.exclude-dirs-use-default."
level=warning msg="[lintersdb] The linter "maligned" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The linter "exhaustivestruct" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The linter "ifshort" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The linter "interfacer" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The linter "nosnakecase" is deprecated (step 2) and deactivated. It should be removed from the list of disabled linters. https://golangci-lint.run/product/roadmap/#linter-deprecation-cycle"
level=warning msg="[lintersdb] The name "goerr113" is deprecated. The linter has been renamed to: err113."
level=warning msg="The linter 'exportloopref' is deprecated (since v1.60.2) due to: Since Go1.22 (loopvar) this linter is no longer relevant. Replaced by copyloopvar."
level=warning msg="The linter 'execinquery' is deprecated (since v1.58.0) due to: The repository of the linter has been archived by the owner. "


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 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.

@github-actions github-actions bot added go Pull requests that update Go code size/xs labels Nov 13, 2024
Copy link

codecov bot commented Nov 13, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 19.63741%. Comparing base (fd8ad75) to head (dea6371).
Report is 25 commits behind head on master.

Additional details and impacted files
@@                 Coverage Diff                  @@
##              master       #3391          +/-   ##
====================================================
- Coverage   33.16732%   19.63741%   -13.52991%     
====================================================
  Files            544         145         -399     
  Lines          34736       12135       -22601     
  Branches          82           0          -82     
====================================================
- Hits           11521        2383        -9138     
+ Misses         22197        9478       -12719     
+ Partials        1018         274         -744     
Flag Coverage Δ
cctp-relayer ?
core ?
ethergo ?
git-changes-action ?
omnirpc ?
opbot 0.18337% <ø> (ø)
packages ?
promexporter 6.81642% <ø> (ø)
rfq 24.89140% <100.00000%> (+0.53003%) ⬆️
screener-api ?
scribe ?
tools ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.


🚨 Try these New Features:

Copy link

cloudflare-workers-and-pages bot commented Nov 13, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: dea6371
Status: ✅  Deploy successful!
Preview URL: https://b237f0cc.sanguine-fe.pages.dev
Branch Preview URL: https://feat-no-quotes-master.sanguine-fe.pages.dev

View logs

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

🧹 Outside diff range and nitpick comments (2)
services/rfq/api/rest/rfq_test.go (1)

311-318: LGTM! Good test coverage for large amount handling

The test case effectively verifies that the system responds with a failure when no quotes are available for a large origin amount. This aligns well with the PR objective of properly handling scenarios where quote amounts are zero.

A few suggestions to make the test even more robust:

  1. Consider adding assertions for the quote amount to verify it's actually zero
  2. Consider testing edge cases around the maximum supported amount
 	userQuoteReq.Data.OriginAmountExact = big.NewInt(1e18).String()
 	userQuoteResp, err = userClient.PutRFQRequest(c.GetTestContext(), userQuoteReq)
 	c.Require().NoError(err)
 
 	// Assert the response
 	c.Assert().False(userQuoteResp.Success)
 	c.Assert().Equal("no quotes found", userQuoteResp.Reason)
+	// Verify quote amount
+	c.Assert().Equal("0", userQuoteResp.DestAmount)
services/rfq/api/rest/server.go (1)

561-561: Add function documentation

Please add a documentation comment explaining the function's purpose, parameters, and return value.

Add this documentation:

+// getQuoteResponse constructs a PutRFQResponse based on the quote data and type.
+// It returns a failure response if the quote is nil or has a zero/invalid destination amount.
+// Parameters:
+//   - ctx: Context for tracing
+//   - quote: Quote data containing destination amount and other details
+//   - quoteType: Type of quote (active or passive)
+// Returns: A PutRFQResponse indicating success or failure
 func getQuoteResponse(ctx context.Context, quote *model.QuoteData, quoteType string) (resp model.PutRFQResponse) {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1ecf200 and a27259b.

📒 Files selected for processing (2)
  • services/rfq/api/rest/rfq_test.go (1 hunks)
  • services/rfq/api/rest/server.go (3 hunks)
🔇 Additional comments (2)
services/rfq/api/rest/server.go (2)

7-7: LGTM: Addition of math/big package

The addition of the math/big package is appropriate for precise handling of large integers in quote amounts.


551-559: LGTM: Clean refactoring of response handling

The code has been improved by:

  1. Clear determination of quote type
  2. Extraction of response logic into a separate function

Comment on lines +566 to +570
amt, ok := destAmount.SetString(*quote.DestAmount, 10)
if ok {
destAmount = amt
}
}
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

Add error handling for SetString operation

The SetString operation's success flag is not properly handled. If parsing fails, the code continues with a zero amount, which could lead to false negatives.

Apply this fix:

 if quote != nil && quote.DestAmount != nil {
-    amt, ok := destAmount.SetString(*quote.DestAmount, 10)
-    if ok {
-        destAmount = amt
-    }
+    if amt, ok := destAmount.SetString(*quote.DestAmount, 10); !ok {
+        span.AddEvent("failed to parse destination amount")
+        return model.PutRFQResponse{
+            Success: false,
+            Reason:  "invalid destination amount",
+        }
+    }
 }

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Collaborator

@ChiTimesChi ChiTimesChi left a comment

Choose a reason for hiding this comment

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

Requesting a change for quoteType. Plus minor nits (up to you).

Comment on lines 551 to 554
quoteType := quoteTypeActive
if activeQuote == nil {
quoteType = quoteTypePassive
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This assumes that the active quote would always be the result of getBestQuote, which is a very big assumption. We should derive the quote type at the same time we choose the best quote imo.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good idea- we use getBestQuote() in several places, so instead of modifying that func I think this would work:

	var quoteType string
	if quote == activeQuote {
		quoteType = quoteTypeActive
	} else if quote == passiveQuote {
		quoteType = quoteTypePassive
	}

destAmount = amt
}
}
if quote == nil || destAmount.Cmp(big.NewInt(0)) <= 0 {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Two small nits here:

  1. quote == nil is redundant here, as it this condition is caught by destAmount being zero.
  2. Why don't we use https://pkg.go.dev/math/big#Int.Sign for comparisons to zero?

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

🧹 Outside diff range and nitpick comments (1)
services/rfq/api/rest/server.go (1)

566-572: Simplify the amount parsing logic

The nil checks and amount parsing can be more concise.

Consider this improvement:

-    destAmount := big.NewInt(0)
-    if quote != nil && quote.DestAmount != nil {
-        amt, ok := destAmount.SetString(*quote.DestAmount, 10)
-        if ok {
-            destAmount = amt
-        }
-    }
+    destAmount := big.NewInt(0)
+    if quote == nil || quote.DestAmount == nil {
+        return model.PutRFQResponse{
+            Success: false,
+            Reason:  "no quotes found",
+        }
+    }
+    if amt, ok := destAmount.SetString(*quote.DestAmount, 10); !ok {
+        span.AddEvent("failed to parse destination amount")
+        return model.PutRFQResponse{
+            Success: false,
+            Reason:  "invalid destination amount",
+        }
+    }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a27259b and dea6371.

📒 Files selected for processing (1)
  • services/rfq/api/rest/server.go (3 hunks)
🔇 Additional comments (3)
services/rfq/api/rest/server.go (3)

7-7: LGTM! Good addition of math/big package

The addition of the math/big package is appropriate for handling large integers and proper zero comparisons.


551-556: LGTM! Clear quote type determination

The implementation follows the suggested approach of determining the quote type based on the comparison with active and passive quotes. This is more reliable than assuming the quote type based on the result of getBestQuote.


568-572: ⚠️ Potential issue

Add error handling for SetString operation

The SetString operation's success flag is not properly handled. If parsing fails, the code continues with a zero amount.

Apply this fix:

-    amt, ok := destAmount.SetString(*quote.DestAmount, 10)
-    if ok {
-        destAmount = amt
-    }
+    if amt, ok := destAmount.SetString(*quote.DestAmount, 10); !ok {
+        span.AddEvent("failed to parse destination amount")
+        return model.PutRFQResponse{
+            Success: false,
+            Reason:  "invalid destination amount",
+        }
+    }

@dwasse dwasse merged commit 79a40b5 into master Nov 20, 2024
43 checks passed
@dwasse dwasse deleted the feat/no-quotes-master branch November 20, 2024 21:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants