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

Fix: FastBridgeV2 (Zellic - 01) #3493

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

Conversation

ChiTimesChi
Copy link
Collaborator

@ChiTimesChi ChiTimesChi commented Jan 24, 2025

Description
This PR fixes removes support for rebasing tokens or tokens with fees on transfers from FastBridgeV2.

  • Instead of dynamically determining the origin amount as the FastBridgeV2 balance change, the user-provided amount is used.
  • The balance change is verified to match the provided amount to prevent bridge transactions with the above mentioned tokens.
  • QOL: originFeeAmount variables were renamed into protocolFeeAmount to better reflect their meaning.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced enhanced bridge transaction handling with improved fee management.
    • Added support for minting and managing a new mock token, WeirdERC20Mock.
  • Testing

    • Expanded test coverage for bridge transactions involving the new weirdToken.
    • Added new test functions to validate amount checks during bridge operations.
  • Improvements

    • Refined validation checks for bridge transactions.
    • Updated fee calculation and handling mechanisms.
    • Improved event emission reliability.

@ChiTimesChi ChiTimesChi requested a review from parodime January 24, 2025 11:44
Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

Walkthrough

The pull request introduces modifications to the FastBridgeV2 contract and associated test files, focusing on enhancing the bridge transaction process. The changes include updating fee handling, simplifying asset transfer logic, and introducing a new WeirdERC20Mock contract for testing scenarios. The modifications aim to improve the clarity and functionality of bridge transactions, particularly in how fees are managed and assets are transferred.

Changes

File Change Summary
packages/contracts-rfq/contracts/FastBridgeV2.sol - Removed _takeBridgedUserAsset function
- Updated bridgeV2 function to integrate direct token transfer
- Modified fee handling with protocolFeeAmount
- Updated cancelV2 and _validateBridgeParams functions
packages/contracts-rfq/test/FastBridgeV2.*.sol - Added support for weirdToken in test setups
- Introduced new test functions for token amount validation
- Created mock contract for testing edge cases
packages/contracts-rfq/test/mocks/WeirdERC20Mock.sol - New mock contract with custom transfer behavior
- Added setter methods for fast bridge and transfer values
- Overridden transfer functions with conditional logic

Sequence Diagram

sequenceDiagram
    participant User
    participant FastBridgeV2
    participant Token
    participant ProtocolFee

    User->>FastBridgeV2: bridgeV2(params)
    FastBridgeV2->>FastBridgeV2: Validate bridge parameters
    FastBridgeV2->>Token: Transfer origin amount
    FastBridgeV2->>ProtocolFee: Calculate and deduct protocol fee
    FastBridgeV2->>FastBridgeV2: Emit bridge event
Loading

Possibly related PRs

Suggested Labels

size/m, needs-go-generate-services/rfq

Suggested Reviewers

  • aureliusbtc
  • parodime
  • trajan0x

Poem

🐰 Bridging tokens with a hop and a leap,
Fees calculated, no secrets to keep!
Weird tokens dance, transfers so bright,
FastBridgeV2 makes everything right!
A rabbit's code, precise and clean! 🌉


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 00b0e21 and 678f978.

