Download audit report
This document presents the security review performed by Nethermind Security for Lagoon Protocol smart contracts. Lagoon Protocol is a decentralized asset management platform that enables asset managers to create Lagoon Vaults. These Vaults provide efficient, non-custodial, and risk-managed asset management solutions.
Built on a foundation of smart contract standards, Lagoon Protocol leverages the power of Gnosis Safe, Zodiac Roles Modifier, and other key components to create highly customizable and secure vaults for managing digital assets.
The audited code comprises 1056 lines of code written in the Solidity language. The audit focuses on the implementation of ERC-7540 Vault contract.
The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, and (c) creation of test cases.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | October 18, 2024 |
| Final Report | November 7, 2024 |
| Repository | lagoon-v0 |
| Commit | 090461aff6 |
| Final Commit | cd6135f5b9 |
| Documentation | Docs |
| Documentation Assessment | High |
| Test Suite Assessment | High |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | src/protocol/Events.sol | 4 | 11 | 275.0% | 3 | 18 |
| 2 | src/protocol/FeeRegistry.sol | 57 | 35 | 61.4% | 14 | 106 |
| 3 | src/vault/Roles.sol | 62 | 36 | 58.1% | 13 | 111 |
| 4 | src/vault/Whitelistable.sol | 51 | 23 | 45.1% | 11 | 85 |
| 5 | src/vault/Silo.sol | 14 | 4 | 28.6% | 5 | 23 |
| 6 | src/vault/FeeManager.sol | 145 | 67 | 46.2% | 42 | 254 |
| 7 | src/vault/ERC7540.sol | 415 | 173 | 41.7% | 129 | 717 |
| 8 | src/vault/Vault.sol | 191 | 91 | 47.6% | 39 | 321 |
| 9 | src/vault/primitives/Errors.sol | 20 | 31 | 155.0% | 24 | 75 |
| 10 | src/vault/primitives/Events.sol | 31 | 39 | 125.8% | 19 | 89 |
| 11 | src/vault/primitives/Enums.sol | 6 | 2 | 33.3% | 3 | 11 |
| 12 | src/vault/primitives/Struct.sol | 14 | 12 | 85.7% | 4 | 30 |
| 13 | src/vault/interfaces/IERC7540.sol | 9 | 2 | 22.2% | 5 | 16 |
| 14 | src/vault/interfaces/IWETH9.sol | 6 | 4 | 66.7% | 3 | 13 |
| 15 | src/vault/interfaces/IERC7540Deposit.sol | 16 | 8 | 50.0% | 7 | 31 |
| 16 | src/vault/interfaces/IERC7540Redeem.sol | 10 | 1 | 10.0% | 5 | 16 |
| 17 | src/vault/interfaces/IERC7575.sol | 5 | 2 | 40.0% | 2 | 9 |
| Total | 1056 | 541 | 51.2% | 328 | 1925 |
| # | Finding | Severity | Update |
| 1 | The user can mint vault shares without providing the correct amount of underlying native assets | Critical | Fixed |
| 2 | Pending assets are moved to the vault while still in a pending state | High | Fixed |
| 3 | The _withdraw(...) and _mint(...) functions do not round in favor of the protocol | Low | Fixed |
| 4 | The highWatermark is set inconsistently | Low | Unresolved |
| 5 | Shares can be burned when depositing to the address(0) | Info | Fixed |
| 6 | DOS attacks on controllers are possible between settlements | Info | Acknowledged |
| 7 | Implementation contracts can be initialized | Best Practices | Fixed |
| 8 | The msg.sender is accessed inconsistently | Best Practices | Fixed |
Lagoon Protocol is a decentralized asset management platform that enables asset managers to create Lagoon Vaults. These Vaults provide efficient, non-custodial, and risk-managed asset management solutions.
Built on a foundation of smart contract standards, Lagoon Protocol leverages the power of Gnosis Safe, Zodiac Roles Modifier, and other key components to create highly customizable and secure vaults for managing digital assets.
Lagoon Protocol enables the creation of decentralized Vaults (Lagoon Vaults) that support various roles, including Asset Managers, NAV Committees, Vault Creators, and Fund Depositors. These Vaults are governed by smart contracts that allow for a wide range of DeFi strategies, from asset management to yield farming, all while maintaining a high level of security and control. The protocol’s design prioritizes flexibility, enabling asset managers to configure their Vaults with specific DeFi protocol whitelists, separation of power, fee structures, and more. It follows the ERC-7540 standard for Asynchronous ERC-4626 Tokenized Vaults.
A Vault can be in three main states: Open, Closing, and Closed. Depending on the current state of the Vault, it will behave differently for certain actions.
It is important to note that requestDeposit operations are always available, even when executing any new settlements is impossible. If a user requests a deposit and no new settlement can be executed, the user can cancel the request and recover the funds.
Deposit and Redemption are the most important operations from the Vault. These are the actions executed by users to deposit assets and redeem shares. These operations are executed asynchronously. Users first need to create a request and wait until a settlement is executed, which will complete their request. After a request is completed, a user can finish the deposit or redeem operation. A request can only be completed if it was placed before the final evaluation for the current settlement period. This means that if the settlement occurs after the request has been placed but without any evaluations between these two events, this settlement will not complete the request. The user will have to wait until the next evaluation and settlement.
Compared to synchronous vaults, in asynchronous vaults, the users do not know the price per share that will be executed for their operation at the moment of the request. When they start a request, the involved assets are sent to the pending silo contract until the operation is settled. After the operation is settled, depending on the type of operation, the funds will be sent to the asset manager or the vault. Users can claim their assets or shares based on the price per share related to their settlement.
The Vault will charge two types of fees: management and performance fees.
The management fees are calculated based on the assets under management (AUM) and are charged over time and collected during vault settlement. The formula used here calculates management fees by multiplying the assets by the management rate (a percentage expressed in basis points or BPS) and prorating it by the time elapsed (relative to one year).
The performance fees are charged on profits and are calculated only when the value of the assets exceeds a high water mark (the highest historical value per one share). This is done to ensure that fees are charged only on actual profits and not on recovered losses.
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:
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:
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 / Likelihood | Low | Medium | High |
| High | Medium | High | Critical |
| Medium | Low | Medium | High |
| Low | Info / Best Practices | Low | Medium |
| Undetermined | Undetermined | Undetermined | Undetermined |
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.
| File | Fix commit | Type | Status |
src/vault/ERC7540.sol | cd6135f | Critical | Fixed |
This issue was found and reported by the Lagoon Protocol team. Whenever the users request a deposit into the Vault contract, they specify the amount of assets they wish to deposit. If the Vault’s asset is configured to be a wrapped native token, the users can send the native tokens as msg.value in the call to requestDeposit(...) function and the vault will wrap the tokens for them automatically. The problem present in the _requestDeposit(...) function is that it assumes that the assets specified by the user match the provided msg.value, which might not be the case.
function _requestDeposit(uint256 assets, address controller, address owner)
internal
returns (uint256)
{
// ...
// @audit `assets` amount is user controlled. Internal accounting
// accepts whatever was provided by the user.
$.epochs[_depositId].depositRequest[controller] += assets;
if (msg.value != 0) {
if (asset() == address($.wrappedNativeToken)) {
// @audit-issue The user can specify arbitrary `assets` amount
// and provide fewer native tokens. The request will go through.
// After that, the user can finish the deposit and mint vault shares,
// even though not enough underlying native tokens were provided.
$.pendingSilo.depositEth{value: msg.value}();
} else {
revert CantDepositNativeToken();
}
} else {
IERC20(asset()).safeTransferFrom(
owner, address($.pendingSilo), assets
);
}
// ...
}In this scenario, the user can specify an arbitrary amount of assets without sending that amount of native tokens to the contract. The provided assets amount is saved in the internal accounting and will be used to compute the shares the user will receive upon deposit completion.
The shares transferred to the user on deposit completion are minted beforehand once the deposits are settled in _settleDeposit(...). The number of shares minted depends on the actual token balances of the PendingSilo contract. Since the user could have provided fewer native tokens, fewer shares would have been minted as a result.
However, on deposit completion, the user will be rewarded with shares computed based on internal accounting, which is higher than expected. There might be a situation where the Vault contract will attempt to transfer more shares to the user than it currently holds and revert. The other scenario is more severe. The Vault might have enough shares to cover the user’s deposit at the cost of other users.
Recommendation
Ensure the asset parameter is equal to msg.value when using native token.
Resolution
The issue was fixed in this commit.
| File | Fix commit | Type | Status |
src/vault/Vault.sol | ce307cd | High | Fixed |
Whenever a user requests an action, the assets/shares are moved to the pendingSilo contract. Then, after a settlement operation, they are moved out from the pendingSilo contract. For example, if a user requests a deposit, the assets will be sent to the pendingSilo. After that, when settleDeposit(...) is called, the funds will be sent from the pendingSilo to the asset manager, and the new shares for the requested assets will be minted.
A problem arises because all the assets in the pendingSilo are moved and used to settle the operation, even though there may be some assets that should remain pending. These assets are the ones related to users who requested their action before the settlement but after the last valuation update that occurred. This behavior has several unwanted impacts.
As a first impact, the users who request a deposit between the last valuation update and the settlement will not be able to cancel their deposit, even though they should be able to. This is due to the funds not being in the pendingSilo anymore.
Secondly, if the previous impact is analyzed in the context of closing the vault, the users would lose their funds, as they will never be able to complete their request or cancel it.
As a third impact, this situation will create an inconsistency in the amount of existing shares. This is because the new shares will be minted in the settlement operation at a specific price per share. However, the user can only execute the deposit at the price per share of the next settlement. If the price per share increases between the two settlements, there will be a remainder of the shares that cannot be claimed. On the other hand, if the price per share decreases between the two settlements, there will not be enough shares to cover the requested deposit from all the users.
Recommendation
Consider only moving from the pendingSilo and executing the request that will move to a completed state.
Resolution
Fixed in this commit.
_withdraw(...) and _mint(...) functions do not round in favor of the protocol| File | Fix commit | Type | Status |
src/vault/ERC7540.sol | fbe6745 | Low | Fixed |
As explained in the EIP4626, it is considered most secure to always round in favor of the vault. This is not the case in the _withdraw(...) and _mint(...) functions where the rounding favors the user.
The _withdraw(...) function receives the amount of assets the user wants to withdraw and computes the amount of shares that must be given in return. The computation of how many shares must be given rounds down.
function _withdraw(uint256 assets, address receiver, address controller) internal returns (uint256 shares) {
ERC7540Storage storage $ = _getERC7540Storage();
uint40 requestId = $.lastRedeemRequestId[controller];
if (requestId > $.lastRedeemEpochIdSettled) {
revert RequestIdNotClaimable();
}
// @audit - The computation of the shares rounds down
shares = convertToShares(assets, requestId);
$.epochs[requestId].redeemRequest[controller] -= shares;
IERC20(asset()).safeTransfer(receiver, assets);
emit Withdraw(msg.sender, receiver, controller, assets, shares);
}The _mint(...) function receives the amount of shares to be minted and computes how many assets the user must transfer. The computation how many assets the user must transfer rounds down.
function _mint(uint256 shares, address receiver, address controller) internal virtual returns (uint256 assets) {
ERC7540Storage storage $ = _getERC7540Storage();
uint40 requestId = $.lastDepositRequestId[controller];
if (requestId > $.lastDepositEpochIdSettled) {
revert RequestIdNotClaimable();
}
// @audit - The computation of how many assets must be transferred rounds down
assets = _convertToAssets(shares, requestId, Math.Rounding.Floor);
$.epochs[requestId].depositRequest[controller] -= assets;
_update(address(this), receiver, shares);
emit Deposit(controller, receiver, assets, shares);
}Recommendation
Consider changing rounding directions to always favor the Vault.
Resolution
Fixed in this commit.
highWatermark is set inconsistently| File | Fix commit | Type | Status |
src/vault/Vault.sol | 6e2e262ce307cd | Low | Unresolved |
The highWatermark value is used to compute the performanceFee. This value represents the highest price of one share. Every time a settlement occurs, the price per share is computed, and if it is greater than the previously stored highWatermark the new value is stored.
function _setHighWaterMark(uint256 _newHighWaterMark) internal {
FeeManagerStorage storage $ = _getFeeManagerStorage();
uint256 _highWaterMark = $.highWaterMark;
if (_newHighWaterMark > _highWaterMark) {
emit HighWaterMarkUpdated(_highWaterMark, _newHighWaterMark);
$.highWaterMark = _newHighWaterMark;
}
}The fees are computed in the _calculateFees(...) function. If the new price per share is higher than the current highWatermark value, this function will compute the current price per share and calculate the performance fee. Since fees are paid in shares, new shares will be minted to accommodate them. As a result of the newly minted shares, the share price in the vault will automatically decrease after the fees are charged.
The _setHighWaterMark(...) function is called right after that. However, the price per share used to compute the fees in the previous step will differ from that used for the _setHighWaterMark(...), creating an inconsistency. The price used in the _setHighWaterMark(...) function is the already decreased share price.
Recommendation
Consider calling the _setHighWaterMark(...) function with the price of the shares before the fees were charged.
Resolution
We made a first implementation inside this commit and then refactored inside this commit. The difference is that the pricePerShare is return from _calculateFees() instead of being passed to it as a parameter.
address(0)| File | Fix commit | Type | Status |
src/vault/ERC7540.sol | 9fa5dfe | Info | Fixed |
To receive the shares for an asset deposit in the asynchronous vault, the deposit controller has to call the deposit(...) function on the Vault contract. The caller controls the receiver address that will receive the shares. Internally, the deposit(...) function uses the _update(...) function from OpenZeppelin’s ERC20 to update the receiver address’s shares. An issue arises when the controller accidentally specifies the receiver as an address(0). Since the _update(...) function treats transfers to the address(0) as burns, the vault share tokens would be burned.
Recommendation
It is considered a best practice to use higher-level ERC20 functions that use _update(...) internally and better capture the caller’s intent, such as _transfer(...), _mint(...), and _burn(...). Consider using _transfer(...) instead of _update(...) to transfer the shares to the receiver address during the deposit.
Resolution
Fixed in this commit.
DOS attacks on controllers are possible between settlements| File | Fix commit | Type | Status |
src/vault/ERC7540.sol | — | Info | Acknowledged |
controllers can only have one request for redeem or deposit in the Pending state. If a redeem or deposit request is created for a controller at epoch x, no other redeem or deposit request can be created for the same controller while the previous one is in the Pending state.
Because any user can create a request associated with any controller, it is possible for a user to create a request for a controller with a minimum amount. As a result, the controller won’t be able to create new requests until a settlement occurs.
It is important to note that until the epoch changes, requests can be modified by the controller without creating a new one.
Recommendation
Consider documenting the previously described behavior. To reduce possible damages caused by this, consider frequently executing settlement operations.
Resolution
We won’t fix this.
| File | Fix commit | Type | Status |
src/vault/Vault.solsrc/protocol/FeeRegistry.sol | e3171d2773e700 | Best Practices | Fixed |
The implementation contracts Vault and FeeRegistry do not disable the initialize(...) functions. This allows anyone to call initialize(...) on these contracts with arbitrary values, which may lead to unwanted behavior. An example of such malicious behavior is initiating a call from the implementation contract to a sanctioned or black-listed contract such as Tornado Cash. This action could lead to unnecessary legal issues for institutions that use the protocol smart contracts.
Recommendation
Consider removing the possibility of calling the initialize(...) functions on the implementation contracts. This may be done by calling the _disableInitializers(...) in the constructor, which will disable calling functions with the initializer modifier.
Resolution
msg.sender is accessed inconsistently| File | Fix commit | Type | Status |
src/vault/Vault.sol | bbcc325 | Best Practices | Fixed |
The Vault contract’s redeem(...) function calls the _msgSender(...) function from OpenZeppelin’s Context module to get the address of an account that initiated the redemption. This is unnecessary since the caller in the current execution context can be accessed directly from the msg.sender property. Usage of _msgSender(...) may lead to inconsistencies in the future.
Recommendation
Consider removing an unnecessary call to _msgSender(...) and replace it with direct access to the msg.sender to make the code more readable.
Resolution
Fixed in commit.
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:
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.
The documentation for the Lagoon Protocol was provided through their official docs. This documentation provided a high-level overview of the protocol and details of its implementation. Moreover, the Lagoon Protocol 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.
Lagoon protocol’s test suite is comprehensive and covers all the core flows of the protocol. To further enhance it and determine potential uncovered code paths, the Nethermind Security team applied a technique called mutation testing. This technique introduces slight modifications to the code called "mutations" or "mutants." An example of a mutation is, for example, changing the operator in an expression (a + b) to (a - b), or removing a require(a > b) statement entirely from the code. With these changes, the code no longer follows the expected business logic of the application, and the test suite should reflect that by failing.
Evaluation of the test suite with mutation testing consists of two phases:
a. Generating the modified version of each contract, called "mutants."
b. Inserting the mutant into the original codebase and running the test suite.
Only one modification can be tested at a time. If the contract has ten mutations, the test suite must run ten times (once for every mutation). If any of the tests fail, it means that the test suite caught the change in the code. Whenever that happens, the particular mutant is considered "slain" or "killed" and is removed from the mutant’s set. If that does not occur, a new test case can be added to cover the code branch and "kill" the mutant.
The following table outlines the results of the analysis performed on the Lagoon protocol’s core contracts. The first column lists the contracts that were tested using mutation testing. The second column indicates the number of mutants generated and how many were "slain" (i.e., caught by the test suite). The third column provides the percentage of mutants slain, reflecting the effectiveness of the test suite in covering the particular contract.
Contract Mutants (slain / total generated) Score ERC7540 261/285 91.57% FeeManager 131/142 92.25% FeeRegistry 8/8 100% Silo 3/3 100% Vault 57/68 83.82%
Whitelistable 17/19 89.47%
The following is a list of code modifications not caught by the existing test suite. Each point highlights a scenario that could benefit from higher test coverage to enhance the protocol’s overall security and resilience in the next code change iterations as the project evolves.
ERC7540.sol
_totalSupply += shares inside the _settleDeposit(...) function is only used to emit an event. The value by which the _totalSupply is incremented can be arbitrarily changed or even set to 0 with no effect on the test suite. The same happens inside the _settleRedeem(...) function. An additional test can be added to check that the value emitted in the event is exactly what it is expected to be.$erc7540.redeemSettleId = redeemSettleId + 2 inside the _settleRedeem(...) function can be entirely removed from the codebase with no effect on the test suite. An additional test can be added to check that the redeemSettleId before and after redemption settlements are different and are changed as expected.pendingDepositRequest(...) is not tested for cases where requestID is smaller than lastDepositEpochIdSettled. In these situations, the default value of 0 is returned since there are no pending deposit requests after settlement. A test case can be added to ensure that the state of the contract reflects this expectation.requestId = $.lastDepositRequestId[controller] in the claimableDepositRequest(...) function can be replaced with a hardcoded requestID of 1 with no effect on the test suite. The tests can be extended with end-to-end scenarios where a single controller goes through the whole protocol flow multiple times to test that the request IDs are updated correctly and point to appropriate asset values.0 after the cancelRequestDeposit(...) was called.FeeManager.sol
managementFee = annualFee.mulDiv(...) in the _calculateManagementFee(...) function, managementFee can be assigned a hardcoded 0 value instead, with no effect on the test suite. Test cases can be added to ensure the computed managementFee matches the expectations._takeFees(...) function. A test case can be added to ensure that the shares are not minted twice if redemptions are settled before the deposits. Additional test cases can be added to test scenarios where the managerShares are minted but not the protocolShares.Vault.sol
NotWhitelisted error. A test case can be added to ensure that a non-whitelisted user cannot call the requestDeposit(...) function (the one with four parameters including the referral; the other requestDeposit(...) is tested).settleRedeem(...) function, the call to the _takeFees(...) function can be entirely removed with no effect on the test suite. Test cases can be added around the amounts of specific fees minted during the redemption settlement. Such tests are also missing for the close(...) function.settleRedeem(...) function’s tests are not checking that the new high watermark was actually set. The _setHighWaterMark(...) can be called with an arbitrary value, and the tests will pass (e.g. setting the watermark to 1, while 1000 was used to determine whether to take the performance fee or not).close(...) function, calls to the _settleDeposit(...) and _settleRedeem(...) functions can be removed with no effect on the test suite. Tests can be added to ensure that the vault is correctly settled before closing it.| 135Tests passed | 0Failed |
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.
The Leading Engineers of Blockchain Infrastructure