Skip to content
Business logic Audit finding Advanced

Wrong liquidity formula used

The protocol's liquidity calculation used the price at the current tick instead of the actual current square-root price, causing incorrect liquidity deltas. This could make transactions revert when minimum amounts are close to desired amounts, and the judge noted it could make a portion of the protocol inaccessible.

prapandey031 Follow

Originally disclosed on Code4rena

Submitted by prapandey031

The protocol provides a function to increment a position’s liquidity:

    function incrPositionC3AC7CAA(
        address pool,
        uint256 id,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 amount0Desired,
        uint256 amount1Desired
    ) external returns (uint256, uint256);

It is present in the SeawaterAmm.sol:

https://github.com/code-423n4/2024-08-superposition/blob/main/pkg/sol/SeawaterAMM.sol#L464

    function incrPositionC3AC7CAA(
        address /* pool */,
        uint256 /* id */,
        uint256 /* amount0Min */,
        uint256 /* amount1Min */,
        uint256 /* amount0Desired */,
        uint256 /* amount1Desired */
    ) external returns (uint256, uint256) {
        directDelegate(_getExecutorUpdatePosition());
    }

It calls a function in lib.rs:

https://github.com/code-423n4/2024-08-superposition/blob/main/pkg/seawater/src/lib.rs#L914

    #[allow(non_snake_case)]
    pub fn incr_position_C_3_A_C_7_C_A_A(
        &mut self,
        pool: Address,
        id: U256,
        amount_0_min: U256,
        amount_1_min: U256,
        amount_0_desired: U256,
        amount_1_desired: U256,
    ) -> Result<(U256, U256), Revert> {
        self.adjust_position_internal(
            pool,
            id,
            amount_0_min,
            amount_1_min,
            amount_0_desired,
            amount_1_desired,
            false,
            None,
        )
    }

This calls an internal function in lib.rs:

https://github.com/code-423n4/2024-08-superposition/blob/main/pkg/seawater/src/lib.rs#L730

    #[allow(clippy::too_many_arguments)]
    pub fn adjust_position_internal(
        &mut self,
        pool: Address,
        id: U256,
        amount_0_min: U256,
        amount_1_min: U256,
        amount_0_desired: U256,
        amount_1_desired: U256,
        giving: bool,
        permit2: Option<(Permit2Args, Permit2Args)>,
    ) -> Result<(U256, U256), Revert> {
        assert_eq_or!(
            msg::sender(),
            self.position_owners.get(id),
            Error::PositionOwnerOnly
        );

        let (amount_0, amount_1) = self.pools.setter(pool).adjust_position(
            id,
            amount_0_desired,
            amount_1_desired,
            giving,
        )?;
        .
        .
        .
    }

This function calls a function in pool.rs:

https://github.com/code-423n4/2024-08-superposition/blob/main/pkg/seawater/src/pool.rs#L253

    pub fn adjust_position(
        &mut self,
        id: U256,
        amount_0: U256,
        amount_1: U256,
        giving: bool,
    ) -> Result<(I256, I256), Revert> {
        // calculate the delta using the amounts that we have here, guaranteeing
        // that we don't dip below the amount that's supplied as the minimum.

        let position = self.positions.positions.get(id);

        let sqrt_ratio_x_96 = tick_math::get_sqrt_ratio_at_tick(self.get_cur_tick().as_i32())?;
        let sqrt_ratio_a_x_96 = tick_math::get_sqrt_ratio_at_tick(position.lower.get().as_i32())?;
        let sqrt_ratio_b_x_96 = tick_math::get_sqrt_ratio_at_tick(position.upper.get().as_i32())?;

        let mut delta = sqrt_price_math::get_liquidity_for_amounts(
            sqrt_ratio_x_96,   // cur_tick
            sqrt_ratio_a_x_96, // lower_tick
            sqrt_ratio_b_x_96, // upper_tick
            amount_0,          // amount_0
            amount_1,          // amount_1
        )?
        .to_i128()
        .map_or_else(|| Err(Error::LiquidityAmountTooWide), Ok)?;

        if giving {
            // If we're giving, then we need to take from the delta.
            delta = -delta;
        }

        #[cfg(feature = "testing-dbg")]
        dbg!((
            "inside adjust_position",
            current_test!(),
            sqrt_ratio_x_96.to_string(),
            sqrt_ratio_a_x_96.to_string(),
            sqrt_ratio_b_x_96.to_string(),
            amount_0.to_string(),
            amount_1.to_string(),
            delta
        ));

        // [update_position] should also ensure that we don't do this on a pool that's not currently
        // running

        self.update_position(id, delta)
    }

