Ineffective slippage mechanism when redeeming proportionally
The minimum exit amounts calculated for proportional redemption from a Curve pool are always lower than the actual amounts returned, so the slippage check never triggers. An attacker could sandwich the settlement trade, causing the vault to receive fewer tokens and incurring losses for shareholders.
Originally disclosed on Sherlock
Source: https://github.com/sherlock-audit/2023-02-notional-judging/issues/12
Found by
xiaoming90
Summary
A trade will continue to be executed regardless of how bad the slippage is since the minimum amount returned by the TwoTokenPoolUtils._getMinExitAmounts function does not work effectively. Thus, a trade might incur significant slippage, resulting in the vault receiving fewer tokens in return, leading to losses for the vault shareholders.
Vulnerability Detail
The params.minPrimary and params.minSecondary are calculated automatically based on the share of the Curve pool with a small discount within the Curve2TokenConvexHelper._executeSettlement function (Refer to Line 124 below)
File: Curve2TokenConvexHelper.sol
112: function _executeSettlement(
113: StrategyContext calldata strategyContext,
114: Curve2TokenPoolContext calldata poolContext,
115: uint256 maturity,
116: uint256 poolClaimToSettle,
117: uint256 redeemStrategyTokenAmount,
118: RedeemParams memory params
119: ) private {
120: (uint256 spotPrice, uint256 oraclePrice) = poolContext._getSpotPriceAndOraclePrice(strategyContext);
121:
122: /// @notice params.minPrimary and params.minSecondary are not required to be passed in by the caller
123: /// for this strategy vault
124: (params.minPrimary, params.minSecondary) = poolContext.basePool._getMinExitAmounts({
125: strategyContext: strategyContext,
126: oraclePrice: oraclePrice,
127: spotPrice: spotPrice,
128: poolClaim: poolClaimToSettle
129: });
File: TwoTokenPoolUtils.sol
46: /// @notice calculates the expected primary and secondary amounts based on
47: /// the given spot price and oracle price
48: function _getMinExitAmounts(
49: TwoTokenPoolContext calldata poolContext,
50: StrategyContext calldata strategyContext,
51: uint256 spotPrice,
52: uint256 oraclePrice,
53: uint256 poolClaim
54: ) internal view returns (uint256 minPrimary, uint256 minSecondary) {
55: strategyContext._checkPriceLimit(oraclePrice, spotPrice);
56:
57: // min amounts are calculated based on the share of the Balancer pool with a small discount applied
58: uint256 totalPoolSupply = poolContext.poolToken.totalSupply();
minPrimary = (poolContext.primaryBalance * poolClaim *
strategyContext.vaultSettings.poolSlippageLimitPercent) / // @audit-info poolSlippageLimitPercent = 9975, # 0.25%
(totalPoolSupply * uint256(VaultConstants.VAULT_PERCENT_BASIS)); // @audit-info VAULT_PERCENT_BASIS = 1e4 = 10000
62: minSecondary = (poolContext.secondaryBalance * poolClaim *
63: strategyContext.vaultSettings.poolSlippageLimitPercent) /
64: (totalPoolSupply * uint256(VaultConstants.VAULT_PERCENT_BASIS));
65: }
When LP tokens are redeemed proportionally via the Curve Pool's remove_liquidity function, the tokens received are based on the share of the Curve pool as the source code.
@external
@nonreentrant('lock')
def remove_liquidity(
_amount: uint256,
_min_amounts: uint256[N_COINS],
) -> uint256[N_COINS]:
"""
@notice Withdraw coins from the pool
@dev Withdrawal amounts are based on current deposit ratios
@param _amount Quantity of LP tokens to burn in the withdrawal
@param _min_amounts Minimum amounts of underlying coins to receive
@return List of amounts of coins that were withdrawn
"""
amounts: uint256[N_COINS] = self._balances()
lp_token: address = self.lp_token
total_supply: uint256 = ERC20(lp_token).totalSupply()
CurveToken(lp_token).burnFrom(msg.sender, _amount) # dev: insufficient funds
for i in range(N_COINS):
value: uint256 = amounts[i] * _amount / total_supply
assert value >= _min_amounts[i], "Withdrawal resulted in fewer coins than expected"
amounts[i] = value
if i == 0:
raw_call(msg.sender, b"", value=value)
else:
assert ERC20(self.coins[1]).transfer(msg.sender, value)
log RemoveLiquidity(msg.sender, amounts, empty(uint256[N_COINS]), total_supply - _amount)
return amounts
Assume a Curve Pool with the following state:
- Consists of 200 US Dollars worth of tokens (100 DAI and 100 USDC). DAI is the primary token
- DAI <> USDC price is 1:1
- Total Supply = 100 LP Pool Tokens
Assume that 50 LP Pool Tokens will be claimed during vault settlement.
TwoTokenPoolUtils._getMinExitAmounts function will return 49.875 DAI as params.minPrimary and 49.875 USDC as params.minSecondary based on the following calculation
minPrimary = (poolContext.primaryBalance * poolClaim * strategyContext.vaultSettings.poolSlippageLimitPercent / (totalPoolSupply * uint256(VaultConstants.VAULT_PERCENT_BASIS)
minPrimary = (100 DAI * 50 LP_TOKEN * 99.75% / (100 LP_TOKEN * 100%)
Rewrite for clarity (ignoring rounding error):
minPrimary = 100 DAI * (50 LP_TOKEN/100 LP_TOKEN) * (99.75%/100%) = 49.875 DAI
minSecondary = same calculation = 49.875 USDC
Curve Pool's remove_liquidity function will return 50 DAI and 50 USDC if 50 LP Pool Tokens are redeemed.
Note that TwoTokenPoolUtils._getMinExitAmounts function performs the calculation based on the spot balance of the pool similar to the approach of the Curve Pool's remove_liquidity function. However, the TwoTokenPoolUtils._getMinExitAmounts function applied a discount to the returned result, while the Curve Pool's remove_liquidity function did not.
As such, the number of tokens returned by Curve Pool's remove_liquidity function will always be larger than the number of tokens returned by the TwoTokenPoolUtils._getMinExitAmounts function regardless of the on-chain economic condition or the pool state (e.g. imbalance). Thus, the minimum amounts (minAmounts) pass into the Curve Pool's remove_liquidity function will never be triggered under any circumstance.
a = Curve Pool's remove_liquidity => x DAI
b = TwoTokenPoolUtils._getMinExitAmounts => (x DAI - 0.25% discount)
a > b => true (for all instances)
Thus, the TwoTokenPoolUtils._getMinExitAmounts function is not effective in determining the slippage when redeeming proportionally.
Impact
A trade will always be executed even if it returns fewer than expected assets since the minimum amount returned by the TwoTokenPoolUtils._getMinExitAmounts function does not work effectively. Thus, a trade might incur unexpected slippage, resulting in the vault receiving fewer tokens in return, leading to losses for the vault shareholders.
Code Snippet
Tool used
Manual Review
Recommendation
When redeeming proportional, theTwoTokenPoolUtils._getMinExitAmounts function can be removed. Instead, give the caller the flexibility to define the slippage/minimum amount (params.minPrimary and params.minSecondary). To prevent the caller from setting a slippage that is too large, consider restricting the slippage to an acceptable range.
The proper way of computing the minimum amount of tokens to receive from a proportional trade (remove_liquidity) is to call the Curve's Pool calc_token_amount function off-chain and reduce the values returned by the allowed slippage amount.
Note that calc_token_amount cannot be used solely on-chain for computing the minimum amount because the result can be manipulated because it uses spot balances for computation.
Sidenote: Removing TwoTokenPoolUtils._getMinExitAmounts function also removes the built-in spot price and oracle price validation. Thus, the caller must remember to define the slippage. Otherwise, the vault settlement will risk being sandwiched. Alternatively, shift the strategyContext._checkPriceLimit(oraclePrice, spotPrice) code outside the TwoTokenPoolUtils._getMinExitAmounts function.
Discussion
jeffywu
Valid, min amounts should be specified by the caller to eliminate the risk of sandwich attacks.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Impact
A trade will always be executed even if it returns fewer than expected assets, so the vault might incur unexpected slippage and receive fewer tokens, leading to losses for shareholders.
What the attacker needed
Vault settlement occurs; attacker can sandwich the trade
The fix
The function should be removed and the caller should specify the minimum amounts, with slippage restricted to an acceptable range, or the minimum should be computed off-chain using Curve's `calc_token_amount` and reduced by the allowed slippage.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
When a vault withdraws its share from a pool, it sets a minimum amount it expects to receive to protect against bad prices. Here, that minimum was calculated with a small discount, but the pool always returns at least the proportional share, so the minimum was always lower than what was received. This meant the protection never worked, and someone could manipulate the price to make the vault get less.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.