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

Update Swap tutorial with better localnet support #490

Merged
merged 3 commits into from
Oct 29, 2024
Merged

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Oct 14, 2024

Updated example commands to match the updated Swap example.

Depends on zeta-chain/example-contracts#203

Summary by CodeRabbit

  • New Features

    • Enhanced tutorials for the SwapToAnyToken and cross-chain swap contracts, allowing users to swap tokens with options for withdrawal or retention on ZetaChain.
    • Introduced a new public swap function for direct interactions on ZetaChain.
  • Documentation

    • Updated deployment instructions and tutorial content for clarity on token swaps, gas fee management, and cross-chain functionalities.

@fadeev fadeev requested review from bbbeeeee, brewmaster012 and a team as code owners October 14, 2024 11:26
Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

Caution

Review failed

The head commit changed during the review from b0370bc to 5dbc617.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant enhancements to the SwapToAnyToken and Swap contracts, focusing on cross-chain token swaps. Key updates include the addition of a withdraw flag in the Params struct, allowing users to choose whether to withdraw swapped tokens to a connected blockchain or retain them on ZetaChain. The swap function is newly introduced for direct interactions on ZetaChain, while the tutorials have been revised for clarity, detailing the updated functionalities and deployment instructions.

Changes

File Path Change Summary
src/pages/developers/tutorials/swap-any.mdx Enhanced tutorial for SwapToAnyToken with updates on token swapping options, withdraw flag in Params, modifications to onCrossChainCall and swapAndWithdraw functions, and updated deployment instructions.
src/pages/developers/tutorials/swap.mdx Updated tutorial on cross-chain swap contract, clarifying operations, refining decoding logic for incoming messages, detailing swapAndWithdraw function, and revising deployment instructions to reflect command changes.

Possibly related PRs

  • Swap from ZetaChain tutorial #393: The changes in this PR directly modify the SwapToAnyToken contract, including the addition of the withdraw flag and updates to the onCrossChainCall and swapAndWithdraw functions, which are also central to the main PR's enhancements.
  • Update examples to use gateway and localnet #470: This PR also focuses on the SwapToAnyToken contract, detailing similar updates to the withdraw functionality and the onCrossChainCall function, aligning closely with the changes made in the main PR.

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.

Copy link

vercel bot commented Oct 14, 2024

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

Name Status Preview Comments Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 14, 2024 0:08am

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 (7)
src/pages/developers/tutorials/swap-any.mdx (4)

Line range hint 1-38: Enhance clarity of the testnet compatibility alert.

The alert message about testnet compatibility is informative but could be more specific. Consider adding an estimated timeframe or a way for users to check when the gateway will be deployed on testnet.

Suggested improvement:

<Alert>
  {" "}
  This tutorial depends on the gateway, which is available on localnet but not yet deployed on testnet. It will be compatible
- with testnet after the gateway is deployed. In other words, you cannot deploy this tutorial on testnet yet.{" "}
+ with testnet after the gateway is deployed. You cannot deploy this tutorial on testnet yet. Check our official 
+ announcements or documentation for updates on the gateway deployment to testnet.{" "}
</Alert>

Line range hint 39-186: Enhance contract code readability and gas efficiency.

The contract implementation is correct, but there are opportunities for improvement in terms of readability and gas efficiency.

Consider the following enhancements:

  1. Use named return variables for better readability:
