`OptionTokenV4.exerciseLP`'s `addLiquidity` lack of slippage can be abused to make victims exercise for a lower liquidity than intended
The exerciseLP function in OptionTokenV4 lacks a slippage check on the amount of LP tokens received, and it calculates the payment token amount using spot reserves. An attacker can front-run and imbalance the pool so that the victim receives far fewer LP tokens for the same amount of option tokens burned.
0xpiken Follow with Avci, Bauchibred and 19 others
Originally disclosed on Sherlock
Source: https://github.com/sherlock-audit/2024-06-velocimeter-judging/issues/199
Found by
0xpiken, Avci, Bauchibred, Bauer, GalloDaSballo, MSaptarshi, Minato7namikazi, Sentryx, StraawHaat, ZanyBonzy, almurhasan, bin2chen, bughuntoor, cryptic, cu5t0mPe0, eeshenggoh, eeyore, jennifer37, joshuajee, pashap9990, pseudoArtist, tvdung94
Summary
OptionTokenV4.exerciseLP uses spot reserves and a fixed _amount by sandwiching an exercise operation, as well as due to the pool being imbalanced, the depositor can receive less liquidity than intended, burning more OptionTokens for less LP tokens
(, , lpAmount) = IRouter(router).addLiquidity( /// @audit I need to do the math here to see the gain when
underlyingToken,
paymentToken,
false,
_amount,
paymentAmountToAddLiquidity,
1,
1,
address(this),
block.timestamp
);
Vulnerability Detail
OptionTokenV4.exerciseLP has a slippage check on the maximum price paid to exercise the option
But there is no check that the lpAmount is within the bounds of what the user intended
The Pool.mint formula for liquidity to be minted is as follows:
liquidity = Math.min(_amount0 * _totalSupply / _reserve0, _amount1 * _totalSupply / _reserve1);
To calculate the correct amount of paymentReserve to add to the pool, spot reserves are checked
(uint256 underlyingReserve, uint256 paymentReserve) = IRouter(router).getReserves(underlyingToken, paymentToken, false);
paymentAmountToAddLiquidity = (_amount * paymentReserve) / underlyingReserve;
This means that spot reserves are read and are supplied in a proportional way, this is rational and superficially correct
However, _amount for the OptionToken is a fixed value, meaning that the amount of liquidity we will get is directly related to how "imbalanced the pool is"
When a pool is perfectly balance (e.g. both reserves are in the same proportion), we will have the following math:
Start balances tokenA: 1000000000000000000 (1e18) tokenB: 1000000000000000000 (1e18)
New Deposit: 1000000000000000000 (1e18) New tokens minted: 1000000000000000000 (1e18)
Meaning we get a proportional amount
However, if we start imbalancing the pool by adding more underlyingToken, then the amount of paymentAmountToAddLiquidity will be reduced, meaning we will be using the same _amount of underlying but we will receive less total LP tokens
This can happen naturally, if the pool is imbalanced and can also be exploited by an attacker to cause the ExerciseLP to be less effective than intended
Impact
Less LP tokens will be produced from burning the OptionTokens, resulting in a loss of the value of the OptionToken
Code Snippet
Run this POC to see how a deposit of amount = 1e18 will result in very different amounts of liquidity out
By purposefully front-running and imbalancing the pool, an attacker can make the exercised options massively less valuable, in this example the result is 9% of the unmanipulated value
address a;
address b;
function getInitializable() external view returns (address, address, bool) {
return (a, b, false);
}
function getFee(address ) external view returns (uint256) {
return 25;
}
function isPaused(address ) external view returns (bool) {
return false;
}
// forge test --match-test test_swapAndSee -vv
function test_swapAndSee() public {
MockERC20 tokenA = new MockERC20("a", "A", 18);
MockERC20 tokenB = new MockERC20("b", "B", 18);
a = address(tokenA);
b = address(tokenB);
tokenA.mint(address(this), 1_000_000e18);
tokenB.mint(address(this), 1_000_000e18);
// Setup Pool
Pair pool = new Pair();
// Classic stable Pool
// TODO
// pool.initialize(address(tokenA), address(tokenB), false);
uint256 initial = 100e18;
tokenA.transfer(address(pool), initial);
tokenB.transfer(address(pool), initial);
pool.mint(address(this));
// We assume we'll deposit 1e18 from the option
// We'll take spot of the other amount
// And see how much liquidity we get
uint256 snapshot = vm.snapshot();
(uint256 underlyingReserve, uint256 paymentReserve, ) = pool.getReserves();
// Amt * payRes / underlyingRes
uint256 paymentAmountToAddLiquidity = (1e18 * paymentReserve) / underlyingReserve;
console2.log("paymentAmountToAddLiquidity Initial", paymentAmountToAddLiquidity);
tokenA.transfer(address(pool), 1e18);
tokenB.transfer(address(pool), paymentAmountToAddLiquidity);
uint256 balanceB4 = pool.balanceOf(address(this));
pool.mint(address(this));
uint256 poolMinted = pool.balanceOf(address(this)) - balanceB4;
console2.log("poolMinted Initial", poolMinted);
vm.revertTo(snapshot);
// swap
uint256 counter = 1000;
while(counter > 0) {
// By swapping more of underlyingReserve, we make `paymentReserve` cheaper and we make them get less liquidity
// this wastes their `_amount` which is limited
// Swap 0
tokenA.transfer(address(pool), 1e18);
uint256 toSwapOut = pool.getAmountOut(1e18, address(tokenA));
pool.swap(0, toSwapOut, address(this), hex"");
--counter;
}
// Basically same as above, but with altered reserves
(underlyingReserve, paymentReserve, ) = pool.getReserves();
// Amt * payRes / underlyingRes
paymentAmountToAddLiquidity = (1e18 * paymentReserve) / underlyingReserve;
console2.log("paymentAmountToAddLiquidity After", paymentAmountToAddLiquidity);
tokenA.transfer(address(pool), 1e18);
tokenB.transfer(address(pool), paymentAmountToAddLiquidity);
balanceB4 = pool.balanceOf(address(this));
pool.mint(address(this));
poolMinted = pool.balanceOf(address(this)) - balanceB4;
console2.log("poolMinted After", poolMinted);
}
Full File is here: https://gist.github.com/GalloDaSballo/d40d7a1d1b2a481450f44ebade421d14
Tool used
Manual Review
Recommendation
Add an additional slippage check for exerciseLP to check that lpAmount is above a slippage threshold
Discussion
0xklapouchy
@nevillehuang Hi 0xnevi,
The duplicates in this issue come from three different issues and should be split accordingly. After rechecking, here is how I believe they should be divided:
-
Main Issue #199: These duplicates are related to the lack of slippage control for lpTokens received or the use of amountAMin and amountBMin. As the result is the same (the lpTokens are received in the proper proportion), they should be grouped together:
- #199
- #89
- #97
- #164
- #216
- #245
- #250
- #256
- #294
- #336
- #473
- #524
-
Second Issue: For example, mine (#291) involves a missing check on the
paymentAmountToAddLiquidityamount. This issue will still be valid even if the Main issue is fixed, as thepaymentAmountToAddLiquiditycan be manipulated even if the user receives lpTokens in the desired proportions:- #291
- #62
- #152
- #217
- #277
- #328
- #401
- #517
- #560
- #600
- #620
- #677
- #188
- #174
-
Third Issue: Issues #431 and mine (#295) relate to the absence of a return of unused tokens, even where the transfer flow is user -> OptionTokenV4 contract -> router:
- #431
- #295
Lastly, #530 is invalid as it pertains to a view function, which is functioning as expected. The same user has issue #517, where this view function is only valid when utilized.
Edit: I missed #524 in first group.
rickkk137
@0xklapouchy thx for escalate this issue and I agree with u first group talk about different root cause and I think first group are invalid because they just mention lack of slippage control but main problem happen because of paymentAmountToAddLiquidity and attacker can manipulate that to harm legimate users and slippage control in this case dosen't matter because second parameter of addLiquidity will be computed in execution time of transaction
addLiquidity(
_tokenA,
_tokenB,
_amountA,
_amountB,
1,
1,
address(this),
block.timestamp
);
handling slippage control is important when user compute _amountB based on reserveA and reserveB before main addliq tx but in this case _amountB will be computed base on current reserveA and reserveB because both of them will be called in exercise function @nevillehuang
#89 #97 #164 #245 #250 #256 #294 #336 #431 #473 #524 also they doesn't have PoC and that is because their attack path is not provable and there isn't any loss of fund for this type of issue
nevillehuang
@0xklapouchy @goheesheng I really appreciate the second look, especially @0xklapouchy, this is the type of escalation that is very exemplary.
Agree with the deduplication with the followinh exceptions:
- I Will double check all duplicates to ensure accuracy and quality for issues 1 and 2
- Issue 3, which I have to take a further look at it
Cc @dawiddrzala, I believe two separate fixes are required for issue 1 and 2, unless I am missing something. Issue 3 is pending validity
0xklapouchy
@nevillehuang As for Issue 3, although it may initially seem valid to me, I can't prove it with a coded PoC (the values are used to last wei). Therefore, it can be considered invalid.
cvetanovv
All issues related to "slippage" are grouped together, regardless of whether they are different contracts or functions. It's in the Sherlock documentation. Therefore, they should remain duplicated together.
nevillehuang
@cvetanovv I think this suggestion here should be applied excluding issues #431 and #295, which should be invalidated, because of the following exception noted in sherlock guidelines. Different fix is involved despite them falling under the umbrella of slippage issues. However since the word and is used, I'm not sure if it should be interpreted as all conditions below must be met or just one? code implementations and fixes are different, but impact is similar. I will leave it to you to decide or if any other watsons have additional inputs
The exception to this would be if underlying code implementations, impact, and the fixes are different, then they can be treated separately.
cvetanovv
@nevillehuang Because the word is and I think it should remain duplicated.
However, with the latest update, the word is being replaced with or.
If you look at the current documentation, you'll see it's a little different in the duplicate rule - https://docs.sherlock.xyz/audits/judging/judging#ix.-duplication-rules
This update happened on 08/07/2024 - https://docs.sherlock.xyz/audits/judging/judging/criteria-changelog
However, the contest was started on 01/07/2024. That is, we are looking at the old rules where all the issues with "slippage" are grouped together. However, this will most likely be different for the new contests. At least, that's how I understand things.
0xklapouchy
@cvetanovv
To my understanding, even under the old rules, these issues should be considered separately as they involve three different factors:
- The root cause and impact are different. In one case, an incorrect (undervalued) LP amount is minted, while in the other, an overpayment occurs due to manipulation of the
paymentAmountToAddLiquidity. - The required fixes are different.
- When we examine the logic of both functions, the underlying code is different.
For the first issue, the problem lies within the following code:
(, , lpAmount) = IRouter(router).addLiquidity(
underlyingToken,
paymentToken,
false,
_amount,
paymentAmountToAddLiquidity,
1,
1,
address(this),
block.timestamp
);
For the second issue, the problem lies within this code:
(uint256 paymentAmount, uint256 paymentAmountToAddLiquidity) = getPaymentTokenAmountForExerciseLp(_amount, _discount);
The only commonality between these issues is the use of the term "slippage." However, they are entirely different from each other. Please refer to my issue #291, where I don't even mention slippage, as the issue there involves price manipulation.
cvetanovv
@0xklapouchy I'll consider your comment and ask Sherlock HoJ whether to keep them duplicated or separate them.
0xklapouchy
@cvetanovv @WangSecurity
Reminder that this should be sorted out.
crypticdefense
I just saw this right now, and would like to quickly respond to @0xklapouchy's comments about #517 and #530. #517 is clearly a duplicate of the issues in the second group and has a coded PoC which shows loss of funds due to inadequate slippage protection regarding paymentAmountToAddLiquidity.
As for #517, the view function is indeed used in OptionTokenV4::exerciseVe and OptionTokenV4::exerciseLp functions. I will let the lead judge to decide on it, but I also wrote a coded PoC for that issue, which I commented on #174.
Lastly, I'm unsure why @rickkk137 mentioned that #524 "does not have a PoC because that attack path is not proveable", when it clearly has a coded PoC written explaining step-by-step why it's valid, with an impact causing loss of funds.
I will refrain from further comment and let the judges decide.
cc: @cvetanovv @WangSecurity @nevillehuang
Edit: I meant to say "As for #530" in the second paragraph, not #517 :)
goheesheng
Hi @WangSecurity @nevillehuang for #174 the problem submitted is using a spot price is manipulatable of the pool instead of TWAP and is also not recommended for any protocol to use LP pool spot price as a price feed. The issue of slippage is inherent but the issue can also be fixed using TWAP price which is challenging to manipulate. Slippage can be used to fix this problem, but in the report that this is a spot price manipulability.
0xklapouchy
@crypticdefense I missed 524 in first group. Edited my comment.
As for the 530, it is invalid, view function works as expected, should this function be used on-chain - NO.
Can it be used off-chain - YES, for example to get the value for the slippage protection for addLiquidity(), you just attach this off-chain read as parameter when exercising.
The difference to 517 is that this view function is utilized on-chain, and only then there is a problem, but not in the view function, but in the function that used it.
cvetanovv
After a discussion with @WangSecurity and LSW, we decided to group all slippage protection issues into one issue. The reason is that a fix can be one. The protocol can check that token amounts are within reasonable deviation from the TWAP price.
I explained why these issues would be duplicated together now, but in a future contest in the same situation could be in separate groups, with this comment - https://github.com/sherlock-audit/2024-06-velocimeter-judging/issues/199#issuecomment-2294819677
sherlock-admin2
The protocol team fixed this issue in the following PRs/commits: https://github.com/Velocimeter/v4-contracts/pull/27
spacegliderrrr
Fix looks good. Slippage protection is now properly applied.
sherlock-admin2
The Lead Senior Watson signed off on the fix.
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
Root cause
Likely the exerciseLP function uses spot reserves to compute the payment token amount and passes a minimum LP amount of 1 to addLiquidity, so it does not enforce a minimum LP tokens received.
Impact
The victim receives fewer LP tokens than intended, reducing the value of the option tokens burned; the text shows a 9% reduction in one example.
What the attacker needed
Attacker can front-run the exercise transaction; pool has sufficient liquidity
The fix
The protocol team fixed this issue by adding slippage protection for the LP amount received.
How it was found
- Set up a pool with initial reserves.
- Calculate paymentAmountToAddLiquidity using spot reserves.
- Add liquidity and record LP tokens minted.
- Swap repeatedly to imbalance the pool.
- Recalculate paymentAmountToAddLiquidity and add liquidity again.
- Observe that the same deposit yields far fewer LP tokens.
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 you exercise an option, you burn option tokens and add liquidity to a pool to get LP tokens. The contract calculates how many payment tokens to add based on the current pool balance, but it does not check that you get a fair number of LP tokens back. An attacker can change the pool balance just before your transaction, so you get much less than you should.
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.