Anyone making use of the MagicLP’s TWAP to determine token prices will be exploitable.
The TWAP price accumulator in MagicLP is updated after reserves change, so an attacker can front-run a query with a large swap to inflate the recorded price for the entire elapsed period. Any integrating contract that uses this TWAP to price tokens could be manipulated into executing a losing trade.
Submitted by Trust, also found by ether_sky, blutorque, and ZanyBonzy
MagicLP provides a TWAP value which can be accessed via _BASE_PRICE_CUMULATIVE_LAST_
It is updated in the function below:
function _twapUpdate() internal {
uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32);
uint32 timeElapsed = blockTimestamp - _BLOCK_TIMESTAMP_LAST_;
if (timeElapsed > 0 && _BASE_RESERVE_ != 0 && _QUOTE_RESERVE_ != 0) {
/// @dev It is desired and expected for this value to
/// overflow once it has hit the max of `type.uint256`.
unchecked {
_BASE_PRICE_CUMULATIVE_LAST_ += getMidPrice() * timeElapsed;
}
}
_BLOCK_TIMESTAMP_LAST_ = blockTimestamp;
}
It is updated by any function that changes the reserves, for example:
function _resetTargetAndReserve() internal returns (uint256 baseBalance, uint256 quoteBalance) {
baseBalance = _BASE_TOKEN_.balanceOf(address(this));
quoteBalance = _QUOTE_TOKEN_.balanceOf(address(this));
if (baseBalance > type(uint112).max || quoteBalance > type(uint112).max) {
revert ErrOverflow();
}
_BASE_RESERVE_ = uint112(baseBalance);
_QUOTE_RESERVE_ = uint112(quoteBalance);
_BASE_TARGET_ = uint112(baseBalance);
_QUOTE_TARGET_ = uint112(quoteBalance);
_RState_ = uint32(PMMPricing.RState.ONE);
_twapUpdate();
}
function _setReserve(uint256 baseReserve, uint256 quoteReserve) internal {
_BASE_RESERVE_ = baseReserve.toUint112();
_QUOTE_RESERVE_ = quoteReserve.toUint112();
_twapUpdate();
}
The root cause of the issue is that the TWAP is updated after reserve changes. Since the TWAP multiplies the duration of time since the last update with the new reserves, an attacker has control over the registered price for the entire passed duration.
For reference, the Uniswap and Beanstalk TWAPs are provided below:
- UniswapV2 - priceXCumulativeLast is written and then reserves are changed
- Beanstalk - pumps are updated before the swap operation.
RareSkills details how TWAP operation works here.
Impact
Any application making use of the MagicLP’s TWAP to determine token prices will be exploitable.
Proof of Concept
- At time T0, `BASEPRICECUMULATIVE_LAST = X.
- Integrating contract records (T0,X)
- T seconds pass, without swaps, meaning price remained X.
- A contract queries
_BASE_PRICE_CUMULATIVE_LAST_to execute a large swap(A->B). The swap could be done through MIMswap or any other AMM. - Attacker frontruns the query by inflating the A reserves with a large swap. New price is Y >> X.
- Integrating contract records (T0+T, X + Y * T)
- When calculating TWAP for last T seconds:
(X+Y*T-X)/(T0+T-T0) = Y*T/T = Y. Attacker has succeeded in manipulating the price to Y. - The victim performs a losing trade
- Attacker swaps back (B->A) to get back their tokens minus swap fees, profiting from the price manipulation.
Recommended Mitigation Steps
_twapUpdate() needs to be called before reserves are updated.
0xCalibur (Abracadabra) disputed and commented:
It’s as designed. Integrating protocol should always check for min output to avoid frontrunning.
I think this is valid, the problem is that the TWAP algorithm is wrong, TWAP: https://en.wikipedia.org/wiki/Time-weighted_average_price By the way, the code here is consistent with DODOV2.
0xCalibur (Abracadabra) commented:
We decided to removed the TWAP functionality at the end. But during the time of this review, this was in the code.
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 TWAP accumulator is updated after the reserves are changed, so the new price is applied retroactively to the entire elapsed interval.
Impact
Any application using the MagicLP TWAP to determine token prices could be exploited, though the protocol argued that integrators should check minimum output to avoid front-running.
What the attacker needed
An integrating contract uses the TWAP; attacker can front-run the query; attacker has capital for a large swap
The fix
The TWAP update should be called before reserves are updated; the protocol ultimately removed the TWAP functionality.
How it was found
- At time T0, the cumulative price is X and an integrating contract records (T0, X).
- T seconds pass without swaps, so the price remains X.
- A contract queries the cumulative price to execute a large swap.
- The attacker front-runs the query by inflating the base reserves with a large swap, making the new price Y much larger than X.
- The integrating contract records (T0+T, X + Y*T), so the computed TWAP becomes Y.
- The victim performs a losing trade, and the attacker swaps back to recover tokens minus fees, profiting.
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.
A TWAP is a way to average a price over time so that a single trade cannot move it much. Here, the contract records the new price after a trade but applies it to the whole time since the last update, so a large trade just before someone reads the price makes the average jump to the attacker's price. The attacker then trades back and profits from the victim's bad trade.