Nodle
zkSync Migration

Nodle moved its grants and rewards from the Eden parachain on Polkadot to zkSync. We reviewed the oracle-approved migration of vesting schedules and the new rewards contract that takes batched submissions.
report id
0286
category
Cross-chain & Bridges
language
Solidity
final report
September 3, 2024
lines of code
500
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind Security for Nodle Network. This review focused on the smart contracts enabling the migration of Nodle Network Grants and rewards system from the Eden parachain on Polkadot to ZkSync on Ethereum.

The Grants system involves locked NODL tokens that are vested according to specific schedules for each user. Users are now able to migrate their vesting schedules to zkSync, which requires Nodle’s off-chain system to capture and translate these schedules accurately. Nodle oracles will then submit the schedules to the zkSync GrantsMigration contract as proposals. The migration process is completed once the proposal receives approval from a predefined number of oracles.

Additionally, rewards distribution has been transitioned from the Eden parachain to zkSync via the Rewards contract. The new system introduces batched rewards submissions, allowing multiple rewards to be signed and submitted in a single transaction. Users are encouraged to participate in batch submissions due to the rewards percentage they earn from performing these operations. However, users who prefer not to wait for batched rewards can still request individual signatures from the backend and submit their rewards separately.

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

Audit assessment
Audit TypeSecurity Review
Initial ReportAug 19, 2024
Response from ClientRegular responses during audit engagement
Final ReportSep 03, 2024
Repositoryrollup
Commit (Audit)c90ba67386
Commit (Final)a76f669198
Documentation AssessmentHigh
Test Suite AssessmentMedium
Total findings
3
Fixed
2
Acknowledged
0
Mitigated
1
Unresolved
0

Findings by severity

  • Critical0
  • High1
  • Medium0
  • Low1
  • Informational1
  • Best Practices0

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/Rewards.sol157182115.9%37376
2src/Grants.sol1453826.2%29212
3src/bridge/BridgeBase.sol866676.7%39191
4src/bridge/GrantsMigration.sol1122421.4%23159
Total50031062%128938

4

System Overview

The reviewed smart contracts are part of Nodle Network’s migration from the Eden parachain on Polkadot to zkSync on Ethereum. These contracts handle both the migration of user grants and the transition of the rewards distribution mechanism, which will be halted on Eden parachain and fully transitioned to zkSync.

The following subsections provide an overview of the grants migration process and the new rewards distribution system, detailing the main user flows and components associated with each.

4.1 Grants Migration

Nodle’s grants migration system overview. The diagram presents only the core flows, excluding standard configuration and admin-specific actions
Fig. 2: Nodle’s grants migration system overview. The diagram presents only the core flows, excluding standard configuration and admin-specific actions.

The grants migration goes through the following main steps:

1. Initiating Grant Migration: Users can initiate the migration of their vesting schedules to zkSync by invoking the bridge_all_vesting_schedules(...) function on the pallet_grants contract on the Eden parachain. This function claims the available tokens and transfers them to the user, then emits an event to initiate the migration of remaining locked tokens in the user’s vesting schedules.

2. Proposal Submission and Voting: Nodle Bridge Oracles listen for events emitted by the pallet_grants contract and submit them as proposals to the GrantsMigration contract on zkSync. Each proposal includes the address of the grant recipient, the total amount of the grant, and the array of its schedules:

struct Proposal {
address target; // Address of the grant recipient.
uint256 amount; // Total amount of tokens to be vested.
Grants.VestingSchedule[] schedules; // Array of vesting schedules.
}

Proposals are submitted on-chain through the bridge(...) function:

function bridge(bytes32 paraTxHash, address user, uint256 amount, Grants.VestingSchedule[] memory schedules) external

When the first oracle submits a proposal, other oracles can vote on it using the same function. Once a proposal gathers a predefined number of votes from trusted oracles (threshold), it can be executed after a safetyDelay period has passed since the last vote. 3. Proposal Execution and Grants Creation:

Any address can execute a proposal that has received enough votes and where the safetyDelay period has elapsed. This is accomplished using the grant(...) function:

function grant(bytes32 paraTxHash) external

This function creates vesting schedules for the target user by invoking the addVestingSchedules(...) function on the Grants contract. For that, it mints and then transfers the total amount to the Grants contract.