In the above function at LOC-265, we have:

https://github.com/code-423n4/2024-08-superposition/blob/main/pkg/seawater/src/pool.rs#L265

let sqrt_ratio_x_96 = tick_math::get_sqrt_ratio_at_tick(self.get_cur_tick().as_i32())?;

Instead of:

let sqrt_price_x_96 = self.sqrt_price.get();

This passes not the current price but the price of the current tick to the get_liquidity_for_amounts() function.

Proof of Concept

The following is a step-by-step PoC that explains the issue in detail. Let’s say there exists a pool with the following configuration:

token0 = X
token1 = FUSDC

There are many available positions; one of them with tick range [0, 5].

Current price of the pool lies between ticks 0 and 1 and is equals to 1.00005

The current tick of a pool is determined by:

Note: please see scenario in warden’s original submission.

Now, a user A, owner of the position stated above, calls the function:

https://github.com/code-423n4/2024-08-superposition/blob/main/pkg/sol/SeawaterAMM.sol#L464

    function incrPositionC3AC7CAA(
        address /* pool */,
        uint256 /* id */,
        uint256 /* amount0Min */,
        uint256 /* amount1Min */,
        uint256 /* amount0Desired */,
        uint256 /* amount1Desired */
    ) external returns (uint256, uint256) {
        directDelegate(_getExecutorUpdatePosition());
    }

Ultimately, the adjust_position() in pool.rs is called. In this function, at LOC-265, the following is set:

let sqrt_ratio_x_96 = tick_math::get_sqrt_ratio_at_tick(self.get_cur_tick().as_i32())?;

This means that sqrt_ratio_x_96 would have 1 (or 2^96) as the curr_tick is 0. Now, get_liquidity_for_amounts() function is called:

pub fn get_liquidity_for_amounts(
    sqrt_ratio_x_96: U256,
    mut sqrt_ratio_a_x_96: U256,
    mut sqrt_ratio_b_x_96: U256,
    amount_0: U256,
    amount_1: U256,
) -> Result<u128, Error> {
    if sqrt_ratio_a_x_96 > sqrt_ratio_b_x_96 {
        (sqrt_ratio_a_x_96, sqrt_ratio_b_x_96) = (sqrt_ratio_b_x_96, sqrt_ratio_a_x_96)
    };

    let delta = if sqrt_ratio_x_96 <= sqrt_ratio_a_x_96 {
        get_liquidity_for_amount_0(sqrt_ratio_a_x_96, sqrt_ratio_b_x_96, amount_0)?
    } else if sqrt_ratio_x_96 < sqrt_ratio_b_x_96 {
        let liq0 = get_liquidity_for_amount_0(sqrt_ratio_x_96, sqrt_ratio_b_x_96, amount_0)?;
        let liq1 = get_liquidity_for_amount_1(sqrt_ratio_a_x_96, sqrt_ratio_x_96, amount_1)?;
        if liq0 > liq1 {
            liq1
        } else {
            liq0
        }
    } else {
        get_liquidity_for_amount_1(sqrt_ratio_a_x_96, sqrt_ratio_b_x_96, amount_1)?
    };

    Ok(delta)
}

This function checks at LOC-312 that:

if sqrt_ratio_x_96 <= sqrt_ratio_a_x_96

and calls:

get_liquidity_for_amount_0(sqrt_ratio_a_x_96, sqrt_ratio_b_x_96, amount_0)?

This is wrong as the current price of the pool (= 1.00005) is in the price range of the position ([1, (1.0001)^5]).

Basically, the main liquidity formula used by the protocol currently is:

Note: please see scenario in warden’s original submission.

The calculation is also wrong. Let’s assume that A calls the function with:

        amount0Min = 95% of amount0Desired
        amount0Desired = 1000 (assume decimal included)

The present calculation would result in an amount0 that would be ~899.98 or 900 which is 90% of amount0Desired and thus, is less than amount0Min. Therefore, this transaction would revert.

Severity

The protocol mentions “We should follow Uniswap V3’s math faithfully” as one of its core invariants. This must not break. However, as this report explains, this invariant stands broken.

If the amount0Desired and amount0Min (also applicable to amount1) are very close to each other, then the transaction to incrPositionC3AC7CAA() function reverts. So, the severity is High.

Tools Used

Desmos scientific calculator.

Recommended Mitigation Steps

