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): Synapse Intent Router #3433

Open
wants to merge 7 commits into
base: master
Choose a base branch
from

Conversation

ChiTimesChi
Copy link
Collaborator

@ChiTimesChi ChiTimesChi commented Dec 3, 2024

Description
Synapse Intent Router (or just SIR) is a contract that completes the user intents using a series of generic Zap steps (see #3352 for more details about Zaps). Actions like swapping, depositing, bridging, sending tokens and many others are supported as long as they could be represented as a Zap.

Contract exposes two entry points with minor differences: completeIntent and completeIntentWithBalanceChecks:

  • Both functions have a deadline protection.
  • Both functions have a slippage protection in a form of "minimum amount used for the last action". Additionally the user is encouraged to embed the slippage protection in the parameters of the last action.
  • completeIntentWithBalanceChecks also verifies that no leftover tokens are left in the auxilary ZapRecipient contract used for performing the Zap steps.

Summary by CodeRabbit

  • New Features

    • Introduced the ISynapseIntentRouter interface for executing complex token transfers with balance checks.
    • Added custom error handling for various scenarios in the ISynapseIntentRouterErrors interface.
    • Implemented the SynapseIntentRouter contract to manage and execute "zap" operations.
    • Created a mock liquidity pool contract for testing token swaps.
    • Enhanced WETHMock contract to support token minting.
  • Bug Fixes

    • Improved error handling and validation in the SynapseIntentRouter for better user experience.
  • Tests

    • Comprehensive test suite for SynapseIntentRouter, validating functionality and error conditions.

Copy link
Contributor

coderabbitai bot commented Dec 3, 2024

Walkthrough

The pull request introduces several new files and functionalities related to the Synapse Intent Router. It adds an interface, ISynapseIntentRouter, defining methods for executing token transfers with balance checks. A new contract, SynapseIntentRouter, implements this interface, providing logic for managing "zap" operations. Additionally, error handling is enhanced through the ISynapseIntentRouterErrors interface, and mock contracts are created for testing purposes. Comprehensive test suites validate the behavior of the router, ensuring robustness and correctness in various scenarios.

Changes

File Path Change Summary
packages/contracts-rfq/contracts/interfaces/ISynapseIntentRouter.sol Added ISynapseIntentRouter interface and StepParams struct; implemented completeIntentWithBalanceChecks and completeIntent functions.
packages/contracts-rfq/contracts/interfaces/ISynapseIntentRouterErrors.sol Introduced ISynapseIntentRouterErrors interface with custom error types for better error handling.
packages/contracts-rfq/contracts/router/SynapseIntentRouter.sol Implemented SynapseIntentRouter contract, including methods for executing intents with and without balance checks.
packages/contracts-rfq/test/mocks/PoolMock.sol Created PoolMock contract for testing, with functions for simulating token swaps and managing exchange rates.
packages/contracts-rfq/test/mocks/WETHMock.sol Modified WETHMock to inherit from CommonBase and added a mint function for token minting.
packages/contracts-rfq/test/router/SynapseIntentRouter.BalanceChecks.t.sol Added tests for balance checks in SynapseIntentRouter, validating various scenarios for handling unspent funds.
packages/contracts-rfq/test/router/SynapseIntentRouter.t.sol Established a test suite for SynapseIntentRouter, covering deposits, swaps, and error handling across multiple scenarios.

Possibly related PRs

Suggested labels

size/m, needs-go-generate-services/rfq

Suggested reviewers

  • aureliusbtc
  • parodime
  • trajan0x

🐰 In the code, we hop and play,
New interfaces lead the way.
With zaps and checks, we pave the road,
For smoother paths, our work bestowed.
Errors caught, no funds astray,
In this smart contract ballet! 🎉


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 the size/l label Dec 3, 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: 2

🧹 Outside diff range and nitpick comments (12)
packages/contracts-rfq/contracts/interfaces/ISynapseIntentRouter.sol (2)

2-2: Consider updating the Solidity pragma for consistency

The current Solidity pragma is ^0.8.4, while other files like SynapseIntentRouter.sol use pragma solidity 0.8.24. Aligning the Solidity version across all related contracts can prevent potential compilation issues and ensure compatibility.


18-18: Define the "SIR" acronym upon first use

The abbreviation "SIR" is used without prior definition. For clarity, consider defining "SIR" (Synapse Intent Router) when it is first mentioned in the documentation.

packages/contracts-rfq/contracts/router/SynapseIntentRouter.sol (2)

19-19: Add documentation for the NATIVE_GAS_TOKEN special address

Including a comment explaining that 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE is used as a placeholder for the native gas token (e.g., ETH) can improve code readability and help other developers understand its purpose.


68-70: Optimize input validation using require statements

For consistency and readability, consider using require statements instead of if...revert for input validations:

- if (block.timestamp > deadline) revert SIR__DeadlineExceeded();
- if (length == 0) revert SIR__StepsNotProvided();
+ require(block.timestamp <= deadline, "SIR__DeadlineExceeded");
+ require(length != 0, "SIR__StepsNotProvided");
packages/contracts-rfq/contracts/interfaces/ISynapseIntentRouterErrors.sol (1)

2-2: Synchronize Solidity version pragma for consistency

The Solidity pragma is set to ^0.8.4, whereas other contracts like SynapseIntentRouter.sol use pragma solidity 0.8.24. Aligning the Solidity versions across all contracts can prevent compilation issues and maintain consistency.

packages/contracts-rfq/test/mocks/WETHMock.sol (2)

21-25: Clarify the use of vm.deal in the mint function

The mint function utilizes vm.deal to adjust the contract's balance for testing purposes. Since vm is a testing utility provided by Foundry, consider adding a comment to emphasize that this function should not be used in production code.


22-23: Prevent potential overflow in balance calculation

When calculating newBalance, adding amount to address(this).balance could potentially overflow. Although unlikely in tests, consider adding a check to prevent overflow:

uint256 newBalance = address(this).balance + amount;
require(newBalance >= address(this).balance, "Overflow in newBalance calculation");
packages/contracts-rfq/test/mocks/PoolMock.sol (3)

23-24: Enhance documentation clarity

The comment could be more explicit about why an empty test function prevents coverage reporting.

-    /// @notice We include an empty "test" function so that this contract does not appear in the coverage report.
+    /// @notice Empty function with "test" prefix to exclude this mock contract from coverage reports,
+    /// as test files starting with "test" are typically excluded from coverage analysis.

26-28: Consider adding access control

While this is a mock contract, consider adding access control to prevent unauthorized ratio changes during tests.

+    address private owner;
+
+    constructor(address token0_, address token1_) {
+        token0 = token0_;
+        token1 = token1_;
+        owner = msg.sender;
+    }
+
+    modifier onlyOwner() {
+        require(msg.sender == owner, "PoolMock: caller is not the owner");
+        _;
+    }

-    function setRatioWei(uint256 ratioWei_) external {
+    function setRatioWei(uint256 ratioWei_) external onlyOwner {
         ratioWei = ratioWei_;
     }

30-43: Add explicit overflow checks for ratio calculations

While Solidity 0.8+ includes overflow checks, consider adding explicit checks for better testing control.

     function swap(uint256 amountIn, address tokenIn) external returns (uint256 amountOut) {
         address tokenOut;
+        unchecked {
+            // Prevent overflow in intermediate calculations
+            require(amountIn <= type(uint256).max / ratioWei, "PoolMock: amount too large");
+        }
         if (tokenIn == token0) {
             tokenOut = token1;
             amountOut = amountIn * ratioWei / 1e18;
         } else if (tokenIn == token1) {
             tokenOut = token0;
             amountOut = amountIn * 1e18 / ratioWei;
         } else {
             revert PoolMock__TokenNotSupported();
         }
+        require(amountOut > 0, "PoolMock: zero amount out");
         IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
         IERC20(tokenOut).safeTransfer(msg.sender, amountOut);
     }
packages/contracts-rfq/test/router/SynapseIntentRouter.BalanceChecks.t.sol (2)

31-62: Consider adding edge case tests

While the current tests cover basic scenarios, consider adding tests for:

  • Zero amount deposits
  • Maximum uint256 amounts
  • Amounts that could cause overflow in intermediate calculations

66-206: Document magic numbers and constants

Consider adding documentation for constants like TOKEN_PRICE, FULL_BALANCE, and AMOUNT to explain their significance in the test scenarios.

+    /// @notice Standard test amount, chosen to be large enough to test meaningful operations
+    /// but small enough to avoid overflow concerns
     uint256 constant AMOUNT = /* current value */;
+
+    /// @notice Mock token price used for swap calculations
     uint256 constant TOKEN_PRICE = /* current value */;
+
+    /// @notice Represents the full balance available for testing
     uint256 constant FULL_BALANCE = /* current value */;
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9fe5765 and 0a3a1ad.

📒 Files selected for processing (7)
  • packages/contracts-rfq/contracts/interfaces/ISynapseIntentRouter.sol (1 hunks)
  • packages/contracts-rfq/contracts/interfaces/ISynapseIntentRouterErrors.sol (1 hunks)
  • packages/contracts-rfq/contracts/router/SynapseIntentRouter.sol (1 hunks)
  • packages/contracts-rfq/test/mocks/PoolMock.sol (1 hunks)
  • packages/contracts-rfq/test/mocks/WETHMock.sol (2 hunks)
  • packages/contracts-rfq/test/router/SynapseIntentRouter.BalanceChecks.t.sol (1 hunks)
  • packages/contracts-rfq/test/router/SynapseIntentRouter.t.sol (1 hunks)
🔇 Additional comments (3)
packages/contracts-rfq/test/router/SynapseIntentRouter.t.sol (1)

20-1035: Well-structured and comprehensive test suite

The test suite is extensive and covers multiple scenarios, ensuring that the SynapseIntentRouter functions correctly under various conditions. The use of helper functions and thorough checks contributes to the maintainability and reliability of the tests.

packages/contracts-rfq/test/mocks/PoolMock.sol (1)

1-15: LGTM! Well-structured contract declarations

Good use of SafeERC20 for secure token operations and appropriate use of immutable variables for token addresses.

packages/contracts-rfq/test/router/SynapseIntentRouter.BalanceChecks.t.sol (1)

1-28: LGTM! Well-implemented test helper function

The completeUserIntent override correctly implements balance checks using completeIntentWithBalanceChecks and properly simulates user context with vm.prank.

Copy link

codecov bot commented Dec 3, 2024

Codecov Report

Attention: Patch coverage is 97.50000% with 1 line in your changes missing coverage. Please review.

Please upload report for BASE (master@9fe5765). Learn more about missing BASE report.
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...racts-rfq/contracts/router/SynapseIntentRouter.sol 97.50000% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master       #3433   +/-   ##
============================================
  Coverage          ?   98.52008%           
============================================
  Files             ?          10           
  Lines             ?         473           
  Branches          ?           0           
============================================
  Hits              ?         466           
  Misses            ?           7           
  Partials          ?           0           
Flag Coverage Δ
solidity 98.52008% <97.50000%> (?)

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.

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.

1 participant