Mangrove
Strategy Library

Mangrove is an on-chain order book DEX where offers can be smart contracts. We reviewed MangroveAmplifier, which posts offers in several markets with the same collateral, and MangroveOrder, which adds order types like Fill Or Kill.
report id
0162
category
DeFi & Yield
language
Solidity
final report
February 14, 2024
lines of code
1175
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind Security for part of the strategy-lib developed by Mangrove. Mangrove is an on-chain order book DEX that allows liquidity providers to post arbitrary smart contracts as offers. To make the execution of common strategies on the platform simpler, the Mangrove team has created a set of smart contracts that can be directly used by users or can be taken as building blocks for more complex use cases. The engagement covered two strategies: MangroveAmplifier and MangroveOrder. The former implements "liquidity amplification", which allows the offer owner to post offers in multiple markets using the same collateral. The latter will allow users to execute "Good Til Canceled" orders, "Good Til Canceled Enforced" orders, "Post Only" orders, "Immediate Or Cancel" orders, and "Fill Or Kill" orders.

The audited code comprises 1175 lines of code. The Mangrove team has provided comprehensive documentation explaining the behavior of the core protocol and the reviewed strategies. Aside from the provided documentation, the Mangrove and Nethermind Security teams have actively communicated to clarify any remaining questions about the expected behavior of the protocol.

The audit was performed using: (a) manual analysis of the codebase, (b) automated analysis tools, and (c) simulation of the smart contracts.

Audit assessment
Audit TypeSecurity Review
Initial ReportJan 26, 2024
Final ReportFeb 14, 2024
MethodsManual Review, Automated Analysis
Repositorymangrove-strats
Commit Hash5462064d6d
Final Commit Hash784758afa4
DocumentationDevelopers documentation
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
12
Fixed
9
Acknowledged
3
Mitigated
0
Unresolved
0

Findings by severity

  • Critical1
  • High1
  • Medium2
  • Low4
  • Informational2
  • Best Practices2

4

System Overview

Mangrove offers unparalleled flexibility for its users through the use of strategies. Users can incorporate defensive code, post unprovisioned offers, and redisplay liquidity after their offers are taken. The protocol provides multiple pre-developed strategies that users can use for common use cases without needing to write their own logic. Moreover, these strategies serve as building blocks for crafting more complex processes. This section provides an overall description of two strategies: MangroveAmplifier and MangroveOrder. Additionally, it delves into other concepts relevant to the development of strategies. The next figure presents an architectural overview of these two strategies. For each contract, its relationships with other contracts and its most relevant functions are presented.

Mangrove system scheme
Fig. 2 : Mangrove system scheme.

4.1 MangroveAmplifier

The MangroveAmplifier is a custom maker contract that implements liquidity amplification. It allows the offer owner to post offers on multiple markets with the same collateral. These offers are coupled together under a single abstraction called a bundle. Users will specify the maximum amount of outbound tokens that they are willing to offer and the bundle cannot give more than this amount even if it is approved to spend more or has access to more funds.

The MangroveAmplifier contract contains three endpoints for the users to interact with:

  • newBundle(...): To post a bundle of offers on Mangrove, amplifying a certain volume of outbound tokens.
  • updateBundle(...): To update common parameters of a bundle of offers (i.e outbound volume and expiry date).
  • retractBundle(...): To retract a bundle of offers.

When a bundle is created, the offers are posted to Mangrove on behalf of the user. If one of the offers is taken, the remaining offers in the bundle are retroactively updated to either use the residual amount or retracted. Users can update their bundle if they want to change the outbound volume and/or expiry date, or retract their bundle if they no longer want to offer the outbound tokens. Additionally, they can update specific offers in the bundle to set more specific expiry times and/or volume or retract them.

4.2 MangroveOrder

The MangroveOrder is a custom maker contract that implements the orders used in traditional finance. It enables a taker to simultaneously place an order on Mangrove and submit an offer with the remaining order values. The following types of orders are supported by the contract:

  • Good Til Canceled Orders: These are limit orders that remain active until it is filled or canceled by the trader. If the GTC order is partially filled, a resting order for the remaining portion is posted. The transaction will not revert if the resting order fails to be posted.
  • Good Til Canceled Enforced Orders: These are limit orders that remain active until it is filled or canceled by the trader. If the GTC order is partially filled, a resting order for the remaining portion is posted. The transaction will revert if the resting order fails to be posted.
  • Post Only Orders: These are limit orders that are posted to the market but not executed immediately.
  • Immediate Or Cancel Orders: These are limit orders that must be filled immediately at the limit price or better. If the order is partially filled, the remaining portion is canceled.
  • Fill Or Kill Orders: These are limit orders that are either completely filled or canceled. There is no partial fill, and no resting order is posted.