function addVestingSchedule(address to, uint256 start, uint256 period, uint32 periodCount, uint256 perPeriodAmount, address cancelAuthority) external

Note that the Grants contract introduces a threshold on the number of vesting schedules a user can have (MAX_SCHEDULES); this limit is checked with every addition of new schedules.

4. Claiming Tokens: Once the vesting schedules are migrated to the Grants contract on zkSync, users can call the claim() function to claim their tokens according to the predefined schedule.

function claim() external

4.2 Rewards Distribution

The Nodle reward distribution mechanism on zkSync is a hybrid system that integrates both off-chain and on-chain components. The offchain system handles the computation of rewards for users and generates signed reward messages. Meanwhile, the on-chain component, consisting of the Rewards contract, allows the submission of these signed messages and the claiming of rewards by users. Nodle’s system supports both individual and batch reward submissions.

The rewards off-chain system consists of the following main components:

  • Public API: This is the primary interface for Nodle users. It enables users to request signed messages for their rewards or retrieve existing signatures for sequences not yet submitted on-chain.
  • Signer Server: A private server accessible only via the API. Its role is to sign new reward messages for unused sequence numbers or return existing signatures from the draft database.
  • Draft Rewards Database: This database maintains records of the issued signatures; it stores information such as the sequence number, the user address, and the reward amount for each signed message. A new entry is added to this database each time the Signer issues a signature.
  • Payout Database: This database tracks all pending rewards for different users. When a new reward message is requested, the database is queried to retrieve and sum up all the pending rewards for the specified user. The calculated amount is then signed, and the used rows in the database are updated to have a completed status.
NODL’s rewards system overview. The diagram presents only the core flows, excluding standard configuration and admin-specific actions
Fig. 2: NODL’s rewards system overview. The diagram presents only the core flows, excluding standard configuration and admin-specific actions.

Each user has a unique sequence number that is used to sign and validate individual reward claims, incremented with each successful submission. Similarly, batch rewards have a distinct sequence number, batchSequence, which is also incremented with each successful batch submission.

a. Individual Rewards: Users who wish to claim rewards manually can request a signed message from the Nodle API. This message includes their address, the total reward amount, and a sequence number. The signed message, along with the relevant information, is then submitted to the Rewards contract via the mintReward(...) function.

function mintReward(Reward memory reward, bytes memory signature) external

This function verifies that the signature is valid (signed by the authorizedOracle) and that the sequence number matches the user’s expected value. Upon validation, the reward amount is minted and transferred to the user, and the sequence number is incremented by 1.

b. Batch Rewards: Users can submit a batch of rewards in a single transaction using the mintBatchReward(...) function.

function mintBatchReward(BatchReward memory batch, bytes memory signature) external

To do this, users must request a signed message from the API for a batch of addresses, specifying the batchSequence number. This signature is then used to submit the batch, which mints and transfers the specified amounts to each user in the batch. The batchSequence number is then incremented by 1.

The Nodle team will automatically handle batch issuance for addresses with the highest rewards. Users are incentivized to participate in the submission process, as they receive a batchSubmitterRewardPercentage of the total rewards for their efforts.

Additionally, the contract imposes a quota on the number of tokens minted within a given period. This limit is enforced in both the individual and batch mint functions. Nodle governance has the ability to adjust the quota if necessary.

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 User grants migration can be blocked by exploiting the MAX_SCHEDULES limit

FileFix commitTypeStatus
Grants.solPR #47
9f13844
HighFixed

The Grants contract manages users’ vesting schedules through the vestingSchedules mapping. The addVestingSchedule(...) function, which is public, enables anyone to add a vesting schedule for any recipient by specifying parameters such as period, start, and perPeriodAmount. This function includes a safeguard to ensure that the number of schedules per user does not exceed the predefined MAX_SCHEDULES limit, set to 100.

However, because the function is public, a malicious actor could exploit it by creating multiple vesting schedules with zero perPeriodAmount and long period values. This abuse would fill the schedule limit with ineffective entries, potentially blocking the GrantsMigration contract from successfully adding new schedules and completing the user migration processes.

function addVestingSchedule(
address to,
uint256 start,
uint256 period,
uint32 periodCount,
// @audit Amount can be `0`
uint256 perPeriodAmount,
address cancelAuthority
) external {
// ...
// @audit Cannot add vesting schedule if the limit is reached
_mustNotExceedMaxSchedules(to);

token.safeTransferFrom(msg.sender, address(this), perPeriodAmount * periodCount);

VestingSchedule memory schedule = VestingSchedule(cancelAuthority, start, period, periodCount, perPeriodAmount);
//@audit Function can be repeatedly called with 0 amount until the array reaches the limit
// Moreover, `perPeriodAmount` can be zero
vestingSchedules[to].push(schedule);

emit VestingScheduleAdded(to, schedule);
}

Recommendation

To mitigate this issue, consider implementing the following recommendations:

1. Eliminate the MAX_SCHEDULES cap and instead implement pagination for functions that iterate through the vesting schedules, such as claim(...), renounce(...), and cancelVestingSchedules(...). This allows users to specify the indices of the schedules they want to interact with, addressing the mentioned issue while maintaining control over iteration limits; 2. Introduce constraints to prevent perPeriodAmount from being zero or excessively small, and set reasonable limits on the period to avoid invalid long durations. This will reduce the incentive for malicious actors, as such an exploit would become costlier and less effective;

Resolution

We are considering to keep the MAX_SCHEDULES limit so all the api of this contract remains as it’s on the parachain but taking the second recommendation here: 5adfcef.

Update from Nethermind Security

The provided change make the attack more costly and so less possible to occur, but still possible. Therefore we recommend to set the limit considerably high. Additionally consider limiting upper range of the period to prevent adding infinitely long periods.

Update from the client

Fixed in 9f13844.

6.2 Incorrect check of the batchSubmitterRewardPercentage parameter during contract construction

FileFix commitTypeStatus
Rewards.solPR #48LowFixed

In the Rewards contract, the constructor includes a check using the _mustBeLessThan100(...) function to ensure that the batchSubmitterRewardPercentage is not set above 100. However, this check is ineffective because batchSubmitterRewardPercentage is initialized after the check with the value of rewardPercentage. At the time of the check, batchSubmitterRewardPercentage has not yet been assigned, so the check will always pass regardless of the value of rewardPercentage.

constructor(
NODL token,
uint256 initialQuota,
uint256 initialPeriod,
address oracleAddress,
uint256 rewardPercentage
) EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {
// ...
//@audit `batchSubmitterRewardPercentage` is not initialized
_mustBeLessThan100(batchSubmitterRewardPercentage);
// ...
// @audit `rewardPercentage` value is not validated
batchSubmitterRewardPercentage = rewardPercentage;
}

As a result, the batchSubmitterRewardPercentage could be set to a value greater than 100.

Recommendation

Update the constructor to perform the check on rewardPercentage: _mustBeLessThan100(rewardPercentage);

Resolution

Fixed in 21b6df7.

6.3 Lack of disabling mechanism in GrantsMigration contract

FileFix commitTypeStatus
GrantsMigration.sol—InfoMitigated

The GrantsMigration contract facilitates the migration of users’ vesting schedules from the Eden parachain to the Zksync network. It mints tokens for users to complete their migration process, with each execution requiring voting from a set number of trusted oracles. The contract will become deprecated once the migration period, as defined by the Nodle team, expires and all users have completed their migration.

However, the current implementation lacks a mechanism to disable the contract’s functions after the migration period concludes. As a result, oracles will retain the ability to execute various functions, including minting new tokens, even after the migration is complete. This ongoing access poses a risk of unauthorized actions or misuse, particularly if the oracles’ private keys are compromised or leaked in the future. Thus, without a disabling mechanism, the contract could be vulnerable to exploitation beyond its intended operational timeframe.

Recommendation

Implement a mechanism to disable the contract’s functionality once the migration is complete.

Resolution

The mint permission of this contract is removable through the governance of the NODL token.

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 Nodle team was actively engaged during meetings, addressing questions and concerns effectively. This interaction provided the auditing team with a thorough understanding of both the system architecture and the technical details of the project. Additionally, the Nodle team provided a comprehensive documentation, which proved invaluable for the code review process. This documentation detailed the entire migration process and rewards mechanism, including an explanation of the off-chain components and their main interactions.

Test suite
96Tests passed0Failed

The complete test output is in the full report.

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.