World
Reserved Grants

World made it possible to redeem WLD grants that were reserved off-chain. We reviewed the updated grant contracts that check a backend signature when users redeem.
report id
0148
category
Token & RWA
language
Solidity
final report
November 2, 2023
lines of code
359
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind on the Redeem Reserved Grants containing 359 lines of code.

In the updated version of grant contracts, the Worldcoin team has made it possible to redeem reserved grants, which are managed offchain for cost efficiency. A backend service signs the current timestamp and the user’s nullifier hash, storing it in the database during reservation. Upon redemption, this off-chain signature is submitted on-chain along with standard claim parameters.

The previously audited version did not provide public access to the nullifiers map, which posed a problem during redemption as it was difficult to determine if a grant had already been claimed. To address this issue, a try/catch was added to the checkClaim(...) function in the legacy contract version, which could catch errors in the nullifier check. However, this was seen as a temporary solution, leading to the creation of two contract versions. Both versions share the same logic, except for the nullifier check. To ensure they are only valid for the necessary grant periods, they are associated with specific Grant contracts that implement time restrictions.

Along the audit of this contract, we report 10 points of attention, where 1 is classified as High, 1 is classified as Low, 3-are classified as Info and 5 are classified as Best Practices.

Audit assessment
Audit TypeSecurity Review
Initial ReportOct. 23, 2023
Response from ClientOct. 30, 2023
Final Report-
MethodsManual Review, Automated Analysis
Repositoryworldcoin-grants-contracts
Commit Hash (Audit)9d22282f11
DocumentationREADME.md
Documentation AssessmentHigh
Test Suite AssessmentMedium
Total findings
10
Fixed
4
Acknowledged
4
Mitigated
0
Unresolved
2

Findings by severity

  • Critical0
  • High1
  • Medium0
  • Low1
  • Informational3
  • Best Practices5

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1IGrant.sol1013130.0%730
2LaunchGrantLegacy.sol30620.0%1248
3RecurringGrantDrop.sol14110775.9%66314
4RecurringGrantDropLegacy.sol15211273.7%69333
5WLDGrant.sol26415.4%1242
Total35924267.4%166767

4

System Overview

This audit involves five main contracts grouped as follows:

  • grant drop contracts;
  • grant contracts.

RecurringGrantDrop and RecurringGrantDropLegacy are grant drop contracts. They implemented a new feature allowing users to redeem reserved grants. RecurringGrantDrop will be used for grants with a grantId of 21 or higher. On the other hand, RecurringGrantDropLegacy is designed to work alongside the previous deployment of RecurringGrantDrop contract for grants with an id between 13 and 20. Each GrantDrop contract points to a Grant contract that manages and verifies grant IDs.

The different grant contracts are: WLDGrant, and LaunchGrantLegacy. They are responsible for calculating the grantId, verifying its validity for claims, and redeeming reservations. WLDGrant will be used for grantId of 21 or higher, while LaunchGrantLegacy will only work for grantId between 13 and 20.

Fig. 3 shows how the contracts interact within different grantId intervals. If grantId is between 13 and 20, users can interact with either the previous RecurringGrantDrop contract at 0xe773335550b63eed23a6e60DCC4709106A1F653c or the RecurringGrantDropLegacy contract. Claims are handled at the previous deployment by calling the function claim(...) while redeeming a reservation is only possible on the RecurringGrantDropLegacy contract by calling the function claimReserved(...).

The legacy contract points to the previous deployment, a call to the function checkClaim(...) is done before redeeming a reservation to check the nullifierHashes mapping stored in the old contract, and catch the InvalidNullifier error. Additionally, both contracts must point to the LaunchGrantLegacy grant contract to correctly handle intervals.

When grantId is 21 or higher, the previous contracts are no longer used. Only the new deployment of RecurringGrantDrop will be operational. Users can claim or redeem a reservation using this contract. This contract should point to the WLDGrant grant contract to correctly handle grantId intervals.

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 Possible double signaling in claim function

