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(contracts-rfq): arbitrary call with value [SLT-233] [SLT-318] #3246

Merged
merged 23 commits into from
Oct 14, 2024

Conversation

ChiTimesChi
Copy link
Collaborator

@ChiTimesChi ChiTimesChi commented Oct 7, 2024

Description
This PR finishes the work started in #3215 by adding the functionality to request a native value to be supplied on the destination chain, when relaying the request.

The requested "call value" will be attached to the recipient hook function call (if callParams is a non-empty payload), or transferred as a separate native transfer after the tokens are sent.

Summary by CodeRabbit

  • New Features

    • Enhanced bridging functionality with new parameters for handling call values and call parameters.
    • Introduced new error handling for unsupported native token call values.
    • Improved clarity in event emissions with named parameters.
  • Bug Fixes

    • Improved logic for relaying transactions to ensure correct handling of call values and reverts.
  • Tests

    • Expanded testing framework with additional scenarios for relaying tokens and ETH, including edge cases for call values and parameters.
    • Enhanced tests for various recipient behaviors regarding call values.

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

Walkthrough

The changes in this pull request focus on enhancing the FastBridgeV2 contract and its associated interfaces and tests. Key modifications include the introduction of a new parameter callValue in the BridgeParamsV2 structure, refactoring of the bridge and relay functions to improve validation logic, and updates to event emit statements. The testing framework has been expanded to cover various scenarios involving call values, ensuring comprehensive validation of contract behavior under different conditions.

Changes

File Change Summary
packages/contracts-rfq/contracts/FastBridgeV2.sol - Added callValue to BridgeParamsV2.
- Refactored bridge and relay functions to use _validateBridgeParams and _validateRelayParams.
- Updated handling of callValue for ETH.
- Modified _pullToken for direct token transfers.
- Updated event emit statements with named parameters.
- Method signatures updated for bridge, relay, claim, and getBridgeTransaction.
packages/contracts-rfq/contracts/interfaces/IFastBridge.sol - Updated getBridgeTransaction method from pure to view.
packages/contracts-rfq/contracts/interfaces/IFastBridgeV2.sol - Added BridgeParamsV2 struct with callValue.
- Modified BridgeTransactionV2 struct to replace sendChainGas with callValue.
- Updated bridge function signature to include BridgeParamsV2.
packages/contracts-rfq/contracts/interfaces/IFastBridgeV2Errors.sol - Added new error NativeTokenCallValueNotSupported().
packages/contracts-rfq/test/FastBridgeV2.Dst.ArbitraryCall.t.sol - Added tests for call value handling in relay operations.
- Updated existing tests for relaying tokens and ETH to include call value checks.
packages/contracts-rfq/test/FastBridgeV2.Dst.Exclusivity.t.sol - Removed direct instantiation of BridgeParamsV2 in createFixturesV2.
- Added calls to new methods for setting exclusivity parameters.
packages/contracts-rfq/test/FastBridgeV2.Dst.t.sol - Added constant CALL_VALUE.
- Introduced functions for balance checks.
- Expanded tests for relaying tokens and ETH with call values.
packages/contracts-rfq/test/FastBridgeV2.Encoding.t.sol - Updated test_getBridgeTransaction_supportsV2 function to clarify expectations regarding callValue.
packages/contracts-rfq/test/FastBridgeV2.Src.ArbitraryCall.t.sol - Added constant CALL_VALUE.
- Enhanced testing capabilities for call parameters and values.
packages/contracts-rfq/test/FastBridgeV2.Src.t.sol - Modified expectBridgeRequested to evaluate sendChainGas based on callValue.
packages/contracts-rfq/test/FastBridgeV2.t.sol - Added callValue and callParams to BridgeParamsV2.
- Introduced methods for setting call values.

Possibly related PRs

Suggested labels

needs-go-generate-services/rfq

Suggested reviewers

  • trajan0x
  • parodime

Poem

In the meadow where bridges gleam,
A rabbit hops with a joyful dream.
With call values now in play,
The tokens dance in a bright ballet.
New tests and tweaks, oh what a sight,
In the world of code, all feels just right! 🐇✨


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.

Copy link

cloudflare-workers-and-pages bot commented Oct 7, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 432c34e
Status: ✅  Deploy successful!
Preview URL: https://15ab7326.sanguine-fe.pages.dev
Branch Preview URL: https://feat-fbv2-arbitrary-call-val.sanguine-fe.pages.dev

View logs

Copy link

codecov bot commented Oct 7, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.77404%. Comparing base (2b05e51) to head (c38f34c).
Report is 23 commits behind head on master.

Additional details and impacted files
@@                 Coverage Diff                  @@
##              master       #3246          +/-   ##
====================================================
+ Coverage   30.68788%   90.77404%   +60.08616%     
====================================================
  Files            447          60         -387     
  Lines          29787        1279       -28508     
  Branches          82         159          +77     
====================================================
- Hits            9141        1161        -7980     
+ Misses         19797         114       -19683     
+ Partials         849           4         -845     
Flag Coverage Δ
cctp-relayer ?
ethergo ?
omnirpc ?
opbot ?
packages 90.44834% <ø> (+0.00932%) ⬆️
promexporter ?
rfq ?
scribe ?
solidity 92.09486% <100.00000%> (?)
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.

packages/contracts-rfq/contracts/FastBridgeV2.sol Dismissed Show dismissed Hide dismissed
packages/contracts-rfq/contracts/FastBridgeV2.sol Dismissed Show dismissed Hide dismissed
Copy link

github-actions bot commented Oct 7, 2024

Changes to gas cost

Generated at commit: 07085658c007a1dc47d78900939e523cae9bc3fc, compared to commit: 0428f30dfac43f0b57d12c6a2c129b27bee02e4b

🧾 Summary (50% most significant diffs)

Contract Method Avg (+/-) %
FastBridgeV2 bridgeProofs
canClaim
getBridgeTransaction
getBridgeTransactionV2
relay(bytes)
relay(bytes,address)
-22 ✅
-22 ✅
+2,635 ❌
-1,076 ✅
-1,290 ✅
-1,290 ✅
-3.53%
-0.70%
+88.93%
-24.67%
-1.79%
-1.77%

Full diff report 👇
Contract Deployment Cost (+/-) Method Min (+/-) % Avg (+/-) % Median (+/-) % Max (+/-) % # Calls (+/-)
FastBridgeV2 2,992,360 (+121,648) REFUNDER_ROLE
RELAYER_ROLE
bridge
bridgeProofs
canClaim
claim(bytes)
claim(bytes,address)
dispute
getBridgeTransaction
getBridgeTransactionV2
nonce
prove(bytes,bytes32)
refund
relay(bytes)
relay(bytes,address)
setProtocolFeeRate
307 (-22)
285 (-22)
70,686 (+224)
602 (-22)
3,141 (-22)
43,814 (-95)
46,667 (-95)
31,262 (-22)
5,598 (+2,635)
1,408 (-2,806)
350 (+110)
35,573 (-22)
47,685 (+16)
64,419 (-266)
64,836 (-266)
47,377 (-22)
-6.69%
-7.17%
+0.32%
-3.53%
-0.70%
-0.22%
-0.20%
-0.07%
+88.93%
-66.59%
+45.83%
-0.06%
+0.03%
-0.41%
-0.41%
-0.05%
307 (-22)
285 (-22)
82,089 (+217)
602 (-22)
3,141 (-22)
50,846 (-90)
52,449 (-90)
31,262 (-22)
5,598 (+2,635)
3,285 (-1,076)
350 (+110)
35,886 (-22)
51,764 (+22)
70,973 (-1,290)
71,390 (-1,290)
47,377 (-22)
-6.69%
-7.17%
+0.27%
-3.53%
-0.70%
-0.18%
-0.17%
-0.07%
+88.93%
-24.67%
+45.83%
-0.06%
+0.04%
-1.79%
-1.77%
-0.05%
307 (-22)
285 (-22)
82,763 (+217)
602 (-22)
3,141 (-22)
51,383 (-89)
52,986 (-89)
31,262 (-22)
5,598 (+2,635)
4,077 (-284)
350 (+110)
35,597 (-22)
51,924 (+21)
70,962 (-1,212)
71,379 (-1,212)
47,377 (-22)
-6.69%
-7.17%
+0.26%
-3.53%
-0.70%
-0.17%
-0.17%
-0.07%
+88.93%
-6.51%
+45.83%
-0.06%
+0.04%
-1.68%
-1.67%
-0.05%
307 (-22)
285 (-22)
94,864 (+209)
602 (-22)
3,141 (-22)
58,916 (-84)
59,269 (-84)
31,262 (-22)
5,598 (+2,635)
4,371 (-137)
350 (+110)
36,549 (-22)
56,164 (+27)
80,312 (-2,415)
80,729 (-2,415)
47,377 (-22)
-6.69%
-7.17%
+0.22%
-3.53%
-0.70%
-0.14%
-0.14%
-0.07%
+88.93%
-3.04%
+45.83%
-0.06%
+0.05%
-2.92%
-2.90%
-0.05%
61 (0)
122 (0)
240 (0)
12 (0)
12 (0)
6 (0)
6 (0)
6 (0)
1 (0)
3 (+1)
4 (0)
63 (0)
12 (0)
6 (0)
6 (0)
19 (0)

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: 15

🧹 Outside diff range and nitpick comments (8)
packages/contracts-rfq/contracts/interfaces/IFastBridgeV2Errors.sol (1)

10-10: LGTM! Consider grouping related errors.

The new error NativeTokenCallValueNotSupported is well-named and consistent with the interface's style. It clearly describes a specific condition related to native token call values.

Consider grouping this error with other related errors (if any) for better organization. For instance, it could be placed near MsgValueIncorrect if they are conceptually related.

packages/contracts-rfq/test/FastBridgeV2.Src.t.sol (2)

Line range hint 1-1024: Consider updating tests for new sendChainGas behavior.

While the existing test suite is comprehensive, the change in sendChainGas logic may require updates to existing tests or the addition of new ones. This ensures that the new behavior is properly validated.

Consider adding or modifying tests to specifically check:

  1. Cases where callValue is zero but sendChainGas was previously true.
  2. Cases where callValue is non-zero but sendChainGas was previously false.
  3. Edge cases around very small non-zero callValue amounts.

This will help ensure that the new logic is working as intended across all scenarios.


Line range hint 1-1024: Summary: Significant change in sendChainGas logic requires careful verification.

The main change in this file is the modification of the sendChainGas logic in the expectBridgeRequested function. This change could have far-reaching effects on how cross-chain gas costs are handled. Key points to address:

  1. Verify that this change aligns with the intended behavior across the entire codebase.
  2. Update existing tests or add new ones to cover the new sendChainGas behavior thoroughly.
  3. Ensure that all stakeholders are aware of this change and its potential implications on gas handling in cross-chain transactions.

Consider documenting this change clearly in the contract's documentation or comments, explaining the rationale behind linking sendChainGas to callValue instead of using a separate flag. This will help future developers understand the design decision.

packages/contracts-rfq/contracts/interfaces/IFastBridgeV2.sol (1)

60-60: Clarify Comment Regarding callValue Replacement

In the comment for callValue in BridgeTransactionV2, it says: "replaces V1's sendChainGas flag". Since sendChainGas was a boolean, and callValue is a uint256, consider updating the comment to provide more clarity on how callValue replaces sendChainGas.

You can revise the comment as follows:

- uint256 callValue; // ETH value to send to the recipient (if any) - replaces V1's sendChainGas flag
+ uint256 callValue; // ETH value to send to the recipient (if any); replaces V1's sendChainGas flag by specifying the amount of ETH to send
packages/contracts-rfq/contracts/FastBridgeV2.sol (2)

366-389: Use of block.timestamp in validation checks.

While the use of block.timestamp for validation in _validateBridgeParams is acceptable, be cautious of potential miner manipulation within a small range. Ensure that any reliance on timestamps does not introduce vulnerabilities or allow exploits due to slight timestamp discrepancies.

🧰 Tools
🪛 GitHub Check: Slither

[notice] 366-389: Block timestamp
FastBridgeV2._validateBridgeParams(IFastBridge.BridgeParams,IFastBridgeV2.BridgeParamsV2,int256) (contracts/FastBridgeV2.sol#366-389) uses timestamp for comparisons
Dangerous comparisons:
- params.deadline < block.timestamp + MIN_DEADLINE_PERIOD (contracts/FastBridgeV2.sol#379)
- exclusivityEndTime <= 0 || exclusivityEndTime > int256(params.deadline) (contracts/FastBridgeV2.sol#386)


392-415: Time-based validation in _validateRelayParams.

Similarly, consider the implications of using block.timestamp in _validateRelayParams. Minor adjustments by miners could affect time-sensitive logic. Review whether this could impact the security or functionality of the relay process.

🧰 Tools
🪛 GitHub Check: Slither

[notice] 392-415: Block timestamp
FastBridgeV2._validateRelayParams(IFastBridgeV2.BridgeTransactionV2,bytes32,address) (contracts/FastBridgeV2.sol#392-415) uses timestamp for comparisons
Dangerous comparisons:
- block.timestamp > transaction.deadline (contracts/FastBridgeV2.sol#405)
- transaction.exclusivityRelayer != address(0) && transaction.exclusivityRelayer != relayer && block.timestamp <= transaction.exclusivityEndTime (contracts/FastBridgeV2.sol#409-411)

packages/contracts-rfq/test/FastBridgeV2.Dst.t.sol (2)

304-309: Specify expected revert reason for clearer test diagnostics.

Including the expected revert reason improves test precision and aids in debugging.


311-316: Consider specifying the expected revert reason for better clarity in test assertions.

This enhances the test's expressiveness and robustness.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4b49879 and 9fb4461.

📒 Files selected for processing (9)
  • packages/contracts-rfq/contracts/FastBridgeV2.sol (7 hunks)
  • packages/contracts-rfq/contracts/interfaces/IFastBridgeV2.sol (2 hunks)
  • packages/contracts-rfq/contracts/interfaces/IFastBridgeV2Errors.sol (1 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Dst.ArbitraryCall.t.sol (7 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Dst.Exclusivity.t.sol (1 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Dst.t.sol (14 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Src.ArbitraryCall.t.sol (2 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Src.t.sol (1 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.t.sol (3 hunks)
🧰 Additional context used
🪛 GitHub Check: Slither
packages/contracts-rfq/contracts/FastBridgeV2.sol

[notice] 366-389: Block timestamp
FastBridgeV2._validateBridgeParams(IFastBridge.BridgeParams,IFastBridgeV2.BridgeParamsV2,int256) (contracts/FastBridgeV2.sol#366-389) uses timestamp for comparisons
Dangerous comparisons:
- params.deadline < block.timestamp + MIN_DEADLINE_PERIOD (contracts/FastBridgeV2.sol#379)
- exclusivityEndTime <= 0 || exclusivityEndTime > int256(params.deadline) (contracts/FastBridgeV2.sol#386)


[notice] 392-415: Block timestamp
FastBridgeV2._validateRelayParams(IFastBridgeV2.BridgeTransactionV2,bytes32,address) (contracts/FastBridgeV2.sol#392-415) uses timestamp for comparisons
Dangerous comparisons:
- block.timestamp > transaction.deadline (contracts/FastBridgeV2.sol#405)
- transaction.exclusivityRelayer != address(0) && transaction.exclusivityRelayer != relayer && block.timestamp <= transaction.exclusivityEndTime (contracts/FastBridgeV2.sol#409-411)

🔇 Additional comments (53)
packages/contracts-rfq/test/FastBridgeV2.Dst.Exclusivity.t.sol (2)

4-4: Verify the impact of removing the IFastBridgeV2 import.

The import statement for IFastBridgeV2 has been removed. Please ensure that this interface is not used directly in this test file and that all necessary types and functions are still accessible through the FastBridgeV2DstTest import.

To confirm that the removal of the import doesn't break any functionality, run the following script:


11-12: Approve changes to createFixturesV2 and verify new methods.

The refactoring of createFixturesV2 to use setTokenTestExclusivityParams and setEthTestExclusivityParams improves code organization and readability. This change simplifies the setup process for test fixtures.

To ensure the new methods correctly set up the test environment, please verify their implementation:

✅ Verification successful

Verified the implementation of new methods.

The methods setTokenTestExclusivityParams and setEthTestExclusivityParams are correctly defined and utilized within the test suite (packages/contracts-rfq/test/FastBridgeV2.t.sol). This ensures the test fixtures are set up as intended, confirming the refactoring in createFixturesV2 improves code organization without introducing issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of new methods

# Test: Check the implementation of setTokenTestExclusivityParams and setEthTestExclusivityParams
rg --type solidity -A 10 '(setTokenTestExclusivityParams|setEthTestExclusivityParams)' packages/contracts-rfq/test/FastBridgeV2.Dst.t.sol

Length of output: 580


Script:

#!/bin/bash
# Description: Search for the implementation of setTokenTestExclusivityParams and setEthTestExclusivityParams in Solidity files

# Find all .sol files and search for the method implementations
fd --extension sol | xargs rg '(setTokenTestExclusivityParams|setEthTestExclusivityParams)'

Length of output: 1713


Script:

#!/bin/bash
# Description: Extract implementations of setTokenTestExclusivityParams and setEthTestExclusivityParams

# Extract the function implementations from Solidity files
rg -A 10 'function setTokenTestExclusivityParams' packages/contracts-rfq/test/**/*.sol
rg -A 10 'function setEthTestExclusivityParams' packages/contracts-rfq/test/**/*.sol

Length of output: 947


Script:

#!/bin/bash
# Description: Comprehensive search for setTokenTestExclusivityParams and setEthTestExclusivityParams implementations across all Solidity files

# Find all .sol files and search for the function implementations without restricting the search to specific directories
fd --extension sol | xargs rg 'function\s+setTokenTestExclusivityParams\s*\('
fd --extension sol | xargs rg 'function\s+setEthTestExclusivityParams\s*\('

Length of output: 443

packages/contracts-rfq/test/FastBridgeV2.Src.t.sol (1)

45-45: Verify the impact of changing sendChainGas logic.

The condition for setting sendChainGas has been changed from bridgeTx.sendChainGas to bridgeTx.callValue > 0. This modification alters when chain gas is considered to be sent, potentially affecting cross-chain transaction behavior.

To ensure this change doesn't introduce unintended side effects, please run the following verification:

Review the results to confirm that this change aligns with the intended behavior across the codebase.

✅ Verification successful

Change to sendChainGas in FastBridgeV2.Src.t.sol is correctly implemented.
The alteration from bridgeTx.sendChainGas to bridgeTx.callValue > 0 is localized to FastBridgeV2.Src.t.sol and does not affect other parts of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all usages of BridgeRequested event and sendChainGas
rg --type solidity -e 'emit BridgeRequested' -e 'sendChainGas'

Length of output: 95


Script:

#!/bin/bash
# Search for all usages of BridgeRequested event and sendChainGas in .sol files
rg -g "*.sol" -e 'emit BridgeRequested' -e 'sendChainGas'

Length of output: 7534

packages/contracts-rfq/test/FastBridgeV2.Src.ArbitraryCall.t.sol (9)

9-9: Definition of CALL_VALUE is appropriate and follows conventions.

The constant CALL_VALUE is correctly defined and adheres to Solidity naming conventions.


48-52: Test test_bridge_token_withCallValue_noCallParams correctly validates token bridging with call value and no call parameters.

The test function appropriately sets up the scenario where a call value is provided without call parameters for token bridging and invokes test_bridge_token() as expected.


54-58: Test test_bridge_token_diffSender_withCallValue_noCallParams correctly handles different sender scenario with call value and no call parameters.

The function correctly tests token bridging with a different sender, providing a call value without call parameters.


60-65: Test test_bridge_eth_withCallValue_noCallParams_revert accurately expects revert when bridging ETH with call value and no call parameters.

The test correctly expects a revert with NativeTokenCallValueNotSupported.selector when attempting to bridge ETH providing a call value without call parameters, ensuring the contract behaves as intended under these conditions.


67-72: Test test_bridge_eth_diffSender_withCallValue_noCallParams_revert correctly tests revert scenario with different sender.

This test ensures that bridging ETH with a different sender, providing a call value without call parameters, correctly reverts with the expected error selector.


76-79: Test test_bridge_token_withCallValue_withCallParams effectively tests token bridging with both call value and call parameters.

The function successfully tests the scenario where both a call value and call parameters are provided for token bridging, validating the contract's handling of this case.


81-84: Test test_bridge_token_diffSender_withCallValue_withCallParams appropriately handles different sender with call value and call parameters.

The test accurately assesses token bridging with a different sender when both call value and call parameters are provided.


86-90: Test test_bridge_eth_withCallValue_withCallParams_revert correctly expects revert when bridging ETH with call value and call parameters.

The test ensures that providing both call value and call parameters while bridging ETH correctly results in a revert with NativeTokenCallValueNotSupported.selector, as the contract does not support this operation.


92-96: Test test_bridge_eth_diffSender_withCallValue_withCallParams_revert accurately tests revert scenario with different sender.

This function validates that bridging ETH with a different sender, providing both call value and call parameters, correctly triggers a revert with the expected error selector.

packages/contracts-rfq/contracts/interfaces/IFastBridgeV2.sol (2)

43-43: ⚠️ Potential issue

Data Type Suggestion: Use uint256 for quoteExclusivitySeconds

In the BridgeParamsV2 struct, quoteExclusivitySeconds is declared as int256. Since time durations cannot be negative, consider changing its type to uint256 to reflect that it should only represent non-negative values.

You can apply the following change:

- int256 quoteExclusivitySeconds;
+ uint256 quoteExclusivitySeconds;

Likely invalid or redundant comment.


60-60: Consistency Check Between callValue Parameters

Ensure that callValue in BridgeTransactionV2 aligns with callValue in BridgeParamsV2. It is important to maintain consistency between these structs to prevent mismatches during the bridging process.

You can run the following script to verify the usage of callValue across the codebase:

✅ Verification successful

Consistency Verified for callValue Parameters

The callValue field in both BridgeTransactionV2 and BridgeParamsV2 structs is consistently defined as uint256. This ensures alignment between the two structs, preventing potential mismatches during the bridging process.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of `callValue` in structs and function parameters.

# Find all declarations of `callValue`
rg --type solidity 'uint256 callValue'

# Find all usages of `callValue` in functions
rg --type solidity -A3 'function.*\((.*?)\)' | rg 'callValue'

Length of output: 168


Script:

#!/bin/bash
# Description: Verify consistent usage of `callValue` in structs and function parameters by searching within .sol files.

# Find all declarations of `callValue` in .sol files
rg 'uint256\s+callValue' --glob '*.sol'

# Find all usages of `callValue` in function parameters within .sol files
rg 'function\s+\w+\s*\(([^)]*callValue[^)]*)\)' --glob '*.sol'

Length of output: 801


Script:

#!/bin/bash
# Description: Locate and extract `callValue` definitions within BridgeTransactionV2 and BridgeParamsV2 structs.

# Find BridgeTransactionV2 struct definition and extract callValue
rg 'struct\s+BridgeTransactionV2\s*\{' --glob '*.sol' -A10 | rg 'uint256\s+callValue'

# Find BridgeParamsV2 struct definition and extract callValue
rg 'struct\s+BridgeParamsV2\s*\{' --glob '*.sol' -A10 | rg 'uint256\s+callValue'

Length of output: 429

packages/contracts-rfq/test/FastBridgeV2.t.sol (4)

131-132: Initialization of callValue and callParams for tokenParamsV2

The callValue is correctly initialized to 0, and callParams is set to an empty byte array. This ensures default values are properly set for token transactions in tests.


138-139: Initialization of callValue and callParams for ethParamsV2

The callValue and callParams are correctly initialized for ETH transactions, matching the token parameters.


172-175: Implementation of setTokenTestCallValue

The function setTokenTestCallValue correctly updates tokenParamsV2.callValue and tokenTx.callValue with the provided callValue. This allows for dynamic testing of call values in token transactions.


191-194: Implementation of setEthTestCallValue

The function setEthTestCallValue correctly updates ethParamsV2.callValue and ethTx.callValue with the provided callValue. This facilitates testing of call values in ETH transactions.

packages/contracts-rfq/test/FastBridgeV2.Dst.ArbitraryCall.t.sol (2)

4-5: Imports updated appropriately

The updated import statements correctly include the necessary interfaces and base test contracts required for these tests.


339-339: Confirm the use of Address.FailedInnerCall.selector

Lines 339 and 346 use vm.expectRevert(Address.FailedInnerCall.selector); when expecting a revert. Verify that this selector correctly corresponds to the expected revert reason and is used consistently where appropriate.

#!/bin/bash
# Description: Ensure that Address.FailedInnerCall.selector is correctly used and defined.

# Check where Address.FailedInnerCall.selector is defined and used.
rg --type solidity 'Address\.FailedInnerCall\.selector' -A 2

Also applies to: 346-346

packages/contracts-rfq/contracts/FastBridgeV2.sol (13)

57-57: Initialization of default parameters in BridgeParamsV2.

Adding callValue: 0 and callParams: bytes("") ensures that default values are properly set when paramsV2 is not provided. This maintains backward compatibility and prevents potential issues with uninitialized parameters.


142-143: Refactoring validation logic into _validateBridgeParams function.

Abstracting the parameter validation into _validateBridgeParams enhances code readability and maintainability by consolidating checks in a single location.


145-146: Secure token transfer using _pullToken.

Utilizing _pullToken to transfer tokens ensures that tokens are securely pulled to the contract, which is crucial for safeguarding assets and preventing unauthorized transfers.


165-165: Including callValue in BridgeTransactionV2 encoding.

Incorporating callValue when encoding the bridge transaction ensures that the specified value is correctly relayed to the destination chain, enhancing the contract's functionality.


177-187: Enhanced event emission with named parameters in BridgeRequested.

Using named parameters in the emit BridgeRequested statement improves clarity and readability of the emitted events, making it easier to track and debug transactions.


195-200: Refactoring relay logic into _validateRelayParams function.

Moving validation logic into _validateRelayParams reduces redundancy and aligns with the single-responsibility principle, improving code organization.


207-211: Validating msg.value for ETH transfers in relays.

The checks ensure that when transferring ETH, callValue must be zero and msg.value must match the expected amount, preventing incorrect fund transfers and enhancing security.


213-217: Validating msg.value for ERC20 transfers and secure token forwarding.

By confirming that msg.value matches transaction.callValue and securely transferring ERC20 tokens from the relayer to the recipient, the contract upholds the integrity of the relay process.


220-229: Handling of arbitrary calls and ETH transfers post-relay.

The logic correctly manages scenarios where callParams are provided, executing an arbitrary call with the supplied callValue. It also appropriately transfers ETH to the recipient when msg.value is non-zero and no callParams are present.


231-241: Detailed event emission in BridgeRelayed.

Emitting comprehensive details in the BridgeRelayed event, including parameters like chainGasAmount, facilitates easier monitoring and auditing of bridge transactions.


308-314: Improved token pull logic in _pullToken function.

The refactored _pullToken method now pulls tokens directly to the contract, simplifying the transfer process and mitigating potential reentrancy risks. The balance checks account for tokens with transfer fees, ensuring accurate tracking of transferred amounts.

Also applies to: 317-317, 320-320, 322-322


339-341: Secure external call implementation in _checkedCallRecipient.

Using Address.functionCallWithValue to perform external calls while forwarding msg.value ensures safe interaction with recipient contracts. The additional checks on returnData confirm that the recipient contract returns the expected value, enhancing reliability.


374-415: Centralization of validation logic enhances maintainability.

By centralizing parameter validations in _validateBridgeParams and _validateRelayParams, the codebase becomes more maintainable and easier to update, adhering to best practices.

🧰 Tools
🪛 GitHub Check: Slither

[notice] 392-415: Block timestamp
FastBridgeV2._validateRelayParams(IFastBridgeV2.BridgeTransactionV2,bytes32,address) (contracts/FastBridgeV2.sol#392-415) uses timestamp for comparisons
Dangerous comparisons:
- block.timestamp > transaction.deadline (contracts/FastBridgeV2.sol#405)
- transaction.exclusivityRelayer != address(0) && transaction.exclusivityRelayer != relayer && block.timestamp <= transaction.exclusivityEndTime (contracts/FastBridgeV2.sol#409-411)

packages/contracts-rfq/test/FastBridgeV2.Dst.t.sol (20)

26-26: Definition of CALL_VALUE constant is appropriate.

The addition of the CALL_VALUE constant sets a consistent value for use in tests involving call values.


72-72: Update of chainGasAmount calculation is correct.

The conditional assignment of chainGasAmount based on whether destToken is ETH_ADDRESS ensures proper handling of call values for different token types.


83-83: Emission of chainGasAmount in BridgeRelayed event is appropriate.

Including chainGasAmount in the event emission provides better transparency and tracking of the relayed transactions.


95-99: Addition of checkTokenBalances function enhances code readability.

The function encapsulates balance assertions for token transfers, improving test maintainability.


101-105: Addition of checkEthBalances function improves balance checks for ETH transfers.

This refactoring promotes code reuse and clarity in tests involving ETH balances.


113-113: Refactoring to use checkTokenBalances improves test consistency.

Using the new helper function streamlines balance checks in the test.


122-122: Refactoring to use checkTokenBalances enhances code consistency in tests.

This promotes uniformity across token-related test cases.


131-131: Refactoring to use checkEthBalances enhances test code readability.

Utilizing the helper function for ETH balances simplifies the test code.


140-140: Update to use checkEthBalances function in the test is appropriate.

This change improves maintainability and clarity of balance assertions.


156-156: Use of checkEthBalances in test enhances code consistency.

Consistent use of helper functions across tests aids in readability.


161-169: Addition of test_relay_token_withCallValue enhances test coverage for token relays with call value.

The test correctly sets up call value scenarios and verifies expected behaviors.


171-178: Addition of test_relay_token_withRelayerAddressCallValue extends tests to cover relayer addresses with call values.

This ensures comprehensive testing of relays involving both call values and specified relayer addresses.


476-480: Addition of test_relay_token_withCallValue_revert_zeroCallValue increases test coverage for invalid call value scenarios.

The test correctly verifies that zero msg.value when a call value is expected causes a revert.


482-486: Addition of test_relay_token_withCallValue_revert_lowerCallValue ensures proper validation of insufficient msg.value.

This enhances the contract's robustness by validating msg.value.


489-493: Addition of test_relay_token_withCallValue_revert_higherCallValue validates rejection of excessive msg.value.

The test ensures that overpayment is correctly handled.


495-499: Addition of test_relay_token_withRelayerAddressCallValue_revert_zeroCallValue checks for correct revert when msg.value is zero.

This test adds necessary validation for relays with relayer addresses.


501-505: Addition of test_relay_token_withRelayerAddressCallValue_revert_lowerCallValue validates handling of insufficient msg.value.

Ensures consistency in how call value discrepancies are handled.


507-511: Addition of test_relay_token_withRelayerAddressCallValue_revert_higherCallValue ensures excess msg.value is rejected.

This contributes to the integrity of the relay process.


513-522: Addition of test_relay_eth_withCallValue_revert_notSupported confirms that call values are not supported for ETH relays.

Validates that ETH transfers do not accept additional call values.


524-537: Addition of test_relay_eth_withRelayerAddressCallValue_revert_notSupported ensures ETH relays do not accept call values with relayer addresses.

This test secures the behavior of ETH relay functions against unsupported scenarios.

@ChiTimesChi ChiTimesChi changed the title feat(contracts-rfq): arbitrary call with value [SLT-233] feat(contracts-rfq): arbitrary call with value [SLT-233] [SLT-318] Oct 8, 2024
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)
packages/contracts-rfq/test/FastBridgeV2.Encoding.t.sol (1)

50-52: Use Correct NatSpec Tags for Internal Comments

The comments starting at line 50 should use the @dev tag instead of @notice since they describe internal implementation details rather than user-facing documentation. This improves clarity for developers.

Apply this diff to adjust the comments:

-    /// @notice We expect all the V1 fields except for `sendChainGas` to match.
-    /// `sendChainGas` is replaced with `callValue` in V2, therefore we expect non-zero `callValue`
-    /// to match `sendChainGas = true` in V1
+    /// @dev We expect all the V1 fields except for `sendChainGas` to match.
+    ///      `sendChainGas` is replaced with `callValue` in V2, therefore we expect non-zero `callValue`
+    ///      to match `sendChainGas = true` in V1
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 156e333 and 271f59d.

📒 Files selected for processing (3)
  • packages/contracts-rfq/contracts/FastBridgeV2.sol (7 hunks)
  • packages/contracts-rfq/contracts/interfaces/IFastBridge.sol (1 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Encoding.t.sol (1 hunks)
🧰 Additional context used
🔇 Additional comments (12)
packages/contracts-rfq/contracts/interfaces/IFastBridge.sol (1)

100-100: Approved: Function modifier change from pure to view

The change from pure to view for the getBridgeTransaction function is appropriate if the implementation needs to read contract state. This modification allows for more flexibility in the function's implementation while maintaining its non-state-modifying nature.

To ensure consistency, please verify that the implementation of this function in the concrete contract matches this interface change. Run the following script to check the implementation:

packages/contracts-rfq/test/FastBridgeV2.Encoding.t.sol (3)

53-53: Appropriate Addition of view Modifier

The addition of the view modifier to the test_getBridgeTransaction_supportsV2 function correctly indicates that it does not modify state, enhancing code clarity and adhering to Solidity best practices.


57-57: Correct Translation of callValue to sendChainGas

The assignment expectedTx.sendChainGas = bridgeTxV2.callValue > 0; accurately maps the V2 callValue to the V1 sendChainGas field. This ensures that a non-zero callValue in V2 corresponds to sendChainGas being true in V1, maintaining consistency between versions.


56-56: ⚠️ Potential issue

Verify the Definition of extractV1 Function

The function extractV1 is called on line 56 but is not defined within this file. Ensure that extractV1 is properly defined or imported to prevent compilation errors.

Run the following script to check for the definition of extractV1:

✅ Verification successful

extractV1 Function Definition Verified

The extractV1 function is defined in packages/contracts-rfq/test/FastBridgeV2.t.sol and is properly imported in FastBridgeV2.Encoding.t.sol:

  • FastBridgeV2.Encoding.t.sol imports FastBridgeV2.t.sol, ensuring access to extractV1.

No compilation errors related to the extractV1 function definition are expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the function `extractV1` is defined in the codebase.

# Test: Search for the definition of `extractV1`.
# Expect: At least one definition found.

rg --type solidity 'function\s+extractV1' --glob '*.sol'

Length of output: 91


Script:

#!/bin/bash
# Description: Verify that the function `extractV1` is defined in the codebase.

# Test: Search for the definition of `extractV1` within Solidity files.
# Expect: At least one definition found.

rg 'function\s+extractV1' --glob '*.sol'

Length of output: 159


Script:

#!/bin/bash
# Description: Check if 'FastBridgeV2.Encoding.t.sol' imports the file where 'extractV1' is defined.

# Extract import statements from 'packages/contracts-rfq/test/FastBridgeV2.Encoding.t.sol'
rg 'import\s+' packages/contracts-rfq/test/FastBridgeV2.Encoding.t.sol

Length of output: 169

packages/contracts-rfq/contracts/FastBridgeV2.sol (8)

57-57: Default callValue set to 0 for backward compatibility

The callValue: 0 initialization ensures that when the bridge function is called without paramsV2, the default callValue is zero, maintaining backward compatibility.


130-155: Backward compatibility handling in getBridgeTransaction

The implementation of getBridgeTransaction correctly attempts to decode the request into a V2 struct, and falls back to V1 if decoding fails. This approach maintains backward compatibility and ensures that both V1 and V2 requests are handled properly.


164-165: Adjusted originAmount to account for transfer fees

The code correctly updates originAmount using the returned value from _pullToken to handle tokens with transfer fees. This ensures that the actual amount received by the contract is used in subsequent calculations.


184-184: Included callValue in BridgeTransactionV2 encoding

Adding callValue: paramsV2.callValue to the BridgeTransactionV2 struct ensures that the call value is accurately captured in the encoded request. This is important for relayers to process the transaction correctly.


196-206: Updated BridgeRequested event with new parameters

The BridgeRequested event now includes updated fields, and correctly computes sendChainGas based on paramsV2.callValue != 0. This provides better transparency and aligns the event data with the updated transaction parameters.


226-248: Relay function correctly handles ETH and ERC20 tokens with callValue

The relay function appropriately distinguishes between ETH and ERC20 tokens, enforcing that callValue is zero for ETH transfers and performing necessary validations on msg.value. The function follows the checks-effects-interactions pattern, enhancing security.


327-341: _pullToken function accounts for tokens with transfer fees

The implementation of _pullToken correctly calculates amountPulled by comparing the contract's balance before and after the transfer. This handles tokens that may have transfer fees or differing transfer behaviors, ensuring accurate accounting.


358-361: Secure external call with explicit return value validation

The _checkedCallRecipient function safely calls the recipient's fastBridgeTransferReceived function using Address.functionCallWithValue and explicitly checks that the correct selector is returned. This adds a layer of security by ensuring the recipient contract acknowledges the call properly.

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 (12)
packages/contracts-rfq/contracts/FastBridgeV2.sol (4)

Line range hint 161-206: Approved: Enhancements to the bridge function

The changes to the bridge function improve code organization, readability, and functionality:

  1. The addition of _validateBridgeParams centralizes parameter validation, enhancing maintainability.
  2. Replacing _pullToken with _takeBridgedUserAsset provides a more descriptive name for the operation.
  3. The BridgeRequested event now includes more detailed information, improving traceability.

Suggestion for improvement:
Consider using named parameters for the BridgeRequested event emission to enhance readability and reduce the risk of parameter order mistakes in future modifications.

Example of using named parameters for the event:

-        emit BridgeRequested({
-            transactionId: transactionId,
-            sender: params.sender,
-            request: request,
-            destChainId: params.dstChainId,
-            originToken: params.originToken,
-            destToken: params.destToken,
-            originAmount: originAmount,
-            destAmount: params.destAmount,
-            sendChainGas: paramsV2.callValue != 0
-        });
+        emit BridgeRequested({
+            transactionId: transactionId,
+            sender: params.sender,
+            request: request,
+            destChainId: params.dstChainId,
+            originToken: params.originToken,
+            destToken: params.destToken,
+            originAmount: originAmount,
+            destAmount: params.destAmount,
+            sendChainGas: paramsV2.callValue != 0
+        });

214-260: Approved: Enhancements to the relay function with improved security

The changes to the relay function significantly improve its functionality and security:

  1. The addition of _validateRelayParams centralizes parameter validation, enhancing maintainability.
  2. New logic for handling callValue and callParams supports the added functionality from the PR objectives.
  3. Explicit checks for correct msg.value improve security by ensuring the expected amount is sent.
  4. The BridgeRelayed event now includes more detailed information, improving traceability.

Suggestion for improvement:
Consider adding a check for the maximum allowed callValue to prevent potential issues with extremely large values.

Add a constant for the maximum allowed callValue and a check in the _validateRelayParams function:

uint256 public constant MAX_CALL_VALUE = 1000 ether; // Adjust as needed

function _validateRelayParams(
    BridgeTransactionV2 memory transaction,
    bytes32 transactionId,
    address relayer
)
    internal
    view
{
    // ... existing checks ...
    if (transaction.callValue > MAX_CALL_VALUE) revert CallValueTooHigh();
}

327-344: Approved: New _takeBridgedUserAsset function with robust asset handling

The new _takeBridgedUserAsset function provides a robust mechanism for taking bridged assets from the user:

  1. It correctly handles both ETH and ERC20 tokens.
  2. Includes checks for correct msg.value, improving security.
  3. Accounts for potential transfer fees in ERC20 tokens, ensuring accurate accounting.

Suggestion for gas optimization:
Consider using unchecked arithmetic for the balance difference calculation, as it's unlikely to overflow.

Optimize the balance difference calculation:

-            amountTaken = IERC20(token).balanceOf(address(this)) - amountTaken;
+            unchecked {
+                amountTaken = IERC20(token).balanceOf(address(this)) - amountTaken;
+            }

384-411: Approved: Comprehensive _validateBridgeParams function

The new _validateBridgeParams function provides a thorough validation of bridge parameters:

  1. It covers both V1 and V2 parameters, ensuring backwards compatibility.
  2. Includes checks for chain IDs, amounts, addresses, deadlines, and exclusivity parameters.
  3. The validations enhance the security and robustness of the bridging process.

Suggestion for improvement:
Consider grouping related checks together and adding comments to improve readability.

Reorganize the checks for better readability:

function _validateBridgeParams(
    BridgeParams memory params,
    BridgeParamsV2 memory paramsV2,
    int256 exclusivityEndTime
)
    internal
    view
{
    // Chain validation
    if (params.dstChainId == block.chainid) revert ChainIncorrect();

    // Amount validation
    if (params.originAmount == 0 || params.destAmount == 0) revert AmountIncorrect();

    // Address validation
    if (params.sender == address(0) || params.to == address(0)) revert ZeroAddress();
    if (params.originToken == address(0) || params.destToken == address(0)) revert ZeroAddress();

    // Deadline validation
    if (params.deadline < block.timestamp + MIN_DEADLINE_PERIOD) revert DeadlineTooShort();

    // V2 specific validations
    if (paramsV2.callParams.length > MAX_CALL_PARAMS_LENGTH) revert CallParamsLengthAboveMax();
    if (paramsV2.callValue != 0 && params.destToken == UniversalTokenLib.ETH_ADDRESS) {
        revert NativeTokenCallValueNotSupported();
    }

    // Exclusivity validation
    if (exclusivityEndTime <= 0 || exclusivityEndTime > int256(params.deadline)) {
        revert ExclusivityParamsIncorrect();
    }
}
packages/contracts-rfq/test/FastBridgeV2.Dst.t.sol (8)

304-309: Specify the expected error in vm.expectRevert for clearer test failures

In test_relay_token_withCallValue_nonPayableRecipient_revert, consider specifying the expected error in vm.expectRevert() to ensure the test only passes when the specific error is thrown. This improves the test's precision and helps in identifying unintended passes.

Apply this diff to enhance the test:

function test_relay_token_withCallValue_nonPayableRecipient_revert() public {
    setTokenTestCallValue(CALL_VALUE);
    setTokenTestRecipient(nonPayableRecipient);
-   vm.expectRevert();
+   vm.expectRevert(bytes("RecipientCannotReceiveEther()"));
    relay({caller: relayerA, msgValue: CALL_VALUE, bridgeTx: tokenTx});
}

311-317: Include the specific error in vm.expectRevert for precise testing

In test_relay_token_withRelayerAddressCallValue_nonPayableRecipient_revert, specifying the expected error in vm.expectRevert() enhances test accuracy by ensuring it only passes when the intended error occurs.

Apply this diff to improve the test clarity:

function test_relay_token_withRelayerAddressCallValue_nonPayableRecipient_revert() public {
    setTokenTestCallValue(CALL_VALUE);
    setTokenTestRecipient(nonPayableRecipient);
-   vm.expectRevert();
+   vm.expectRevert(bytes("RecipientCannotReceiveEther()"));
    relayWithAddress({caller: relayerB, relayer: relayerA, msgValue: CALL_VALUE, bridgeTx: tokenTx});
}

558-563: Add expected error in vm.expectRevert for better test validation

In test_relay_token_withRelayerAddress_revert_approvedZero, consider adding the expected error to vm.expectRevert() to ensure the test fails only when the specific approval error occurs.

Apply this diff:

function test_relay_token_withRelayerAddress_revert_approvedZero() public {
    vm.prank(relayerB);
    dstToken.approve(address(fastBridge), 0);
-   vm.expectRevert();
+   vm.expectRevert("ERC20: transfer amount exceeds allowance");
    relayWithAddress({caller: relayerB, relayer: relayerA, msgValue: 0, bridgeTx: tokenTx});
}

565-571: Specify expected error in vm.expectRevert to enhance test robustness

In test_relay_token_withRelayerAddress_revert_approvedNotEnough, including the expected error in vm.expectRevert() makes the test more reliable by confirming it only passes on the correct failure condition.

Apply this diff:

function test_relay_token_withRelayerAddress_revert_approvedNotEnough() public {
    vm.prank(relayerB);
    dstToken.approve(address(fastBridge), tokenParams.destAmount - 1);
-   vm.expectRevert();
+   vm.expectRevert("ERC20: transfer amount exceeds allowance");
    relayWithAddress({caller: relayerB, relayer: relayerA, msgValue: 0, bridgeTx: tokenTx});
}

572-576: Define expected error in vm.expectRevert for accurate test outcomes

In test_relay_token_withRelayerAddress_revert_nonZeroMsgValue, specifying the expected error in vm.expectRevert() ensures that the test accurately checks for the intended revert condition.

Apply this change:

function test_relay_token_withRelayerAddress_revert_nonZeroMsgValue() public {
-   vm.expectRevert();
+   vm.expectRevert(MsgValueIncorrect.selector);
    relayWithAddress({caller: relayerB, relayer: relayerA, msgValue: tokenParams.destAmount, bridgeTx: tokenTx});
}

579-591: Include expected error messages in vm.expectRevert for precise testing

In the ETH relay tests (test_relay_eth_revert_lowerMsgValue, test_relay_eth_revert_higherMsgValue, and test_relay_eth_revert_zeroMsgValue), specifying the expected error enhances test clarity and ensures they only pass when the correct error is thrown.

Example diff for test_relay_eth_revert_lowerMsgValue:

function test_relay_eth_revert_lowerMsgValue() public {
-   vm.expectRevert();
+   vm.expectRevert(MsgValueIncorrect.selector);
    relay({caller: relayerB, msgValue: ethParams.destAmount - 1, bridgeTx: ethTx});
}

Repeat similar changes for the other two functions.


592-604: Specify expected errors in vm.expectRevert for consistent test behavior

In the ETH relay tests with relayer address (test_relay_eth_withRelayerAddress_revert_lowerMsgValue, test_relay_eth_withRelayerAddress_revert_higherMsgValue, and test_relay_eth_withRelayerAddress_revert_zeroMsgValue), adding the expected error to vm.expectRevert() ensures tests are robust and only pass on the correct error.

Example diff for test_relay_eth_withRelayerAddress_revert_lowerMsgValue:

function test_relay_eth_withRelayerAddress_revert_lowerMsgValue() public {
-   vm.expectRevert();
+   vm.expectRevert(MsgValueIncorrect.selector);
    relayWithAddress({caller: relayerA, relayer: relayerB, msgValue: ethParams.destAmount - 1, bridgeTx: ethTx});
}

Apply similar adjustments to the other functions.


26-27: Consider using a descriptive name for CALL_VALUE

While CALL_VALUE is functional, a more descriptive constant name could improve readability. For instance, DEFAULT_CALL_VALUE or TEST_CALL_VALUE might better convey its purpose in tests.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2317a58 and 189931c.

📒 Files selected for processing (3)
  • packages/contracts-rfq/contracts/FastBridgeV2.sol (7 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Dst.t.sol (15 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Src.t.sol (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/contracts-rfq/test/FastBridgeV2.Src.t.sol
🧰 Additional context used
🔇 Additional comments (4)
packages/contracts-rfq/contracts/FastBridgeV2.sol (4)

57-57: LGTM: Addition of callValue to BridgeParamsV2

The addition of the callValue field to the BridgeParamsV2 struct enhances the flexibility of bridging operations, allowing for native value transfers on the destination chain. This change aligns well with the PR objectives.


361-361: LGTM: Updated _checkedCallRecipient to forward msg.value

The addition of value: msg.value to the functionCallWithValue call in _checkedCallRecipient is correct and consistent with the new functionality for handling callValue. This change allows the forwarding of native tokens to the recipient's hook function when required.


413-437: Approved: Robust _validateRelayParams function

The new _validateRelayParams function provides comprehensive validation for relay parameters:

  1. It checks the relayer address, ensuring it's not the zero address.
  2. Verifies that the transaction hasn't been relayed already.
  3. Validates the destination chain ID.
  4. Checks the deadline for the relay.
  5. Handles the exclusivity period correctly.

These validations significantly enhance the security and correctness of the relay process. The function is well-structured and covers all necessary aspects of parameter validation.


130-155: Approved: Enhanced getBridgeTransaction with V2 support

The function has been successfully updated to support both V1 and V2 transaction structures, maintaining backwards compatibility. This is a good approach for handling the transition to the new structure.

However, note that there's a subtle change in behavior:

  • The sendChainGas field is now derived from whether callValue is non-zero, rather than being explicitly set.

Ensure that this change in behavior is documented and that all dependent systems are updated accordingly.

To verify the impact of this change, we can search for usages of getBridgeTransaction:

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 (6)
packages/contracts-rfq/contracts/FastBridgeV2.sol (6)

57-57: LGTM! Consider adding documentation for callValue.

The addition of callValue to the BridgeParamsV2 struct enhances the flexibility of bridging operations. This change aligns well with the PR objectives.

Consider adding a brief comment explaining the purpose and usage of callValue to improve code clarity.


130-155: LGTM! Consider a minor optimization for V1 transactions.

The implementation of getBridgeTransaction effectively handles both V1 and V2 structures, ensuring backward compatibility. The use of a try-catch block for decoding is appropriate.

Consider adding a version byte to the encoded request to avoid unnecessary try-catch for V1 transactions. This could slightly improve performance for older transaction formats.


Line range hint 161-206: LGTM! Consider enhancing error handling for _takeBridgedUserAsset.

The refactoring of the bridge function improves code organization and adds support for new functionality. The use of _validateBridgeParams and _takeBridgedUserAsset enhances the robustness of the bridging process.

Consider wrapping the call to _takeBridgedUserAsset in a try-catch block to handle potential errors more gracefully, especially for tokens with unusual behavior.


214-262: LGTM! Consider a gas optimization for ETH transfers.

The refactoring of the relay function improves code organization and adds support for callValue and arbitrary calls. The implementation correctly handles different token types and follows good security practices.

For ETH transfers without callParams, consider using a low-level call instead of Address.sendValue to save gas. However, ensure proper checks are in place to handle potential failure.


329-347: LGTM! Consider adding a sanity check for the transferred amount.

The _takeBridgedUserAsset function is well-implemented, handling both ETH and ERC20 tokens correctly. It properly accounts for potential transfer fees in ERC20 tokens.

Consider adding a sanity check to ensure that amountTaken is not zero after the transfer, which could indicate a failed transfer for certain token implementations.


386-413: LGTM! Consider grouping related checks.

The _validateBridgeParams function performs comprehensive validation of both V1 and V2 parameters. The checks are thorough and cover all necessary aspects.

Consider grouping related checks together (e.g., all address checks, all amount checks) to improve readability and maintainability of the function.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 189931c and 432c34e.

📒 Files selected for processing (1)
  • packages/contracts-rfq/contracts/FastBridgeV2.sol (7 hunks)
🧰 Additional context used
🔇 Additional comments (1)
packages/contracts-rfq/contracts/FastBridgeV2.sol (1)

415-439: LGTM! Comprehensive validation of relay parameters.

The _validateRelayParams function performs thorough checks on all relevant aspects of the relay operation. The validation of the exclusivity period is particularly well-implemented.

The logical ordering of checks, starting with the most basic ones, is a good practice that can help in early rejection of invalid requests.

@ChiTimesChi
Copy link
Collaborator Author

@coderabbitai summary

Copy link
Contributor

coderabbitai bot commented Oct 10, 2024

✅ Actions performed

Summary regeneration triggered.

@ChiTimesChi
Copy link
Collaborator Author

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Oct 10, 2024

✅ Actions performed

Full review triggered.

@ChiTimesChi
Copy link
Collaborator Author

Requesting a follow-up review from @parodime and @trajan0x.

The inclusion of the version in the request payload is now tracked as SLT-328 and will be done in a separate PR.

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)
packages/contracts-rfq/test/FastBridgeV2.t.sol (1)

Line range hint 159-171: Consider initializing callValue and callParams in setStorageBridgeTxV2.

The setStorageBridgeTxV2 function currently does not assign values to the newly added callValue and callParams fields in the txV2 struct. This omission might lead to uninitialized fields during testing, potentially causing unexpected behavior.

Apply the following changes to include these fields:

function setStorageBridgeTxV2(
    IFastBridgeV2.BridgeTransactionV2 storage txV2,
    IFastBridge.BridgeTransaction memory txV1
)
    internal
{
    txV2.originChainId = txV1.originChainId;
    txV2.destChainId = txV1.destChainId;
    txV2.originSender = txV1.originSender;
    txV2.destRecipient = txV1.destRecipient;
    txV2.originToken = txV1.originToken;
    txV2.destToken = txV1.destToken;
    txV2.originAmount = txV1.originAmount;
    txV2.destAmount = txV1.destAmount;
    txV2.originFeeAmount = txV1.originFeeAmount;
    txV2.deadline = txV1.deadline;
    txV2.nonce = txV1.nonce;
+   txV2.callValue = 0;
+   txV2.callParams = bytes("");
}

Alternatively, if callValue and callParams are available in txV1, copy them accordingly:

+   txV2.callValue = txV1.callValue;
+   txV2.callParams = txV1.callParams;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 432c34e and c38f34c.

📒 Files selected for processing (1)
  • packages/contracts-rfq/test/FastBridgeV2.t.sol (3 hunks)
🧰 Additional context used
🔇 Additional comments (3)
packages/contracts-rfq/test/FastBridgeV2.t.sol (3)

131-133: Initialization of new fields in BridgeParamsV2 is correctly implemented.

The callValue and callParams fields are properly initialized in both tokenParamsV2 and ethParamsV2, ensuring that the new parameters are correctly set up for testing purposes.

Also applies to: 138-140


172-175: Method setTokenTestCallValue correctly updates test parameters.

The function appropriately sets the callValue in both tokenParamsV2 and tokenTx, maintaining consistency in the test environment for token transactions.


191-194: Method setEthTestCallValue correctly updates test parameters.

This function accurately sets the callValue in both ethParamsV2 and ethTx, ensuring consistency for ETH transactions in the tests.

Copy link
Collaborator

@parodime parodime left a comment

Choose a reason for hiding this comment

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

LGTM

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.

3 participants