The primary entry point for the contract is the take(...) function, where takers utilize it to post a market order on Mangrove by providing the necessary order details as input.

  • The created order is executed on Mangrove through the executeMarketOrder(...) function. In this step, inbound tokens are extracted from the user’s reserves and directed to the MangroveOffer contract using the specified routing logic. If the market order succeeds, the acquired outbound tokens are transferred back to the taker’s reserves using the appropriate router.
  • In cases where the original order fails to be filled or is only partially filled, a resting order is placed using the postRestingOrder(...) function. This involves posting an offer on the opposite market, achieved by flipping the outbound and inbound tokens and including the residual amounts from the initial order. Any bounty accrued during order execution, along with the wei sent by the caller to the function, is utilized for provisioning the new offer. The remaining funds are promptly returned to the caller.

The function manages the execution flow based on the Order type, reverting in scenarios where the order type restricts a particular situation. For instance, if a Fill Or Kill order is partially filled, the function reverts before posting the residual offer.

4.3 Routers

Routers play an important role within the mangrove ecosystem as they are responsible for moving liquidity to and from user reserves. The router schema is shown in Fig. 3.

Mangrove routers scheme
Fig. 3 : Mangrove routers scheme.

4.3.1 RouterProxyFactory and RouterProxy

The RouterProxyFactory and RouterProxy contracts are used to manage the deployment of different routers within the strategies.

The RouterProxyFactory is a factory contract that allows the creation of RouterProxy instances for different users using deterministic addresses. The deployed router address is highly dependent on its default owner and the implementation address. This contract has the following main functions:

  • deployProxy(): serves as the main entry point to deploy a proxy, it takes the owner address and the implementation addresses as an input.
  • instantiate(): this function encapsulates a call to the deployProxy() by first checking if the proxy was not already deployed; if it is the case, its address is returned.
  • computeProxyAddress(): a utility function to precompute the deployed address, it is used within the instantiate() function to determine if the proxy was previously deployed.

The RouterProxy contract is a simple implementation of a proxy, pointing to an immutable router implementation. Similar to any proxy contract, calls to this contract are delegated to its implementation.

4.3.2 AbstractRouter

An abstract contract that represents the base layer for implementing routing mechanisms such as in SimpleRouter and SmartRouter. The AbstractRouter contract inherits from AccessControlled and utilizes the RoutingOrderLib library, which contains functions for managing access controls and creating routing order structures respectively. The router can be bound to one or more maker addresses, allowing those maker addresses to pull or push the liquidity from it.

The main functions in AbstractRouter includes:

  • pull(): An external function callable only by bounded addresses, it pulls liquidity from the user reserves and sends it to the caller using a custom logic defined in child contracts within the internal __pull__() function.
  • push(): Similar to pull(), it’s an external function used to push liquidity from the caller to the reserve using a custom logic defined in child contracts within the internal __push__() function.
  • flush(): Allows pushing balances of multiple tokens to the reserve. It operates by iterating through the routing orders and calling the __push__() internal function on them.
  • bind(): Function used to bind a new maker contract to the router.
  • unbind(): Function used to remove addresses from the mapping of bounded maker contracts.

4.3.3 SimpleRouter

The SimpleRouter contract inherits from AbstractRouter and implements the __pull__(), __push__() and tokenBalanceOf() functions by overriding them. This contract implements a simple routing logic where the funds are pulled and pushed from the owner’s account using a direct ERC20 transfer.

4.3.4 SmartRouter

The SmartRouter inherits the functionalities of a SimpleRouter and implements a more complex routing logic. It delegates routing requests to arbitrary contracts that implement the AbstractRoutingLogic interface, referred to as routing logic. It introduces new functions to manage the routing logic associated with each offer and token:

  • setLogic(): sets the logic contract that will be used for routing requests relative to a specific token, offer list, and offerId.
  • getLogic(): get the address of the associated logic for the provided inputs.
  • __push__() and __pull__(): These internal functions are redefined to reflect the SmartRouter behavior. If a routing logic is set for the specified inputs, the request is forwarded to that logic through a delegatecall. Otherwise, the default implementation defined within the SimpleRouter is used.

Additionally, the SmartRouter contract has an immutable state variable forcedBinding, used to bind a default address to a router. This is used to allow users to post an order and bind the maker contract is the same transaction.

4.3.5 Routers usage within the Amplifier strategy

The amplifier strategy uses a single RouterProxyFactory contract in addition to an immutable router implementation shared across all deployed proxy routers, directing them to a SmartRouter contract.

