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

refactor(SwapHelperLib)!: replace system contract with uniswap router address #197

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Nov 18, 2024

System contract is being deprecated, so I've replaced it with Uniswap router.

Summary by CodeRabbit

  • New Features

    • Enhanced flexibility of the swap library by allowing it to work with any router conforming to the IUniswapV2Router01 interface.
    • Updated token swap functions to dynamically retrieve necessary addresses, improving modularity and usability.
  • Bug Fixes

    • Improved logic for checking pair pool existence and liquidity sufficiency by utilizing the router's factory address.

@fadeev fadeev requested review from andresaiello and a team as code owners November 18, 2024 05:21
Copy link
Contributor

coderabbitai bot commented Nov 18, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant modifications to the SwapHelperLib library in contracts/SwapHelperLib.sol. The primary change is the removal of the SystemContract parameter from several function signatures, replaced by an address router parameter. This adjustment allows the library to retrieve factory and WETH addresses directly from the IUniswapV2Router01 interface, enhancing its modularity. Additionally, the logic for checking pair pool existence has been updated to use the new factory address, and the token swap paths now utilize the WETH address from the router, eliminating reliance on a specific system contract.

Changes

File Change Summary
contracts/SwapHelperLib.sol - Updated method signatures to replace SystemContract with address router for several functions:
- swapExactTokensForTokens
- swapExactTokensForTokensDirectly
- swapTokensForExactTokens
- getMinOutAmount
- Updated logic for pair pool existence checks and token swap paths to use addresses retrieved from the router.

Possibly related PRs

  • feat: Swap helpers to always swap through ZETA #163: The changes in this PR also modify the swapExactTokensForTokens function in SwapHelperLib, which is directly related to the main PR's updates to the same function, indicating a shared focus on enhancing the token swapping mechanism.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between defaa9e and f593e45.

📒 Files selected for processing (1)
  • contracts/SwapHelperLib.sol (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/SwapHelperLib.sol

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.

@fadeev fadeev changed the title SwapHelperLib: replace system contract with uniswap router address refactor!: SwapHelperLib: replace system contract with uniswap router address Nov 18, 2024
@fadeev fadeev changed the title refactor!: SwapHelperLib: replace system contract with uniswap router address refactor(SwapHelperLib)!: replace system contract with uniswap router address Nov 18, 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: 9

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 78fa8d7 and defaa9e.

⛔ Files ignored due to path filters (28)
  • typechain-types/@openzeppelin/contracts/index.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC1155Errors.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC20Errors.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC721Errors.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/index.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/index.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/token/ERC20/ERC20.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/token/ERC20/IERC20.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.ts is excluded by !typechain-types/**
  • typechain-types/contracts/EthZetaMock.sol/ZetaEthMock.ts is excluded by !typechain-types/**
  • typechain-types/contracts/SwapHelperLib.ts is excluded by !typechain-types/**
  • typechain-types/contracts/TestZRC20.ts is excluded by !typechain-types/**
  • typechain-types/contracts/shared/MockZRC20.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/index.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC1155Errors__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC20Errors__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC721Errors__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/index.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/index.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/token/ERC20/ERC20__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/token/ERC20/IERC20__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/contracts/EthZetaMock.sol/ZetaEthMock__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/contracts/SwapHelperLib__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/contracts/TestZRC20__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/contracts/shared/MockZRC20__factory.ts is excluded by !typechain-types/**
  • typechain-types/hardhat.d.ts is excluded by !typechain-types/**
  • typechain-types/index.ts is excluded by !typechain-types/**
📒 Files selected for processing (1)
  • contracts/SwapHelperLib.sol (6 hunks)
🔇 Additional comments (1)
contracts/SwapHelperLib.sol (1)

140-140: ⚠️ Potential issue

Potential Path Error: wzeta May Not Be the Correct Intermediate Token

Setting path[1] = wzeta assumes that wzeta is the correct intermediate token for swaps involving zrc20 and targetZRC20. If wzeta does not represent the intended token, the swap path may be incorrect, leading to failed transactions or asset loss.

Ensure that wzeta is the correct intermediary token for the swap. If not, update the code to use the appropriate token:

-            path[1] = wzeta;
+            path[1] = wZetaAddress; // Replace with the correct wZETA address

Likely invalid or redundant comment.

uint256[] memory amounts = IUniswapV2Router01(
systemContract.uniswapv2Router02Address()
).swapTokensForExactTokens(
IZRC20(zrc20).approve(router, amountInMax);
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Approval Addresses Need Standardization

The verification reveals inconsistent approval addresses across the contract:

  • Line 1: Approves targetZRC20 for gas fee handling
  • Line 2: Approves address(router) explicitly cast
  • Line 3: Approves wzeta for token swaps
  • Line 4: Approves router directly

While the specific line in question uses router, there's inconsistency in how router approvals are handled (address(router) vs router). Additionally, other approvals to different addresses (targetZRC20, wzeta) exist for specific purposes.

🔗 Analysis chain

Inconsistent Approval Address: Ensure Approval is Granted to router

In the swapTokensForExactTokens function, confirm that the approval is correctly set to the router address and not any other contract.

Run the following script to check for inconsistencies in approval addresses:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all approvals are granted to the `router` address.

# Search for approval statements in the contract
rg 'approve\(([^,]+),' contracts/SwapHelperLib.sol -A 2

# Expected result: All `approve` calls should target `router`.

Length of output: 661

uint256[] memory amounts = IUniswapV2Router01(
systemContract.uniswapv2Router02Address()
).swapExactTokensForTokens(
IZRC20(zrc20).approve(wzeta, amount);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect Approval: Approving wzeta Instead of router

In the line IZRC20(zrc20).approve(wzeta, amount);, the contract approves wzeta to spend amount of zrc20 tokens. This seems incorrect, as typically, the approval should be granted to the router, not to wzeta.

Update the approval to target the router address:

-        IZRC20(zrc20).approve(wzeta, amount);
+        IZRC20(zrc20).approve(router, amount);

This aligns with the pattern used in other functions and ensures the router can execute the swap.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
IZRC20(zrc20).approve(wzeta, amount);
IZRC20(zrc20).approve(router, amount);

uint256[] memory amounts = IUniswapV2Router01(
systemContract.uniswapv2Router02Address()
).swapExactTokensForTokens(
IZRC20(zrc20).approve(address(router), amount);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security Concern: Approving Unverified router to Spend Tokens

Approving the router to spend amount of zrc20 tokens without ensuring the router is trusted poses a significant security risk. If the router address is malicious, it could drain tokens from the contract.

Before granting approval, validate the router address:

+        require(isTrustedRouter(router), "SwapHelperLib: Untrusted router address");
         IZRC20(zrc20).approve(address(router), amount);

Implement or update the isTrustedRouter function to perform proper validation.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +163 to +165
address factory = IUniswapV2Router01(router).factory();
address wzeta = IUniswapV2Router01(router).WETH();

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Repeat Validation: Ensure Consistent router Address Checks

Similar to earlier functions, the swapExactTokensForTokensDirectly function uses the router address to obtain factory and wzeta without validation.

Add validation for the router address before using it:

+        require(isTrustedRouter(router), "SwapHelperLib: Untrusted router address");
         address factory = IUniswapV2Router01(router).factory();
         address wzeta = IUniswapV2Router01(router).WETH();

Ensure that this validation is consistently applied across all functions that use the router address.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
address factory = IUniswapV2Router01(router).factory();
address wzeta = IUniswapV2Router01(router).WETH();
require(isTrustedRouter(router), "SwapHelperLib: Untrusted router address");
address factory = IUniswapV2Router01(router).factory();
address wzeta = IUniswapV2Router01(router).WETH();

amount,
minAmountOut,
path
);

bool isZETA = targetZRC20 == systemContract.wZetaContractAddress() ||
zrc20 == systemContract.wZetaContractAddress();
bool isZETA = targetZRC20 == wzeta || zrc20 == wzeta;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect Comparison: wzeta May Not Correspond to wZETA Token

The comparison targetZRC20 == wzeta || zrc20 == wzeta relies on wzeta being the correct wZETA token address. If wzeta is obtained from router.WETH() and does not represent the wZETA token on ZetaChain, this comparison may fail or produce unintended results.

Confirm that wzeta represents the correct wZETA token address. If necessary, adjust the code to retrieve the correct address or compare against the proper token:

-        bool isZETA = targetZRC20 == wzeta || zrc20 == wzeta;
+        address wZetaAddress = /* obtain correct wZETA address */;
+        bool isZETA = targetZRC20 == wZetaAddress || zrc20 == wZetaAddress;

Committable suggestion skipped: line range outside the PR's diff.

address zrc20,
uint256 amount,
address targetZRC20,
uint256 minAmountOut
) internal returns (uint256) {
address factory = IUniswapV2Router01(router).factory();
address wzeta = IUniswapV2Router01(router).WETH();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential Mismatch: WETH() May Not Return wZETA Address

The WETH() function in the IUniswapV2Router01 interface typically returns the address of the Wrapped Ether (WETH) token on Ethereum. In the context of ZetaChain, this may not correspond to the wZETA token as intended.

Verify that router.WETH() correctly returns the wZETA address in the ZetaChain environment. If not, consider modifying the contract to retrieve the correct wZETA address:

-        address wzeta = IUniswapV2Router01(router).WETH();
+        address wzeta = IWZETA(wzetaContractAddress).address;

Ensure that the correct interface or method is used to obtain the wZETA address.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +234 to +236
address factory = IUniswapV2Router01(router).factory();
address wzeta = IUniswapV2Router01(router).WETH();

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validation Required: Unverified Use of router in View Function

The getMinOutAmount function uses the router to obtain factory and wzeta addresses without validation. Despite being a view function, it could still return incorrect values if router is untrusted.

Add a validation check for the router address:

+        require(isTrustedRouter(router), "SwapHelperLib: Untrusted router address");
         address factory = IUniswapV2Router01(router).factory();
         address wzeta = IUniswapV2Router01(router).WETH();

Ensure that all functions interacting with external contracts validate input addresses.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +114 to 118
address router,
address zrc20,
uint256 amount,
address targetZRC20,
uint256 minAmountOut
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical Security Concern: Validate the router Address

The function now accepts an address router parameter. Since this address is used to interact with external contracts and is critical for the swapping functionality, it's imperative to ensure that the router address provided is a trusted Uniswap router contract. Passing an unverified router address could lead to interactions with malicious contracts, resulting in loss of funds or other security breaches.

Consider adding a validation mechanism to ensure the router address is trusted:

+        require(isTrustedRouter(router), "SwapHelperLib: Untrusted router address");

Implement the isTrustedRouter function to check the router address against a whitelist of known, trusted router addresses.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +120 to +121
address factory = IUniswapV2Router01(router).factory();
address wzeta = IUniswapV2Router01(router).WETH();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security Risk: Relying on Unverified router for Critical Addresses

By obtaining the factory and wzeta addresses directly from the unvalidated router, there's a risk of retrieving incorrect or malicious addresses. This could compromise the integrity of the swapping operations and lead to potential security vulnerabilities.

Ensure that the router address is validated before using it to obtain critical addresses:

+        require(isTrustedRouter(router), "SwapHelperLib: Untrusted router address");
         address factory = IUniswapV2Router01(router).factory();
         address wzeta = IUniswapV2Router01(router).WETH();

Alternatively, consider obtaining factory and wzeta from trusted sources or passing them as parameters after validation.

Committable suggestion skipped: line range outside the PR's diff.

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.

1 participant