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-api): enforce max quote age for passive quotes [SLT-463] #3392

Merged
merged 4 commits into from
Nov 18, 2024

Conversation

dwasse
Copy link
Collaborator

@dwasse dwasse commented Nov 13, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new function to retrieve passive quotes, enhancing RFQ handling.
    • Improved error handling for passive quote retrieval processes.
  • Bug Fixes

    • Enhanced logic for calculating destination amounts and handling invalid origin amounts.
  • Tests

    • Added a new test for retrieving the best passive quote, ensuring functionality aligns with user request parameters.
    • Updated test suite to include various attributes for passive quotes.
  • Configuration Changes

    • Updated the default maximum quote age from 1 hour to 5 minutes.

Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce a new function GetPassiveQuote in the rest package for testing purposes, enhancing the RFQ (Request for Quote) handling in the QuoterAPIServer class. This function retrieves passive quotes based on provided data and includes improved error handling. Additionally, a new test method TestGetPassiveQuote is added to verify the functionality of retrieving passive quotes. The import statements are updated to include necessary packages, ensuring the new functionality integrates smoothly with existing code.

Changes

File Path Change Summary
services/rfq/api/rest/export_test.go Added function GetPassiveQuote(cfg config.Config, quotes []*db.Quote, request *model.PutRFQRequest) (*model.QuoteData, error) for testing.
services/rfq/api/rest/rfq.go Added method getPassiveQuote(cfg config.Config, quotes []*db.Quote, request *model.PutRFQRequest) (*model.QuoteData, error); updated handlePassiveRFQ for error handling and quote retrieval.
services/rfq/api/rest/server_test.go Added test method TestGetPassiveQuote() to test passive quote retrieval functionality. Updated imports for handling large integers and decimals.
services/rfq/api/config/config.go Updated constant defaultMaxQuoteAge from 1 * time.Hour to 5 * time.Minute.

Possibly related PRs

Suggested reviewers

  • aureliusbtc
  • trajan0x
  • ChiTimesChi

Poem

🐰 In the meadow where quotes do play,
A new function hops in, brightening the day.
With passive quotes now easy to find,
Testing is joyful, and errors left behind.
So let’s cheer for the code, let it bloom,
In the world of RFQs, there’s always more room! 🌼

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/s labels Nov 13, 2024
Copy link

codecov bot commented Nov 13, 2024

Codecov Report

Attention: Patch coverage is 62.50000% with 3 lines in your changes missing coverage. Please review.

Project coverage is 19.46552%. Comparing base (fd8ad75) to head (a35bd99).
Report is 11 commits behind head on master.

Files with missing lines Patch % Lines
services/rfq/api/rest/rfq.go 62.50000% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@                 Coverage Diff                  @@
##              master       #3392          +/-   ##
====================================================
- Coverage   33.16732%   19.46552%   -13.70180%     
====================================================
  Files            544         145         -399     
  Lines          34736       12124       -22612     
  Branches          82           0          -82     
====================================================
- Hits           11521        2360        -9161     
+ Misses         22197        9486       -12711     
+ Partials        1018         278         -740     
Flag Coverage Δ
cctp-relayer ?
core ?
ethergo ?
git-changes-action ?
omnirpc ?
opbot 0.18337% <ø> (ø)
packages ?
promexporter 6.81642% <ø> (ø)
rfq 24.67109% <62.50000%> (+0.30972%) ⬆️
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

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 09f81eb
Status: ✅  Deploy successful!
Preview URL: https://ea4df8de.sanguine-fe.pages.dev
Branch Preview URL: https://feat-passive-quote-age.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 (3)
services/rfq/api/rest/server_test.go (1)

395-462: Consider adding test cases for edge conditions

The test could be enhanced with additional cases:

  1. Empty quotes array
  2. All quotes outside MaxQuoteAge
  3. Quote exactly at MaxQuoteAge boundary
  4. Multiple quotes with identical destination amounts but different ages

Here's a suggested addition:

 func (c *ServerSuite) TestGetPassiveQuote() {
+    // Existing test case...
+
+    // Test: Empty quotes
+    quote, err := rest.GetPassiveQuote(c.cfg, []*db.Quote{}, userQuoteReq)
+    c.Require().NoError(err)
+    c.Assert().Nil(quote)
+
+    // Test: All quotes expired
+    expiredQuotes := []*db.Quote{
+        {
+            RelayerAddr:     "0x5",
+            DestAmount:      decimal.NewFromBigInt(new(big.Int).Sub(userRequestAmount, big.NewInt(100)), 0),
+            MaxOriginAmount: decimal.NewFromBigInt(userRequestAmount, 0),
+            UpdatedAt:       time.Now().Add(-time.Hour * 2),
+        },
+    }
+    quote, err = rest.GetPassiveQuote(c.cfg, expiredQuotes, userQuoteReq)
+    c.Require().NoError(err)
+    c.Assert().Nil(quote)
 }
