Mangrove
Vault

MangroveVault lets users deposit a base and quote token into Mangrove's Kandel market-making strategy in exchange for vault shares. We reviewed share minting and burning and the owner's controls over Kandel settings and fees.
report id
0339
category
DeFi & Yield
language
Solidity
final report
October 28, 2024
lines of code
970
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind Security for Mangrove vault. The Mangrove team has developed the MangroveVault contract, a vault built on top of Mangrove’s Kandel strategy. This vault manages two underlying assets: a base and a quote token, and it serves two types of actors: regular users and the contract owner. Users can mint vault shares by depositing the required amounts of underlying tokens. These tokens are subsequently allocated to the Kandel strategy managed by the vault, which implements an automated market-making strategy on Mangrove. Shareholders can burn their shares in exchange for an equivalent amount of underlying tokens.

The vault owner is responsible for setting and updating the Kandel parameters, as well as adjusting other vault parameters, including fee percentages and the state of the funds within the vault.

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 ReportOct 25, 2024
Response from ClientRegular responses during audit engagement
Final ReportOct 28, 2024
Repositorymangrove-vault
Commit (Audit)d03e9731b0
Commit (Final)2d00ae71c9
Documentation AssessmentHigh
Test Suite AssessmentMedium
Total findings
3
Fixed
1
Acknowledged
1
Mitigated
1
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium1
  • Low1
  • Informational1
  • Best Practices0

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1MangroveVault.sol53740074.5%1231060
2MangroveVaultFactory.sol2114.8%325
3oracles/IOracle.sol610166.7%218
4oracles/chainlink/MangroveChainlinkOracleFactory.sol352468.6%463
5oracles/chainlink/MangroveChainlinkOracle.sol675176.1%12130
6lib/MangroveVaultEvents.sol4384195.3%13140
7lib/MangroveVaultErrors.sol1461435.7%1186
8lib/GeometricKandelExtra.sol865462.8%12152
9lib/MangroveVaultConstants.sol8675.0%317
10lib/DistributionLib.sol1367252.9%16224
11lib/MangroveLib.sol1715.9%422
Total97076478.8%2031937

4

System Overview

The Mangrove vault consists of the main MangroveVault contract, which implements essential functionalities for both users and the contract owner. Each vault holds two underlying assets: a base token and a quote token, and it is associated with its own Kandel strategy. The vault interacts with several external dependencies, as illustrated in the figure below:

  • MangroveVaultFactory: Factory contract allowing the creation of MangroveVault instances.
  • MangroveChainLinkOracle: An oracle adapter that connects to up to four Chainlink price feeds to provide the current price of the base/quote pair.
  • Mangrove, KandelSeeder and Kandel: The vault interacts with these contracts to manage provisions and update its position on Kandel.
  • AllowedSwapContract: An external contract whitelisted by the vault owner, enabling it to execute swap operations on behalf of the vault.

Fig. 2: Mangrove Vault overview.

In the following subsections, we outline the key functionalities of the Mangrove Vault, including both user and owner operations.

4.1 User Flow: Minting and Burning Vault Shares

Minting Shares

The MangroveVault allows users to mint shares through the mint(. . . ) function, where they specify the desired mintAmount along with the maximum allowable base and quote amount to transfer to the vault.

function mint(uint256 mintAmount, uint256 baseAmountMax, uint256 quoteAmountMax)
external
whenNotPaused
nonReentrant
returns (uint256 shares, uint256 baseAmount, uint256 quoteAmount)

This function calculates the equivalent underlying tokens for the specified mintAmount using the current share price. If the computed amounts exceed the provided maximums, the function reverts. Otherwise, the tokens are transferred from the user to the vault, and the corresponding number of shares is minted to the user.

Burning Shares

Shareholders can similarly burn their shares using the burn(. . . ) function, specifying the number of shares to burn and the minimum amounts to receive for each token.

function burn(uint256 shares, uint256 minAmountBaseOut, uint256 minAmountQuoteOut)
external
whenNotPaused
nonReentrant
returns (uint256 amountBaseOut, uint256 amountQuoteOut)

This function burns the specified number of shares and calculates the corresponding amounts of base and quote tokens. The tokens are transferred to the user if the amounts are not below the defined minimums.

Representation of Shares

When the vault’s total supply is zero, shares in the MangroveVault are represented as the total value in the vault, expressed in quote amounts, computed as follows:

uint256 sharesAmount = ((tick.inboundFromOutboundUp(baseAmount) + quoteAmount) * QUOTE_SCALE)