When grantId is in the interval [13;20[, users can claim either at the previous RecurringGrantDrop contract or the RecurringGrantDropLegacy contract. These two contracts manage separate instances of the nullifierHashes mapping. The RecurringGrantDropLegacy contract verifies the previously stored value in RecurringGrantDrop before executing any claim. However, the other way around is not handled, opening the possibility of a user making a duplicate claim using the same nullifierHash. To illustrate this vulnerability, we provide a diagram showing the attack flow and detail the steps involved:

Storage

@0xe773335550b63eed23a6e60DCC4709106A1F653c

RecurringGrantDrop.sol

LaunchGrantLegacy.sol

User

RecurringGrantDropLegacy.sol

Storage

Consider a user attempting to claim grantId with nullifierHash 5. Initially, nullifierHashes[5] is set to false in both contracts.

  • (1) User initiates a call to RecurringGrantDropLegacy.claim(...) with nullifierHash == 5;
  • (2,3) Check for !nullifierHashes[5] is performed on both contracts;
  • (4,5) checkValidity(...) is called on the grant contract to verify that the grantId is within the accepted range. The contract sets nullifierHashes[5] to true and transfers tokens to the user;
  • (7) User initiates another claim call to RecurringGrantDrop.claim(...) with nullifierHash = 5;
  • (8,9) The contract checks the allowedCallers and nullifierHashes[5] mappings. The mapping in this contract is not updated from the previous call, resulting in the check successfully passing;
  • (10,11) checkValidity(...) is called on the grant contract, nullifierHashes[5] is set to true in the RecurringGrantDrop contract, and tokens are transferred to the user;

In this scenario, the user successfully claimed the tokens using the same nullifierHash twice.

Recommendation

Managing two contracts with separate instances of the same storage data introduces complexity and increases the likelihood of errors and vulnerabilities. To mitigate this, it is advised to restrict claims within the [13,20) grantId range to be handled exclusively by the RecurringGrantDrop contract. This eliminates the possibility of duplicate claims and simplifies the flow.

Resolution

Deployment procedure was now changed to the following:

  • Existing contract gets updated to use LaunchGrantLegacy (allowing claiming only until grantId 20);
  • Claiming logic got removed from RecurringGrantDropLegacy (only reservation redemption); This contract also has LaunchGrantLegacy set.
  • RecurringGrantDrop is deployed with WLDGrant (allowing both redemption of reservations and normal claiming starting grantId 21);

Also updated in the previously flawed PR comment.

6.2 Centralization risk for intended behavior

The intended behavior of contracts differs based on specific grantId intervals. Users are expected to claim or redeem grants at either the previous RecurringGrantDrop contract or RecurringGrantDropLegacy contract for grantIds [13;20[, and at the new RecurringGrantDrop contract for grantIds [20;∞[.

A centralization risk emerges because the logic handling grantId intervals are implemented within the Grant contracts. Both the contracts RecurringGrantDrop and RecurringGrantDropLegacy point to a specific Grant contract, and the owner can update its address through the function setGrant(...). This gives the owner the possibility to disrupt the expected behavior by setting a wrong grant address.

Recommendation

Consider revisiting the centralization risk within the protocol and whether it is acceptable for the owner to have this level of control over the intended behavior. If necessary, design changes should be made to the solution in order to ensure a less error-prone approach.

Resolution

Acknowledged. Limitation of current design. Ownership will be handed over to a governance contract in the future.

6.3 Unnecessary external call for the current timestamp

FileFix commitTypeStatus
RecurringGrantDropLegacy.solPR #7InfoFixed

In the function checkClaimReserved(...), a timestamp is provided as input and used to fetch the corresponding grantId. This grandtId is necessary to check the reservation validity through a call to the function checkReservationValidity(...). If the provided timestamp indicates a future time, the function reverts. However, if the timestamp corresponds to the current block timestamp (block.timestamp), the grantId will represent the currentGrantId in both LaunchGrantLegacy and WLDGrant contracts. This leads to the checkReservationValidity(...) call always reverting.

function checkClaimReserved(
uint256 timestamp,
address receiver,
uint256 root,
uint256 nullifierHash,
uint256[8] calldata proof,
bytes calldata signature
) public {
uint256 grantId = grant.calculateId(timestamp);

if (receiver == address(0)) revert InvalidReceiver();
if (timestamp > block.timestamp) revert InvalidTimestamp();
...

// @audit call to `checkReservationValidity` always reverts with the current timestamp
grant.checkReservationValidity(timestamp);
...
}

Recommendation

Consider updating the timestamp check to avoid an unnecessary external call. Below is the code with the suggested change:

if (timestamp >= block.timestamp) revert InvalidTimestamp();

Resolution

Recommendation implemented.

6.4 Unnecessary external calls could be replaced by using internal calls

FileFix commitTypeStatus
LaunchGrantLegacy.sol
WLDGrant.sol
RecurringGrantDropLegacy.sol
—InfoAcknowledged

When this.functionName(...) is used, the contract makes an external call to itself, causing the sender to become address(this). This is useful when the target function’s logic depends on the sender’s address. However, in the context of RecurringGrantDropLegacy, LaunchGrantLegacy, and WLDGrant contracts, these are unnecessary. They can be replaced with normal internal calls to save gas while maintaining the same result. For instance, this.calculateId(...) can be changed to calculateId(...).

function checkReservationValidity(uint256 timestamp) external view override {
// @audit `this.calculateId()` is unnecessary and wasting gas
uint256 grantId = this.calculateId(timestamp);

// No future grants can be claimed.
if (grantId >= this.getCurrentId()) revert InvalidGrant();

// Only grants 20 and above can be reserved.
if (grantId < 20) revert InvalidGrant();

// Reservations are only valid for 12 months.
if (block.timestamp > timestamp + 52 weeks) revert InvalidGrant();
}

Recommendation

Consider using internal calls instead to save gas.

Resolution

External calls are kept because of the grant interface.

6.5 allowedCallers check can be bypassed for claiming process

FileFix commitTypeStatus
RecurringGrantDropLegacy.sol
RecurringGrantDrop.sol
—InfoAcknowledged

Between grantId values 13 and 19, users can claim using either the previous RecurringGrantDrop contract or the newly deployed RecurringGrantDropLegacy contract. Both paths are expected to operate identically. However, this is not the case, as the RecurringGrantDrop contract enforces a caller validation check before allowing a claim. This check is absent in the RecurringGrantDropLegacy contract. Consequently, users can bypass this check by exclusively calling the claim function on the latter contract.

function claim(uint256 grantId, address receiver, uint256 root, uint256 nullifierHash, uint256[8] calldata proof) external {
// @audit check is removed in the `RecurringGrantDropLegacy` contract. Users can bypass this check by calling `claim(...)` on the later contract instead.
if (!allowedCallers[msg.sender]) revert Unauthorized();
...
}

Recommendation

Given that the allowedCallers check will be deprecated after grantId 20, it is important to verify if this is also the case for lower values when both RecurringGrantDrop and RecurringGrantDropLegacy contracts are operating. If not, we recommend updating the contract logic to ensure identical claiming behavior across the two contracts. This can be achieved by either integrating the allowedCallers in the RecurringGrantDropLegacy contract or restricting claims to be done exclusively on the previous RecurringGrantDrop contract.

Resolution

allowedCallers is not relied on in production since the MultiCall3 contract is also allowed caller. This check can be savely ignored.

6.6 External call before input validations

FileFix commitTypeStatus
RecurringGrantDropLegacy.solPR #7Best PracticesUnresolved

The checkClaimReserved(...) function calls grant.calculateId(...) function to retrieve the grantId. This call is made before performing input checks, resulting in unneeded gas consumption if checks will revert.

function checkClaimReserved(
uint256 timestamp,
address receiver,
uint256 root,
uint256 nullifierHash,
uint256[8] calldata proof,
bytes calldata signature
) public {
uint256 grantId = grant.calculateId(timestamp);
// @audit verifications can be done before the external call, to avoid unnecessary gas consumption
if (receiver == address(0)) revert InvalidReceiver();
if (timestamp > block.timestamp) revert InvalidTimestamp();
...
}

Recommendation

Consider reordering code to perform input checks before retrieving the grantId.

Resolution

Recommendation implemented.

Update from Nethermind Security

The suggested optimization in checkClaimReserved(...) function was not implemented.

6.7 Redundant call to grant.calculateId(...) in the function claimReserved(...)

FileFix commitTypeStatus
RecurringGrantDrop.sol
RecurringGrantDropLegacy.sol
—Best PracticesAcknowledged

The function claimReserved(...) initially calls the grant contract to calculate grantId. It then uses the function checkClaimReserved(...) to verify the claim’s validity. This function, however, performs the same call to the grant contract to calculate the grantId again, which is not efficient.

function claimReserved(uint256 timestamp, address receiver, uint256 root, uint256 nullifierHash, uint256[8] calldata proof, bytes calldata signature)
external
{
uint256 grantId = grant.calculateId(timestamp); // @audit First call to calculate ID
checkClaimReserved(timestamp, receiver, root, nullifierHash, proof, signature);
...
}

function checkClaimReserved(uint256 timestamp, address receiver, uint256 root, uint256 nullifierHash, uint256[8] calldata proof, bytes calldata signature)
public
{
uint256 grantId = grant.calculateId(timestamp); // @audit Second call to calculate ID
...
}

Recommendation

Consider passing grantId to the function checkClaimReserved(...) or have the function checkClaimReserved(...) return the value of grantId to avoid unnecessary external calls. Another possible solution is to introduce an internal function _checkClaimReserved(...) to avoid changing the interfaces of the two existing external functions.

Resolution

Not implemented.

6.8 Redundant check for grantId less than 13 in the function checkReservationValidity(...)

FileFix commitTypeStatus
LaunchGrantLegacy.solPR #7Best PracticesFixed

The function checkReservationValidity(...) contains a redundant check for grantId < 13, which is unnecessary due to the constraints set by the function calculateId(...). The function calculateId(...) ensures that grantId is always greater than or equal to 13 or triggers a revert.

// @audit Return value at least 13
function calculateId(uint256 timestamp) external pure returns (uint256) {
if (timestamp < launchDayTimestampInSeconds) revert InvalidGrant();

uint weeksSinceLaunch = (timestamp - launchDayTimestampInSeconds) / 1 weeks;
// Monday, 24 July 2023 07:00:00 until Monday, 07 August 2023 06:59:59 (2 weeks)
if (weeksSinceLaunch < 2) return 13;
// Monday, 07 August 2023 03:00:00 until Monday, 14 August 2023 02:59:59 (1 week)
if (weeksSinceLaunch < 3) return 14;
return 15 + (weeksSinceLaunch - 3) / 2;
}

function checkReservationValidity(uint256 timestamp) external view override {
uint256 grantId = this.calculateId(timestamp);
...
// @audit Check for grantId < 13 is unnecessary
if (grantId < 13 || grantId >= 20) revert InvalidGrant();
...
}

Recommendation

Consider removing the redundant check in the function checkReservationValidity(...). It will also help to maintain the consistency with the check in the function checkValidity(...).

Resolution

Recommendation implemented.

6.9 Unused imports

FileFix commitTypeStatus
RecurringGrantDropLegacy.sol
RecurringGrantDrop.sol
PR #7Best PracticesFixed

The following imports are not being used in the RecurringGrantDrop and RecurringGrantDropLegacy contracts.

// @audit imports are not used by the contract
import { SafeTransferLib } from 'solmate/utils/SafeTransferLib.sol';
...
import { IWorldID } from 'world-id-contracts/interfaces/IWorldID.sol';

Recommendation

Consider removing unused imports from both contracts.

Resolution

Recommendation implemented.

6.10 Wrong or missing NatSpec documentation

FileFix commitTypeStatus
RecurringGrantDropLegacy.solPR #7Best PracticesUnresolved

The following issues have been identified in the RecurringGrantDropLegacy contract’s NatSpec comments:

  • Wrong title for contract:;
/// @title RecurringGrantDrop
// @audit wrong contract title
/// @author Worldcoin
contract RecurringGrantDropLegacy is Ownable2Step {
  • Absence of NatSpec description for signature input of claimReserved(...) function;
  • Outdated @dev note referring to the removed hashToField function in both claim(...) and claimReserved(...) functions;
/// @dev hashToField function docs are in lib/world-id-contracts/src/libraries/ByteHasher.sol
function claim(
/// @dev hashToField function docs are in lib/world-id-contracts/src/libraries/ByteHasher.sol
function claimReserved(

Recommendation

Consider implementing the documentation updates and fixes listed above.

Resolution

Recommendation implemented.

Update from Nethermind Security

We confirm that the previous documentation issues were fixed. However, we noticed a few comments that need to be corrected in the new commits. Consider fixing them.

  • Comment using the previous grantId interval here;
  • Date in this comment refers to the old timestamp;

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 is presented in README.md. Additionally, we found that the insights shared in this comment within the pull request are quite valuable for grasping the contracts’ design and intended functionality.

8.3 Code Coverage

The relevant output is presented below.

Test suite
11Tests 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.