services/rfq/api/rest/rfq.go (2)

Line range hint 245-249: Prevent division by zero when computing quotePrice

There is a potential division by zero error when quote.MaxOriginAmount.BigInt() is zero. This would cause new(big.Float).Quo to attempt division by zero, leading to a runtime error. Ensure that quote.MaxOriginAmount.BigInt() is not zero before performing the division.

Apply this diff to add a check for zero:

quoteOriginAmount, ok := new(big.Int).SetString(quote.MaxOriginAmount.String(), 10)
-if !ok {
+if !ok || quoteOriginAmount.Sign() == 0 {
	continue
}
if quoteOriginAmount.Cmp(originAmount) < 0 {
	continue
}
quotePrice := new(big.Float).Quo(
	new(big.Float).SetInt(quote.DestAmount.BigInt()),
	new(big.Float).SetInt(quote.MaxOriginAmount.BigInt()),
)

Line range hint 263-270: Set OriginAmountExact to the requested amount

In the quoteData struct, OriginAmountExact is set to quote.MaxOriginAmount.String(), which represents the maximum origin amount from the quote, not the actual amount requested by the user. To accurately reflect the user's request, consider setting OriginAmountExact to request.Data.OriginAmountExact.

Apply this diff:

quoteData := &model.QuoteData{
	OriginChainID:     int(quote.OriginChainID),
	DestChainID:       int(quote.DestChainID),
	OriginTokenAddr:   quote.OriginTokenAddr,
	DestTokenAddr:     quote.DestTokenAddr,
-	OriginAmountExact: quote.MaxOriginAmount.String(),
+	OriginAmountExact: request.Data.OriginAmountExact,
	DestAmount:        &destAmount,
	RelayerAddress:    &quote.RelayerAddr,
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

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

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

6-6: LGTM: Required import for model package

The added import is necessary for the new GetPassiveQuote function signature.


14-17: LGTM: Proper test export implementation

The GetPassiveQuote test export follows the established pattern and enables testing of passive quote age enforcement.

Let's verify the consistency between the exported and internal functions:

✅ Verification successful

Verification confirms correct test export implementation

The verification confirms that:

  • The internal getPassiveQuote function signature in rfq.go exactly matches the exported test function
  • The exported function is used in test files (server_test.go and export_test.go)
  • The implementation properly filters quotes by age using filterQuoteAge before processing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that getPassiveQuote (internal) matches GetPassiveQuote (exported) signature

# Check internal function signature
ast-grep --pattern 'func getPassiveQuote(cfg config.Config, quotes []*db.Quote, request *model.PutRFQRequest) (*model.QuoteData, error)'

# Verify usage in tests
rg -l "GetPassiveQuote" --type go

Length of output: 3246

services/rfq/api/rest/server_test.go (2)

8-8: LGTM! Required imports for handling currency calculations

The added imports are appropriate for handling large integers and precise decimal calculations in financial operations.

Also applies to: 13-13


395-462: LGTM! Well-structured test for passive quote selection

The test effectively verifies the selection of the best passive quote within the MaxQuoteAge window, aligning with the PR objective of enforcing max quote age for passive quotes.

Comment on lines +230 to +236
quote, err := getPassiveQuote(r.cfg, quotes, request)
if err != nil {
return nil, fmt.Errorf("failed to get passive quote: %w", err)
}

return quote, nil
}
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 case when no suitable passive quote is found

If getPassiveQuote returns nil without an error, the quote will be nil, and the function will return nil, nil. This could lead to unexpected nil references in calling code. It's important to handle the scenario where no suitable quote is found by returning an appropriate error.

Apply this diff to handle the nil quote case:

quote, err := getPassiveQuote(r.cfg, quotes, request)
if err != nil {
	return nil, fmt.Errorf("failed to get passive quote: %w", err)
}
+if quote == nil {
+	return nil, errors.New("no suitable passive quote found")
+}
return quote, 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
quote, err := getPassiveQuote(r.cfg, quotes, request)
if err != nil {
return nil, fmt.Errorf("failed to get passive quote: %w", err)
}
return quote, nil
}
quote, err := getPassiveQuote(r.cfg, quotes, request)
if err != nil {
return nil, fmt.Errorf("failed to get passive quote: %w", err)
}
if quote == nil {
return nil, errors.New("no suitable passive quote found")
}
return quote, nil
}

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.

LGTM. Side note: we might want to decrease defaultMaxQuoteAge, for reference the current SDK implementation uses the 5 minutes period to filter out old quotes.

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