World
WLD Vault

World App users can deposit WLD into the Vault and earn interest, but only while their World ID is verified. We reviewed the interest accrual logic and its link to the WorldIDAddressBook registry.
report id
0268
category
DeFi & Yield
language
Solidity
final report
July 23, 2024
lines of code
392
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind Security for the Worldcoin Vault. The Vault is a smart contract allowing World App users to deposit WLD tokens and earn interest for their deposited amounts. Interest accrual is calculated based on the time elapsed since the deposit or the last claimed rewards. Furthermore, the contract integrates with the WorldIDAddressBook, which maintains a registry of verified users alongside with their verification time. Rewards are only accrued during periods when users are verified.

The audited code comprises 392 lines of code in Solidity. The Worldcoin team has provided inline documentation that explains the purpose and functionality behind the audited contracts. The audit was performed using: (a) manual analysis of the codebase, (b) simulation of the smart contracts.

Audit assessment
Audit TypeSecurity Review
Initial ReportJuly 19, 2024
Final ReportJuly 23, 2024
MethodsManual Review
Repositoryworldcoin-vault
Commit Hash7e24810f0b
Final Commit Hash28171872a2
DocumentationInline comments
Documentation AssessmentLow
Test Suite AssessmentMedium
Total findings
8
Fixed
6
Acknowledged
2
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium0
  • Low2
  • Informational1
  • Best Practices5

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1WLDVault.sol22611149.1%86423
2WorldIDAddressBook.sol1077570.1%39221
3interfaces/IVault.sol403485.0%1387
4interfaces/IAddressBook.sol131184.6%226
5utils/ByteHasher.sol6583.3%112
Total39223660.2%141769

4

System Overview

The WLDVault enables World App users to deposit WLD tokens and earn yield over time. It interacts with the WorldIDAddressBook contract, which maintains a registry of verified users along with their verification timestamps. This ensures that only verified users can accrue interest based on their deposits.

4.1 WorldIDAddressBook

The WorldIDAddressBook contract is responsible for the verification of user addresses that can earn yield in WLDVault. This contract integrates with the WorldID proof verification system to authenticate users using zero-knowledge proofs.

The WorldIDAddressBook contract is initialized with several key parameters that control the verification process. These parameters are set during the contract’s deployment:

  • worldIdRouter: The instance of the WorldID router responsible for managing groups and verifying zero-knowledge proofs.
  • groupId: A unique identifier for the group within the WorldID system.
  • externalNullifierHash: A hash used to prevent double-signaling by ensuring each proof is unique.
  • verificationLength: The duration, in seconds, for which a verification is considered valid.
  • maxProofTime: The maximum allowable time, in seconds, in which a proof must be validated to be considered legitimate.

Users submit their verification proof through the verify(...) function, providing necessary details such as account address, nullifier hash, proof, and proof time.

function verify(
address account,
uint256 root,
uint256 nullifierHash,
uint256[8] calldata proof,
uint256 proofTime
) external payable override;

The contract verifies the proof’s validity with the worldIdRouter and updates the (nullifierHashes and addressVerifiedUntil) mappings to reflect the user’s verification status and validity period.

4.2 WLDVault

The WLDVault contract is a savings vault designed to allow verified users within the Worldcoin ecosystem to deposit their WLD tokens and earn yield over time. The WLDVault contract’s functionality include:

  • Deposits: Users can deposit WLD tokens into the vault. Upon deposit, the tokens start accruing interest immediately if the user is verified. The contract maintains a record of each user’s deposited amount.
  • Withdrawals: Users can withdraw their deposited tokens along with the accrued interest at any time. The contract ensures that the correct amount of interest is calculated and distributed upon withdrawal.
  • Interest Calculation: Interest is computed based on a predefined yield rate, the amount deposited, and the duration for which the tokens have been saved in the vault.

4.2.1 Deposits and Withdrawals

Users primarily engage with the WLDVault contract through its deposit and withdrawal functions. These functionalities allow users to deposit their WLD tokens and subsequently withdraw them along with any accrued interest. The accrued interest is calculated and immediately added to the user’s balance during each deposit operation.

The deposit(...) function allows users to deposit WLD tokens into the vault. This function can be called with or without specifying an account, allowing deposits for other users.

During the deposits, the vault interacts with WorldIDAddressBook to query the addressVerifiedUntil mapping to obtain a timestamp, which will be saved to the user’s deposit struct Deposit as endTime variable. This timestamp refers to the point to which the user can accrue interest for his deposited amount.

function deposit(uint256 amount) external virtual;

The withdraw(...) and withdrawAll(...) functions allow users to withdraw their tokens from the vault. Users can also use the withdrawWithSig(...) function to authorize withdrawals with an off-chain signature.

function withdraw(uint256 amount) external virtual;

function withdrawAll() external virtual;

function withdrawWithSig(
address receiver,
uint256 amount,
uint256 nonce,
bytes calldata signature
) external virtual;

Moreover, users can use the recoverDeposit() function to withdraw their deposited amounts only, excluding the accrued interests.