When a user initiates the creation of a new bundle, the contract interacts with the RouterProxyFactory to deploy a RouterProxy contract for the user. The deployment is done through a call to the instantiate() function and uses the strategy’s default implementation. At this step, users have the flexibility to specify the routing logic address for each offer in the bundle, which will be specific to the inbound tokens. Additionally, a single routing logic can be designated for the shared outbound token of the bundle.

When liquidity needs to be routed to or from the reserve, such as during the offer execution, the strategy initiates a call to the push() or pull() functions on the RouterProxy contract. This process involves fetching the associated routing logic based on the user’s request and subsequently delegating the push or pull call to it. In cases where no specific logic is provided, the default implementation is used, ensuring funds are transferred to/from the owner’s wallet.

4.4 Analysis of amplified offers implementation

The amplifier strategy introduces the concept of Bundles, aiming to enable liquidity amplification by allowing offer owners to post offers on multiple markets with the same collateral. The bundle structure consists of a list of offers that share common parameters, including the promised asset outbound_tkn, the promised volume per offer outVolume, the outbound token’s routing logic outboundLogic, and the expiration date of each offer in the bundle expiryDate.

struct FixedBundleParams {
IERC20 outbound_tkn;
uint outVolume;
AbstractRoutingLogic outboundLogic;
uint expiryDate;
}

Bundles are designed with the intention to prevent users from overspending. The bundle owner can spend up to the promised volume of the bundle, even if he approves the strategy to spend more. However, there are inherent risks associated with this concept that need careful consideration:

4.4.1 Offer failure within a Bundle

In scenarios where an offer within a bundle fails to deliver the promised tokens, the remaining offers in the same bundle are also at risk of reverting. This is because of the shared routing logic for the outbound token among offers within the same bundle.

One of the current system limitations is the lack of the immediate ability to retract remaining offers in the bundle during execution. This action is necessary to prevent multiple penalties for the maker. When the maker fails to deliver the promised tokens to Mangrove, the transaction will revert, making it impossible to execute any logic at that time.

The existing solution utilizes the __posthookFallback__ function to retract the bundle, executed after the trade, which mitigates the risk but does not completely eliminate it. Malicious actors could exploit this situation within the same transaction of the offer execution by targeting remaining offers for cleaning and collecting the bounty for the entire bundle.

4.4.2 Discrepancy between the traded volume and offer.gives()

The protocol utilizes a volume condition cond.volume to update the traded volume of offers within a bundle that failed to be updated directly on Mangrove. A potential issue arises from the discrepancy between the offer’s offer.gives() amount and the actual traded volume stored in cond.volume. Malicious actors can exploit this by targeting these bundles, causing offers to fail and bundles to be retracted.

For instance, if the bundle is updated with a smaller outbound volume, and an offer (e.g., Offer A) fails to be immediately updated on Mangrove, that offer will have cond.volume < offer.gives(). When a market order is matched with offer A, Mangrove uses the stored offer.gives() value as the trade volume. However, since the actual volume is lower, the offer execution can potentially fail, resulting in penalties imposed on the maker. Malicious actors can target offers in a similar situation, leading to unfair bundle retractions and penalties for the maker, who initially provided the promised amount reflected in cond.volume.

Conclusion: impact and considerations

In conclusion, the identified issues have dual impacts on the protocol. Firstly, they can disrupt the smooth functioning by causing offers to fail and triggering the retraction of entire bundles. Secondly, the financial implication is mostly constrained by the provisions paid by the maker, with the total paid amount capped at the provided provision during bundle creation.

Different factors are to be taken into consideration when evaluating the likelihood of such attacks and the motivation for bad actors. For instance, the chain where the protocol is deployed plays a significant role. When the gas price is low, attackers may be less motivated to trigger bundle retractions due to the potential higher attack cost than gains. Furthermore, the size of the bundle impacts the potential gains, with smaller bundles resulting in smaller bounties for each targeted bundle.

Understanding the impact and motivation factors for these attacks is important to design preventive measures and enhance the overall resilience of the protocol against malicious activities.

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 Unauthorized user can update and retract offers within a bundle

FileFix commitTypeStatus
MangroveAmplifier.solea1b1f7CriticalFixed

In the updateBundle(...) and retractBundle(...) functions, the bundle to be updated or deleted is identified using a bundleId and the associated outbound token outbound_tkn. However, the value of the outbound token is set by the caller and can be manipulated. It is used within the _extractOwnerOf(...) function to authorize the user to proceed with the bundle changes if he is the bundle owner.

function updateBundle(
// ...
bool updateExpiry,
// ...
) external {
BundledOffer[] memory bundle = __bundles[bundleId];
// @audit `outbound_tkn` can be different from the actual outbound token of the bundle.
require(_extractOwnerOf(bundle, outbound_tkn) == msg.sender, "MgvAmplifier/unauthorized");
// ...
}

