Skip to content

SYN-100: legacy workflows for mint and withdraw#335

Merged
ChiTimesChi merged 6 commits intofeat/syn-bridge-unifiedfrom
syn-100-legacy-workflows
Jun 5, 2025
Merged

SYN-100: legacy workflows for mint and withdraw#335
ChiTimesChi merged 6 commits intofeat/syn-bridge-unifiedfrom
syn-100-legacy-workflows

Conversation

@ChiTimesChi
Copy link
Collaborator

@ChiTimesChi ChiTimesChi commented May 30, 2025

Summary by CodeRabbit

  • Refactor

    • Improved maintainability by centralizing shared logic for minting and withdrawing, and streamlined legacy workflow handling for certain bridge operations.
  • Tests

    • Added comprehensive tests for legacy bridge operations, including event validation, access control, edge cases, and reentrancy protection.
    • Introduced mock contracts to support advanced testing scenarios.

@coderabbitai
Copy link

coderabbitai bot commented May 30, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes refactor the SynapseBridge contract by introducing internal helper functions for minting and withdrawing, reducing code duplication and enabling conditional logic for legacy mode. Additionally, new mock contracts and a comprehensive test suite are added to simulate legacy bridge scenarios, including reentrancy and revert cases, enhancing test coverage and validation.

Changes

File(s) Change Summary
contracts/bridge/SynapseBridge.sol Refactored: Added internal _withdraw and _mint helpers; external functions delegate to them; legacy mode fallback logic added to mintAndSwap and withdrawAndRemove.
test/bridge/legacy/PoolMock.sol Added: New PoolMock contract with stubbed swap and liquidity removal functions for testing.
test/bridge/legacy/ReenteringToken.sol Added: ReenteringToken contract simulates reentrant calls during transfers/mints for tests.
test/bridge/legacy/SynapseBridge.Dst.t.sol Added: SynapseBridgeLegacyDstTest contract with extensive tests for legacy bridge destination, covering events, balances, reentrancy, access control, and legacy mode.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SynapseBridge
    participant Token
    participant PoolMock

    User->>SynapseBridge: mintAndSwap(...)
    alt isLegacySendDisabled == true
        SynapseBridge->>SynapseBridge: _mint(...)
        SynapseBridge->>Token: mint tokens
    else
        SynapseBridge->>SynapseBridge: _mint(...)
        SynapseBridge->>Token: mint tokens
        SynapseBridge->>PoolMock: swap tokens
    end
    SynapseBridge-->>User: emit event / transfer tokens
Loading
sequenceDiagram
    participant User
    participant SynapseBridge
    participant Token
    participant PoolMock

    User->>SynapseBridge: withdrawAndRemove(...)
    alt isLegacySendDisabled == true
        SynapseBridge->>SynapseBridge: _withdraw(...)
        SynapseBridge->>Token: transfer tokens
    else
        SynapseBridge->>SynapseBridge: _withdraw(...)
        SynapseBridge->>Token: transfer tokens
        SynapseBridge->>PoolMock: remove liquidity
    end
    SynapseBridge-->>User: emit event / transfer tokens
Loading

Poem

A rabbit hopped through legacy code,
Refactored paths where logic flowed.
With helpers neat and tests anew,
It checked for bugs that might slip through.
Reentrancy traps and swaps in play—
The bridge is safer every day!
🐇✨


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@coveralls
Copy link

coveralls commented May 30, 2025

Pull Request Test Coverage Report for Build 15447013869

Details

  • 0 of 6 (0.0%) changed or added relevant lines in 1 file are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage decreased (-0.02%) to 12.818%

Changes Missing Coverage Covered Lines Changed/Added Lines %
contracts/bridge/SynapseBridge.sol 0 6 0.0%
Totals Coverage Status
Change from base Build 15446216395: -0.02%
Covered Lines: 664
Relevant Lines: 4723

💛 - Coveralls

@ChiTimesChi
Copy link
Collaborator Author

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented May 30, 2025

✅ Actions performed

Full review triggered.

Copy link

@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 (5)
test/bridge/legacy/ReenteringToken.sol (1)

10-11: Consider using private visibility for test isolation.

The target and data state variables are currently internal. For better test isolation and to prevent unintended inheritance issues, consider changing them to private.

-    address internal target;
-    bytes internal data;
+    address private target;
+    bytes private data;
test/bridge/legacy/PoolMock.sol (1)

9-16: Document the default return values for mock functions.

The calculateSwap and calculateRemoveLiquidityOneToken functions have empty implementations and will return 0 by default. Consider adding comments to make this behavior explicit for test clarity.

     function calculateSwap(
         uint8 tokenIndexFrom,
         uint8 tokenIndexTo,
         uint256 amount
-    ) external returns (uint256) {}
+    ) external returns (uint256) {
+        // Mock returns 0 by default
+    }

     function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex) external returns (uint256) {}
