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(solidity): add max quote index to improve data retrieval efficiency #763

Merged
merged 2 commits into from
Oct 22, 2024

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Oct 22, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new getQuote method for retrieving quotes based on chain name, token, oracle, and index.
    • Added support for managing multiple quotes per oracle with an indexing mechanism.
    • Enhanced the getQuoteByToken method to return an array of quotes.
  • Bug Fixes

    • Enhanced error handling for invalid quote indices.
  • Tests

    • Updated tests to accommodate new indexing for quotes and ensure proper functionality and retrieval of multiple quotes.

Copy link

coderabbitai bot commented Oct 22, 2024

Walkthrough

The pull request introduces significant modifications to the IBridgeFeeQuote contract and its related components. Key changes include the addition of a QuoteIndex field in the IBridgeFeeQuoteQuoteInput struct, the implementation of a new getQuote method, and updates to the GetQuoteByToken method to return multiple quotes. The BridgeFeeQuote contract is enhanced to manage multiple quotes per oracle with a new maxQuoteIndex variable. Additionally, various test cases are updated to reflect these structural changes, ensuring proper handling of the new indexing system.

Changes

File Path Change Summary
contract/ibridge_fee_quote.sol.go - Added QuoteIndex to IBridgeFeeQuoteQuoteInput struct.
- Introduced getQuote method.
- Updated GetQuoteByToken method to return multiple quotes.
- Modified method signatures for GetQuoteById, GetQuoteList, and Quote.
solidity/contracts/bridge/BridgeFeeQuote.sol - Added maxQuoteIndex variable.
- Updated initialize function to accept maxQuoteIndex.
- Adjusted quotes mapping to include index.
- Added getQuote method.
- Introduced QuoteIndexInvalid error.
solidity/contracts/bridge/IBridgeFee.sol - Added quoteIndex to QuoteInput struct.
- Updated getQuoteByToken and getQuote methods to include new parameters.
solidity/test/bridge_fee_quote.ts - Updated newBridgeFeeQuote function to include index parameter.
- Modified test cases to handle new quote indexing.

Possibly related PRs

🐰 In the meadow, where quotes abound,
A new index is found, oh what a sound!
With each hop and each leap,
Multiple quotes we keep,
For every oracle, a treasure profound! 🐇✨


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@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

🧹 Outside diff range and nitpick comments (5)
solidity/contracts/bridge/IBridgeFee.sol (1)

10-10: LGTM. Consider adding documentation for the new field.

The addition of quoteIndex to the QuoteInput struct is a good enhancement, allowing for multiple quotes per oracle or token. This aligns well with the new indexing system mentioned in the PR summary.

Consider adding a comment to explain the purpose and usage of the quoteIndex field for better code readability and maintainability.

solidity/test/bridge_fee_quote.ts (2)

51-51: Consider replacing the hardcoded '3' with a named constant for clarity

Using a named constant instead of a magic number enhances readability and maintainability. Defining MAX_QUOTE_INDEX at the beginning improves code clarity.

Here is the suggested change:

+const MAX_QUOTE_INDEX = 3;

-await bridgeFeeQuote.initialize(bridgeFeeOracle.getAddress(), 3);
+await bridgeFeeQuote.initialize(bridgeFeeOracle.getAddress(), MAX_QUOTE_INDEX);

234-234: Use strict equality operator === instead of ==

For consistency and to avoid unexpected type coercion, it's recommended to use the strict equality operator === in comparisons.

Apply this diff:

-            if (i == 0) {
+            if (i === 0) {
solidity/contracts/bridge/BridgeFeeQuote.sol (2)

Line range hint 314-327: Include quoteIndex in Signature Hash for Security

The makeMessageHash function does not include _input.quoteIndex in the hash computation. Excluding quoteIndex may allow replay attacks where a signature for one quote index is used for another.

Include _input.quoteIndex in the hash to ensure the signature uniquely represents the quote.

function verifySignature(QuoteInput memory _input) private pure {
    bytes32 hash = makeMessageHash(
        _input.chainName,
        _input.token,
        _input.fee,
        _input.gasLimit,
        _input.expiry
+       , _input.quoteIndex
    );
    address signer = hash.toEthSignedMessageHash().recover(
        _input.signature
    );
    if (_input.oracle != signer) {
        revert VerifySignatureFailed(_input.oracle, signer);
    }
}

function makeMessageHash(
    string memory _chainName,
    address _token,
    uint256 _fee,
    uint256 _gasLimit,
    uint256 _expiry
+   , uint256 _quoteIndex
) public pure returns (bytes32) {
    return
        keccak256(abi.encode(_chainName, _token, _fee, _gasLimit, _expiry, _quoteIndex));
}

430-435: Emit Event When Updating maxQuoteIndex

To maintain transparency, emit an event when maxQuoteIndex is updated. This allows external parties to track changes to critical contract parameters.

Add an event declaration and emit it in the updateMaxQuoteIndex function.

+ event MaxQuoteIndexUpdated(uint256 oldMaxQuoteIndex, uint256 newMaxQuoteIndex);

function updateMaxQuoteIndex(
    uint256 _maxQuoteIndex
) external onlyOwner returns (bool) {
+   emit MaxQuoteIndexUpdated(maxQuoteIndex, _maxQuoteIndex);
    maxQuoteIndex = _maxQuoteIndex;
    return true;
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 378231d and f49f151.

📒 Files selected for processing (4)
  • contract/ibridge_fee_quote.sol.go (4 hunks)
  • solidity/contracts/bridge/BridgeFeeQuote.sol (12 hunks)
  • solidity/contracts/bridge/IBridgeFee.sol (2 hunks)
  • solidity/test/bridge_fee_quote.ts (10 hunks)
🧰 Additional context used
🔇 Additional comments (10)
solidity/contracts/bridge/IBridgeFee.sol (2)

40-45: LGTM. Verify usage and consider documenting the changes.

The modifications to the getQuote function signature are appropriate:

  1. Adding _oracle and _index parameters allows for more precise quote retrieval.
  2. Removing the _amount parameter suggests a shift to pre-computed quotes.

These changes align well with the PR objectives of improving data retrieval efficiency.

Please run the following script to verify that all calls to getQuote have been updated to match the new signature:

#!/bin/bash
# Description: Verify all function calls to `getQuote` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg -A 5 $'getQuote\s*\('

Consider adding inline comments or updating the function documentation to explain the purpose of the new parameters and the removal of the _amount parameter. This will help maintain clear understanding of the function's behavior for future developers.


36-38: LGTM. Verify usage across the codebase.

The changes to getQuoteByToken function signature are appropriate:

  1. Adding _chainName parameter allows for more specific quote retrieval.
  2. Returning an array of QuoteInfo objects supports multiple quotes per token.

These modifications align well with the PR objectives.

Please run the following script to verify that all calls to getQuoteByToken have been updated to match the new signature:

solidity/test/bridge_fee_quote.ts (1)

82-83: LGTM

The newBridgeFeeQuote function is correctly called with the updated parameters, including the oracle and quoteIndex.

solidity/contracts/bridge/BridgeFeeQuote.sol (1)

147-165: Ensure Consistent Loop Bounds for maxQuoteIndex

The loops iterating over k use k < maxQuoteIndex, which is correct if indexes range from 0 to maxQuoteIndex - 1. However, to align with the updated validation in verifyInput, ensure that all loops consistently use the corrected maxQuoteIndex value.

No changes needed if the validation condition is updated as suggested.

Also applies to: 241-250, 375-384

contract/ibridge_fee_quote.sol.go (6)

45-52: LGTM!

The QuoteIndex field is appropriately added to the IBridgeFeeQuoteQuoteInput struct. The types are consistent with the existing fields.


206-221: LGTM!

The new GetQuote method is implemented correctly and matches the contract's ABI. The parameters and return types are properly defined.


223-236: LGTM!

The session methods for GetQuote are correctly implemented in both IBridgeFeeQuoteSession and IBridgeFeeQuoteCallerSession. They correctly delegate to the main GetQuote method.


285-296: LGTM!

The session methods for GetQuoteByToken are correctly updated to reflect the new return type. They are consistent with the updated method in the caller.


330-346: LGTM!

The Quote method has been correctly updated to align with the new ABI definitions. The parameters and transaction bindings are properly defined.


268-281: ⚠️ Potential issue

Update downstream code to handle the new return type of GetQuoteByToken

The GetQuoteByToken method now returns a slice of IBridgeFeeQuoteQuoteInfo instead of a single quote and a boolean. Please ensure that any downstream code that calls this method is updated to handle the new return type appropriately.

Run the following script to identify all usages of GetQuoteByToken:

solidity/test/bridge_fee_quote.ts Show resolved Hide resolved
solidity/contracts/bridge/BridgeFeeQuote.sol Outdated Show resolved Hide resolved
solidity/contracts/bridge/BridgeFeeQuote.sol Show resolved Hide resolved
Copy link

@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)
solidity/contracts/bridge/BridgeFeeQuote.sol (2)

Line range hint 286-295: Include quoteIndex in the signature to ensure uniqueness across indices

The verifySignature function and makeMessageHash do not include _input.quoteIndex in the message hash used for signature verification. This omission can lead to security vulnerabilities where a valid signature for one quoteIndex could be reused for another quoteIndex, potentially allowing unauthorized quotes to be accepted. Including quoteIndex in the message hash ensures that each signature is unique to a specific quote index.

Apply this diff to include quoteIndex in the signature:

 // In verifySignature function
 function verifySignature(QuoteInput memory _input) private pure {
     bytes32 hash = makeMessageHash(
         _input.chainName,
         _input.token,
         _input.fee,
         _input.gasLimit,
         _input.expiry,
+        _input.quoteIndex
     );
     address signer = hash.toEthSignedMessageHash().recover(
         _input.signature
     );
     if (_input.oracle != signer) {
         revert VerifySignatureFailed(_input.oracle, signer);
     }
 }

 // Update makeMessageHash function to include quoteIndex
-function makeMessageHash(
-    string memory _chainName,
-    address _token,
-    uint256 _fee,
-    uint256 _gasLimit,
-    uint256 _expiry
-) public pure returns (bytes32) {
+function makeMessageHash(
+    string memory _chainName,
+    address _token,
+    uint256 _fee,
+    uint256 _gasLimit,
+    uint256 _expiry,
+    uint256 _quoteIndex
+) public pure returns (bytes32) {
     return
-        keccak256(abi.encode(_chainName, _token, _fee, _gasLimit, _expiry));
+        keccak256(abi.encode(_chainName, _token, _fee, _gasLimit, _expiry, _quoteIndex));
 }

Also applies to: 317-326


430-435: Emit an event when updating maxQuoteIndex for transparency

The updateMaxQuoteIndex function alters a crucial parameter that affects the contract's behavior. Emitting an event when maxQuoteIndex is updated enhances transparency and allows off-chain systems to track changes to this value.

Apply this diff to emit an event:

+    event MaxQuoteIndexUpdated(uint256 oldMaxQuoteIndex, uint256 newMaxQuoteIndex);

     function updateMaxQuoteIndex(
         uint256 _maxQuoteIndex
     ) external onlyOwner returns (bool) {
+        emit MaxQuoteIndexUpdated(maxQuoteIndex, _maxQuoteIndex);
         maxQuoteIndex = _maxQuoteIndex;
         return true;
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f49f151 and 0ea1b5a.

📒 Files selected for processing (1)
  • solidity/contracts/bridge/BridgeFeeQuote.sol (12 hunks)
🧰 Additional context used

solidity/contracts/bridge/BridgeFeeQuote.sol Show resolved Hide resolved
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