Where:

  • baseAmount and quoteAmount represent the current balances of the base and quote tokens, including the Kandel balance.
  • The inboundFromOutboundUp(...) function converts the baseAmount to a quote amount using the current tick.
  • QUOTE_SCALE is a constant that adjusts the result to match the share decimals. It represents the difference between the share decimals and quote decimals.

Once an initial share amount is minted (i.e., when totalSupply is not zero), the conversion between shares and underlying tokens is performed based on the proportion of shares relative to the total supply:

quoteAmount = shareAmount * quoteBalance / totalSupply
baseAmount = shareAmount * baseBalance / totalSupply

4.2 Vault Rebalancing

The vault includes a rebalancing functionality accessible only to the contract owner via the swap(...) function. This function allows the owner to execute swap operations on an external target contract, specifying the data for the call, the amount to transfer out from the vault, and the minimum amount to be received. The sell boolean indicates whether the swap operation involves selling or buying base tokens.

function swap(address target, bytes calldata data, uint256 amountOut, uint256 amountInMin, bool sell)
external
onlyOwner
nonReentrant

The target contract must be among the allowed swap contracts defined in the allowedSwapContracts mapping, which excludes the vault and Kandel addresses.

4.3 Funds State and Position Management

The Mangrove Vault defines three distinct states for its funds: VAULT, PASSIVE, and ACTIVE.

Vault State: In this state, the deposited funds remain within the vault. Any open positions on Kandel are closed, and tokens are transferred back to the vault.

Passive State: When the vault is in a passive state, the underlying tokens are deposited into the Kandel strategy but are not actively used in market making. No offers are created on Mangrove, and any existing active offers are retracted.

Active State: The active state is the only case where funds are actively market-making. In that case, all tokens are deposited into Kandel and used to create the distribution of offers.

Upon deployment, the vault is in the Vault state. The contract owner can update the state through the setPosition(. . . ) function, which also allows updates to Kandel parameters.

function setPosition(KandelPosition memory position) external onlyOwner

After each mint, burn, swap, or Kandel parameter update, the vault adjusts the Kandel position to reflect changes in the underlying balances and parameters. If an offer update fails due to low density or other reasons, all Kandel offers are retracted to prevent under-collateralization.

4.4 Vault Fees

The vault incurs two types of fees: management fees and performance fees.

  • Management Fees: Charged as a yearly percentage of the total vault value in quote tokens.
  • Performance Fees: A percentage applied to the accrued interest on the vault.

Fees are taken in shares, which are minted to the feeRecipient address. This operation is implemented within the _accrueFee() function, which is called before each mint or burn to ensure accurate share pricing.

function _accrueFee() internal returns (uint256 newTotalInQuote, Tick tick)

4.5 Oracle Integration

The MangroveVault interacts with the MangroveChainlinkOracle contract to obtain the current tick for the underlying base/quote tokens. This contract serves as an adapter for Mangrove, supporting up to four Chainlink price feeds and combining the fetched prices to return a quote/base price. It exposes a single external function:

function tick() external view returns (Tick)

The oracle contract can be deployed via the MangroveChainlinkOracleFactory factory contract, which enables the creation of MangroveChainlinkOracle instances and tracks deployed oracle addresses.

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 Missing check for stale data from Chainlink oracle

FileFix commitTypeStatus
ChainlinkConsumer.sol—MediumAcknowledged

The getTick(...) function is designed to calculate the tick value for a base/quote pair using the price fetched from the Chainlink oracle. This function internally calls getPrice(...) to retrieve the latest price from Chainlink. However, it currently fails to check the updatedAt timestamp of the returned price, which may lead to the acceptance of stale prices.

Moreover, the function does not check whether the L2 Arbitrum sequencer is down. In such a scenario, the oracle data is not up to date and the returned price will become stale.

function getPrice(AggregatorV3Interface _aggregator) internal view returns (uint256) {
if (address(_aggregator) == address(0)) return 1;

(, int256 price,,,) = _aggregator.latestRoundData();
// @audit missing check for stale prices
if (price < 0) revert MangroveVaultErrors.OracleInvalidPrice();
return uint256(price);
}

Recommendation

Consider implementing additional checks to ensure the price is not stale.

function getPrice(AggregatorV3Interface _aggregator) internal view returns (uint256) {
- (, int256 price,,,) = _aggregator.latestRoundData();
+ (uint80 roundId, int256 price,, uint256 updatedAt, uint80 answeredInRound) =
+ AggregatorV3Interface(_quotePriceFeed).latestRoundData();
+ require(answeredInRound >= roundId, "Stale price!");
+ require(updatedAt != 0, "Round not complete!");
+ require(block.timestamp - updatedAt <= VALID_TIME_PERIOD);
}

Additionally, ensure the L2 Sequencer is up, following the recommendation by Chainlink team.