- function swapAndWithdraw(
+ function swapAndWithdraw(
    address inputToken,
    uint256 amount,
    address targetToken,
    bytes memory recipient,
    bool withdraw
- ) internal {
+ ) internal returns (uint256 outputAmount) {
    // ... existing code ...

-   uint256 outputAmount = SwapHelperLib.swapExactTokensForTokens(
+   outputAmount = SwapHelperLib.swapExactTokensForTokens(
        systemContract,
        inputToken,
        swapAmount,
        targetToken,
        0
    );

    // ... rest of the function ...
}
  1. Optimize gas usage by avoiding unnecessary storage reads:
function swap(
    address inputToken,
    uint256 amount,
    address targetToken,
    bytes memory recipient,
    bool withdraw
) public {
+   IZRC20 inputZRC20 = IZRC20(inputToken);
-   IZRC20(inputToken).transferFrom(msg.sender, address(this), amount);
+   inputZRC20.transferFrom(msg.sender, address(this), amount);

    swapAndWithdraw(inputToken, amount, targetToken, recipient, withdraw);
}
  1. Consider adding input validation to prevent potential issues:
function swap(
    address inputToken,
    uint256 amount,
    address targetToken,
    bytes memory recipient,
    bool withdraw
) public {
+   require(inputToken != address(0) && targetToken != address(0), "Invalid token addresses");
+   require(amount > 0, "Amount must be greater than zero");

    IZRC20(inputToken).transferFrom(msg.sender, address(this), amount);

    swapAndWithdraw(inputToken, amount, targetToken, recipient, withdraw);
}

These changes will improve the contract's readability, gas efficiency, and robustness.


Line range hint 266-283: Provide more context for system contract and gateway addresses.

The deployment instructions are clear, but additional information about the system contract and gateway addresses would be beneficial for users.

Consider adding the following explanation after the deployment instructions:

Note: The `systemContractAddress` and `gatewayAddress` are required for contract deployment. On localnet, these addresses are pre-configured:

- System Contract Address: 0x...
- Gateway Address: 0x...

For other networks, you'll need to provide the correct addresses for that specific network.

Replace the ellipsis (...) with the actual addresses used in the localnet environment. This addition will help users understand the importance of these addresses and prepare them for deploying to other networks in the future.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~300-~300: Possible missing comma found.
Context: ...ZRC-20 to the recipient In the command above the withdraw is true, so the target...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~312-~312: Possible missing comma found.
Context: ...66 --withdraw false ``` In the command above the withdraw is `true`, so the target...

(AI_HYDRA_LEO_MISSING_COMMA)


Line range hint 332-348: Enhance conclusion with next steps or related resources.

The conclusion effectively summarizes the tutorial's achievements. However, it could be improved by providing readers with guidance on next steps or related resources.

Consider adding a paragraph at the end of the conclusion:

## Next Steps

Now that you've learned how to create and interact with the SwapToAnyToken contract, consider exploring the following:

1. Implement error handling and event emission in the contract for better monitoring and debugging.
2. Explore integrating this swap functionality into a decentralized application (dApp).
3. Learn about other ZetaChain features and how they can be combined with this swap functionality.

For more advanced topics and tutorials, visit our [Developer Documentation](https://www.zetachain.com/docs/developers/).

This addition provides readers with direction for further learning and application of the concepts covered in the tutorial.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~300-~300: Possible missing comma found.
Context: ...ZRC-20 to the recipient In the command above the withdraw is true, so the target...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~312-~312: Possible missing comma found.
Context: ...66 --withdraw false ``` In the command above the withdraw is `true`, so the target...

(AI_HYDRA_LEO_MISSING_COMMA)

src/pages/developers/tutorials/swap.mdx (3)

269-271: Deployment commands updated appropriately.

The change to npx hardhat commands is consistent with modern Node.js project practices. The --force flag for compilation ensures a clean build, which is a good practice.

Consider adding a brief comment explaining the purpose of the --force flag for clarity:

-npx hardhat compile --force
+# Ensure a clean build by forcing recompilation
+npx hardhat compile --force

294-297: Swap command updated with new receiver address.

The updated command reflects changes in the contract deployment or structure, which is necessary for the tutorial's accuracy.

To improve flexibility and reduce the need for updates, consider using a placeholder or variable for the --receiver address:

-npx hardhat swap-from-evm --network localhost --receiver 0xE6E340D132b5f46d1e472DebcD681B2aBc16e57E --amount 1 --target 0x9fd96203f7b22bCF72d9DCb40ff98302376cE09c --recipient 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
+npx hardhat swap-from-evm --network localhost --receiver <SWAP_CONTRACT_ADDRESS> --amount 1 --target 0x9fd96203f7b22bCF72d9DCb40ff98302376cE09c --recipient 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266

Then, add a note explaining that <SWAP_CONTRACT_ADDRESS> should be replaced with the actual deployed contract address.


Line range hint 328-337: Updated command and explanation for ERC-20 to gas token swap.

The updated command and expanded explanation provide more details about the swap process, enhancing the tutorial's educational value.

To improve flexibility and reduce the need for updates, consider using placeholders or variables for the addresses:

-npx hardhat swap-from-evm --network localhost --receiver 0xE6E340D132b5f46d1e472DebcD681B2aBc16e57E --amount 1 --target 0x2ca7d64A7EFE2D62A725E2B35Cf7230D6677FfEe --recipient 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 --erc20 0x0DCd1Bf9A1b36cE34237eEaFef220932846BCD82
+npx hardhat swap-from-evm --network localhost --receiver <SWAP_CONTRACT_ADDRESS> --amount 1 --target <TARGET_TOKEN_ADDRESS> --recipient <RECIPIENT_ADDRESS> --erc20 <SOURCE_ERC20_ADDRESS>

Then, add a note explaining that these placeholders should be replaced with actual addresses when running the command.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2b44f68 and 2767071.

📒 Files selected for processing (2)
  • src/pages/developers/tutorials/swap-any.mdx (2 hunks)
  • src/pages/developers/tutorials/swap.mdx (4 hunks)
🧰 Additional context used
🪛 LanguageTool
src/pages/developers/tutorials/swap-any.mdx

[uncategorized] ~300-~300: Possible missing comma found.
Context: ...ZRC-20 to the recipient In the command above the withdraw is true, so the target...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~312-~312: Possible missing comma found.
Context: ...66 --withdraw false ``` In the command above the withdraw is `true`, so the target...

(AI_HYDRA_LEO_MISSING_COMMA)

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

280-280: Contract address updated in example output.

The updated contract address reflects a new deployment, which is appropriate for maintaining the accuracy of the tutorial.


311-317: Improved explanation of contract execution flow.

The updated explanation provides a clearer and more concise description of how ZetaChain handles the cross-chain call and executes the onCrossChainCall function. This enhancement improves the overall clarity of the tutorial.


343-346: Improved explanation of swap execution and withdrawal process.

The updated explanation provides a clearer and more concise description of how the Swap contract handles the cross-chain call, decodes the message, and initiates the swap logic. The withdrawal process is also accurately described. These improvements enhance the overall clarity and accuracy of the tutorial.

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

fadeev commented Oct 25, 2024

@brewmaster012 @bbbeeeee @zeta-chain/fullstack please, review.

@fadeev fadeev merged commit ac79071 into main Oct 29, 2024
6 checks passed
@fadeev fadeev deleted the swap-localnet branch October 29, 2024 10:57
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