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

Swap: update to handle reverts #512

Merged
merged 1 commit into from
Dec 5, 2024
Merged

Swap: update to handle reverts #512

merged 1 commit into from
Dec 5, 2024

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Nov 29, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced the SwapToAnyToken contract to allow swapping tokens to any target token with options for withdrawal.
    • Introduced a new swap function for direct interactions on ZetaChain, improving user flexibility.
    • Added gas fee management features for more efficient cross-chain token swaps.
  • Bug Fixes

    • Improved error handling with new error types for approval and transfer failures.
  • Documentation

    • Updated tutorials to reflect the new functionality and changes in the contracts.

Copy link

vercel bot commented Nov 29, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview Nov 29, 2024 2:56pm

Copy link
Contributor

coderabbitai bot commented Nov 29, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant enhancements to the SwapToAnyToken and Swap contracts, allowing for improved functionality in token swaps, including cross-chain capabilities. Key modifications include the addition of a withdraw flag, updates to the constructor to accept a gasLimitAmount, and the introduction of new error types for better error handling. The swapAndWithdraw function has been replaced with a new swap function, and a handleGasAndSwap function has been added to manage gas fees and token swaps effectively.

Changes

File Path Change Summary
src/pages/developers/tutorials/swap-any.mdx - Constructor updated to accept gasLimitAmount.
- Added swap and handleGasAndSwap functions.
- Updated withdraw function visibility.
- Added onRevert function.
- Introduced ApprovalFailed and TransferFailed error types.
src/pages/developers/tutorials/swap.mdx - Added gasLimit variable and ApprovalFailed error.
- Constructor updated to accept gasLimitAmount.
- Refactored swapAndWithdraw to handleGasAndSwap.
- Updated onRevert function.

Possibly related PRs

Suggested reviewers

  • bbbeeeee
  • brewmaster012
  • 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
Copy link
Member Author

fadeev commented Nov 29, 2024

Related: zeta-chain/example-contracts#219

@fadeev fadeev marked this pull request as ready for review November 29, 2024 15:02
@fadeev fadeev requested review from bbbeeeee, brewmaster012 and a team as code owners November 29, 2024 15:02
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: 3

🧹 Outside diff range and nitpick comments (4)
src/pages/developers/tutorials/swap-any.mdx (2)

71-72: Consider enhancing error messages with context

The error types could be more informative by including relevant details about the failed operation.

-    error ApprovalFailed();
-    error TransferFailed();
+    error ApprovalFailed(address token, address spender, uint256 amount);
+    error TransferFailed(address token, address to, uint256 amount);

251-273: Enhance onRevert with better error handling and events

Add event emission and additional error handling for failed revert scenarios.

+    event RevertHandled(
+        address indexed sender,
+        address indexed originalAsset,
+        address indexed targetToken,
+        uint256 amount,
+        uint256 outputAmount
+    );

     function onRevert(RevertContext calldata context) external onlyGateway {
         (address sender, address zrc20) = abi.decode(
             context.revertMessage,
             (address, address)
         );
+        require(context.amount > 0, "Zero amount in revert");
+        require(zrc20 != address(0), "Invalid target token");

         (uint256 out, , ) = handleGasAndSwap(
             context.asset,
             context.amount,
             zrc20
         );

+        emit RevertHandled(sender, context.asset, zrc20, context.amount, out);
         // ... rest of the function
     }
src/pages/developers/tutorials/swap.mdx (2)

184-201: Consider refactoring approval checks to reduce duplication.

The approval checks contain duplicated logic that could be extracted into a helper function.

Consider refactoring like this:

+    function approveToken(address token, address spender, uint256 amount) internal returns (bool) {
+        if (!IZRC20(token).approve(spender, amount)) {
+            revert ApprovalFailed();
+        }
+        return true;
+    }

     function withdraw(...) public {
         if (gasZRC20 == params.target) {
-            if (
-                !IZRC20(gasZRC20).approve(
-                    address(gateway),
-                    outputAmount + gasFee
-                )
-            ) {
-                revert ApprovalFailed();
-            }
+            approveToken(gasZRC20, address(gateway), outputAmount + gasFee);
         } else {
-            if (!IZRC20(gasZRC20).approve(address(gateway), gasFee)) {
-                revert ApprovalFailed();
-            }
-            if (
-                !IZRC20(params.target).approve(address(gateway), outputAmount)
-            ) {
-                revert ApprovalFailed();
-            }
+            approveToken(gasZRC20, address(gateway), gasFee);
+            approveToken(params.target, address(gateway), outputAmount);
         }

207-213: Consider adding a constant for the empty address in RevertOptions.

The empty address (address(0)) is used in RevertOptions. Consider defining it as a constant for better maintainability.

+    address constant EMPTY_ADDRESS = address(0);

     RevertOptions({
         revertAddress: address(this),
         callOnRevert: true,
-        abortAddress: address(0),
+        abortAddress: EMPTY_ADDRESS,
         revertMessage: abi.encode(sender, inputToken),
         onRevertGasLimit: gasLimit
     })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between df80461 and 19440e3.

📒 Files selected for processing (2)
  • src/pages/developers/tutorials/swap-any.mdx (2 hunks)
  • src/pages/developers/tutorials/swap.mdx (3 hunks)
🔇 Additional comments (4)
src/pages/developers/tutorials/swap.mdx (4)

84-84: LGTM: Well-structured state variable and error definition additions.

The new gasLimit immutable variable and ApprovalFailed error enhance the contract's gas management and error handling capabilities.

Also applies to: 88-88


95-104: LGTM: Constructor properly handles initialization and validation.

The constructor correctly validates input addresses and initializes the immutable variables, including the new gasLimit.


133-138: LGTM: Improved function organization with clear separation of concerns.

The refactoring to use handleGasAndSwap enhances code maintainability by separating the swap logic from the withdrawal process.


217-238: LGTM: Well-implemented revert handling with proper gas management.

The onRevert function correctly handles revert scenarios by:

  • Properly decoding the revert context
  • Utilizing handleGasAndSwap for token management
  • Applying the configured gas limit

src/pages/developers/tutorials/swap-any.mdx Show resolved Hide resolved
src/pages/developers/tutorials/swap-any.mdx Show resolved Hide resolved
src/pages/developers/tutorials/swap-any.mdx Show resolved Hide resolved
Copy link
Member

@hernan-clich hernan-clich left a comment

Choose a reason for hiding this comment

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

Tested ACK

@fadeev fadeev merged commit 513b729 into main Dec 5, 2024
5 checks passed
@fadeev fadeev deleted the swap-revert-update branch December 5, 2024 17:05
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