Resolution

We decided to ignore this finding as such failure from Chainlink or Arbitrum’s sequencer is highly unlikely and wouldn’t prevent affected LPs to withdraw their funds. We note that other projects also apply this practice.

6.2 The function _swap allows arbitrary calls and is underconstrained

FileFix commitTypeStatus
MangroveVault.sol0d0b90eLowMitigated

The _swap(...) function allows the contract owner to rebalance the vault by executing swaps between quote and base tokens. However, this function poses some risks due to its ability to make arbitrary calls to the target contract, which can lead to malicious behaviors.

For instance, the target address can be set to the addresses of the BASE or QUOTE tokens, a direct call to these token contracts allows for a direct transfer of the vault assets outside the contract. Additionally, there is no control on the swap rate, which can result in unfair swaps or the depletion of contract funds. This behaviour is possible as the amountInMin parameter, which is defined by the caller, could be set to zero or an excessively low value.

// @audit `amountInMin` can be set to a zero or very low value
function _swap(address target, bytes calldata data, uint256 amountOut, uint256 amountInMin, bool sell) internal {
// @audit `allowedSwapContracts` does not exclude the base and quote token addresses
if (!allowedSwapContracts[target]) {
revert MangroveVaultErrors.UnauthorizedSwapContract(target);
}
// ...
// @audit Arbitrary call to the `target` address
target.functionCall(data);
// ...
}

Recommendation

Reinforce checks within the _swap(...) function to prevent potential misuse that could lead to the depletion of vault funds or unfair asset swaps.

Resolution

The issues were mitigated via multiple changes.

The first one is the addition of the manager role. A manager is only allowed to swap (rebalance) and set the position. This is the 2 functions that will be done by bots. Thus, the owner can be a multisig or any other trusted and secure account. The owner has all powers still but is the only one able to whitelist swap contract, change the fee data and more.

The second one is the addition of the max spread that is set by the owner of the vault only. Once we get the price from the oracle, we adjust it with the designated spread in order to get the minimum amount we should get. The final minimum amount to receive will be the maximum between the one passed to the swap function and the one we got from this operation. Here is the code to get the adjusted amount to receive :

function adjustedAmountInMin(uint256 amountOut, uint256 _amountInMin, bool sell)
public
view
returns (uint256 amountInMin)
{
// If maxPriceSpread is set to type(uint).max, we use the default amountInMin
if (maxPriceSpread == type(uint256).max) {
return _amountInMin;
}

Tick tick = _currentTick();
uint256 _maxPriceSpread = maxPriceSpread;

if (sell) {
// If we are selling, this means that we have to reduce the tick to reduce the amount of quote we receive
// So we decrease the tick by the max price spread
tick = Tick.wrap(Tick.unwrap(tick) - _maxPriceSpread.toInt256());
amountInMin = tick.inboundFromOutboundUp(amountOut);
} else {
// If we are buying, this means that we have to increase the tick to increase the amount of quote we receive
// So we increase the tick by the max price spread
tick = Tick.wrap(Tick.unwrap(tick) + _maxPriceSpread.toInt256());
amountInMin = tick.outboundFromInbound(amountOut);
}
// We make sure that the amountInMin is at least the amountInMin provided
amountInMin = Math.max(amountInMin, _amountInMin);
}

The third one is that the owner can not add the base nor quote token to the list of allowed swap contracts.

The fixes were implemented in commit 0d0b90e6526c3a119f670c57496a04aed1d23bb0.

6.3 Use of transfer instead of low level call to send native assets

FileFix commitTypeStatus
MangroveVault.sol04c0ed2InfoFixed

The withdrawNative(...) function in MangroveVault currently uses transfer() to send native ether to the contract owner. This approach can result in several issues, particularly with multisig wallets that may implement complex fallback functions or additional logic which execution exceeds the gas limit imposed by transfer(). Consequently, the usage of transfer() could result in failed ether transfers in such scenarios.

Recommendation

To avoid the limitations of transfer(), consider using a low-level call function to transfer native ether.

function withdrawNative() external onlyOwner {
- payable(msg.sender).transfer(address(this).balance);
+ (bool success, bytes memory result) = payable(msg.sender).call{value : address(this.balance)}("");
+ require(success, "Transfer failed");
}

Resolution

This was fixed by the recommended implementation on commit 04c0ed27f13bcd8de970cbdae10a2892c9c0d29b.

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 Mangrove team has provided comprehensive documentation in the provided README file. This documentation outlines the vault’s primary functionalities and highlights its key dependencies, including Mangrove’s Kandel strategy. Additionally, the code includes NatSpec documentation for different functions and explanatory comments on complex logic and computations.

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