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

feat(rfq-relayer): apply zap fee to dest amount for active quotes [SLT-465] #3395

Merged
merged 5 commits into from
Nov 14, 2024

Conversation

dwasse
Copy link
Collaborator

@dwasse dwasse commented Nov 14, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced quote generation process by incorporating new parameters (ZapNative and ZapData).
    • Introduced a new method for generating active RFQs.
  • Bug Fixes

    • Adjusted destination amount calculations to accurately reflect fees, preventing negative values.
  • Tests

    • Added new test cases for generating active RFQs to ensure correct handling of requests and expected outcomes.
    • Expanded test suite for the Quoter functionality with mock setups for better scenario handling.

Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request involve modifications to the QuoteData struct by removing the OriginAmount field, which affects how quote requests are structured. Additionally, a new method GenerateActiveRFQ is introduced in the Manager struct, enhancing the functionality for generating active RFQs. The generateActiveRFQ method is updated to handle new fields and adjust destination amounts by accounting for fees. The test suite is also expanded with a new test method to validate the active RFQ generation process.

Changes

File Path Change Summary
services/rfq/api/model/request.go Removed field: OriginAmount from QuoteData struct.
services/rfq/relayer/quoter/export_test.go Added method: GenerateActiveRFQ to Manager struct.
services/rfq/relayer/quoter/quoter.go Updated generateActiveRFQ method to handle ZapNative and ZapData, adjusted destination amount. Modified QuoteInput struct to include QuoteRequest.
services/rfq/relayer/quoter/quoter_test.go Added test method: TestGenerateActiveRFQ to validate RFQ generation. Imported encoding/json.

Possibly related PRs

Suggested labels

size/m

Suggested reviewers

  • aureliusbtc
  • trajan0x
  • dwasse

🐰 In the meadow, changes bloom,
Removing amounts, making room.
New methods sprout, tests take flight,
Quoting with care, all feels right.
With every hop, we grow and play,
In code we trust, come what may! 🌼

Warning

Rate limit exceeded

@github-actions[bot] has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 19 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1caa62c and 40eb027.

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 14, 2024
Copy link

codecov bot commented Nov 14, 2024

Codecov Report

Attention: Patch coverage is 29.16667% with 17 lines in your changes missing coverage. Please review.

Project coverage is 30.87471%. Comparing base (7d47ab0) to head (40eb027).
Report is 1 commits behind head on feat/arb-call-fee-pricer.

Files with missing lines Patch % Lines
services/rfq/relayer/quoter/quoter.go 29.16667% 14 Missing and 3 partials ⚠️
Additional details and impacted files
@@                        Coverage Diff                         @@
##           feat/arb-call-fee-pricer       #3395         +/-   ##
==================================================================
+ Coverage                  30.58729%   30.87471%   +0.28742%     
==================================================================
  Files                           457         457                 
  Lines                         30019       30193        +174     
  Branches                         82          82                 
==================================================================
+ Hits                           9182        9322        +140     
- Misses                        19986       19993          +7     
- Partials                        851         878         +27     
Flag Coverage Δ
opbot 0.18337% <ø> (ø)
promexporter 6.81642% <ø> (ø)
rfq 25.53862% <29.16667%> (+1.02304%) ⬆️

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.

Copy link

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

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 40eb027
Status: ✅  Deploy successful!
Preview URL: https://2952e095.sanguine-fe.pages.dev
Branch Preview URL: https://feat-zap-quote-pricing.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: 2

🧹 Outside diff range and nitpick comments (3)
services/rfq/relayer/quoter/quoter_test.go (2)

450-534: Enhance test readability and coverage

The new test method could be improved in several ways:

  1. Add comments explaining the test scenarios and expected outcomes
  2. Document the significance of magic numbers (e.g., "500000000000", "499899950000")
  3. Consider using table-driven tests to cover more scenarios
  4. Add test cases for error conditions

