Incorrect calculation of usedFunds in LiquidityPool leads to lower than expected token price
The LiquidityPool contract fails to deduct hedging fees from usedFunds when opening or closing trades, causing usedFunds to be overstated. This reduces available funds and lowers the token price, shortchanging liquidity providers.
peakbolt Follow with auditor0517 and KIntern_NA
Originally disclosed on Code4rena
Submitted by peakbolt, also found by auditor0517 and KIntern_NA
In LiquidityPool.sol, the functions openLong(), closeLong(), openShort() and closeShort() do not deduct hedgingFees from usedFunds to offset the hedgingFees that was added due to _hedge().
Impact
The missing deduction of hedgingFees will increase the usedFunds in LiquidityPool, thus reducing the availableFunds. This leads to a lower token price, causing LiquidityPool token holders to be shortchanged, losing a portion of their token value.
Detailed Explanation
Passive users can provide liquidity to the Liquidity Pool to earn exchange fees, while traders can take long or short position against the Exchange.
The trade functions openLong(), closeLong(), openShort() and closeShort() in LiquidityPool.sol will call _hedge to hedge the liquidity pool’s exposure during a trade.
The hedge() will actually increase usedFunds by the margin required, which includes hedgingFees as these are transfered over to the perpMarket for the hedging.
uint256 marginRequired = _calculateMargin(hedgingSize) + hedgingFees;
usedFunds += int256(marginRequired);
require(usedFunds <= 0 || totalFunds >= uint256(usedFunds));
perpMarket.transferMargin(int256(marginRequired));
Using the OpenLong() trade as an example, the trader transfers the tradeCost + fees to LiquidityPool, which includes the premium, hedgingFees, feesCollected and externalFee. That means the hedgingFees that was transfered in _hedge() is actually provided by the trader and not the LiquidityPool.
Hence, the usedFunds should be reduced by hedgingFees to offset the addition in _hedge().
uint256 fees = orderFee(int256(amount));
totalCost = tradeCost + fees;
SUSD.safeTransferFrom(user, address(this), totalCost);
uint256 hedgingFees = _hedge(int256(amount), false);
uint256 feesCollected = fees - hedgingFees;
uint256 externalFee = feesCollected.mulWadDown(devFee);
SUSD.safeTransfer(feeReceipient, externalFee);
usedFunds -= int256(tradeCost);
totalFunds += feesCollected - externalFee;
Proof of Concept
Then add the following imports and test case to test/LiquidityPool.Trades.t.sol
import {wadMul} from "solmate/utils/SignedWadMath.sol";
import {IPerpsV2Market} from "../src/interfaces/synthetix/IPerpsV2Market.sol";
function testLiquidityPoolFundCalculation() public {
uint256 longAmount = 1e18;
(uint256 markPrice, bool isInvalid) = pool.getMarkPrice();
uint256 tradeCost = longAmount.mulWadDown(markPrice);
uint256 fees = pool.orderFee(int256(longAmount));
uint256 delta = pool.getDelta();
int256 hedgingSize = wadMul(int256(longAmount), int256(delta));
IPerpsV2Market perp = pool.perpMarket();
(uint256 hedgingFees, ) = perp.orderFee(hedgingSize, IPerpsV2MarketBaseTypes.OrderType.Delayed);
uint256 feesCollected = fees - hedgingFees;
uint256 externalFee = feesCollected.mulWadDown(pool.devFee());
uint256 totalFundsBefore = pool.totalFunds();
int256 usedFundsBefore = pool.usedFunds();
// Open a Long trade
openLong(longAmount, longAmount * 1000, user_1);
// Calculated expected totalFunds and usedFunds
uint256 expectedTotalFunds = totalFundsBefore + feesCollected - externalFee;
uint256 marginRequired = tradeCost + hedgingFees;
int256 expectedUsedFunds = usedFundsBefore - int256(tradeCost) - int256(hedgingFees) + int256(marginRequired);
// This is correct as the pool will increase by net fee (feesCollected - externalFee)
assertEq(pool.totalFunds(), expectedTotalFunds);
// LiquidityPool's UsedFunds is wrong and is higher than expected as it included hedgingFees.
assertGt(pool.usedFunds(), expectedUsedFunds);
uint256 poolAvailableFunds = pool.totalFunds() - uint256(pool.usedFunds());
uint256 expectedAvailableFunds = expectedTotalFunds - uint256(expectedUsedFunds);
// LiquidityPool's available funds is wrong and is less than expected as it factored in hedgingFees
assertLt(poolAvailableFunds, expectedAvailableFunds);
assertEq(poolAvailableFunds, expectedAvailableFunds - hedgingFees);
// LiquidityPool's available funds is wrong and is also less than SUSD balance
assertLt(poolAvailableFunds, susd.balanceOf(address(pool)));
// LiquidityPool's available fund is expected to be the same as Pool's SUSD balance
assertEq(expectedAvailableFunds, susd.balanceOf(address(pool)));
// LiquidityPool Token price is less than expected.
assertLt(pool.getTokenPrice(), getExpectedTokenPrice(expectedTotalFunds, expectedUsedFunds, perp));
}
function getExpectedTokenPrice(uint256 expectedTotalFunds, int256 expectedUsedFunds, IPerpsV2Market perp) public returns (uint256 expectedTokenPrice) {
(uint256 markPrice,) = pool.getMarkPrice();
uint256 totalValue = expectedTotalFunds;
uint256 totalSupply = lqToken.totalSupply() + pool.totalQueuedWithdrawals();
uint256 amountOwed = markPrice.mulWadDown(powerPerp.totalSupply());
uint256 amountToCollect = markPrice.mulWadDown(shortToken.totalShorts());
//uint256 totalMargin = _getTotalMargin();
(uint256 totalMargin,) = perp.remainingMargin(address(pool));
totalValue += totalMargin + amountToCollect;
totalValue -= uint256((int256(amountOwed) + expectedUsedFunds));
expectedTokenPrice = totalValue.divWadDown(totalSupply);
}
Recommended Mitigation Steps
Deduct hedgingFees from usedFunds to offset the hedgingFees added in _hedge().
For example, in openLong change
usedFunds -= int256(tradeCost);
to
usedFunds -= int256(tradeCost) - int256(hedgingFees);
mubaris (Polynomial) confirmed
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 trade functions do not subtract hedgingFees from usedFunds after _hedge adds them, so the fees are double-counted as used funds.
Impact
Liquidity pool token holders could lose a portion of their token value because the token price is lower than it should be.
What the attacker needed
A trade that triggers hedging
The fix
Deduct hedgingFees from usedFunds to offset the hedgingFees added in _hedge().
How it was found
- Open a long trade with a given amount.
- Calculate expected totalFunds and usedFunds based on fees and margin.
- Observe that pool.usedFunds() is greater than expected.
- Observe that available funds are less than expected and less than the SUSD balance.
- Observe that the token price is lower than expected.
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.
In a liquidity pool, the token price depends on how much money is available versus how much is owed. The code mistakenly counts some fees as still being used when they were actually paid by the trader, so the pool looks poorer than it is. This makes each pool token worth less than it should be, and people who put money in lose out.
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.