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

Merge swap tutorials in one #517

Merged
merged 7 commits into from
Dec 16, 2024
Merged

Merge swap tutorials in one #517

merged 7 commits into from
Dec 16, 2024

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Dec 9, 2024

We have two Swap tutorials. One is meant to be slightly more compact, the other one more feature-rich (for example, being able to swap to ZETA on ZetaChain and swap directly from ZetaChain). The problem is, both contracts have grown fairly large and the LOC difference between them is no longer significant. I've decided to merge these contracts into one so that developers don't have to choose which tutorial to follow.

I've also modified the code to be upgradeable and added a companion contract.

Related: zeta-chain/example-contracts#223

Summary by CodeRabbit

  • New Features

    • Updated the Swap contract tutorial with a clearer step-by-step process for creating cross-chain swaps.
    • Introduced an Alert component in the UniversalKit documentation to indicate active development status.
  • Bug Fixes

    • Corrected the link for the swap tutorial in the UniversalKit documentation.
  • Documentation

    • Enhanced clarity and usability of the UniversalKit documentation, including initialization instructions and component usage examples.
  • Chores

    • Removed the tutorial for SwapToAnyToken and its associated metadata entry.

@fadeev fadeev requested a review from a team as a code owner December 9, 2024 10:01
Copy link

vercel bot commented Dec 9, 2024

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

Name Status Preview Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview Dec 10, 2024 5:17pm

Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request involves the deletion of the swap-any.mdx tutorial, which detailed the SwapToAnyToken contract's functionality for cross-chain token swaps. Additionally, the swap.mdx tutorial has been significantly restructured to enhance clarity and instructional quality. Key updates include the introduction of new contract interfaces for upgradeability, an expanded Params struct, and improved error handling. The changes aim to provide a clearer, step-by-step guide for implementing a cross-chain swap contract.

Changes

File Path Change Summary
src/pages/developers/tutorials/swap-any.mdx Deleted tutorial on the SwapToAnyToken contract, which included functionality for cross-chain swaps.
src/pages/developers/tutorials/swap.mdx Restructured tutorial with detailed steps for creating a cross-chain swap contract; updated Solidity code to include new interfaces, modified constructor, added initialize function, expanded Params struct to include bool withdraw, and enhanced error handling with new TransferFailed error.
src/pages/developers/tutorials/_meta.json Removed entry for "swap-any" from the JSON structure, which included title, read time, and description.
src/pages/developers/frontend/universalkit.mdx Updated documentation for the UniversalKit library, adding an Alert component and correcting the link for the swap tutorial.

Possibly related PRs

  • Swap from ZetaChain tutorial #393: Modifications to the Swap contract tutorial are related as they both involve enhancements to the swapping functionality, including the introduction of a withdraw flag and modifications to the onCall function.
  • Update examples to use gateway and localnet #470: This PR updates the SwapToAnyToken contract to include a withdraw flag, which aligns with the changes made in the main PR regarding the handling of token swaps and withdrawals.
  • Swap: update to handle reverts #512: The updates to the SwapToAnyToken contract in this PR enhance its functionality to handle reverts, which is directly related to the changes made in the main PR that also focus on improving the swap functionality and error handling.

Suggested reviewers

  • bbbeeeee
  • brewmaster012
  • hernan-clich

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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between da4d38f and 5a56e8c.

📒 Files selected for processing (2)
  • src/pages/developers/tutorials/swap-any.mdx (0 hunks)
  • src/pages/developers/tutorials/swap.mdx (9 hunks)
💤 Files with no reviewable changes (1)
  • src/pages/developers/tutorials/swap-any.mdx
🧰 Additional context used
🪛 LanguageTool
src/pages/developers/tutorials/swap.mdx

[uncategorized] ~349-~349: Loose punctuation mark.
Context: ... of information: - address target: The ZRC-20 address of the target token ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~350-~350: Loose punctuation mark.
Context: ...get token on ZetaChain. - bytes to: The recipient's address on the destinat...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~353-~353: Loose punctuation mark.
Context: ...ns like Bitcoin. - bool withdraw: Indicates whether to withdraw the swapp...

(UNLIKELY_OPENING_PUNCTUATION)

🔇 Additional comments (3)
src/pages/developers/tutorials/swap.mdx (3)