Here's a suggested refactor:

 func (s *QuoterSuite) TestGenerateActiveRFQ() {
+    // Test cases for different RFQ scenarios
+    testCases := []struct {
+        name           string
+        originAmount   string
+        expectedDest   string
+        description    string
+    }{
+        {
+            name: "small_amount",
+            originAmount: "100000",
+            expectedDest: "0",
+            description: "Small amount below minimum threshold returns zero",
+        },
+        {
+            name: "large_amount",
+            originAmount: "500000000000",
+            expectedDest: "499899950000",
+            description: "Large amount gets processed with fee deduction",
+        },
+    }
+
     origin := int(s.origin)
     dest := int(s.destination)
     originAddr := common.HexToAddress("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48")
     // ... setup code ...
 
-    req := model.PutRFQRequest{
-        UserAddress:  "0x123",
-        // ... first test case ...
-    }
-    // ... test execution ...
-
-    req = model.PutRFQRequest{
-        UserAddress:  "0x123",
-        // ... second test case ...
-    }
-    // ... test execution ...
+    for _, tc := range testCases {
+        s.Run(tc.name, func() {
+            // Test description for clarity
+            s.T().Logf("Testing %s: %s", tc.name, tc.description)
+            
+            req := model.PutRFQRequest{
+                UserAddress:  "0x123",
+                IntegratorID: "123",
+                QuoteTypes:   []string{"active"},
+                Data: model.QuoteData{
+                    OriginChainID:     origin,
+                    DestChainID:       dest,
+                    OriginAmountExact: tc.originAmount,
+                    OriginTokenAddr:   originAddr.String(),
+                    DestTokenAddr:     destAddr.String(),
+                },
+            }
+            // ... test execution ...
+            s.Equal(tc.expectedDest, resp.DestAmount)
+        })
+    }
 }

465-470: Document gas price assumptions

The test uses hardcoded gas price values without explaining their significance. Consider adding comments to explain these values and their impact on the test outcomes.

-    currentHeader := big.NewInt(100_000_000_000) // 100 gwei
+    // Set gas price to 100 gwei to simulate moderate network congestion
+    currentHeader := big.NewInt(100_000_000_000)
+    
+    // Simulate standard gas consumption for RFQ operations
+    expectedGasUsage := uint64(100_000)
services/rfq/relayer/quoter/quoter.go (1)

401-414: Refactor repetitive big integer parsing code

The code for parsing rawQuote.DestAmount and rawQuote.FixedFee into *big.Int and handling errors is repetitive. Consider extracting this logic into a helper function to improve maintainability and reduce duplication.

Apply this diff to refactor the code:

+func parseBigInt(value string, fieldName string) (*big.Int, error) {
+    bigIntValue, ok := new(big.Int).SetString(value, 10)
+    if !ok {
+        return nil, fmt.Errorf("invalid %s: %s", fieldName, value)
+    }
+    return bigIntValue, nil
+}

...

    // adjust dest amount by fixed fee
-   destAmountBigInt, ok := new(big.Int).SetString(rawQuote.DestAmount, 10)
-   if !ok {
-       return nil, fmt.Errorf("invalid dest amount: %s", rawQuote.DestAmount)
-   }
+   destAmountBigInt, err := parseBigInt(rawQuote.DestAmount, "dest amount")
+   if err != nil {
+       return nil, err
+   }

-   fixedFeeBigInt, ok := new(big.Int).SetString(rawQuote.FixedFee, 10)
-   if !ok {
-       return nil, fmt.Errorf("invalid fixed fee: %s", rawQuote.FixedFee)
-   }
+   fixedFeeBigInt, err := parseBigInt(rawQuote.FixedFee, "fixed fee")
+   if err != nil {
+       return nil, err
+   }

    destAmountAdj := new(big.Int).Sub(destAmountBigInt, fixedFeeBigInt)
    if destAmountAdj.Sign() < 0 {
        destAmountAdj = big.NewInt(0)
    }
    rawQuote.DestAmount = destAmountAdj.String()
    span.SetAttributes(attribute.String("dest_amount", rawQuote.DestAmount))
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7d47ab0 and 1caa62c.

📒 Files selected for processing (4)
  • services/rfq/api/model/request.go (0 hunks)
  • services/rfq/relayer/quoter/export_test.go (1 hunks)
  • services/rfq/relayer/quoter/quoter.go (2 hunks)
  • services/rfq/relayer/quoter/quoter_test.go (2 hunks)
💤 Files with no reviewable changes (1)
  • services/rfq/api/model/request.go
🔇 Additional comments (2)
services/rfq/relayer/quoter/export_test.go (1)

25-27: LGTM! The test export follows established patterns.

The new GenerateActiveRFQ method follows the consistent pattern used throughout the file for exposing internal methods for testing purposes. The implementation is clean and straightforward.

services/rfq/relayer/quoter/quoter_test.go (1)

471-473: Add error case testing for price fetcher

The price fetcher mock is set up to always return an error, but the test doesn't verify how the system handles this error condition.

Comment on lines +25 to +27
func (m *Manager) GenerateActiveRFQ(ctx context.Context, msg *model.ActiveRFQMessage) (resp *model.ActiveRFQMessage, err error) {
return m.generateActiveRFQ(ctx, msg)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing test coverage for zap fee calculations

The test coverage for the addZapFees functionality is incomplete. While there are tests for general fee calculations in fee_pricer_test.go, there are no specific test cases for:

  • Zap data gas estimation (getZapGasEstimate)
  • Zap native token value conversion
  • Combined zap fees with both data and native token components

Required test additions:

  • Test cases in fee_pricer_test.go for addZapFees with various zap data scenarios
  • Test cases for zap native token value calculations
  • Edge cases with zero values and invalid inputs
🔗 Analysis chain

Verify test coverage for the new functionality.

Since this is a test export, ensure that comprehensive tests are implemented for the underlying generateActiveRFQ method, particularly around the new zap fee calculations mentioned in the PR title.


Let me gather more information about the test coverage by checking the actual test implementations.


Let me check for specific test coverage of the zap fee calculations.


Let me check for tests in the pricer package since that's where the zap fee implementation is located.


Let me check the actual content of the fee pricer test files to verify the test coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for test coverage of the generateActiveRFQ functionality
# Look for test files that might contain tests for the new functionality

# Search for test files containing ActiveRFQ tests
echo "Searching for relevant test files..."
rg -l "TestGenerate.*ActiveRFQ|TestManager.*ActiveRFQ" --type go

# Look for actual test implementations of the functionality
echo "Searching for test implementations..."
rg -A 10 "func Test.*ActiveRFQ" --type go

# Check for zap fee related test assertions
echo "Checking for zap fee related tests..."
rg "zap.*fee|zapFee|ZapFee" --type go

Length of output: 950


Script:

#!/bin/bash
# Check the actual test implementations in the identified test file
echo "Checking test implementations in quoter_test.go..."
cat services/rfq/relayer/quoter/quoter_test.go

# Also check the implementation of generateActiveRFQ to understand what should be tested
echo -e "\nChecking the actual implementation..."
rg -A 20 "func.*generateActiveRFQ" services/rfq/relayer/quoter/

Length of output: 29647


Script:

#!/bin/bash
# Look for test files that might contain tests for zap fee calculations
echo "Checking test coverage for zap fee calculations..."
rg -A 10 "TestAdd.*ZapFee|Test.*ZapFee" --type go

# Look for test assertions related to zap fees
echo -e "\nChecking for zap fee related test assertions..."
rg "assert.*[Zz]ap.*[Ff]ee|expect.*[Zz]ap.*[Ff]ee" --type go

# Check the implementation of addZapFees to understand what should be tested
echo -e "\nChecking addZapFees implementation..."
rg -A 20 "func.*addZapFees" services/rfq/relayer/pricer/

Length of output: 2280


Script:

#!/bin/bash
# Check for test files in the pricer package
echo "Checking for test files in pricer package..."
fd ".*_test.go" services/rfq/relayer/pricer/

# Look for test implementations related to fee calculations
echo -e "\nChecking fee calculation test implementations..."
rg -A 10 "func Test.*Fee" services/rfq/relayer/pricer/

# Check for test setup and mocks related to fee calculations
echo -e "\nChecking test setup and mocks..."
rg "type.*Suite.*struct|func.*Suite.*Setup" services/rfq/relayer/pricer/

Length of output: 785


Script:

#!/bin/bash
# Check the content of fee pricer test files
echo "Checking fee_pricer_test.go content..."
cat services/rfq/relayer/pricer/fee_pricer_test.go

echo -e "\nChecking suite_test.go content..."
cat services/rfq/relayer/pricer/suite_test.go

Length of output: 20603

Comment on lines +383 to +394
if rfqRequest.Data.ZapNative != "" || rfqRequest.Data.ZapData != "" {
zapNative, ok := new(big.Int).SetString(rfqRequest.Data.ZapNative, 10)
if !ok {
return nil, fmt.Errorf("invalid zap native amount: %s", rfqRequest.Data.ZapNative)
}
quoteInput.QuoteRequest = &reldb.QuoteRequest{
Transaction: fastbridgev2.IFastBridgeV2BridgeTransactionV2{
ZapNative: zapNative,
ZapData: []byte(rfqRequest.Data.ZapData),
},
}
}
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

Incorrect conversion of ZapData to byte slice

The code converts rfqRequest.Data.ZapData directly to a byte slice using []byte(rfqRequest.Data.ZapData). If ZapData is a hex-encoded string representing binary data, this conversion will not produce the intended byte slice. Instead, it will convert the string's characters to their byte values, which may lead to incorrect data being used in the transaction. To handle ZapData correctly, you should decode the hex string into a byte slice.

Apply this diff to fix the issue:

+import (
+    "encoding/hex"
+    "strings"
+)

...

    if rfqRequest.Data.ZapNative != "" || rfqRequest.Data.ZapData != "" {
        zapNative, ok := new(big.Int).SetString(rfqRequest.Data.ZapNative, 10)
        if !ok {
            return nil, fmt.Errorf("invalid zap native amount: %s", rfqRequest.Data.ZapNative)
        }
+       zapDataBytes, err := hex.DecodeString(strings.TrimPrefix(rfqRequest.Data.ZapData, "0x"))
+       if err != nil {
+           return nil, fmt.Errorf("invalid zap data: %s", rfqRequest.Data.ZapData)
+       }
        quoteInput.QuoteRequest = &reldb.QuoteRequest{
            Transaction: fastbridgev2.IFastBridgeV2BridgeTransactionV2{
                ZapNative: zapNative,
-               ZapData:   []byte(rfqRequest.Data.ZapData),
+               ZapData:   zapDataBytes,
            },
        }
    }
📝 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
if rfqRequest.Data.ZapNative != "" || rfqRequest.Data.ZapData != "" {
zapNative, ok := new(big.Int).SetString(rfqRequest.Data.ZapNative, 10)
if !ok {
return nil, fmt.Errorf("invalid zap native amount: %s", rfqRequest.Data.ZapNative)
}
quoteInput.QuoteRequest = &reldb.QuoteRequest{
Transaction: fastbridgev2.IFastBridgeV2BridgeTransactionV2{
ZapNative: zapNative,
ZapData: []byte(rfqRequest.Data.ZapData),
},
}
}
if rfqRequest.Data.ZapNative != "" || rfqRequest.Data.ZapData != "" {
zapNative, ok := new(big.Int).SetString(rfqRequest.Data.ZapNative, 10)
if !ok {
return nil, fmt.Errorf("invalid zap native amount: %s", rfqRequest.Data.ZapNative)
}
zapDataBytes, err := hex.DecodeString(strings.TrimPrefix(rfqRequest.Data.ZapData, "0x"))
if err != nil {
return nil, fmt.Errorf("invalid zap data: %s", rfqRequest.Data.ZapData)
}
quoteInput.QuoteRequest = &reldb.QuoteRequest{
Transaction: fastbridgev2.IFastBridgeV2BridgeTransactionV2{
ZapNative: zapNative,
ZapData: zapDataBytes,
},
}
}

@dwasse dwasse merged commit f93b3b3 into feat/arb-call-fee-pricer Nov 14, 2024
33 checks passed
@dwasse dwasse deleted the feat/zap-quote-pricing branch November 14, 2024 22:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
go Pull requests that update Go code needs-go-generate-services/rfq size/s
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant