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

Add revert handling to the Swap example #219

Merged
merged 70 commits into from
Dec 6, 2024
Merged

Add revert handling to the Swap example #219

merged 70 commits into from
Dec 6, 2024

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Nov 22, 2024

Added revert handling to the swap contract to handle scenarios where withdraw function fails on destination chain.

To test add this:

    fallback() external payable {
        revert("");
    }

    receive() external payable {
        revert("");
    }

And then withdraw tokens to the same swap contract on localnet, it will revert and trigger onRevert, which will send tokens back to the original sender.

Summary by CodeRabbit

  • New Features

    • Introduced gas management enhancements in the Swap and SwapToAnyToken contracts.
    • Added new error handling types for improved transaction reliability.
    • Updated contract functions for better handling of token swaps and withdrawals.
  • Bug Fixes

    • Improved error handling during token approvals and transfers.
  • Chores

    • Modified deployment scripts for better contract interaction on local networks.
    • Enhanced deployment tasks to allow specification of gas limits.

Copy link

coderabbitai bot commented Nov 22, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant enhancements to the Swap and SwapToAnyToken contracts, focusing on gas management and error handling. Key changes include the addition of an immutable gasLimit variable, updated constructors to accept this parameter, and new error types for improved error management. The swapAndWithdraw function is refactored into handleGasAndSwap, which returns multiple values for better control over gas fees. Modifications to the withdraw function improve token approval handling, while the deployment script and task definitions are updated to reflect these changes, ensuring smoother contract interactions.

Changes

File Path Change Summary
examples/swap/contracts/Swap.sol - Added uint256 public immutable gasLimit.
- Introduced errors: ApprovalFailed, Unauthorized.
- Updated constructor to accept gasLimitAmount.
- Refactored swapAndWithdraw to handleGasAndSwap.
- Updated withdraw function for gas fee handling.
- Modified onRevert function.
- Added fallback and receive functions.
examples/swap/contracts/SwapToAnyToken.sol - Added uint256 public immutable gasLimit.
- Introduced errors: ApprovalFailed, TransferFailed.
- Updated constructor to accept gasLimitAmount.
- Renamed swapAndWithdraw to swap.
- Added handleGasAndSwap function.
- Updated withdraw function for approval checks.
- Modified onRevert function.
- Added fallback and receive functions.
examples/swap/scripts/localnet.sh - Added variable ZRC20_BNB.
- Updated CONTRACT_ZETACHAIN to CONTRACT_SWAP.
- Added CONTRACT_SWAPTOANY for new contract deployment.
- Updated deployment and interaction logic for new contracts.
examples/swap/tasks/deploy.ts - Updated import statement for task function.
- Added args.gasLimit parameter to contract deployment.
- Updated task definition to include optional gasLimit parameter.

Possibly related PRs

Suggested reviewers

  • andresaiello

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@fadeev fadeev changed the base branch from main to auth-call-hello-swap November 22, 2024 07:36
examples/swap/contracts/Swap.sol Fixed Show fixed Hide fixed
examples/swap/contracts/Swap.sol Fixed Show fixed Hide fixed
examples/swap/contracts/Swap.sol Fixed Show fixed Hide fixed
examples/swap/contracts/Swap.sol Fixed Show fixed Hide fixed
examples/swap/contracts/Swap.sol Fixed Show fixed Hide fixed
examples/swap/contracts/Swap.sol Fixed Show fixed Hide fixed
examples/swap/contracts/Swap.sol Fixed Show fixed Hide fixed
@fadeev fadeev marked this pull request as ready for review November 22, 2024 16:04
@fadeev fadeev requested a review from andresaiello as a code owner November 22, 2024 16:04
@fadeev fadeev changed the title swap revert Add revert handling to the Swap example Nov 24, 2024
Base automatically changed from auth-call-hello-swap to main November 24, 2024 17:09
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (5)
examples/swap/tasks/deploy.ts (2)

49-53: Enhance gasLimit parameter documentation

While the parameter is correctly defined, the documentation could be more specific.

   .addOptionalParam(
     "gasLimit",
-    "Gas limit for the transaction",
+    "Gas limit for the transaction in gas units (minimum recommended: 1,000,000)",
     1000000,
     types.int
   );

Line range hint 1-53: Consider adding dynamic gas estimation

Currently, the gas limit is hardcoded with a default value. For production deployments, consider implementing dynamic gas estimation based on network conditions and contract complexity.

You could:

  1. Add a gas estimation function that simulates the deployment
  2. Use the estimated value as the default instead of a fixed number
  3. Add a safety margin (e.g., 20%) to the estimated value
examples/swap/scripts/localnet.sh (3)

12-16: Remove unused GATEWAY_ETHEREUM variable

The GATEWAY_ETHEREUM variable is declared but never used in the script. Consider removing it to maintain code cleanliness.

 ZRC20_BNB=$(jq -r '.addresses[] | select(.type=="ZRC-20 BNB on 97") | .address' localnet.json)
-GATEWAY_ETHEREUM=$(jq -r '.addresses[] | select(.type=="gatewayEVM" and .chain=="ethereum") | .address' localnet.json)
 GATEWAY_ZETACHAIN=$(jq -r '.addresses[] | select(.type=="gatewayZEVM" and .chain=="zetachain") | .address' localnet.json)
🧰 Tools
🪛 Shellcheck (0.10.0)

[warning] 13-13: GATEWAY_ETHEREUM appears unused. Verify use (or export if used externally).

(SC2034)


18-23: Add error handling for contract deployments

While the deployments are well-structured, consider adding error handling to ensure the script fails gracefully if deployments are unsuccessful.

+if ! CONTRACT_SWAP=$(npx hardhat deploy --name Swap --network localhost --gateway "$GATEWAY_ZETACHAIN" --uniswap-router "$UNISWAP_ROUTER" --json | jq -r '.contractAddress'); then
+    echo "Failed to deploy Swap contract"
+    exit 1
+fi
-CONTRACT_SWAP=$(npx hardhat deploy --name Swap --network localhost --gateway "$GATEWAY_ZETACHAIN" --uniswap-router "$UNISWAP_ROUTER" --json | jq -r '.contractAddress')
 echo -e "\n🚀 Deployed Swap contract on ZetaChain: $CONTRACT_SWAP"

+if ! CONTRACT_SWAPTOANY=$(npx hardhat deploy --name SwapToAnyToken --network localhost --gateway "$GATEWAY_ZETACHAIN" --uniswap-router "$UNISWAP_ROUTER" --json | jq -r '.contractAddress'); then
+    echo "Failed to deploy SwapToAnyToken contract"
+    exit 1
+fi
-CONTRACT_SWAPTOANY=$(npx hardhat deploy --name SwapToAnyToken --network localhost --gateway "$GATEWAY_ZETACHAIN" --uniswap-router "$UNISWAP_ROUTER" --json | jq -r '.contractAddress')
 echo -e "\n🚀 Deployed SwapToAny contract on ZetaChain: $CONTRACT_SWAPTOANY"

24-71: Document the purpose of each swap operation

The script includes multiple swap operations with different configurations, but their specific purposes are not documented. Consider adding comments to explain the test scenarios being covered.

+# Test 1: Swap with immediate withdrawal
 npx hardhat swap-from-evm \
   --network localhost \
   --receiver "$CONTRACT_SWAP" \
   --amount 1 \
   --target "$ZRC20_BNB" \
   --recipient "$SENDER"

 npx hardhat localnet-check

+# Test 2: Swap without immediate withdrawal
 npx hardhat swap-from-evm \
   --network localhost \
   --receiver "$CONTRACT_SWAP" \
   --amount 1 \
   --target "$ZRC20_BNB" \
   --recipient "$SENDER" \
   --withdraw false

+# Test 3: SwapToAnyToken with immediate withdrawal
 npx hardhat swap-from-evm \
   --network localhost \
   --receiver "$CONTRACT_SWAPTOANY" \
   --amount 1 \
   --target "$ZRC20_BNB" \
   --recipient "$SENDER"

+# Test 4: SwapToAnyToken without immediate withdrawal
 npx hardhat swap-from-evm \
   --network localhost \
   --receiver "$CONTRACT_SWAPTOANY" \
   --amount 1 \
   --target "$ZRC20_BNB" \
   --recipient "$SENDER" \
   --withdraw false

+# Test 5: Cross-chain swap from ZetaChain to Ethereum
 npx hardhat swap-from-zetachain \
   --network localhost \
   --contract "$CONTRACT_SWAPTOANY" \
   --amount 1 \
   --zrc20 "$ZRC20_BNB" \
   --target "$ZRC20_ETHEREUM" \
   --recipient "$SENDER"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 02373a6 and 77418a8.

📒 Files selected for processing (4)
  • examples/swap/contracts/Swap.sol (3 hunks)
  • examples/swap/contracts/SwapToAnyToken.sol (2 hunks)
  • examples/swap/scripts/localnet.sh (1 hunks)
  • examples/swap/tasks/deploy.ts (3 hunks)
🧰 Additional context used
🪛 Shellcheck (0.10.0)
examples/swap/scripts/localnet.sh

[warning] 13-13: GATEWAY_ETHEREUM appears unused. Verify use (or export if used externally).

(SC2034)

🔇 Additional comments (7)
examples/swap/tasks/deploy.ts (2)

1-1: LGTM: Clean import addition

The addition of types import is appropriate for type-safe parameter definition.


17-18: Verify gas limit sufficiency for revert scenarios

The gas limit parameter is now properly passed to the contract constructor. However, we should verify if the default value of 1,000,000 gas units is sufficient for complex operations involving reverts.

✅ Verification successful

Gas limit value is appropriate for complex operations

Based on the contract analysis, the gas limit of 1,000,000 units is sufficient for the contract's operations. The contract includes multiple gas-intensive operations:

  • Complex swap operations through Uniswap router
  • Multiple token approvals and transfers
  • Revert handling with message encoding/decoding
  • Cross-chain message passing via gateway

The gas limit aligns with similar production patterns and provides adequate headroom for these operations, including revert scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for gas-consuming operations in the contract
rg -A 5 "withdraw|revert|transfer|call" --type solidity

# Look for existing gas estimations or similar deployments
rg -A 5 "gasLimit|gas:" --type yaml --type json

Length of output: 140


Script:

#!/bin/bash
# Search for Solidity files first
fd -e sol

# Search for gas-consuming operations in all files (without file type filter)
rg -A 5 "withdraw|revert|transfer|call"

# Look for gas configurations in TypeScript/JavaScript files
rg -A 5 "gasLimit|gas:" -g "*.{ts,js}"

# Look for deployment configurations
fd -e json -e yaml | xargs cat

Length of output: 131156


Script:

#!/bin/bash
# Search for Solidity files in the swap example to analyze gas usage
fd -e sol -p examples/swap/contracts | xargs cat

# Look for gas limit configurations in the deployment tasks
rg -A 5 "gasLimit.*=.*[0-9]+" examples/swap/tasks/deploy.ts

Length of output: 12435

examples/swap/scripts/localnet.sh (1)

Line range hint 1-71: Add test case for revert handling

The PR's main objective is to add revert handling for failed withdrawals, but the script doesn't explicitly test this scenario. Consider adding a test case where the withdrawal is expected to fail and trigger the onRevert function.

Would you like me to provide an example test case that verifies the revert handling functionality?

🧰 Tools
🪛 Shellcheck (0.10.0)

[warning] 11-11: ZRC20_USDC appears unused. Verify use (or export if used externally).

(SC2034)


[warning] 13-13: GATEWAY_ETHEREUM appears unused. Verify use (or export if used externally).

(SC2034)

examples/swap/contracts/SwapToAnyToken.sol (4)

19-19: LGTM: Added gasLimit as an immutable state variable

The addition of the uint256 public immutable gasLimit; enhances the contract by ensuring the gasLimit remains constant after deployment.


23-24: LGTM: Added custom errors for ApprovalFailed and TransferFailed

Defining specific errors improves clarity and gas efficiency during error handling.


80-85: Refactoring enhances modularity and readability

The use of handleGasAndSwap function improves code organization by separating concerns and reusing logic.


203-226: Revert handling logic is correctly implemented

The onRevert function appropriately handles reversion scenarios by decoding the revert message, recalculating the swap, and withdrawing the assets back to the sender. The usage of gasLimit ensures that gas fees are managed effectively.

Comment on lines +175 to +177
fallback() external payable {}

receive() external payable {}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure fallback and receive functions revert as intended

The fallback and receive functions are currently empty, which means they will accept Ether sent to the contract without any action. According to the PR objectives, these functions should revert when called to handle cases where the withdraw function fails on the destination chain. This ensures that any unexpected Ether transfers are properly rejected and the onRevert function is triggered appropriately.

Apply this diff to make the functions revert when called:

-fallback() external payable {}
+fallback() external payable {
+    revert("");
+}

-receive() external payable {}
+receive() external payable {
+    revert("");
+}
📝 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
fallback() external payable {}
receive() external payable {}
fallback() external payable {
revert("");
}
receive() external payable {
revert("");
}

Comment on lines +31 to +35
constructor(
address payable gatewayAddress,
address uniswapRouterAddress,
uint256 gasLimitAmount
) {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for gasLimitAmount in the constructor

It's recommended to validate the gasLimitAmount parameter in the constructor to ensure it's within an acceptable range (e.g., greater than zero). This prevents potential misconfigurations that could lead to failed transactions due to insufficient gas limits.

Apply this suggested change:

     constructor(
         address payable gatewayAddress,
         address uniswapRouterAddress,
         uint256 gasLimitAmount
     ) {
+        if (gasLimitAmount == 0) {
+            revert InvalidGasLimit();
+        }
         if (gatewayAddress == address(0) || uniswapRouterAddress == address(0))
             revert InvalidAddress();
         uniswapRouter = uniswapRouterAddress;
         gateway = GatewayZEVM(gatewayAddress);
         gasLimit = gasLimitAmount;
     }

Add a new error declaration:

+    error InvalidGasLimit();

Also applies to: 40-40

Comment on lines +193 to +199
bool success = IWETH9(params.target).transfer(
address(uint160(bytes20(params.to))),
out
);
if (!success) {
revert TransferFailed();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use IZRC20 interface instead of IWETH9 for token transfers

In the withdraw function, when params.withdraw is false, the contract attempts to transfer tokens using the IWETH9 interface:

bool success = IWETH9(params.target).transfer(
    address(uint160(bytes20(params.to))),
    out
);

Unless params.target is guaranteed to be an IWETH9 compliant token, this may result in unexpected behavior. It is recommended to use the IZRC20 interface for standard token transfers to ensure compatibility with general ERC20 tokens.

Apply the following change:

-bool success = IWETH9(params.target).transfer(
+bool success = IZRC20(params.target).transfer(
    address(uint160(bytes20(params.to))),
    out
);

Comment on lines +228 to +230
fallback() external payable {}

receive() external payable {}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure fallback and receive functions revert as per PR objectives

According to the PR objectives, the fallback and receive functions should revert when called to handle situations where the withdraw function may fail on the destination chain. The current implementation adds empty functions that do not revert. To align with the intended functionality, these functions should be modified to revert upon invocation.

Apply the following changes:

-fallback() external payable {}
+fallback() external payable {
+    revert("");
+}

-receive() external payable {}
+receive() external payable {
+    revert("");
+}
📝 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
fallback() external payable {}
receive() external payable {}
fallback() external payable {
revert("");
}
receive() external payable {
revert("");
}

Comment on lines +132 to +157
uint256 swapAmount;

if (withdraw) {
(gasZRC20, gasFee) = IZRC20(targetToken).withdrawGasFee();
(gasZRC20, gasFee) = IZRC20(targetToken).withdrawGasFee();

if (gasZRC20 == inputToken) {
swapAmount = amount - gasFee;
} else {
inputForGas = SwapHelperLib.swapTokensForExactTokens(
uniswapRouter,
inputToken,
gasFee,
gasZRC20,
amount
);
swapAmount = amount - inputForGas;
}
if (gasZRC20 == inputToken) {
swapAmount = amount - gasFee;
} else {
inputForGas = SwapHelperLib.swapTokensForExactTokens(
uniswapRouter,
inputToken,
gasFee,
gasZRC20,
amount
);
swapAmount = amount - inputForGas;
}

uint256 outputAmount = SwapHelperLib.swapExactTokensForTokens(
uint256 out = SwapHelperLib.swapExactTokensForTokens(
uniswapRouter,
inputToken,
swapAmount,
targetToken,
0
);
return (out, gasZRC20, gasFee);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure swapAmount is validated to be greater than zero

The swapAmount might be zero if gasFee equals amount or inputForGas equals amount, leading to potential issues when performing swaps with zero amount. It's prudent to add a check to ensure that swapAmount > 0 before proceeding.

Implement the following check:

     if (gasZRC20 == inputToken) {
         swapAmount = amount - gasFee;
+        require(swapAmount > 0, "Swap amount must be greater than zero");
     } else {
         inputForGas = SwapHelperLib.swapTokensForExactTokens(
             uniswapRouter,
             inputToken,
             gasFee,
             gasZRC20,
             amount
         );
         swapAmount = amount - inputForGas;
+        require(swapAmount > 0, "Swap amount must be greater than zero");
     }
📝 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
uint256 swapAmount;
if (withdraw) {
(gasZRC20, gasFee) = IZRC20(targetToken).withdrawGasFee();
(gasZRC20, gasFee) = IZRC20(targetToken).withdrawGasFee();
if (gasZRC20 == inputToken) {
swapAmount = amount - gasFee;
} else {
inputForGas = SwapHelperLib.swapTokensForExactTokens(
uniswapRouter,
inputToken,
gasFee,
gasZRC20,
amount
);
swapAmount = amount - inputForGas;
}
if (gasZRC20 == inputToken) {
swapAmount = amount - gasFee;
} else {
inputForGas = SwapHelperLib.swapTokensForExactTokens(
uniswapRouter,
inputToken,
gasFee,
gasZRC20,
amount
);
swapAmount = amount - inputForGas;
}
uint256 outputAmount = SwapHelperLib.swapExactTokensForTokens(
uint256 out = SwapHelperLib.swapExactTokensForTokens(
uniswapRouter,
inputToken,
swapAmount,
targetToken,
0
);
return (out, gasZRC20, gasFee);
}
uint256 swapAmount;
(gasZRC20, gasFee) = IZRC20(targetToken).withdrawGasFee();
if (gasZRC20 == inputToken) {
swapAmount = amount - gasFee;
require(swapAmount > 0, "Swap amount must be greater than zero");
} else {
inputForGas = SwapHelperLib.swapTokensForExactTokens(
uniswapRouter,
inputToken,
gasFee,
gasZRC20,
amount
);
swapAmount = amount - inputForGas;
require(swapAmount > 0, "Swap amount must be greater than zero");
}
uint256 out = SwapHelperLib.swapExactTokensForTokens(
uniswapRouter,
inputToken,
swapAmount,
targetToken,
0
);
return (out, gasZRC20, gasFee);
}

Comment on lines +88 to +122
function swap(
address inputToken,
uint256 amount,
address targetToken,
bytes memory recipient,
bool withdraw
) internal {
bool withdrawFlag
) public {
bool success = IZRC20(inputToken).transferFrom(
msg.sender,
address(this),
amount
);
if (!success) {
revert TransferFailed();
}

(uint256 out, address gasZRC20, uint256 gasFee) = handleGasAndSwap(
inputToken,
amount,
targetToken
);

withdraw(
Params({
target: targetToken,
to: recipient,
withdraw: withdrawFlag
}),
msg.sender,
gasFee,
gasZRC20,
out,
inputToken
);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider adding reentrancy protection to the swap function

The swap function involves token transfers and external calls, which could potentially be exploited in a reentrancy attack. It is advisable to add reentrancy protection using OpenZeppelin's ReentrancyGuard by inheriting from it and applying the nonReentrant modifier to the swap function.

Apply the following changes:

  1. Import ReentrancyGuard and inherit from it:
+import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

-contract SwapToAnyToken is UniversalContract {
+contract SwapToAnyToken is UniversalContract, ReentrancyGuard {
     address public immutable uniswapRouter;
     GatewayZEVM public gateway;
     uint256 constant BITCOIN = 18332;
     uint256 public immutable gasLimit;
  1. Apply the nonReentrant modifier to the swap function:
     function swap(
         address inputToken,
         uint256 amount,
         address targetToken,
         bytes memory recipient,
         bool withdrawFlag
-    ) public {
+    ) public nonReentrant {
📝 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
function swap(
address inputToken,
uint256 amount,
address targetToken,
bytes memory recipient,
bool withdraw
) internal {
bool withdrawFlag
) public {
bool success = IZRC20(inputToken).transferFrom(
msg.sender,
address(this),
amount
);
if (!success) {
revert TransferFailed();
}
(uint256 out, address gasZRC20, uint256 gasFee) = handleGasAndSwap(
inputToken,
amount,
targetToken
);
withdraw(
Params({
target: targetToken,
to: recipient,
withdraw: withdrawFlag
}),
msg.sender,
gasFee,
gasZRC20,
out,
inputToken
);
}
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract SwapToAnyToken is UniversalContract, ReentrancyGuard {
address public immutable uniswapRouter;
GatewayZEVM public gateway;
uint256 constant BITCOIN = 18332;
uint256 public immutable gasLimit;
function swap(
address inputToken,
uint256 amount,
address targetToken,
bytes memory recipient,
bool withdrawFlag
) public nonReentrant {
bool success = IZRC20(inputToken).transferFrom(
msg.sender,
address(this),
amount
);
if (!success) {
revert TransferFailed();
}
(uint256 out, address gasZRC20, uint256 gasFee) = handleGasAndSwap(
inputToken,
amount,
targetToken
);
withdraw(
Params({
target: targetToken,
to: recipient,
withdraw: withdrawFlag
}),
msg.sender,
gasFee,
gasZRC20,
out,
inputToken
);
}

@fadeev fadeev merged commit 08d15c5 into main Dec 6, 2024
13 checks passed
@fadeev fadeev deleted the swap-revert branch December 6, 2024 10:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants