Royco
CCDM

Covered a new feature letting depositors prove and withdraw funds on the destination chain via Merkle proofs.
report id
0418
category
Token & RWA
language
Solidity
final report
January 20, 2025
lines of code
1321
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind Security of the Cross-chain Deposit Module (CCDM). The review focused on a new feature introduced to the CCDM protocol, enabling deposits on the source chain to be included in a Merkle tree. This enhancement optimizes gas costs by bridging only the Merkle root to the destination chain instead of explicitly sending individual depositor data, such as addresses and deposit amounts. Depositors can later prove their deposits on the destination chain using Merkle proofs to withdraw their funds. This feature aligns with CCDM’s goal of facilitating gas-efficient cross-chain deposit campaigns and was assessed for its impact on the protocol’s security and functionality.

The audited code comprises 1321 lines of code written in the Solidity language. The audit focused on the new Merkle deposit feature introduced to the CCDM system.

The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, and (c) creation of test cases.

Audit assessment
Audit TypeSecurity Review
Initial ReportJanuary 20, 2025
Final ReportJanuary 20, 2025
Repositorycross-chain-deposit-module
Commit0f92459025
Final Commit22e8058a23
DocumentationDocs
Documentation AssessmentHigh
Test Suite AssessmentLow
Total findings
2
Fixed
2
Acknowledged
0
Mitigated
0
Unresolved
0

Findings by severity

  • Critical1
  • High0
  • Medium1
  • Low0
  • Informational0
  • Best Practices0

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/core/DepositLocker.sol71955376.9%2211493
2src/core/DepositExecutor.sol49147396.3%1641128
3src/libraries/CCDMPayloadLib.sol1026664.7%17185
4src/libraries/CCDMFeeLib.sol914155.6%427
Total1321110683.7%4062833

4

System Overview

The overview of the entire CCDM system can be found in the CCDM audit report: NM-0366-FINAL_CCDM.

This section focuses exclusively on the newly added functionality of Merkle Deposits and Merkle Withdrawals. These features extend CCDM’s capabilities by introducing Merkle tree-based mechanisms for aggregating and verifying deposits and withdrawals.

On the source chain, the DepositLocker contract facilitates deposits using the merkleDeposit function. Key information, such as the deposit nonce, depositor’s address, and deposit amount, is hashed into a leaf node and added to the Merkle tree. Once all deposits for a market are complete, and the market is marked as ready to bridge, the merkleBridgeSingleTokens function can be called. This function finalizes the Merkle root, writes it into the composeMsg, and sends it to the destination chain using the LayerZero protocol. For markets utilizing Uniswap V2 LP tokens, the equivalent bridging function is merkleBridgeLpTokens.

During the audit, a market halting feature was introduced to enhance control and security. Once the system administrator halts a market, no further deposits can be made to that market. Additionally, funds in the halted market cannot be bridged to the destination chain. However, users retain the ability to withdraw their Merkle deposits from the source chain using the merkleWithdraw function. The halting action is irreversible.

On the destination chain, the DepositExecutor contract includes the withdrawMerkleDeposit function. To withdraw their funds, users must provide a Merkle proof and the original data used to create the leaf on the source chain. If the recipe associated with the market has been successfully executed on the destination chain, users will receive the corresponding receipt tokens. If the recipe was not executed, users can withdraw the tokens they originally deposited.

These updates improve the CCDM system by enabling efficient aggregation and verification of deposits while adding safeguards and flexibility for deposit and withdrawal processes.

The primary objective was to support bridging a significantly larger number of users compared to the previous design.

5

Risk Rating Methodology

The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.

Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.

Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 Incorrect accounting in withdrawMerkleDeposit(...) leads to loss of funds

FileFix commitTypeStatus
src/core/DepositExecutor.solaf45906CriticalFixed

The withdrawMerkleDeposit(...) function can be called on the destination chain to withdraw the funds deposited using the merkleDeposit(...) function in the DepositLocker contract on the source chain. It transfers the receipt token and dust amount if the deposit recipe was executed. Otherwise, it transfers the original tokens by calculating the user's shares. There's an issue in withdrawMerkleDeposit(...) in a scenario where the recipe hasn't been executed. The problem is that the calculation of the amountOwed in the withdrawMerkleDeposit(...) should be done using the totalMerkleTreeSourceAmountLeftToWithdraw and not using totalMerkleTreeAmountDepositedOnSource. In the current implementation, the later users withdraw, the fewer tokens they will get, leading to incorrect calculation of shares.

function withdrawMerkleDeposit(
address _weirollWallet,
uint256 _merkleDepositNonce,
uint256 _amountDepositedOnSource,
bytes32[] calldata _merkleProof
)
external
nonReentrant
{
// Instantiate Weiroll Wallet from the address
WeirollWallet weirollWallet = WeirollWallet(payable(_weirollWallet));
// ...
// Get the campaign details for the source market
DepositCampaign storage campaign = sourceMarketHashToDepositCampaign[weirollWallet.marketHash()];
// Get the accounting ledger for this Weiroll Wallet (amount arg is repurposed as the CCDM Nonce on destination)
WeirollWalletAccounting storage walletAccounting = campaign.weirollWalletToAccounting[_weirollWallet];
// ...
// Generate the leaf for this depositor to verify the proof against the root
bytes32 depositLeaf = keccak256(abi.encodePacked(_merkleDepositNonce, msg.sender, _amountDepositedOnSource));
// ...
// Process the withdrawal
// Get the original amount deposited on source
uint256 totalMerkleTreeAmountDepositedOnSource = walletAccounting.totalMerkleTreeAmountDepositedOnSource;
// Get the amount left to withdraw from merkle tree
uint256 totalMerkleTreeSourceAmountLeftToWithdraw = walletAccounting.totalMerkleTreeSourceAmountLeftToWithdraw;
if (weirollWallet.executed()) {
// ...
} else {
// ...
// If deposit recipe hasn't been executed, return the depositor's share of the input tokens
for (uint256 i = 0; i < campaign.inputTokens.length; ++i) {
// Get the amount of this input token deposited by the depositor
ERC20 inputToken = campaign.inputTokens[i];
uint256 totalAmountDepositedOnDest = walletAccounting.tokenToTotalAmountDepositedOnDest[inputToken];

// Make sure that the depositor can withdraw all campaign's input tokens atomically to avoid race conditions with recipe execution
require(totalAmountDepositedOnDest > 0, WaitingToReceiveAllTokens());

// @audit-issue totalAmountDepositedOnDest will be reduced proportionally to the amount withdrawn, whereas totalMerkleTreeAmountDepositedOnSource remains the same
// Calculate the tokens owed to the depositor
uint256 amountOwed = (totalAmountDepositedOnDest * _amountDepositedOnSource) / totalMerkleTreeAmountDepositedOnSource;
// Account for withdrawal
walletAccounting.tokenToTotalAmountDepositedOnDest[inputToken] -= amountOwed;

// Transfer the amount deposited back to the depositor
inputToken.safeTransfer(msg.sender, amountOwed);
}
}
// ...
}

Consider the following scenario:

  • There are five deposits on the source chain for 20 LP tokens each. Thus, a total of 100 LP tokens;
  • While bridging, 100 LP tokens were equal to 200 token0 and 200 token1;
  • Now, in case the recipe isn't executed and it's a Merkle tree withdrawal:
    • The first user to call withdrawMerkleDeposit(...) will get 40 token0 and 40 token1 as totalAmountDepositedOnDest will be 200, _amountDepositedOnSource will be 20, and totalMerkleTreeAmountDepositedOnSource will be 100.
    • The second user to withdraw will get 32 token0 and 32 token1 as totalAmountDepositedOnDest will be 160, _amountDepositedOnSource will be 20, and totalMerkleTreeAmountDepositedOnSource will be 100. It is incorrect as the second one to call should also get 40 token0 and 40 token1 as all the depositors have the same shares.

Recommendation

Consider replacing totalMerkleTreeAmountDepositedOnSource with totalMerkleTreeSourceAmountLeftToWithdraw in the calculation of amountOwed in the withdrawMerkleDeposit(...) for the case in which the recipe isn't executed.

6.2 Bridging LP tokens with skewed pool ratios can result in funds being locked

FileFix commitTypeStatus
src/core/DepositLocker.sol2ce40c1MediumFixed

The campaign owner has to call merkleBridgeLpTokens(...) to bridge LP tokens. This will remove liquidity from the Uniswap V2 pair. The issue is that there's no check to ensure that one (or both) of the token's quantity received after removing liquidity is non-zero. If one of the tokens's quantity is zero and for the other, it's non-zero, then the bridged token would be permanently stuck in the DepositExecutor. This happens since the campaign owner cannot call executeDepositRecipes(...) for that market as it further calls _transferInputTokensToWeirollWallet(...), which reverts if the token amount is zero. Nor can depositors call withdrawMerkleDeposit(...) as it reverts if one of the token amounts is zero for the Weiroll wallet and a withdrawal recipe isn't executed.

Recommendation

Consider adding a check in merkleBridgeLpTokens(...) to make sure that the amount of tokens received after removing liquidity is not zero.

7

Documentation Evaluation

Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.

8

Remarks & Test Suite

The documentation for the CCDM contracts was provided through their official docs as well as detailed code comments. This documentation provided a high-level overview of the protocol and details of its implementation. Moreover, the CCDM team addressed all questions and concerns raised by the Nethermind Security team, providing valuable insights and a comprehensive understanding of the project's technical aspects.

Remarks about the CCDM contract's test suite

The test suite of the CCDM contracts covers all major flows of the protocol. However, upon closer review, it was observed that the suite lacks the necessary depth to validate certain edge cases and specific state changes. This limitation makes the test suite prone to errors, such as off-by-one issues, which can compromise the reliability of the protocol in critical scenarios.

In particular, the absence of targeted assertions to verify state transitions after each operation reduces the effectiveness of the tests in identifying subtle bugs. Enhancing the granularity and precision of the assertions could significantly improve the suite's resilience.

To address these gaps, incorporating mutation testing could be an effective approach. Mutation testing introduces small changes to the contract code to verify whether the test suite is capable of detecting them. This method can highlight untested or weakly tested paths in the code, providing a clear roadmap for improving test coverage.

All the relevant issues raised by the AuditAgent have been incorporated into this report. The AuditAgent is an AI-powered smart contract auditing tool that analyses code, detects vulnerabilities, and provides actionable fixes. It accelerates the security analysis process, complementing human expertise with advanced AI models to deliver efficient and comprehensive smart contract audits. Available at https://app.auditagent.nethermind.io.

As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.

This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.