+        // Mock returns 0 by default
+    }
contracts/bridge/SynapseBridge.sol (2)

393-396: Consider event emission consistency in legacy fallback.

When isLegacySendDisabled is true, the function falls back to _mint which emits TokenMint event instead of TokenMintAndSwap. This might cause confusion for off-chain monitoring systems expecting TokenMintAndSwap events.

Consider emitting a TokenMintAndSwap event with swapSuccess=false to maintain event consistency:

         // Fallback to regular mint if legacy workflows are disabled.
         if (isLegacySendDisabled) {
-            return _mint(to, token, amount, fee, kappa);
+            _mint(to, token, amount, fee, kappa);
+            emit TokenMintAndSwap(
+                to,
+                token,
+                amount.sub(fee),
+                fee,
+                tokenIndexFrom,
+                tokenIndexTo,
+                minDy,
+                deadline,
+                false,
+                kappa
+            );
+            return;
         }

501-504: Maintain event consistency for withdrawAndRemove fallback.

Similar to the mintAndSwap function, consider emitting a TokenWithdrawAndRemove event with swapSuccess=false when falling back to regular withdraw.

         // Fallback to regular withdraw if legacy workflows are disabled.
         if (isLegacySendDisabled) {
-            return _withdraw(to, token, amount, fee, kappa);
+            _withdraw(to, token, amount, fee, kappa);
+            emit TokenWithdrawAndRemove(
+                to,
+                token,
+                amount.sub(fee),
+                fee,
+                swapTokenIndex,
+                swapMinAmount,
+                swapDeadline,
+                false,
+                kappa
+            );
+            return;
         }
test/bridge/legacy/SynapseBridge.Dst.t.sol (1)

129-338: Consider adding edge case tests for completeness.

While the test coverage is comprehensive, consider adding tests for:

  • Zero amount scenarios for mint/withdraw operations
  • Maximum uint256 values to test for overflow conditions
  • Duplicate kappa usage (should revert)
  • Multiple sequential operations to test state consistency

Would you like me to generate these additional edge case tests?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3407298 and f9cda06.

📒 Files selected for processing (4)
  • contracts/bridge/SynapseBridge.sol (4 hunks)
  • test/bridge/legacy/PoolMock.sol (1 hunks)
  • test/bridge/legacy/ReenteringToken.sol (1 hunks)
  • test/bridge/legacy/SynapseBridge.Dst.t.sol (1 hunks)
🔇 Additional comments (6)
test/bridge/legacy/ReenteringToken.sol (1)

32-40: Good reentrancy implementation pattern!

The implementation correctly clears the state variables before making the external call, preventing repeated reentrancy. This is a solid pattern for testing reentrancy protection.

contracts/bridge/SynapseBridge.sol (2)

224-225: Excellent refactoring to reduce code duplication!

The extraction of common withdrawal logic into the _withdraw internal function improves maintainability and ensures consistency across different withdrawal paths.

Also applies to: 231-252


270-271: Well-structured refactoring for mint operations!

The _mint internal function properly consolidates the minting logic, maintaining all security checks and event emissions.

Also applies to: 277-292

test/bridge/legacy/SynapseBridge.Dst.t.sol (3)

2-3: Consider the implications of using Solidity 0.6.12.

While this might be intentional for testing legacy functionality, Solidity 0.6.12 is quite outdated and lacks many security improvements and optimizations from newer versions. Additionally, ABIEncoderV2 is marked as experimental in this version.

Could you confirm that using this specific version is required for compatibility with the legacy SynapseBridge contract?


13-127: Well-structured test setup with comprehensive helper functions.

The test contract is well-organized with:

  • Clear separation of state variables, events, modifiers, and helper functions
  • Comprehensive event expectation helpers that match the expected bridge behavior
  • Good use of modifiers to set up different test scenarios

129-338: Comprehensive test coverage with proper edge case handling.

The test implementations excellently cover:

  • Normal operations (mint, mintAndSwap, withdraw, withdrawAndRemove)
  • Legacy mode disabled scenarios with proper fallback verification
  • Reentrancy protection validation with expected revert messages
  • Access control verification using fuzzing with vm.assume
  • Reverting pool scenarios

The tests properly validate events, balances, and state changes (kappa existence).

@ChiTimesChi ChiTimesChi merged commit ec6948b into feat/syn-bridge-unified Jun 5, 2025
10 checks passed
@ChiTimesChi ChiTimesChi deleted the syn-100-legacy-workflows branch June 5, 2025 13:44
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

Comments