83-88: LGTM: Well-implemented upgradeable pattern

The contract correctly implements the OpenZeppelin upgradeable pattern with proper initialization and ownership controls.

Also applies to: 114-124


Line range hint 264-336: LGTM: Robust withdrawal and revert handling

The implementation provides comprehensive error handling and recovery mechanisms for failed withdrawals.


346-420: LGTM: High-quality documentation

The documentation is comprehensive, well-structured, and provides clear examples for both testnet and localnet deployments.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~349-~349: Loose punctuation mark.
Context: ... of information: - address target: The ZRC-20 address of the target token ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~350-~350: Loose punctuation mark.
Context: ...get token on ZetaChain. - bytes to: The recipient's address on the destinat...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~353-~353: Loose punctuation mark.
Context: ...ns like Bitcoin. - bool withdraw: Indicates whether to withdraw the swapp...

(UNLIKELY_OPENING_PUNCTUATION)

src/pages/developers/tutorials/swap.mdx Show resolved Hide resolved
src/pages/developers/tutorials/swap.mdx Show resolved Hide resolved
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 (2)
src/pages/developers/frontend/universalkit.mdx (2)

Line range hint 1-14: Enhance the warning message for production readiness

The current alert about testnet usage is good, but could be more comprehensive for production-grade documentation.

Consider expanding the alert message to include:

-<Alert> The component library is in under active development and currently is recommended for testnet use only.</Alert>
+<Alert type="warning">
+  ⚠️ Production Notice:
+  This component library is under active development and is currently recommended for testnet use only.
+  Breaking changes may occur without notice.
+  For production deployments, please await stable release announcements.
+</Alert>
🧰 Tools
🪛 LanguageTool

[uncategorized] ~142-~142: Possible missing comma found.
Context: ...ns on connected chains For cross-chain swaps the component depends on a universal sw...

(AI_HYDRA_LEO_MISSING_COMMA)


Line range hint 156-182: Enhance code examples for production readiness

The current example uses a hardcoded contract address without proper context or error handling.

Consider updating the example to be more production-ready:

 const contract = "0xb459F14260D1dc6484CE56EB0826be317171e91F"; // universal swap contract
+
+// In production, consider using environment variables
+const UNIVERSAL_SWAP_CONTRACT = process.env.NEXT_PUBLIC_UNIVERSAL_SWAP_CONTRACT;
+if (!UNIVERSAL_SWAP_CONTRACT) {
+  throw new Error("Universal swap contract address not configured");
+}

 const Page = () => {
   return (
     <div className="m-4">
       <div className="flex justify-end gap-2 mb-10">
         <ConnectBitcoin />
         <ConnectButton label="Connect EVM" showBalance={false} />
       </div>
       <div className="flex justify-center">
         <div className="w-[400px]">
-          <Swap contract={contract} />
+          <Swap contract={UNIVERSAL_SWAP_CONTRACT} />
         </div>
       </div>
     </div>
   );
 };
🧰 Tools
🪛 LanguageTool

[uncategorized] ~142-~142: Possible missing comma found.
Context: ...ns on connected chains For cross-chain swaps the component depends on a universal sw...

(AI_HYDRA_LEO_MISSING_COMMA)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5a56e8c and b34af10.

📒 Files selected for processing (2)
  • src/pages/developers/frontend/universalkit.mdx (1 hunks)
  • src/pages/developers/tutorials/_meta.json (0 hunks)
💤 Files with no reviewable changes (1)
  • src/pages/developers/tutorials/_meta.json

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

src/pages/developers/tutorials/swap.mdx Outdated Show resolved Hide resolved
src/pages/developers/tutorials/swap.mdx Outdated Show resolved Hide resolved
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 (2)
src/pages/developers/tutorials/swap.mdx (2)

94-98: Enhance error messages for better debugging

The current error messages are too generic, making it difficult to identify the specific cause of failures.

Consider making the error messages more descriptive:

- error InvalidAddress();
- error Unauthorized();
- error ApprovalFailed();
- error TransferFailed();
+ error InvalidAddress(address addr);
+ error Unauthorized(address sender, address expected);
+ error ApprovalFailed(address token, address spender, uint256 amount);
+ error TransferFailed(address token, address from, address to, uint256 amount);

349-354: Fix markdown formatting inconsistencies

There are some formatting inconsistencies in the documentation.

Apply these changes:

  • Remove extra spaces before bullet points
  • Add consistent spacing after bullet points
  • Ensure uniform indentation in the list items
🧰 Tools
🪛 LanguageTool

[uncategorized] ~349-~349: Loose punctuation mark.
Context: ... of information: - address target: The ZRC-20 address of the target token ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~350-~350: Loose punctuation mark.
Context: ...get token on ZetaChain. - bytes to: The recipient's address on the destinat...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~353-~353: Loose punctuation mark.
Context: ...ns like Bitcoin. - bool withdraw: Indicates whether to withdraw the swapp...

(UNLIKELY_OPENING_PUNCTUATION)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b34af10 and c8d2952.

📒 Files selected for processing (1)
  • src/pages/developers/tutorials/swap.mdx (9 hunks)
🧰 Additional context used
🪛 LanguageTool
src/pages/developers/tutorials/swap.mdx

[uncategorized] ~349-~349: Loose punctuation mark.
Context: ... of information: - address target: The ZRC-20 address of the target token ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~350-~350: Loose punctuation mark.
Context: ...get token on ZetaChain. - bytes to: The recipient's address on the destinat...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~353-~353: Loose punctuation mark.
Context: ...ns like Bitcoin. - bool withdraw: Indicates whether to withdraw the swapp...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~400-~400: Possible missing comma found.
Context: ...kens are approved, either combined or separately depending on whether they are the same....

(AI_HYDRA_LEO_MISSING_COMMA)

🔇 Additional comments (1)
src/pages/developers/tutorials/swap.mdx (1)

255-262: ⚠️ Potential issue

Add slippage protection to prevent sandwich attacks

The swap is performed without specifying a minimum output amount, which could lead to significant slippage or sandwich attacks.

This issue was previously identified. The fix involves adding a minOutputAmount parameter to protect users from unfavorable trades.

src/pages/developers/tutorials/swap.mdx Show resolved Hide resolved
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c8d2952 and 00b5dc0.

📒 Files selected for processing (1)
  • src/pages/developers/tutorials/swap.mdx (9 hunks)
🧰 Additional context used
🪛 LanguageTool
src/pages/developers/tutorials/swap.mdx

[uncategorized] ~345-~345: Loose punctuation mark.
Context: ... of information: - address target: The ZRC-20 address of the target token ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~346-~346: Loose punctuation mark.
Context: ...get token on ZetaChain. - bytes to: The recipient's address on the destinat...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~349-~349: Loose punctuation mark.
Context: ...ns like Bitcoin. - bool withdraw: Indicates whether to withdraw the swapp...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~396-~396: Possible missing comma found.
Context: ...kens are approved, either combined or separately depending on whether they are the same....

(AI_HYDRA_LEO_MISSING_COMMA)

🔇 Additional comments (3)
src/pages/developers/tutorials/swap.mdx (3)

255-262: Remove hardcoded minimum output amount

Using 0 as the minimum output amount is unsafe and could lead to significant slippage or sandwich attacks.


334-336: Enhance upgrade implementation with additional safeguards

The current upgrade implementation lacks important safety measures and transparency features.


187-228: ⚠️ Potential issue

Add slippage and deadline protection

The swap function should include slippage protection and a deadline parameter to prevent sandwich attacks and stale transactions.

 function swap(
     address inputToken,
     uint256 amount,
     address targetToken,
     bytes memory recipient,
-    bool withdrawFlag
+    bool withdrawFlag,
+    uint256 minOutputAmount,
+    uint256 deadline
 ) public {
+    if (block.timestamp > deadline) revert DeadlineExpired();
     bool success = IZRC20(inputToken).transferFrom(
         msg.sender,
         address(this),
         amount
     );
     if (!success) {
         revert TransferFailed();
     }

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

Likely invalid or redundant comment.

src/pages/developers/tutorials/swap.mdx Show resolved Hide resolved
src/pages/developers/tutorials/swap.mdx Show resolved Hide resolved
@fadeev fadeev merged commit 7aa56db into main Dec 16, 2024
5 checks passed
@fadeev fadeev deleted the swap-companion branch December 16, 2024 08:15
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