function recoverDeposit() external virtual;

4.2.2 Interest Calculation

Interest in the WLDVault contract is calculated based on several key parameters:

  • Yield Rate: The annual percentage yield for the vault. This value is set by the owners of the WLDVault contract.
  • Deposit Amount: The amount of WLD tokens deposited by the user.
  • Time Elapsed: The time (in seconds) that has elapsed since the last interest calculation.

The formula for the interest calculation is as follows:

Interest = ( ) Seconds Per Year × 10000

Additionally, users’ interests are controlled by additional parameters managed by the contract owner:

1. maxYieldAmount: The maximum amount of tokens for which the user is able to earn interest.

2. yieldAccrualDeadline: The maximum timestamp to which the user is able to accrue rewards.

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 check in _withdraw(...) function could prevent valid withdrawals

FileFix commitTypeStatus
WLDVault.sol0eb0dacLowFixed

The _withdraw(...) function is an internal function responsible for processing user withdrawal requests. It performs several validation checks before updating all states and executing the withdrawal. The first validation check, contractBalance < amount, ensures that the contract’s balance has enough tokens to cover the withdrawal. The second validation check, contractBalance - amount < totalUserDeposits, aims to prevent withdrawals that would dip into other users’ deposits. However, this second check makes an incorrect assumption about the totalUserDeposits variable, as it includes the current user deposits without subtracting the withdrawn amount.

Below is the relevant section of the code:

function _withdraw(address user, uint256 amount) internal {
// ...
uint256 contractBalance = token.balanceOf(address(this));
if (
contractBalance < amount ||
// @audit: `totalUserDeposits` includes the current user withdrawn `amount`
contractBalance - amount < totalUserDeposits
) {
revert ContractInsolvent();
}
// ...
}

For example:

  • User 1 deposits 100 tokens;
  • User 2 deposits 200 tokens;
  • totalUserDeposits is 300 tokens;

After some time, User 1 earned 10 tokens, and User 2 earned 20 tokens in interest. The contractBalance must now be at least 330 tokens (110 + 220) while totalUserDeposits remains at 300 since it does not account for accrued interest. If User 1 attempts to withdraw 50 tokens, the check will fail:

contractBalance - amount < totalUserDeposits
// 330 - 50 < 300

This issue will be amplified when the contract doesn’t own enough reward tokens.

Recommendation

Consider updating totalUserDeposits before the check to account for the current withdrawal.

Resolution

superseded by 0eb0dac952a005a88c92c73a6e392aa60543cc32

Update from Nethermind Security

Issue fixed. For a more complete condition here, you could also consider verifying if the yield source balance covers the fromYieldSourceAmount. However, implementing this check would increase gas costs of the function.

6.2 Potential interest loss due to Address Book and verification length changes

FileFix commitTypeStatus
WLDVault.solPR #10LowFixed

The WorldIDAddressBook contains a mapping that WLDVault queries to determine the verification timestamp until which a user can accrue rewards. This timestamp is stored in the user’s Deposit structure as the endTime variable during the call to the deposit(...) function. Once a user deposits, the endTime should only increase by depositing additional tokens or calling the refresh(...) function if the user is verified for additional periods. In both cases, the WorldIDAddressBook is queried again to check if the verification timestamp has been extended.

However, an issue arises when the addressBook in WLDVault is updated to a new deployment of the WorldIDAddressBook contract. The new address book will contain a fresh mapping, causing any previously verified users to become unverified. If a user then calls deposit(...), it will reset their endTime to zero, causing the user to stop accruing rewards. This can result in users losing a portion of their rewards if this occurs before their original endTime expires.

A similar situation occurs when the verificationLength is updated to a shorter value, as re-verifying a user can set an earlier endTime. Consequently, users will accrue fewer rewards if they interact with the protocol before reaching their original endTime.

Recommendation

To avoid potential inconsistencies in rewards distribution, consider disallowing the user’s endTime to be decreased within the WLDVault contract.

Resolution

Addressed in db0044c03b8ae983449464e2f3373632f4cedd36.

6.3 Payable verify(...) function may lead to locked Ether

FileFix commitTypeStatus
WorldIDAddressBook.sol—InfoAcknowledged

The verify(...) function in the WorldIDAddressBook contract is currently marked as payable, allowing Ether to be sent during invocation. However, this function calls verifyProof(...) from the worldIdRouter contract without utilizing any Ether in the process.

As there is no mechanism to withdraw Ether from the WorldIDAddressBook contract, any Ether sent to this function will become permanently locked in the contract.

Recommendation

To address this issue, consider removing the payable modifier from the verify(...) function. If the payable modifier is necessary for interface compatibility, implement a mechanism to prevent users from sending Ether during the function call.

Resolution

Acknowledged, won’t fix.

6.4 Avoid the usage of magic numbers

FileFix commitTypeStatus
WLDVault.solPR #13Best PracticesFixed

A magic number is a numerical value hard-coded in the source code, which, without the context, makes it hard to understand the developer’s intent in using that number. To avoid this anti-pattern, it’s recommended to define a constant with a meaningful name instead of using magic numbers directly.