Passing a manipulated outbound token address to the _extractOwnerOf(...) function results in the computation of an olKey pointing to a different offer list. This can lead to unauthorized access, enabling the caller to alter a bundle they do not own.

function _extractOwnerOf(BundledOffer[] memory bundle, IERC20 outbound_tkn) internal view returns (address) {
// @audit a manipulated `inbound_tkn` results in verifying the offerID in a different offer list.
OLKey memory olKey = OLKey({
outbound_tkn: address(outbound_tkn),
inbound_tkn: address(bundle[0].inbound_tkn),
tickSpacing: bundle[0].tickSpacing
});
return (ownerOf(olKey.hash(), bundle[0].offerId));
}

A malicious user can pass an outbound token address so that the computed olKey inside this function has an offer with the same bundle[0].offerId, and he owns that offer. That way, the caller bypasses the authentication check and can alter or retract offers he doesn’t own.

Recommendation

Consider validating the outbound_token input within the updateBundle(...) and retractBundle(...) functions to ensure it accurately corresponds to the specified bundle’s outbound token.

Resolution

Offer bundles are now mapped uniquely to their bundleId but requires the outbound token as well.

///@notice maps a bundle Id and its outbound token to a set of bundled offers
mapping(uint bundleId => mapping(IERC20 outbound_tkn => BundledOffer[])) private __bundles;

Fixed in commit ea1b1f7ca8ef52f3cee9bf14de0e54afa56b5008.

6.2 Wrong computation of residual values

FileFix commitTypeStatus
MangroveAmplifier.sol33877b6HighFixed

The execution of makerExecute(...) in the MangroveAplifier is split into three different hooks:

  • __lastLook__(...): This hook checks if the offer can be executed in the current context. For an offer to be valid in the current context, it must not have expired, and the order.takerWants must be lower or equal to the maximum volume the offer accepts. The maximum volume that the offer accepts is offer.gives() or cond.volume when cond.volume is different from zero. The cond.volume value limits the number of outbound tokens the offer can give when the offer cannot be updated during the execution of a different offer from the same bundle;
  • __put__(...): This hook contains the logic for storing the received tokens;
  • __get__(...): This hook contains the logic for pulling the tokens that will be given from the reserve. In this strategy, this hook also updates the rest of the offers in the bundle. The rest of the bundle should be retracted when the offer was completely consumed or updated with the correct residual amount in case it was partially consumed;

The current implementation of the __get__(...) hook in the MangroveAmplifier.sol contract incorrectly updates the rest of the bundle when the offer is partially filled under certain circumstances.

function __get__(uint amount, MgvLib.SingleOrder calldata order) internal override returns (uint) {
...
// @audit - This value is incorrect when `order.offer.gives()` is not up to date.
uint newOutVolume = order.offer.gives() - order.takerWants;
if (missing == 0 && newOutVolume > 0) {
_updateBundle(bundle, IERC20(order.olKey.outbound_tkn), olKeyHash, newOutVolume);
} else {
...
}
return missing;
}

When the order.offer.gives() value is not up to date, the newOutVolume value, which represents the residual tokens, is incorrect. This value may not be updated if an offer of the bundle was executed before and failed while trying to update this offer; in this case, the code.volume is used to set the maximum volume of the order. The newOutVolume value will be greater than what it should be. This will cause all the updated offers to overpromise on the number of outbound tokens they offer. These overpromises may lead to the creator of the bundle giving more outbound tokens than desired.

Similarly, the residual tokens may also be incorrect during the reposting of an offer in the __posthookSuccess__(...) hook execution. The __residualValues__(...) function implemented in the RenegingForwarder.sol contract accounts for cond.volume values when they are different from zero.

function __residualValues__(MgvLib.SingleOrder calldata order)
internal
virtual
override
returns (uint newGives, Tick newTick)
{
Condition memory cond = __renegeMap[order.olKey.hash()][order.offerId];
if (cond.volume == 0) {
return super.__residualValues__(order);
} else {
// new volume to be offered
// if __residualValues__ is called in __posthookFallback__ the offer reneged and cond.volume could be higher than takerWants
newGives = order.takerWants < cond.volume ? cond.volume - order.takerWants : 0;
// same price
newTick = order.offer.tick();
}
}

However, during the execution of __residualValues__(...), the cond.volume will always be equal to zero because it will be set to zero in the __lastLook__(...) hook.

function __lastLook__(MgvLib.SingleOrder calldata order) internal virtual override returns (bytes32) {
...
if (cond.volume != 0) {
// if a max volume is set and we are not reneging, we set it back to 0 so that we don't check again and save some gas.
// note this is OK since reposting the offer in MangroveOffer.__posthookSuccess__ will update the volume according to `__residualValues__`
_setReneging(olKeyHash, order.offerId, cond.date, 0);
}
return super.__lastLook__(order);
}

Recommendation

Consider resetting the volume condition to zero within the _updateOffer(...) function by overriding it in the RenegingForwarder contract. Additionally, modify the computation of the newOutVolume to use the __residualValues__(...) function so it accounts for cond.volume values.

Resolution

We addressed this vulnerability in two steps. First we make sure that the computation of the new outbound volume always uses __residualValues__ function which takes cond.volume into consideration.

(uint newOutVolume,) = __residualValues__(order);

Second, we make sure that cond.volume is reset to 0 in the override of _updateOffer in RenegingForwarder.

function _updateOffer(OfferArgs memory args, uint offerId) internal override returns (bytes32 reason) {
Condition memory cond = reneging(args.olKey.hash(), offerId);
if (cond.volume > 0) {
// resetting reneging volume to 0 when updating offer
// When reposting on partial fill, residual values are computed based on the reneging volume.
// So new we can safely set back the max volume to 0.
_setReneging(args.olKey.hash(), offerId, cond.date, 0);
}
return super._updateOffer(args, offerId);
}

During makerExecute we have the following flow:

1. In __lastLook__ order.wants is compared to cond.volume if any. Offer reverts if the taker wants more than the maximum volume. 2. If the offer proceeds, and is partially filled, __residualValues__ will take cond.volume as virtual offered volume (and not offer.gives) in order to compute residual gives for reposting. 3. In __posthookSuccess__ offer is reposted via the _updateOffer function, which then sets cond.volume back to 0.

Fixed in commit 33877b6cdadac156efc9b885e9fa572a70a8b190.

6.3 Total withdrawn provision incorrectly computed in _retractBundle(...)

FileFix commitTypeStatus
MangroveAmplifier.sol16f67e0MediumFixed

The _retractBundle(...) function returns the total freed wei when retracting the offers inside the specified bundle. However, this value is reset inside the loop within every iteration instead of being accumulated.

function _retractBundle(BundledOffer[] memory bundle, IERC20 outbound_tkn, bytes32 skipOlKeyHash, bool deprovision)
internal
returns (uint freeWei)
{
for (uint i; i < bundle.length; i++) {
// ...
// @audit `freeWei` is reset within every iteration
(freeWei, status) = _retractOffer(olKey_i, bundle[i].offerId, true, deprovision);
// ...
}
}

The function will only return the withdrawn wei of the last removed offer. The remaining provisions will stay in the contract balance, and the bundle owner will lose access to them.

Recommendation

Adjust the logic to accumulate the freeWei value across the different iterations instead of resetting it within each iteration.

Resolution

To address this issue, we added a temp _freeWei variable as recommended.

function _retractBundle(BundledOffer[] memory bundle, IERC20 outbound_tkn, bytes32 skipOlKeyHash, bool deprovision)
internal
returns (uint freeWei)
{
bytes32 status;
uint _freeWei;
bytes32 olKeyHash_i;
for (uint i; i < bundle.length; i++) {
OLKey memory olKey_i = OLKey({
outbound_tkn: address(outbound_tkn),
inbound_tkn: address(bundle[i].inbound_tkn),
tickSpacing: bundle[i].tickSpacing
});
olKeyHash_i = olKey_i.hash();
if (skipOlKeyHash != olKeyHash_i) {
(_freeWei, status) = _retractOffer(olKey_i, bundle[i].offerId, true, deprovision);
freeWei += _freeWei;
if (status != bytes32(0)) {
// this only happens if offer `i` of the bundle is in a locked offer list --see `_updateBundle`
_setReneging(olKeyHash_i, bundle[i].offerId, block.timestamp, 0);
}
}
}
}

Fixed in commit 16f67e03ce0b5d6279da11bad7659d593cb0ff98.

6.4 _retractOffer(...) returns an unwithdrawn freeWei amount, resulting in the depletion of the contract funds

FileFix commitTypeStatus
Forwarder.sol5c0fde0MediumFixed

The _retractOffer(...) function removes an offer from the offer list and returns a freeWei amount, indicating the ETH withdrawn from Mangrove. This value is then used to transfer funds to the respective owner. However, an issue arises when the call to Mangrove’s retractOffer(...) function fails, and noRevert is set to true. In such cases, no funds are withdrawn from Mangrove, but the freeWei can still hold a non-zero value.

function _retractOffer(...) internal returns (uint freeWei, bytes32 status) {
OwnerData storage od = ownerData[olKey.hash()][offerId];
// @audit If the offer deletion fails, `freeWei` can hold the amount of `od.weiBalance`
freeWei = deprovision ? od.weiBalance : 0;

try MGV.retractOffer(olKey, offerId, deprovision) returns (uint weis) {
// ...
} catch Error(string memory reason) {
// @audit on failing calls, no wei is actually withdrawn from Mangrove
require(noRevert, reason);
status = bytes32(bytes(reason));
}
}

This issue is possible within the _retractBundle(...) function of the MangroveAmplifier contract as it does not consider the returned status of _retractOffer(...) while using the freeWei amount. Consequently, in case of a failure, the freeWei amount is not withdrawn from Mangrove, yet it remains accounted for in the owner’s balance od.weiBalance. Subsequently, the retractBundle(...) function attempts to transfer this unwithdrawn amount to the owner from its contract balance.

function _retractBundle(...) internal returns (uint freeWei) {
for (uint i; i < bundle.length; i++) {
// ...
if (skipOlKeyHash != olKeyHash_i) {
bytes32 status;
// @audit when status indicates a failure, the amount in `freeWei` is not withdrawn from Mangrove.
(freeWei, status) = _retractOffer(olKey_i, bundle[i].offerId, true, deprovision);
if (status != bytes32(0)) {
_setReneging(olKeyHash_i, bundle[i].offerId, block.timestamp, 0);
}
}
}
}

A malicious user can take advantage of this vulnerability by repeatedly invoking the retractBundle(...) function on a bundle where offer deletion consistently fails. This could lead to the depletion of contract funds as the caller accumulates od.weiBalance with each call.

Recommendation

Consider modifying the _retractOffer(...) or the _retractBundle(...) functions to either return 0 when the status indicates a failure or ignore the returned freeWei amount in case of failure, preventing the transfer of unwithdrawn funds to the owner.

Resolution

To solve this issue, we decoupled currently available weis assigned to owner (in ownerData.weiBalance) from the additional wei freed by a successful call to retractOffer. If retractOffer fails while the noRevert flag is positioned we can still return the weiBalance of the owner. This balance is augmented by freed weis if the call to retractOffer did not fail.

OwnerData storage od = ownerData[olKey.hash()][offerId];
freeWei = deprovision ? od.weiBalance : 0;

try MGV.retractOffer(olKey, offerId, deprovision) returns (uint weis) {
// We add `weis` credited to the contract to `freeWei` amount
// They were the locked native token provision of the offer that has been retracted
freeWei += weis;
} catch Error(string memory reason) {
require(noRevert, reason);
status = bytes32(bytes(reason));
}
// if `deprovision` is set to false, `freeWei` is 0 because `retractOffer` will return 0
if (freeWei > 0) {
// pulling free wei from Mangrove to `this`
require(MGV.withdraw(freeWei), "Forwarder/withdrawFail");
// resetting pending returned provision
// calling code must now assign freeWei to owner
od.weiBalance = 0;
}

Fixed in commit 5c0fde0716363ca21187340a1fef0ce0e2ad9855.

6.5 Strategy admin can seize users unlocked wei balances

FileFix commitTypeStatus
MangroveOffer.sol—LowAcknowledged

The MangroveOffer contract provides the withdrawFromMangrove(...) function that allows the contract admin to retrieve the unlocked funds from Mangrove. The objective behind this function is to prevent any residual wei, mainly arising from approximations done within the __handleResidualProvision__ function, from being locked within Mangrove.

However, this function enables the contract admin to either maliciously or mistakenly withdraw unlocked funds allocated to a specific user in the Forwarder strategy. The admin can then seize a user’s ownerData.weiBalance. Essentially, any amount reflected in the user’s ownerData.weiBalance as unlocked in Mangrove becomes susceptible to withdrawal by the strategy admin.

Furthermore, the withdrawn funds are still accounted for in the ownerData.weiBalance users struct, resulting in an inconsistency between the user’s balances in the strategy accounting and the actual funds in Mangrove. This might cause some transactions to revert, particularly when attempting operations such as retracting an offer or bundle, as they may try to withdraw an amount exceeding the available wei in Mangrove.

Recommendation

Consider updating the function to consider the user’s balances by retracting them from the total amount to be withdrawn from Mangrove. As a different option, consider giving access to this functionality only to multisig contracts and carefully reviewing every transaction done from it to reduce the possibility of errors.

Resolution

This issue will stay unresolved. Admin cannot seize inbound or outbound token which are not assigned to the contract balance between transactions. The only thing admin could seize is free weis from Mangrove unlocked wei balance assigned to the given forwarder, but the reputational value of such operations is not worth the bounty. Moreover, admin control of the balance is a way to recover unreachable funds that would have been transferred by mistake.

6.6 The __lastLook__(...) function might revert because of the strict inequality check

FileFix commitTypeStatus
RenegingForwarder.sol4f5ce2eLowFixed

The __lastLook__(...) function checks if the order is expired or oversized before executing the trade. These cases are called reneging conditions. In a scenario where the offer was locked on Mangrove, but it is still necessary to update how much outbound volume it should offer, its cond.volume is set to avoid over-promising. The __lastLook(...)__ function compares the token amount that the taker wants with the cond.volume - the number of tokens the offer can sell. The problem present in this function is that it uses a strict inequality sign to determine whether the transaction should revert.

require(
cond.volume == 0 || order.takerWants < uint(cond.volume),
"RenegingForwarder/overSized"
);

For example, if cond.volume was set to 500 tokens, any taker should still be able to take the remaining 500 tokens promised by the offer, but this is not the case. Because of the strict inequality sign, it is only possible to execute this offer by requesting 499 tokens.

Recommendation

Consider using a weak inequality sign.

Resolution

This issue is resolved by changing the strict inequality check to a non-strict one.

require(cond.volume == 0 || order.takerWants <= uint(cond.volume), "RenegingForwarder/overSized");

Fixed in commit 4f5ce2e22184b08d0d3b0cc59a76f9acbc24ac76.

6.7 Unnecessary call to _retractBundle(...) when the maker fails to get the outbound tokens

FileFix commitTypeStatus
MangroveAmplifier.sold7149c5
20dee5b
LowFixed

The __get__(...) function redefined in MangroveAmplifier is called within the makerExecute(...) function, which will always revert when the returned value missing is different than 0:

require(__get__(order.takerWants, order) == 0, "mgvOffer/abort/getFailed");

However, the function’s logic attempts to retract the bundle when missing value is different than 0, as the code shows below:

function __get__(uint amount, MgvLib.SingleOrder calldata order) internal override returns (uint) {
uint missing = super.__get__(amount, order);

if (missing == 0 && newOutVolume > 0) {
_updateBundle(bundle, IERC20(order.olKey.outbound_tkn), olKeyHash, newOutVolume);
} else {
// not deprovisionning to save execution gas
_retractBundle(bundle, IERC20(order.olKey.outbound_tkn), olKeyHash, false);
}
return missing;
}

The issue lies in the fact that, due to the revert condition in makerExecute(...), the actions within the else block of the __get__(...) function. Specifically, attempting to retract the bundle will never be executed when missing != 0. Consequently, a failed offer within the bundle will not trigger the expected bundle retraction. Additionally, this results in unnecessary gas consumption to retract the bundle, which will increase the bounty amount paid by the maker.

Recommendation

Consider moving the _retractBundle(...) call to the __posthookFallback__(...) function for the case where missing != 0.

Resolution

_retractOffer is now only called if missing is 0 and residual volume is 0.

(uint newOutVolume,) = __residualValues__(order);
if (missing == 0) {
if (newOutVolume > 0) {
_updateBundle(bundle, IERC20(order.olKey.outbound_tkn), olKeyHash, newOutVolume);
} else {
// not deprovisionning to save gas
_retractBundle(bundle, IERC20(order.olKey.outbound_tkn), olKeyHash, false);
}
}
return missing;
}

If missing was non zero, we now retract bundle in posthookFallback

/// @inheritdoc MangroveOffer
/// @dev Because the offer execution failed, we will retract the rest of the bundle.
function __posthookFallback__(MgvLib.SingleOrder calldata order, MgvLib.OrderResult calldata result)
internal
virtual
override
returns (bytes32 data)
{
bytes32 olKeyHash = order.olKey.hash();
uint bundleId = __bundleIdOfOfferId[olKeyHash][order.offerId];
BundledOffer[] memory bundle = __bundles[bundleId][IERC20(order.olKey.outbound_tkn)];
// not deprovisionning to save gas
_retractBundle(bundle, IERC20(order.olKey.outbound_tkn), olKeyHash, false);
return super.__posthookFallback__(order, result);
}

Fixed in commits d7149c5c421b6a8b069467fe9abebd9f039f13b3 and 20dee5b4db4780397a6c365970129f91fcff377d.

6.8 Updated offers after retraction can use an outdated volume condition

FileFix commitTypeStatus
RenegingForwarder.sol33877b6LowFixed

The RenegingForwarder contract introduces a volume condition on offers that couldn’t be successfully updated. This condition is used instead of the offer.gives(), indicating the actual traded volume of outbound tokens. However, when an offer is retracted, the volume condition of that offer (the cond.volume) is not reset to zero. This poses a potential problem as Mangrove permits the reuse of an old offerId to post a new offer with updated fields.