📒 Files selected for processing (1)
  • packages/contracts-rfq/contracts/FastBridgeV2.sol (7 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/contracts-rfq/contracts/FastBridgeV2.sol (1)
Learnt from: ChiTimesChi
PR: synapsecns/sanguine#3284
File: packages/contracts-rfq/contracts/FastBridgeV2.sol:100-118
Timestamp: 2024-11-12T03:37:08.148Z
Learning: When reviewing code in `packages/contracts-rfq/contracts/FastBridgeV2.sol` (Solidity), focus on changes introduced in the PR and avoid commenting on existing functions like `refund` if they are not modified by the PR, as such comments are considered out of scope.
⏰ Context from checks skipped due to timeout of 90000ms (17)
  • GitHub Check: Slither (contracts-rfq)
  • GitHub Check: Foundry Gas Diff (contracts-rfq)
  • GitHub Check: Deploy Docs (contracts-rfq)
  • GitHub Check: Foundry Size Check (contracts-rfq)
  • GitHub Check: Foundry Coverage (contracts-rfq)
  • GitHub Check: Slither (contracts-rfq)
  • GitHub Check: Foundry Coverage (contracts-rfq)
  • GitHub Check: Foundry Size Check (contracts-rfq)
  • GitHub Check: Deploy Docs (contracts-rfq)
  • GitHub Check: Foundry Gas Diff (contracts-rfq)
  • GitHub Check: Go Generate (Solidity Only) (agents)
  • GitHub Check: test
  • GitHub Check: SonarCloud
  • GitHub Check: lint
  • GitHub Check: changesets-integrity-checker
  • GitHub Check: lint
  • GitHub Check: test
🔇 Additional comments (7)
packages/contracts-rfq/contracts/FastBridgeV2.sol (7)

192-198: Good handling of protocol fee deduction logic.
By separating out the protocolFeeAmount, you maintain a clear distinction between the fee portion and the net bridging amount. This aligns well with the new naming change away from originFeeAmount.


212-212: Clear assignment of fee field for compatibility.
Using protocolFeeAmount to populate the originFeeAmount field in the encoded request helps preserve compatibility while reflecting the updated terminology.


228-228: Proper event ordering.
Emitting events before external calls follows best practices for ensuring accurate on-chain logs even if an external call fails.


241-252: Correctly rejecting fee-on-transfer and rebasing tokens.
The balance check ensures the contract’s token balance increases exactly by the requested deposit amount, effectively disallowing tokens with transfer fees or rebasing mechanics.


410-411: Accurate accumulation of protocol fees.
Storing the collected fees in protocolFees[token] cleanly centralizes fee bookkeeping. This approach is straightforward and maintains clarity on total fees for each token.


491-497: Comprehensive checks for zero values.
Disallowing zero amounts and zero addresses ensures bridging requests remain valid and helps prevent erroneous transactions or lost funds.


510-520: Robust validation of msg.value.
Differentiating native token transactions from ERC20 transactions via strict msg.value checks keeps bridging requirements unambiguous and prevents accidental fund transfers.


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. (Beta)
  • @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 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

cloudflare-workers-and-pages bot commented Jan 24, 2025

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 678f978
Status: ✅  Deploy successful!
Preview URL: https://57c06e0f.sanguine-fe.pages.dev
Branch Preview URL: https://fix-fbv2-zellic-01.sanguine-fe.pages.dev

View logs

Copy link

codecov bot commented Jan 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 93.76125%. Comparing base (2847b63) to head (678f978).
Report is 12 commits behind head on master.

Additional details and impacted files
@@                 Coverage Diff                 @@
##              master       #3493         +/-   ##
===================================================
- Coverage   98.89241%   93.76125%   -5.13116%     
===================================================
  Files             11          65         +54     
  Lines            632        1667       +1035     
  Branches           0          82         +82     
===================================================
+ Hits             625        1563        +938     
- Misses             7         102         +95     
- Partials           0           2          +2     
Flag Coverage Δ
packages 90.59166% <ø> (?)
solidity 98.89937% <100.00000%> (+0.00696%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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: 0

🧹 Nitpick comments (3)
packages/contracts-rfq/contracts/FastBridgeV2.sol (1)

491-492: Redundant local references
These lines duplicate existing references to params.originToken and params.originAmount within the same function. Consider directly using params to avoid increasing local variable count, which can trigger stack-depth issues.

- address originToken = params.originToken;
- uint256 originAmount = params.originAmount;
+ // Access params.originToken and params.originAmount directly below
packages/contracts-rfq/test/mocks/WeirdERC20Mock.sol (1)

16-18: Set FastBridge address
Providing a setter for fastBridge is convenient for test scenarios. If this setter is used only for testing, consider restricting it to specialized roles or test environments.

packages/contracts-rfq/test/FastBridgeV2.Src.Base.t.sol (1)

56-59: Consider minting weirdToken for both userA and userB.
Currently, only userA receives weirdToken, whereas both userA and userB receive srcToken. If future tests require userB bridging with weirdToken, consider minting it for userB as well for symmetry.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8811b0d and 00b0e21.

📒 Files selected for processing (6)
  • packages/contracts-rfq/contracts/FastBridgeV2.sol (7 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Src.Base.t.sol (1 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Src.FBRV2.t.sol (1 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.Src.t.sol (1 hunks)
  • packages/contracts-rfq/test/FastBridgeV2.t.sol (4 hunks)
  • packages/contracts-rfq/test/mocks/WeirdERC20Mock.sol (1 hunks)
🧰 Additional context used
📓 Learnings (4)
packages/contracts-rfq/test/FastBridgeV2.Src.FBRV2.t.sol (1)
Learnt from: ChiTimesChi
PR: synapsecns/sanguine#3284
File: packages/contracts-rfq/test/FastBridgeV2.t.sol:53-56
Timestamp: 2024-11-12T03:37:02.230Z
Learning: Modifying test utility contracts in the `test` directory is unnecessary and would only pollute the code.
packages/contracts-rfq/test/FastBridgeV2.Src.t.sol (3)
Learnt from: ChiTimesChi
PR: synapsecns/sanguine#3284
File: packages/contracts-rfq/test/FastBridgeV2.Src.t.sol:919-993
Timestamp: 2024-11-12T03:37:02.230Z
Learning: In Solidity test files for FastBridgeV2 (e.g., `packages/contracts-rfq/test/FastBridgeV2.Src.t.sol`), code duplication in test functions is acceptable to maintain readability and maintainability, even if it contradicts DRY principles.
Learnt from: ChiTimesChi
PR: synapsecns/sanguine#3284
File: packages/contracts-rfq/test/FastBridgeV2.Src.Base.t.sol:97-97
Timestamp: 2024-11-12T03:37:08.148Z
Learning: In `packages/contracts-rfq/test/FastBridgeV2.t.sol`, when testing expected revert behaviors, `abi.encodeWithSelector` is used with custom errors and should not be replaced with `BridgeTransactionV2Lib.encodeV2`.
Learnt from: ChiTimesChi
PR: synapsecns/sanguine#3284
File: packages/contracts-rfq/test/FastBridgeV2.t.sol:53-56
Timestamp: 2024-11-12T03:37:02.230Z
Learning: Modifying test utility contracts in the `test` directory is unnecessary and would only pollute the code.
packages/contracts-rfq/test/FastBridgeV2.t.sol (1)
Learnt from: ChiTimesChi
PR: synapsecns/sanguine#3284
File: packages/contracts-rfq/test/FastBridgeV2.t.sol:53-56
Timestamp: 2024-11-12T03:37:02.230Z
Learning: Modifying test utility contracts in the `test` directory is unnecessary and would only pollute the code.
packages/contracts-rfq/contracts/FastBridgeV2.sol (1)
Learnt from: ChiTimesChi
PR: synapsecns/sanguine#3284
File: packages/contracts-rfq/contracts/FastBridgeV2.sol:100-118
Timestamp: 2024-11-12T03:37:08.148Z
Learning: When reviewing code in `packages/contracts-rfq/contracts/FastBridgeV2.sol` (Solidity), focus on changes introduced in the PR and avoid commenting on existing functions like `refund` if they are not modified by the PR, as such comments are considered out of scope.
🪛 GitHub Actions: Solidity
packages/contracts-rfq/contracts/FastBridgeV2.sol

[error] 239-239: Stack too deep error. Compiler suggests using --via-ir flag or enabling viaIR: true in JSON settings, or reducing local variables.

⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Slither (contracts-rfq)
  • GitHub Check: Foundry Size Check (contracts-rfq)
  • GitHub Check: Foundry Gas Diff (contracts-rfq)
  • GitHub Check: Deploy Docs (contracts-rfq)
  • GitHub Check: Foundry Coverage (contracts-rfq)
  • GitHub Check: Go Generate (Solidity Only) (agents)
  • GitHub Check: test
  • GitHub Check: SonarCloud
  • GitHub Check: lint
  • GitHub Check: changesets-integrity-checker
🔇 Additional comments (19)
packages/contracts-rfq/contracts/FastBridgeV2.sol (11)

192-194: Initialize local variables neatly
Defining originToken, originAmount, and initializing protocolFeeAmount to zero provides a clear setup for fee calculations and token references.


196-196: Check for potential overflow in fee calculation
Although Solidity 0.8+ automatically checks for overflow/underflow, consider validating extreme edge cases (e.g., large originAmount or protocolFeeRate) to ensure the calculation remains safe.


199-199: Subtracting fee from the user’s amount
Subtracting protocolFeeAmount from originAmount is correct. Ensure subsequent references to originAmount reflect the updated value.


209-209: Reference to local variable
Passing originToken directly to the struct is consistent with the new approach of calculating fees beforehand.


213-213: Renamed fee variable
Storing computed fee in originFeeAmount clarifies that this fee was calculated at origin. This aligns well with the new naming (protocolFeeAmount).


229-229: Emit events first
Emitting events before external calls follows best practices to mitigate risk in the event of reentrancy.


242-251: Prevent use of fee-on-transfer or rebasing tokens
This logic checks if the balance increase matches the intended transfer, reverting if not. It effectively excludes fee-on-transfer or rebasing tokens from usage.


410-411: Accumulate protocol fees
Adding protocolFeeAmount into protocolFees[token] ensures correct fee accounting. Confirm that the rest of the system correctly handles and tracks these accumulated fees.


495-495: Zero amounts
Reverting if either amount is zero eliminates no-op or accidental bridging. This is a valid guard check.


497-497: Zero addresses
Reverting for zero addresses ensures invalid bridging addresses and tokens do not slip through.


510-520: Distinct handling of native gas vs. ERC20
This block fully covers ensuring the correct msg.value for native tokens and rejecting non-zero Ether with ERC20 usage. It also rejects non-contract tokens.

packages/contracts-rfq/test/mocks/WeirdERC20Mock.sol (4)

7-12: Contract initialization
Appending a custom constructor to the MockERC20 base is straightforward. Ensure the decimals_ argument matches test expectations.


20-22: Set user-defined transfer amount
The ability to define a custom transferToFastBridgeValue helps test weird transfer behaviors. Just confirm you reset or control it in each test to avoid test interference.


24-30: Override transfer
If to is fastBridge, a custom transfer amount is used instead of the original value. This approach effectively simulates tokens with unusual fee or rebasing mechanics.


32-38: Override transferFrom
Same logic as transfer override, ensuring consistent “weird” behavior from both direct and allowance-based transfers.

packages/contracts-rfq/test/FastBridgeV2.Src.FBRV2.t.sol (1)

22-24: Extend setup for WeirdERC20
Approving router and minting to router for weirdToken ensures that tests exercise logic involving custom token behavior. Verify test coverage for edge cases concerning weird transfers.

packages/contracts-rfq/test/FastBridgeV2.t.sol (1)

16-16: The new weirdToken references look consistent.
All newly introduced import statements, variable declarations, and initializations for WeirdERC20Mock seamlessly integrate into the test scaffolding. The setFastBridge call is a good addition and ensures the mock token can simulate bridging behavior accurately. No immediate issues are observed.

Also applies to: 34-34, 81-81, 90-90

packages/contracts-rfq/test/FastBridgeV2.Src.t.sol (2)

297-302: Test ensures correct revert when actual transfer exceeds originAmount.
This thorough check confirms that bridging fails if the token transfer surpasses the defined originAmount. Great test coverage.


304-309: Test ensures correct revert when actual transfer is below originAmount.
This scenario confirms that bridging fails if the token transfer is less than the originAmount. Solid negative test coverage.

Copy link
Collaborator

@parodime parodime left a comment

Choose a reason for hiding this comment

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

LGTM - agree on the protocolFee relabel also

Copy link

github-actions bot commented Feb 8, 2025

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days.

@github-actions github-actions bot added Stale and removed Stale labels Feb 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants