Skip to content

Comments

chore: add updates#112

Merged
Ugo-X merged 1 commit intomainfrom
chore-cleanups
Aug 21, 2025
Merged

chore: add updates#112
Ugo-X merged 1 commit intomainfrom
chore-cleanups

Conversation

@JoE11-y
Copy link
Contributor

@JoE11-y JoE11-y commented Aug 21, 2025

Summary by CodeRabbit

  • New Features

    • Deposit events now include leavesCount, exposing the current Merkle leaf count.
    • Updated DepositEvent signature to add leavesCount between commitmentHash and newRoot.
  • Bug Fixes

    • ETH and ERC20 unlocking flows now complete end-to-end, correctly reducing reserves and transferring funds upon valid proofs.
  • Tests

    • Expanded coverage for full unlock flows (ETH and USDC) aligned with the new event format.
    • Removed legacy test suites that no longer apply.

@coderabbitai
Copy link

coderabbitai bot commented Aug 21, 2025

Walkthrough

This PR removes MerkleStateManager and its tests, updates ZeroXBridgeL1 to emit leavesCount in DepositEvent and to return leavesCount from appendDepositHash, and expands ZeroXBridgeL1 tests to cover unlock flows (ETH/USDC). It also deletes an unused ZeroXBridgeProof test suite.

Changes

Cohort / File(s) Summary
Remove MerkleStateManager
contracts/L1/src/MerkleStateManager.sol, contracts/L1/test/MerkleStateManager.t.sol
Entire MerkleStateManager contract and its comprehensive test suite deleted, including roots/state, relayer management, proof verification, and rate limiting.
ZeroXBridgeL1 event and append flow
contracts/L1/src/ZeroXBridgeL1.sol
DepositEvent signature updated to include leavesCount; appendDepositHash now returns (newRoot, leavesCount, elementCount); minor cleanup in unlockFundsWithProof.
ZeroXBridgeL1 tests updated/expanded
contracts/L1/test/ZeroXBridgeL1.t.sol
Adjusted to new DepositEvent shape; added full unlock tests for USDC and ETH; enabled ERC20 unlock assertions; new test testClaimReducesTokenReserveUSDC.
Remove ZeroXBridgeProof tests
contracts/L1/test/ZeroXBridgeProof.t.sol
Deleted legacy/placeholder proof test suite and scaffolding.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant ZeroXBridgeL1 as ZeroXBridgeL1
  participant MMR as Merkle/MMR Append Logic

  rect rgba(230,245,255,0.6)
  note over User,ZeroXBridgeL1: Deposit flow
  User->>ZeroXBridgeL1: deposit(asset, amount, ...)
  ZeroXBridgeL1->>MMR: appendDepositHash(commitment)
  MMR-->>ZeroXBridgeL1: newRoot, leavesCount, elementCount
  ZeroXBridgeL1-->>User: emit DepositEvent(..., commitmentHash, leavesCount, newRoot, elementCount)
  end
Loading
sequenceDiagram
  autonumber
  actor Relayer
  participant ZeroXBridgeL1 as ZeroXBridgeL1
  participant Token as ERC20/ETH Reserve

  rect rgba(240,255,240,0.6)
  note over Relayer,ZeroXBridgeL1: Unlock with proof (tests exercise path)
  Relayer->>ZeroXBridgeL1: unlockFundsWithProof(proof, sig, params)
  alt Proof valid
    ZeroXBridgeL1->>Token: transfer/unlock to recipient
    ZeroXBridgeL1-->>Relayer: emit FundsUnlocked(...)
  else Proof invalid
    ZeroXBridgeL1-->>Relayer: revert
  end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • Ugo-X

Poem

A hare hops past the Merkle grove,
Leaves counted, roots now on the move.
Old manager burrowed out of sight,
Tests now twinkle, proofs alight.
ETH and USDC unfreeze—how spry!
I thump approval, whiskers high. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore-cleanups

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
contracts/L1/src/ZeroXBridgeL1.sol (4)

235-243: Require the target ‘user’ to be registered before minting a commitment

depositAsset builds the commitment with userRecord[user] but does not require that user has registered. Deposits to an unregistered user will commit a zero pubkey and can later burn funds during unlock (see comment on Lines 300–306).

Apply this guard before computing the commitment:

   // Get the next nonce for this user
   uint256 nonce = nextDepositNonce[user];
   nextDepositNonce[user] = nonce + 1;

+  // Ensure the L2 identity is bound for the receiver
+  require(userRecord[user] != 0, "ZeroXBridge: User not registered");

295-306: Replay-protection keyed by root blocks multi-claim batches; also accept-zero risk

  • You mark proofs as used by verifiedRoot. In a batch, multiple leaves share the same root; after the first claim, all remaining leaves will revert.
  • If the registry returns 0 for an unknown commitment, the current code will set verifiedProofs[0] = true and brick subsequent unlocks, even after a legit root is registered.

Use per-leaf replay protection and reject zero roots.

-    // Track verified proofs to prevent replay attacks
-    mapping(uint256 => bool) public verifiedProofs;
+    // Track claimed leaves to prevent per-leaf replay attacks
+    mapping(bytes32 => bool) public claimedLeaves;
-        uint256 verifiedRoot = proofRegistry.getVerifiedMerkleRoot(commitmentHash);
-        // assert root hasn't been used
-        require(!verifiedProofs[verifiedRoot], "ZeroXBridge: Proof has already been used");
+        uint256 verifiedRoot = proofRegistry.getVerifiedMerkleRoot(commitmentHash);
+        require(verifiedRoot != 0, "ZeroXBridge: Unverified merkle root");
+        bytes32 leaf = bytes32(commitmentHash);
+        require(!claimedLeaves[leaf], "ZeroXBridge: Leaf already claimed");
-        // Store the proof hash to prevent replay attacks
-        verifiedProofs[verifiedRoot] = true;
+        // Mark leaf as claimed
+        claimedLeaves[leaf] = true;

If you still need root-level idempotency, keep a separate mapping for finalized batches, but don’t conflate the two.


300-306: Avoid burning funds when Starknet pubkey is unknown

starkPubKeyRecord[starknetPubKey] can be address(0) if the user never registered. Sending ETH/ERC20 to address(0) either burns funds or locks them forever.

Add a guard:

         // get user address from starknet pubkey
         address user = starkPubKeyRecord[starknetPubKey];
+        require(user != address(0), "ZeroXBridge: Unknown Starknet pub key");

Also consider requiring registration at deposit time (see Lines 235–243).


278-280: Re-enable relayer gating before production

The call to unlockFundsWithProof currently has the relayer check commented out, leaving it open to any caller and significantly expanding the attack surface. Before deploying to production, restore this authorization guard.

• File: contracts/L1/src/ZeroXBridgeL1.sol
• Location: unlockFundsWithProof (around lines 277–281)

-        // require(approvedRelayers[msg.sender], "ZeroXBridge: Only approved relayers can submit proofs");
+        require(approvedRelayers[msg.sender], "ZeroXBridge: Only approved relayers can submit proofs");

If your test suite relies on permissionless access, wrap this check in a test‐only hook or enable it via a constructor flag.

♻️ Duplicate comments (1)
contracts/L1/test/ZeroXBridgeL1.t.sol (1)

1006-1009: USDC unlock test shares the same signature issue

Same fix as above; also ensure you register the proof and pass the exact commitment used to sign.

🧹 Nitpick comments (10)
contracts/L1/src/ZeroXBridgeL1.sol (5)

75-85: Event schema change adds leavesCount; ensure indexers and UIs are updated

Adding leavesCount and reordering fields is a breaking change for off-chain consumers. Confirm downstream indexers (The Graph, log parsers, analytics) are updated to the new ABI and argument order. Also consider whether commitmentHash or depositId should be indexed to improve queryability (you still have one free indexed slot).


247-258: Event emission aligns with new ABI; minor nits

  • Casting bytes32 commitmentHash to uint256 is fine, but consider keeping bytes32 in the event to avoid downstream casting assumptions.
  • If you keep uint256, document endianness for off-chain decoders.

311-314: Amount reconstruction formula is correct; use full-precision math and remove TODO

The scaling matches your deposit path: amount = usd * 10^dec / (price * 10^10). Use Math.mulDiv to avoid overflow/precision loss, and delete the lingering TODO.

-        // uint256 amount = (usd_amount * (10 ** dec)) / price;
-        uint256 amount = (usd_amount * 10 ** dec) / (price * 10 ** 10); //TODO Check if Calculation is correct
+        // amount = usd_amount * 10^dec / (price * 10^10)
+        uint256 amount = Math.mulDiv(usd_amount, 10 ** dec, price * 10 ** 10);

Remember to import OpenZeppelin’s Math.


142-152: Do not assume 8-decimal Chainlink feeds

Some feeds use 8 decimals, others differ. Query decimals() and normalize instead of hardcoding 1e8 in price math, and propagate that value to deposit/unlock conversions.

Example:

-        (, int256 priceInt,,,) = priceFeed.latestRoundData();
+        (, int256 priceInt,,,) = priceFeed.latestRoundData();
+        uint8 feedDec = priceFeed.decimals();
         require(priceInt > 0, "Invalid price from feed");
-        return uint256(priceInt);
+        return uint256(priceInt); // return alongside feedDec or store per token

And replace divisions by 1e8 with the dynamic 10**feedDec.


316-336: ETH transfer reentrancy is low risk but add a guard for defense-in-depth

State is updated before the external call, so you’re safe, but marking unlockFundsWithProof nonReentrant prevents future regressions or complex reentrancy paths when logic evolves.

contracts/L1/test/ZeroXBridgeL1.t.sol (5)

7-11: Duplicate import of Ownable

Ownable is imported twice. Remove the duplicate to keep the test tidy.

-import "@openzeppelin/contracts/access/Ownable.sol";
-import "@openzeppelin/contracts/access/Ownable.sol";
+import "@openzeppelin/contracts/access/Ownable.sol";

483-501: Calculate expected leavesCount instead of hardcoding

You left a hint comment but didn’t compute it. If leavesCount is tracked separately from elementCount, tests should read current leaves and add 1 for the next append to avoid brittleness across test order.

-    function calculateExpectedMmrValues(bytes32 _commitmentHash)
+    function calculateExpectedMmrValues(bytes32 _commitmentHash)
         internal
         view
         returns (bytes32 expectedNewRoot, uint256 expectedElementCount)
     {
         // ...
-        (uint256 nextElementsCount, bytes32 nextRoot,) =
+        (uint256 nextElementsCount, bytes32 nextRoot,) =
             StatelessMmr.appendWithPeaksRetrieval(_commitmentHash, currentPeaks, currentElementsCount, currentRoot);
-
-        // leavesCount += 1;
+
         return (nextRoot, nextElementsCount);
     }

Then, when emitting expectations below, derive expectedLeavesCount = bridge.getLeavesCount() + 1 (assuming MerkleManager exposes this).


526-538: Don’t hardcode leavesCount = 1

If any prior test appends to the MMR, this assertion becomes flaky. Compute expectedLeavesCount from contract state.

-            uint256(expectedCommitmentHash),
-            1,
+            uint256(expectedCommitmentHash),
+            bridge.getLeavesCount() + 1,
             expectedNewRoot,
             expectedElementCount

If getLeavesCount() isn’t exposed, either expose it on MerkleManager for tests or parse the event and assert the rest of the fields instead.


572-584: Same issue: hardcoded leavesCount = 1

Repeat of the previous comment for ERC20.

-            uint256(expectedCommitmentHash),
-            1,
+            uint256(expectedCommitmentHash),
+            bridge.getLeavesCount() + 1,
             expectedNewRoot,
             expectedElementCount

1069-1076: vm.mockCall won’t intercept internal solidity calls

verifyStarknetSignature is invoked internally, so vm.mockCall against address(bridge) is ineffective. Use the harness approach above or make the function external and call this.verifyStarknetSignature(...) to enable mocking (test-only).

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 34b99e4 and b09ef8c.

📒 Files selected for processing (5)
  • contracts/L1/src/MerkleStateManager.sol (0 hunks)
  • contracts/L1/src/ZeroXBridgeL1.sol (2 hunks)
  • contracts/L1/test/MerkleStateManager.t.sol (0 hunks)
  • contracts/L1/test/ZeroXBridgeL1.t.sol (5 hunks)
  • contracts/L1/test/ZeroXBridgeProof.t.sol (0 hunks)
💤 Files with no reviewable changes (3)
  • contracts/L1/test/ZeroXBridgeProof.t.sol
  • contracts/L1/src/MerkleStateManager.sol
  • contracts/L1/test/MerkleStateManager.t.sol
🔇 Additional comments (3)
contracts/L1/src/ZeroXBridgeL1.sol (1)

244-245: Confirm appendDepositHash return ordering

You’re capturing (newRoot, leavesCount, elementCount). Double-check this matches MerkleManager.appendDepositHash’s latest signature; a mismatch in tuple ordering will silently corrupt emitted values and tests relying on them.

contracts/L1/test/ZeroXBridgeL1.t.sol (2)

43-55: Event ABI update mirrored correctly in tests

DepositEvent includes leavesCount in the correct position.


98-143: TVL tests now correctly reflect tracked reserves model

These changes assert that direct transfers don’t affect TVL, which matches the contract’s tokenReserves-based accounting.

Comment on lines +931 to +936
bridge.unlockFundsWithProof(ZeroXBridgeL1.AssetType.ERC20, address(dai), proofdata, commitmentHash, starknetSig);

// Step 9: Assertions
assertEq(bridge.tokenReserves(address(dai)), 0, "tokenReserves should be reduced after unlock");
assertEq(dai.balanceOf(user), depositAmount, "User should receive full unlocked amount");
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Bug: wrong variable passed as commitmentHash to unlock

You compute commitmentHash_ but pass commitmentHash (from setUp, different format). This will always fail the commitment equality check.

-        bridge.unlockFundsWithProof(ZeroXBridgeL1.AssetType.ERC20, address(dai), proofdata, commitmentHash, starknetSig);
+        bridge.unlockFundsWithProof(ZeroXBridgeL1.AssetType.ERC20, address(dai), proofdata, commitmentHash_, starknetSig);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
bridge.unlockFundsWithProof(ZeroXBridgeL1.AssetType.ERC20, address(dai), proofdata, commitmentHash, starknetSig);
// Step 9: Assertions
assertEq(bridge.tokenReserves(address(dai)), 0, "tokenReserves should be reduced after unlock");
assertEq(dai.balanceOf(user), depositAmount, "User should receive full unlocked amount");
}
bridge.unlockFundsWithProof(ZeroXBridgeL1.AssetType.ERC20, address(dai), proofdata, commitmentHash_, starknetSig);
// Step 9: Assertions
assertEq(bridge.tokenReserves(address(dai)), 0, "tokenReserves should be reduced after unlock");
assertEq(dai.balanceOf(user), depositAmount, "User should receive full unlocked amount");
🤖 Prompt for AI Agents
In contracts/L1/test/ZeroXBridgeL1.t.sol around lines 931 to 936, the test calls
bridge.unlockFundsWithProof with commitmentHash (the setup variable in a
different format) but the correct value computed for this unlock is
commitmentHash_; replace the passed commitmentHash with commitmentHash_ so the
proof verification compares the intended computed commitment; ensure
commitmentHash_ is in scope at this call site (or rename/move the computation)
so the test uses the exact computed commitment for the equality check.

@JoE11-y JoE11-y mentioned this pull request Aug 21, 2025
@Ugo-X Ugo-X merged commit bfae1a2 into main Aug 21, 2025
2 of 3 checks passed
@GideonBature GideonBature mentioned this pull request Aug 27, 2025
3 tasks
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