An example of this behavior is the numeric literal 10000 used in the calculateInterest(...) function.

Recommendation

To keep the code easier to read and comprehend, consider defining a constant like ONE_HUNDRED_PERCENT instead of using the literal 10000.

Resolution

Addressed in 3b729f38444f848e1a379c22c5da3731711e4a9b.

Update from Nethermind Security

Issue fixed. Note that this comment can be completed in a similar way to the yieldRate, indicating the 2 decimals representation, i.e basis points.

6.5 Missing inputs validation

FileFix commitTypeStatus
WLDVault.sol
WorldIDAddressBook.sol
PR #13
2817187
Best PracticesAcknowledged

Whenever the caller is expected to provide input to the function, performing validation checks on the values provided is recommended as a best practice. It ensures that the contract does not end up in an undesired state. Below is a non-exclusive list of significant missing checks:

  • WorldIDAddressBook -> verificationLength: The constructor ensures verificationLength cannot be set to 0, but this validation is absent in the setVerificationLength(...) function. This inconsistency could result in verificationLength being set to 0, preventing user validation;
  • The deposit(...) function does not check if the account is not the zero address. As a result, a user might mistakenly lose the funds by sending them to the zero address;
  • The token and addressBook variables in the WLDVault contract lack zero address check in both the contract constructor and the setAddressBook(...) function;
  • The maxProofTime can be set to 0 in the setMaxProofTime(...) function;
  • The yieldRate and maxYieldAmount variables could be bounded to reasonable values to prevent setting them unreasonably high by accident;

Recommendation

To prevent the contracts from entering an unexpected state, consider extending the input validation to eliminate the risks mentioned above from happening.

Resolution

Partially addressed in f9fea2ac999c591b90df9e47aae9caac7904e7b4. Acknowledged missing deposit check for gas savings.

Update from Nethermind Security

The outlined checks are fixed except for the acknowledged deposit check. We have added two additional bullet points to the list where the checks could be implemented.

Update from the client

Partially addressed in 28171872a23a03bef49898eb939934765157fa4b. Bounding the yieldRate and maxYieldAmount is not considered neccesary.

6.6 Redundant check in refresh(...) function

FileFix commitTypeStatus
WLDVault.solPR #13Best PracticesFixed

The refreshInterest(...) function checks the current user’s amount and exits if it is zero:

function refreshInterest(...) internal {
if (userDeposit.amount == 0) return;
// ...
}

However, this internal function is never invoked when userDeposit.amount == 0 as this check is already performed in all external functions that call it. Specifically, in the public refresh(...) function, the check is implemented as follows:

function refresh(...) public override {
// ...
Deposit storage userDeposit = getDeposit[account];
// @audit Duplicated check
if (userDeposit.amount != 0) refreshInterest(userDeposit);
// ...
}

Recommendation

Remove the redundant check from the public refresh(...) function.

Resolution

Addressed in a525fb9f805eb59d3c6c511918f477eaef4c8bc5.

6.7 The WalletVerified event is not emitted in the verify(...) function

FileFix commitTypeStatus
WorldIDAddressBook.solPR #13Best PracticesFixed

The WorldIDAddressBook contract defines the WalletVerified event to be emitted upon account verification. However, the verify(...) function, which handles the account verification process, currently does not emit this event upon successful verifications.

Recommendation

Consider implementing the emission of the WalletVerified event within the verify(...) function. Alternatively, if the event is unnecessary, consider removing its definition to maintain clarity and prevent confusion.

Resolution

Event removed in ba60f3355c34b55f441067dd2e9e654bcad800dc.

6.8 The verify(...) function does not follow C-E-I pattern

FileFix commitTypeStatus
WorldIDAddressBook.solPR #13Best PracticesFixed

The Checks, Effects, and Interactions pattern is generally a best practice that functions should follow. It prevents the possible impact of reentrancy as the state of the contract is updated before the external interactions.

The verify(...) function inside the WorldIDAddressBook contract does not follow this pattern. It invokes the verifyProof(...) function on the worldIdRouter before updating the state of mappings for address verification. Fortunately, there is currently no direct impact as worldIdRouter is a contract controlled by Worldcoin.

Recommendation

To prevent future issues, consider following this pattern by updating the state of the contract before external calls.

Resolution

Addressed in 446c89ec08fec6fbad9259eae5bd9a1f5ee12e9b.

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 Worldcoin team has provided documentation about their protocol in the form of in-line comments within the code. However, these comments did not provide a comprehensive explanation of the architecture and decisions behind various functionalities. Despite this, the Worldcoin team was available to address any questions or concerns from the Nethermind Security team.

Remarks about Worldcoin test suite

The Worldcoin team has developed an broad testing suite that comprehensively covers a variety of user workflows, including scenarios related to interest calculation. However, it is worth noting that initially, the vault was pre-funded with a substantial number of tokens. This approach resulted in certain states of the contract unexplored during testing phases.

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