Replace the following in the adjust_position() function below:

    pub fn adjust_position(
        &mut self,
        id: U256,
        amount_0: U256,
        amount_1: U256,
        giving: bool,
    ) -> Result<(I256, I256), Revert> {
        // calculate the delta using the amounts that we have here, guaranteeing
        // that we don't dip below the amount that's supplied as the minimum.

        let position = self.positions.positions.get(id);

-       let sqrt_ratio_x_96 = tick_math::get_sqrt_ratio_at_tick(self.get_cur_tick().as_i32())?;
+       let sqrt_ratio_x_96 = self.sqrt_price.get();
        let sqrt_ratio_a_x_96 = tick_math::get_sqrt_ratio_at_tick(position.lower.get().as_i32())?;
        let sqrt_ratio_b_x_96 = tick_math::get_sqrt_ratio_at_tick(position.upper.get().as_i32())?;

        let mut delta = sqrt_price_math::get_liquidity_for_amounts(
            sqrt_ratio_x_96,   // cur_tick
            sqrt_ratio_a_x_96, // lower_tick
            sqrt_ratio_b_x_96, // upper_tick
            amount_0,          // amount_0
            amount_1,          // amount_1
        )?
        .to_i128()
        .map_or_else(|| Err(Error::LiquidityAmountTooWide), Ok)?;

        if giving {
            // If we're giving, then we need to take from the delta.
            delta = -delta;
        }

        #[cfg(feature = "testing-dbg")]
        dbg!((
            "inside adjust_position",
            current_test!(),
            sqrt_ratio_x_96.to_string(),
            sqrt_ratio_a_x_96.to_string(),
            sqrt_ratio_b_x_96.to_string(),
            amount_0.to_string(),
            amount_1.to_string(),
            delta
        ));

        // [update_position] should also ensure that we don't do this on a pool that's not currently
        // running

        self.update_position(id, delta)
    }

Assessed type

Math

0xsomeone (judge) commented:

While the submission is elaborate and goes into great detail, I do not believe that a tangible issue can manifest from calculating the square root price from the current tick as it should match the current price whenever this particular function is invoked. As such, I would advise a PoC to be introduced for this particular submission.

prapandey031 (warden) commented:

@0xsomeone - The issue is not a mere use of the price of current_tick instead of the current_sqrt_price. Rather, this report describes how the Superposition protocol uses the wrong Uniswap v3 liquidity math formula.

Difference between current_sqrt_price and price of the current_tick

Uniswap v3 wrote a blog describing the relationship between current_tick, current_tick_price, and current_sqrt_price. The blog states that:

This explains why using ticks can be less precise than sqrtPriceX96 in Uniswap v3.

Just like ticks can be in between initialized ticks, ticks can also be in between integers as well! The protocol itself reports the floor ⌊ic⌋ of the current tick, which the sqrtPriceX96 retains.

To simplify, getting the price of the current_tick would not be equal to getting the current_sqrt_price, as Uniswap v3 stores the current_tick as the floor of the tick derived through the current_sqrt_price:

Note: please see scenario in warden’s original comment.

The above is equation 6.8 from Uniswap v3 whitepaper. The example in the blog makes it clear:

current_sqrt_price = 649004842.70137
price using current_tick = 648962487.5642413

Mathematical PoC for deviation from Uniswap v3 math

Note: please see scenario in warden’s original comment.

Result

Both parts lead to the wrong calculation of Delta Liquidity. Finally, this results in the wrong calculation of amount_0 and amount_1 when adjust_position() function calls update_position(&mut self, id: U256, delta: i128) function with the wrongly calculated delta:

https://github.com/code-423n4/2024-08-superposition/blob/main/pkg/seawater/src/pool.rs#L299

        self.update_position(id, delta)

The root cause of the issue is the use of price of the current_tick instead of the current_sqrt_price:

https://github.com/code-423n4/2024-08-superposition/blob/main/pkg/seawater/src/pool.rs#L265

        let sqrt_ratio_x_96 = tick_math::get_sqrt_ratio_at_tick(self.get_cur_tick().as_i32())?;

This should be replaced with:

        let sqrt_ratio_x_96 = self.sqrt_price.get();

With this fix, the correct liquidity formulas are used for both parts. This issue is valid as the sponsor has mentioned faithful use of Uniswap v3 math as a core invariant in the Readme of the audit. This report successfully shows that this core invariant stands broken.

0xsomeone (judge) commented:

@prapandey031 - I greatly appreciate the in-depth mathematical analysis of the issue; however, a simple deviation of the mathematical formulae implemented by Uniswap V3 is not adequate to consider this an HM risk submission.

I would advise you to quantify the precise error that would result from this flooring mechanism of the tick, as well as produce a PoC that demonstrates the issue (i.e., an execution of the same operations in Uniswap V3 and the SuperPosition system) to illustrate the vulnerability in practice.

While the error is clear, we need to have a quantifiable impact to assess it as an HM risk.

prapandey031 (warden) commented:

@0xsomeone - I would quantify the funds that Superposition looses due to the explained error as well as detail other impacts.

Below I present calculation PoCs to quantify the impact. I break the complete PoC into 2 parts corresponding to the 2 parts in my previous response.

I build this response on top of my previous response. In my previous response, I proved that Superposition uses wrong liquidity equations. I did this using the in-scope code snippets of Superposition and Uniswapv3 math equations. In this response I calculate values based on the correct and wrong equations to quantify the impact.

Note: please see scenario in warden’s original comment.


To confirm that the Uniswapv3 really uses the equations that I state above (although whatever equations stated above can be found in Uniswapv3 whitepaper; I took all of them from there) I provide the relevant code snippets from Uniswapv3-periphery repo:

addLiquidity(AddLiquidityParams memory params) which is similar to adjust_position() in Superposition:

    /// @notice Add liquidity to an initialized pool
    function addLiquidity(AddLiquidityParams memory params)
        internal
        returns (
            uint128 liquidity,
            uint256 amount0,
            uint256 amount1,
            IUniswapV3Pool pool
        )
    {
        PoolAddress.PoolKey memory poolKey =
            PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee});

        pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));

        // compute the liquidity amount
        {
>           (uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
            uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(params.tickLower);
            uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(params.tickUpper);

            liquidity = LiquidityAmounts.getLiquidityForAmounts(
                sqrtPriceX96,
                sqrtRatioAX96,
                sqrtRatioBX96,
                params.amount0Desired,
                params.amount1Desired
            );
        }

        (amount0, amount1) = pool.mint(
            params.recipient,
            params.tickLower,
            params.tickUpper,
            liquidity,
            abi.encode(MintCallbackData({poolKey: poolKey, payer: msg.sender}))
        );

        require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Price slippage check');
    }
}

Notice how Uniswapv3 uses current_sqrt_price instead of price of current_tick at marked (>) LOC above. This is the fix that I proposed in the original report.

getLiquidityForAmounts() which is similar to get_liquidity_for_amounts() in Superposition:

    function getLiquidityForAmounts(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
            uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);

            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
        } else {
            liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
        }
    }

0xsomeone (judge) decreased severity to Medium and commented:

@prapandey031 - thank you for diving deeper into this particular submission! The original submission’s impact indicated that transactions would fail when the minimum amounts are close to the expected amounts; however, your latest feedback indicates that actual fund loss would occur.

Given that the submission must be judged on its original merits and its validity has been demonstrated, I will award this as a medium-severity submission that would cause a portion of the protocol to become inaccessible versus resulting in fund loss, as this is an aspect not described in the original report.

af-afk (Superposition) confirmed


The original report as published on Code4rena, by prapandey031. 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

Likely the code used the square-root ratio derived from the current tick instead of the stored current square-root price when computing liquidity.

Impact

Transactions to increase liquidity could revert when minimum amounts are close to desired amounts, and the judge noted it could make a portion of the protocol inaccessible.

What the attacker needed

A position in a pool; amount0Min close to amount0Desired

The fix

The code should use the stored current square-root price instead of the tick-derived price.

How it was found

  1. A pool exists with token0, token1, and a position with tick range [0, 5].
  2. The current price is between ticks 0 and 1, equal to 1.00005.
  3. The position owner calls incrPositionC3AC7CAA with amount0Desired and amount0Min close to each other.
  4. The call reaches adjust_position, which sets sqrt_ratio_x_96 from the current tick (0) instead of the actual square-root price.
  5. get_liquidity_for_amounts uses this incorrect value, leading to a calculated amount0 that is below amount0Min.
  6. The transaction reverts.

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 automated market makers like Uniswap, the current price is stored as a square root value, and the 'tick' is a rounded-down version of that price. The code mistakenly used the rounded tick price instead of the precise square-root price when calculating how much liquidity a user gets. This small rounding error can cause the calculated amounts to fall below the user's minimum, making the transaction fail.

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 prapandey031

View all

2 more disclosed reports, best first.

More from Superposition

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.