Consider the scenario where an offer with offerId A is retracted, and its cond.volume differs from zero. If the offer owner reuses this offerId A to post new offer data, there will be a discrepancy between the user expectations and the actual behavior.

Despite the user anticipating the offer to promise only offer.gives(), the offer will utilize the outdated cond.volume value as its real promised amount. Moreover, if the posted offer is part of a bundle, all offers within the same bundle will erroneously be updated using the outdated cond.volume amount.

Recommendation

Consider resetting the volume condition for retracted offers before reusing them. This adjustment can be implemented within the _updateOffer(...) function by overriding it in the RenegingForwarder contract.

Resolution

As we decided to move the _setReneging execution inside _updateOffer, if you want to reuse an offer, you have to call updateOffer, thus resetting cond.volume.

Fixed in commit 33877b6cdadac156efc9b885e9fa572a70a8b190.

6.9 Offers from the same offerList in a bundle are not updated when _updateBundle(...) is called.

FileFix commitTypeStatus
MangroveAmplifier.sol—InfoAcknowledged

When the amplified offer is partially executed the remaining offers in the bundle have to be updated. The _updateBundle(...) function updates the newOutVolume for the remaining offers. Since we want to avoid updating the current offer, this function skips the current olKeyHash. The skipped offer will be updated in the __posthookSuccess__(...) function instead.

The problem arises when a bundle is created with multiple offers from the same offerList. These offers will all be skipped because they share the same olKeyHash as the offer that is currently being taken. As a result, when these unmodified offers are taken, the maker may trade more outbound tokens than intended or have their offers fail and lose the provision in progress.

Recommendation

Consider skipping only the offer being taken or documenting this behavior so users know the strategy does not support this use case.

Resolution

This has not been fixed as the expected behavior is not to use the amplifier twice on the same market. We do not want to programmatically prevent this in order to save some execution gas.

6.10 outboundVolume of bundles can be unintentionally modified

FileFix commitTypeStatus
MangroveAmplifier.sol—InfoAcknowledged

Offers in a bundle are highly coupled. This means that if one offer is taken, the other offers in the bundle will be retroactively updated to use the remaining outboundVolume. The standard way of adjusting the outboundVolume is through the updateBundle(...) function. However, there also exists an updateOffer(...) function in the inherited RenegingForwarder contract that allows the user to modify the gives of a single offer.

Modifying the gives of a single offer (that is part of a bundle) does not break the bundle’s functionality. However, when the modified offer is taken, the other offers in the bundle will be retroactively adjusted to use the new outboundVolume. This value may potentially be higher than the original value. As a result, the offer may give more than intended.

Recommendation

Consider restricting the possibility of updating single offers from a bundle.

Resolution

Gives of single offers are not to be modified independently, even though it’s not programmatically enforced. The expected behavior is to create bundles and modify them as a whole. We do not want to programmatically prevent this in order to keep the abstraction from the Forwarder more readable.

6.11 Incorrect NatSpec comments

FileFix commitTypeStatus
*.solda50594
df5d3ad
ab8f911
Best PracticesFixed

The codebase presents some wrong or outdated comments, below is a non-exhaustive list:

  • The comments in TakerOrderLib explaining GTC and GTCE orders, have the names flipped;
  • In the IOfferLogic interface, the NatSpec documentation of the OfferArgs structure has an outdated param and dev comment;
  • The comments in RouterProxyFactory state that the Access Controlled Admin address is immutable but this is not the case, as it can be updated with the setAdmin(...) function;

Recommendation

Consider updating the comments in the code.

Resolution

Fixed in commits da50594d4fe7d65b5c921edc71f7183b62b5e0cd, df5d3ad0583d2cdd2434b9c3f63eb89e02c974df, and ab8f911e4a235075f467fca52640734061faf6e7.

6.12 Unused imports

FileFix commitTypeStatus
*.sol949464eBest PracticesFixed

The codebase contains imported files that are not being used:

RouterProxyFactory.sol -> IERC20
SimpleRouter.sol -> IERC20
SmartRouter.sol -> TransferLib
AbstractRouter.sol -> IERC20
MangroveAmplifier -> TickLib

Recommendation

To keep the codebase clean and readable, consider removing unused imports.

Resolution

Fixed in commit 949464ee314be93f9bc6e14763ab10603a48fefe.

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 documentation about the core mechanism of their protocol and the reviewed strategies. The documentation is public as part of the developers documentation. The reviewed code also contained numerous comments giving more insights about the implementation and design choices. Moreover, the Mangrove team was available to address any inquiries or concerns raised by Nethermind Security.

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