Skip to content
Business logic Audit finding Intermediate

Users cannot stop loss in AutoRange and AutoExit

The AutoRange and AutoExit contracts call _validateSwap even when amountIn is zero, meaning no swap is intended. This causes transactions to revert when the price deviates from the TWAP by more than the configured threshold, preventing users from withdrawing their tokens and cutting losses.

ktg Follow

Originally disclosed on Code4rena

Submitted by ktg

https://github.com/code-423n4/2024-03-revert-lend/blob/main/src/automators/Automator.sol#L151-L153

https://github.com/code-423n4/2024-03-revert-lend/blob/main/src/automators/AutoExit.sol#L162-L169

https://github.com/code-423n4/2024-03-revert-lend/blob/main/src/transformers/AutoRange.sol#L157-L164

Impact

  • Users cannot stop loss in AutoRange and AutoExit, resulting in huge loss.
  • Users cannot withdraw their tokens and cut loss even when they choose no swap option.

Proof of Concept

Contract AutoRange and AutoExit both inherits contract Automator and uses its function _validateSwap:

function _validateSwap(
        bool swap0For1,
        uint256 amountIn,
        IUniswapV3Pool pool,
        uint32 twapPeriod,
        uint16 maxTickDifference,
        uint64 maxPriceDifferenceX64
    ) internal view returns (uint256 amountOutMin, int24 currentTick, uint160 sqrtPriceX96, uint256 priceX96) {
        // get current price and tick
        (sqrtPriceX96, currentTick,,,,,) = pool.slot0();

        // check if current tick not too far from TWAP
        if (!_hasMaxTWAPTickDifference(pool, twapPeriod, currentTick, maxTickDifference)) {
            revert TWAPCheckFailed();
        }
....

 function _hasMaxTWAPTickDifference(IUniswapV3Pool pool, uint32 twapPeriod, int24 currentTick, uint16 maxDifference)
        internal
        view
        returns (bool)
    {
        (int24 twapTick, bool twapOk) = _getTWAPTick(pool, twapPeriod);
        if (twapOk) {
            return twapTick - currentTick >= -int16(maxDifference) && twapTick - currentTick <= int16(maxDifference);
        } else {
            return false;
        }
    }

...

function _getTWAPTick(IUniswapV3Pool pool, uint32 twapPeriod) internal view returns (int24, bool) {
        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = 0; // from (before)
        secondsAgos[1] = twapPeriod; // from (before)

        // pool observe may fail when there is not enough history available
        try pool.observe(secondsAgos) returns (int56[] memory tickCumulatives, uint160[] memory) {
            return (int24((tickCumulatives[0] - tickCumulatives[1]) / int56(uint56(twapPeriod))), true);
        } catch {
            return (0, false);
        }
    }

The function will revert if the difference between current tick and twap tick > maxTickDifference. Currently, maxTickDifference must <= 200 as you can see in function setTWAPConfig:

function setTWAPConfig(uint16 _maxTWAPTickDifference, uint32 _TWAPSeconds) public onlyOwner {
        if (_TWAPSeconds < MIN_TWAP_SECONDS) {
            revert InvalidConfig();
        }
        if (_maxTWAPTickDifference > MAX_TWAP_TICK_DIFFERENCE) {
            revert InvalidConfig();
        }
        emit TWAPConfigChanged(_TWAPSeconds, _maxTWAPTickDifference);
        TWAPSeconds = _TWAPSeconds;
        maxTWAPTickDifference = _maxTWAPTickDifference;
    }

MAX_TWAP_TICK_DIFFERENCE = 200.

If for example, maxTWAPTickDifference = 100, then the function will revert if price difference = 1.0001 * 100 = 1%. This will prevent users of AutoExit and AutoRange from stopping their loss in case the market drops > 1%.

Lets take an example:

  • Alice chooses AutoRange transformer.
  • Then AutoRange.execute is called with amountIn = 0, according to the comment in AutoRange.ExecuteParams struct, then if amountIn = 0, it means no swap:
struct ExecuteParams {
        uint256 tokenId;
        bool swap0To1;
        uint256 amountIn; // if this is set to 0 no swap happens
        bytes swapData;
        uint128 liquidity; // liquidity the calculations are based on
        uint256 amountRemoveMin0; // min amount to be removed from liquidity
        uint256 amountRemoveMin1; // min amount to be removed from liquidity
        uint256 deadline; // for uniswap operations - operator promises fair value
        uint64 rewardX64; // which reward will be used for protocol, can be max configured amount (considering onlyFees)
    }
  • In case of no swap, Alice just wants to withdraw her tokens and cut loss.
  • However, after AutoRange has called _decreaseFullLiquidityAndCollect to withdraw tokens for Alice, AutoRange still call _validateSwap to check (although amountIn is set to 0 - meaning no swap):
        (state.amount0, state.amount1, state.feeAmount0, state.feeAmount1) = _decreaseFullLiquidityAndCollect(
            params.tokenId, state.liquidity, params.amountRemoveMin0, params.amountRemoveMin1, params.deadline
        );

        ...
        // check oracle for swap
        (state.amountOutMin, state.currentTick,,) = _validateSwap(
            params.swap0To1,
            params.amountIn,
            state.pool,
            TWAPSeconds,
            maxTWAPTickDifference,
            params.swap0To1 ? config.token0SlippageX64 : config.token1SlippageX64
        );
  • If (currentTick - twapTick) > 100 (meaning 1% price difference), then the transaction will revert and the operator failed to stop Alice’s loss.
  • Alice has to wait when the condition (currentTick - twapTick) < 100 to cut loss, by then it’s too late.

The same thing happens in AutoExit, users cannot withdraw their tokens in case the prices change > 1%.

Below is a POC for the above example, save this test case to file test/integration/automators/AutoRange.t.sol and run it using command: forge test --match-path test/integration/automators/AutoRange.t.sol --match-test testNoSwapRevert -vvvv.

function testNoSwapRevert() public {
        bool onlyFees = false;
        SwapTestState memory state;

        // Config AutoRange
        vm.startPrank(TEST_NFT_2_ACCOUNT);
        NPM.setApprovalForAll(address(autoRange), true);
        autoRange.configToken(
            TEST_NFT_2,
            address(0),
            AutoRange.PositionConfig(
                0, 0, 0, 60, uint64(Q64 / 100), uint64(Q64 / 100), onlyFees, onlyFees ? MAX_FEE_REWARD : MAX_REWARD
            )
        );

        (,,,,,,, state.liquidity,,,,) = NPM.positions(TEST_NFT_2);
        vm.stopPrank();

        //
        (, int24 currentTick,,,,,) = IUniswapV3Pool(0xC2e9F25Be6257c210d7Adf0D4Cd6E3E881ba25f8).slot0();
        console.logInt(currentTick);

        // mock twap data
        // _maxTWAPTickDifference is currently set as 100
        // twapPeriod is 60,
        // currenttick = -73244
        // so the mock twap price  = (-6912871013261 - -6912866037401) / 60 = -82931
        int56[] memory tickCumulative = new int56[](2);
        tickCumulative[0] = -6912871013261;
        tickCumulative[1] = -6912866037401;

        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = 0;
        secondsAgos[1] = 60;
        uint160[] memory secondsPerLiquidityCumulativeX128s = new uint160[](2);

        vm.mockCall(
            0xC2e9F25Be6257c210d7Adf0D4Cd6E3E881ba25f8,(abi.encodeWithSelector(0x883bdbfd,secondsAgos)),
            abi.encode(tickCumulative,secondsPerLiquidityCumulativeX128s)
        );

        //Operator run
        vm.prank(OPERATOR_ACCOUNT);
        vm.expectRevert();
        autoRange.execute(
            AutoRange.ExecuteParams(
                TEST_NFT_2, false, 0, "", state.liquidity, 0, 0, block.timestamp, onlyFees ? MAX_FEE_REWARD : MAX_REWARD
            )
        );
    }

In the test case, I creates a mockCall to uniswap v3 observe function to simulate a market drop.

Recommended Mitigation Steps

I recommend skipping the swap operation if _hasMaxTWAPTickDifference returns false instead of reverting.

Assessed type

Invalid Validation

EV_om (lookout) commented:

Users have no control over the timing of Automator calls, operators do. If a user wants to quickly exit a position, they can repay.

This is an in-built protection mechanism.

ktg (warden) commented:

@EV_om, AutoExit will be called by a bot, users uses a bot to avoid manually exiting their UniswapV3 positions so I think the point If a user wants to quickly exit a position, they can repay. is not related.

What I meant in this issue is that even if amountIn is set to 0 (which means no swap), the code still call _validateSwap and revert if the price fluctuation is too high. Therefore, if execute is called with amountIn = 0 (which clearly indicates no swap, just withdraw and exit) and the price fluctuation is too high, it will revert. In another word, the code check the condition and revert in situations where users/callers clearly want to neglect that condition.

About This is an in-built protection mechanism., I think this is indeed a built-in protection mechanism, but that mechanism is only for cases where swap is needed. In this issue, this mechanism is still activated even when users don’t want it and result in their losses.

EV_om (lookout) commented:

You’re right, repayment of positions is unrelated, my bad. What I should have said was “If a user wants to quickly exit a position, they can do so manually.” As for the no swap case, there is no loss being prevented as the position owner will remain exposed to the same price action.

Nevertheless, the unnecessary call to _validateSwap() and resulting reverting behavior is a good observation. The judge may want to consider this as QA despite the overinflated severity and invalid assumptions of the original submission.

ktg (warden) commented:

@EV_om , @ronnyx2017 - I think the statement If a user wants to quickly exit a position, they can do so manually. is also unrelated here because the role of AutoExit is to help users automatically exit a position. You can’t expect users to look at market data and exit manually all the time; that’s why AutoExit/AutoRange exists.

The loss here is that AutoExit cannot help users to automatically exit a position because it reverts on a condition that clearly needed to be omitted due to amountIn =0 (no swap).

I think we all agree that the call to _validateSwap() is unnecessary here but I disagree that it’s just a QA because it can cost huge loss due to users (through AutoExit or AutoRange) unable to exit or re arrange their position.

If users choose to set amountIn (or swapAmount) = 0, then what they want is “I don’t want to swap, just exit/autorange my position”, but then AutoExit/AutoRange fails to do this.

ronnyx2017 (judge) decreased severity to Medium and commented:

Good catch! Unnecessary _validateSwap here has genuinely compromised certain functionalities of the protocol. Medium is justified, in my opinion. Looking forward to the sponsor’s perspective, @kalinbas.

kalinbas (Revert) confirmed and commented:

_validateSwap() is not necessary only if there is no swap, we are going to remove if in that case.

Revert mitigated:

Fixed here.

Status: Mitigation Confirmed. Full details in reports from b0g0, thank_you and ktg.


The original report as published on Code4rena, by ktg. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

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

The code calls _validateSwap unconditionally, even when amountIn is zero and no swap will occur, so the TWAP check reverts unnecessarily.

What the attacker needed

User has an AutoRange or AutoExit position; Market price deviates from TWAP beyond threshold

The fix

The unnecessary _validateSwap call should be skipped when amountIn is zero; the project fixed this by removing the call in that case.

How it was found

  1. Alice configures AutoRange for her position.
  2. AutoRange.execute is called with amountIn = 0, indicating no swap.
  3. The contract decreases liquidity and collects tokens.
  4. It then calls _validateSwap, which checks the TWAP difference.
  5. If the price difference exceeds the threshold, the transaction reverts, preventing withdrawal.

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.

AutoRange and AutoExit are automated tools that help users manage their investments on a decentralised exchange. When a user wants to exit without swapping, the code still checks if the price is stable enough and cancels the exit if not, so users cannot withdraw when the market moves sharply.

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.

More by ktg

View all

10 more disclosed reports, best first.

More from Revert Lend

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.