synapsecns / sanguine

Synapse Monorepo
MIT License
43 stars 31 forks source link

feat(contracts-rfq): Token Zap [SLT-389] #3352

Closed ChiTimesChi closed 1 week ago

ChiTimesChi commented 1 month ago

Description

Minimal implementation of a contract that facilitates the generic Zap action for ERC20 tokens or native gas tokens (ETH/BNB/AVAX/others).

This enables atomic workflows like:

The challenge here is that we don't know how much tokens will we receive on destination chain in advance, so we can't form the exact calldata for the destination deposit call during the quoting phase. Therefore a hot-swapping mechanism was used, where a placeholder value is used for initial encoding, which is replaced in place by the actual bridged amount on the destination chain.

A single permisionless TokenZap contract could be used for any DeFi protocol and any FastBridge (V2+) deployment, assuming:

Full Workflow

Let's suppose Alice wants to deposit USDC into a Vault contract on Arbitrum. Alice has 100 USDC to start with on Optimism. The Arbitrum Vault exposes a following function to make the deposits: depositFunds(address token, uint256 amount, address onBehalfOf). Following steps need to be done (abstracted away from the Alice by the FE):

  1. ABI-encode calldata of the deposit call: payload = abi.encodeCall(vault.depositFunds, (arbUSDC, 0, alice))

    Note: we don't know the destination amount yet, so we use placeholder zero value instead

  2. Determine the position of the encoded amount within payload: amountPosition = 4 + 32 * 1 = 36

    Note: this is usually 4 (function selector), plus extra 32 per every argument before amount in the list of parameters (regardless of the argument type). If the amount is not encoded within payload at all, any value greater or equal than payload length could be used in step 3.

  3. Generate parameters for the Zap:
    • TokenZap exposes an off-chain getter: zapData = tokenZap.encodeZapData(arbVault, payload, amountPosition)
    • zapNative = 0 - this should be changed only when a Zap with ERC20 requires an additional native payment (e.g. token bridged via native bridge)
  4. Request a quote specifying the following parameters:
    origin_chain: 10
    origin_token: "0xOP_USDC"
    origin_amount: 100 * 10**6
    origin_sender: "0xALICE"
    dest_chain: 42141
    dest_token: "0xARB_USDC"
    dest_recipient: "0xARB_TOKEN_ZAP"
    zap_data: zapData
    zapNative: 0
  5. Suppose one of the Relayers responded that they are ready to relay such transaction, giving 99.9 USDC on Arbitrum.
  6. Alices accepts a quote and initiates a transaction on Optimism using the parameters from step (4) and adding dest_amount from step (5).
  7. Relayer completes the fill on Arbitrum:
    • They supply 99.9 USDC, which are transferred to TokenZap.
    • Then a Zap is performed using the Zap Data: TokenZap performs a 99.9 USDC deposit on behalf of Alice

      Note: initially encoded placeholder zero value is replaced by the actual bridged amount by TokenZap automatically.

  8. As a result, Relayer later receives 100 USDC on Optimism, while Aice has 99.9 USDC deposited on Optimism into the Vault.

Summary by CodeRabbit

Summary by CodeRabbit

coderabbitai[bot] commented 1 month ago

[!CAUTION]

Review failed

The pull request is closed.

Walkthrough

The changes introduce several new Solidity files, including a library (ZapDataV1) for encoding and validating tightly packed data structures, a contract (TokenZapV1) for executing "Zap" actions with ERC20 tokens, and various testing contracts. The tests validate the functionality of these components, ensuring correct encoding, decoding, and error handling. Additionally, mock contracts are created for testing purposes, enhancing the overall test coverage of the new features.

Changes

File Path Change Summary
packages/contracts-rfq/contracts/libs/ZapDataV1.sol Added library ZapDataV1 with functions for validation, encoding, and extracting data from tightly packed structures. Introduced custom errors for improved error handling.
packages/contracts-rfq/contracts/zaps/TokenZapV1.sol Introduced contract TokenZapV1 implementing IZapRecipient, enabling Zap actions with ERC20 tokens. Added methods for zapping, encoding, and decoding Zap data.
packages/contracts-rfq/test/harnesses/ZapDataV1Harness.sol Created ZapDataV1Harness for testing the ZapDataV1 library, with public functions to validate and encode zap data.
packages/contracts-rfq/test/integration/FastBridgeV2.TokenZapV1.Dst.t.sol Added FastBridgeV2TokenZapV1DstTest for integration testing of FastBridge V2 functionality, including event logging and various test functions for bridge transactions.
packages/contracts-rfq/test/integration/FastBridgeV2.TokenZapV1.Src.t.sol Introduced FastBridgeV2TokenZapV1SrcTest for integration testing of the FastBridge V2 functionality, focusing on bridge requests and event assertions.
packages/contracts-rfq/test/integration/TokenZapV1.t.sol Added abstract contract TokenZapV1IntegrationTest for testing TokenZapV1, including setup and utility functions for managing bridge parameters and token interactions.
packages/contracts-rfq/test/libs/ZapDataV1.t.sol Created ZapDataV1Test for testing the ZapDataV1 library, validating encoding and decoding processes, and handling various error scenarios.
packages/contracts-rfq/test/mocks/VaultManyArguments.sol Introduced VaultManyArguments mock contract for testing, including deposit functions and error handling.
packages/contracts-rfq/test/mocks/VaultMock.sol Added abstract contract VaultMock for testing, managing user balances and deposit functionalities with error handling.
packages/contracts-rfq/test/zaps/TokenZapV1.t.sol Created TokenZapV1Test contract for comprehensive testing of the TokenZapV1 functionality, covering various scenarios and edge cases for token deposits and zap operations.

Possibly related PRs

Suggested reviewers

Poem

In a world of bytes and zaps,
A rabbit hops with joyful claps.
Encoding data, tight and neat,
With every function, a tasty treat!
So let us cheer, with hops and bounds,
For smart contracts and joyful sounds! 🐇✨


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 - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)
🪧 Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit , 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit. - Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.
codecov[bot] commented 1 month ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 42.32681%. Comparing base (79a40b5) to head (678dcb5). Report is 1 commits behind head on master.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #3352 +/- ## =================================================== + Coverage 3.10368% 42.32681% +39.22313% =================================================== Files 44 87 +43 Lines 2932 3017 +85 Branches 0 82 +82 =================================================== + Hits 91 1277 +1186 + Misses 2838 1737 -1101 Partials 3 3 ``` | [Flag](https://app.codecov.io/gh/synapsecns/sanguine/pull/3352/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=synapsecns) | Coverage Δ | | |---|---|---| | [packages](https://app.codecov.io/gh/synapsecns/sanguine/pull/3352/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=synapsecns) | `90.44834% <ø> (?)` | | | [promexporter](https://app.codecov.io/gh/synapsecns/sanguine/pull/3352/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=synapsecns) | `?` | | | [solidity](https://app.codecov.io/gh/synapsecns/sanguine/pull/3352/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=synapsecns) | `98.85714% <100.00000%> (?)` | | Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=synapsecns#carryforward-flags-in-the-pull-request-comment) to find out more.

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.


🚨 Try these New Features:

cloudflare-workers-and-pages[bot] commented 1 month ago

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 678dcb5
Status: ✅  Deploy successful!
Preview URL: https://491cf1c4.sanguine-fe.pages.dev
Branch Preview URL: https://feat-token-zap.sanguine-fe.pages.dev

View logs

ChiTimesChi commented 2 weeks ago

@coderabbitai review

coderabbitai[bot] commented 2 weeks ago
:white_check_mark: Actions performed Review triggered. > Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.