Skip to content
Business logic Audit finding Advanced

XYK `reflect_curve` is incorrect and decreases K over time leading to loss of funds for LP providers

The XYK `reflect_curve` function computes passive order sizes using the initial quote reserve instead of the constant product invariant, resulting in prices that are more favourable to takers than a regular AMM swap. This causes the pool's K invariant to decrease over time, leading to a loss of funds for liquidity providers.

0xc0ffEE Follow with haxagon

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2025-09-dango-dex-judging/issues/384

Found by

0xc0ffEE, haxagon

Summary

XYK reflect_curve underperforms regular XYK AMM algorithm

Root Cause

The XYK reflect_curve algorithm that generates passive orders is unfavorable to the pool, computing more unfavorable prices than what the actual AMM algorithm would give.

https://github.com/left-curve/left-curve/blob/cff1bf826bd64ebab16fc7d1947a98e1e1fa4776/dango/dex/src/core/xyk.rs#L97-L167

RS
pub fn reflect_curve(
    mut base_reserve: Uint128,
    mut quote_reserve: Uint128,
    params: Xyk,
    swap_fee_rate: Bounded<Udec128, ZeroExclusiveOneExclusive>,
) -> anyhow::Result<(
    Box<dyn Iterator<Item = (Price, Uint128)>>,
    Box<dyn Iterator<Item = (Price, Uint128)>>,
)> {
    // Withhold the funds corresponding to the reserve requirement.
    // These funds will not be used to place orders.
    let one_sub_reserve_ratio = Udec128::ONE - *params.reserve_ratio;
    base_reserve.checked_mul_dec_floor_assign(one_sub_reserve_ratio)?;
    quote_reserve.checked_mul_dec_floor_assign(one_sub_reserve_ratio)?;

    // If either reserve is zero, return empty iterators as there's no liquidity to reflect
    if base_reserve.is_zero() || quote_reserve.is_zero() {
        return Ok((
            Box::new(iter::empty()),
            Box::new(iter::empty()),
        ));
    }

    // Compute the marginal price. We will place orders above and below this price.
    let marginal_price = Price::checked_from_ratio(quote_reserve, base_reserve)?;

    // Construct the bid order iterator.
    // Start from the marginal price minus the swap fee rate.
    let bids = {
        let one_sub_fee_rate = Udec128::ONE.checked_sub(*swap_fee_rate)?;
        let mut maybe_price = marginal_price.checked_mul(one_sub_fee_rate).ok();
        let mut prev_size = Uint128::ZERO;
        let mut prev_size_quote = Uint128::ZERO;

        iter::from_fn(move || {
            // Terminate if price is less or equal to zero.
            let price = match maybe_price {
                Some(price) if price.is_non_zero() => price,
                _ => return None,
            };

            // Compute the total order size (in base asset) at this price.
            let quote_reserve_div_price = quote_reserve.checked_div_dec(price).ok()?;
            let mut size = quote_reserve_div_price.checked_sub(base_reserve).ok()?;

            // Compute the order size (in base asset) at this price.
            //
            // This is the difference between the total order size at
            // this price, and that at the previous price.
            let mut amount = size.checked_sub(prev_size).ok()?;

            // Compute the total order size (in quote asset) at this price.
            let mut amount_quote = amount.checked_mul_dec_ceil(price).ok()?;
            let mut size_quote = prev_size_quote.checked_add(amount_quote).ok()?;

            // If total order size (in quote asset) is greater than the
            // reserve, cap it to the reserve size.
            if size_quote > quote_reserve {
                size_quote = quote_reserve;
                amount_quote = size_quote.checked_sub(prev_size_quote).ok()?;
                amount = amount_quote.checked_div_dec_floor(price).ok()?;
                size = prev_size.checked_add(amount).ok()?;
            }

            // If order size is zero, we have ran out of liquidity.
            // Terminate the iterator.
            if amount.is_zero() {
                return None;
            }

            // Update the iterator state.
            prev_size = size;
            prev_size_quote = size_quote;
            maybe_price = price.checked_sub(params.spacing).ok();

            Some((price, amount))
        })
        .take(params.limit)
    };

    // Construct the ask order iterator.
    let asks = {
        let one_plus_fee_rate = Udec128::ONE.checked_add(*swap_fee_rate)?;
        let mut maybe_price = marginal_price.checked_mul(one_plus_fee_rate).ok();
        let mut prev_size = Uint128::ZERO;

        iter::from_fn(move || {
            let price = maybe_price?;

            // Compute the total order size (in base asset) at this price.
            let quote_reserve_div_price = quote_reserve.checked_div_dec(price).ok()?;
            let size = base_reserve.checked_sub(quote_reserve_div_price).ok()?;

            // If total order size (in base asset) exceeds the base asset
            // reserve, cap it to the reserve size.
            let size = cmp::min(size, base_reserve);

            // Compute the order size (in base asset) at this price.
            //
            // This is the difference between the total order size at
            // this price, and that at the previous price.
            let amount = size.checked_sub(prev_size).ok()?;

            // If order size is zero, we have ran out of liquidity.
            // Terminate the iterator.
            if amount.is_zero() {
                return None;
            }

            // Update the iterator state.
            prev_size = size;
            maybe_price = price.checked_add(params.spacing).ok();

            Some((price, amount))
        })
        .take(params.limit)
    };

    Ok((Box::new(bids), Box::new(asks)))
}

The reason for this is that for instance, for bid orders, the function uses the following to determine the order size at step $n$

$$ \Delta b_{n} = \frac{Q_0}{P_n}-{B_{n-1}} $$

The flaw here is that we are using the initial quote_reserve value $Q_0$ when dividing by price. This assumes that the quote assets do not change as we move away from our initial point of the AMM but in reality it does change. The only thing that does not change should be the $K = B_0 \cdot Q_0$. Instead, it should be using the formula:

$$ \Delta b_{n} = \sqrt{\frac{K}{P_n}}-{B_{n-1}} $$

This works because for a given AMM, at the price $P_n = \frac{Q_n}{B_n} $, we can compute the value of $B_n$ in the AMM using:

$$ \sqrt{\frac{K}{P_n}} = \sqrt{\frac{B_n \cdot Q_n}{P_n}} = B_n $$

Similarly for ask orders, the correct function would be:

$$ \Delta b_{n} = - \sqrt{\frac{K}{P_n}}+{B_{n-1}} $$

As such, due to the incorrect pricing, the pool is charging lower than what an regular CP-AMM would charge. This causes the K-invariant to decrease, instead of increase over time causing a loss of funds for LP providers.

Internal Pre-conditions

External Pre-conditions

Attack Path

If we refer to the results pasted at the Python notebook located here. Let's perform a sample comparison for a bid order when at step n. This reflects a SOL-USDC XYK pool with initial liquidity 1 SOL and 200 USDC and a fee of 0.3%

Text
---------------------- Bids -----------------------
        p         a        da          b        db
0   200.0  0.000000  0.000000   0.000000  0.000000
1   199.4  0.003009  0.003009   0.600000  0.600000
2   198.4  0.008065  0.005055   1.603009  1.003009
3   197.4  0.013171  0.005107   2.611074  1.008065
4   196.4  0.018330  0.005159   3.624245  1.013171
5   195.4  0.023541  0.005212   4.642575  1.018330
6   194.4  0.028807  0.005265   5.666116  1.023541
7   193.4  0.034126  0.005320   6.694923  1.028807
8   192.4  0.039501  0.005375   7.729049  1.034126
9   191.4  0.044932  0.005431   8.768550  1.039501
10  190.4  0.050420  0.005488   9.813482  1.044932
...

At step n, interpreting the table, we can observe we can sell 0.050420 SOL to the order book for 9.81 USDC.

If we were to perform a regular swap instead, the total USDC received will be (1-0.003)(200-200/(1+0.050420)) = 9.57 USDC.

Hence, the pool spends 0.24 USDC more on passive orders than if it were using a regular swap.

For the passive order, the pool contents after filling it will be 1.050420 SOL and 190.186518 USDC. Multiplying both will yield K = 199.7757, since the K has decreased, the LP providers are actually losing funds from the XYK pool creating passive orders.

If we perform the same analysis using the fixed functions.

PYTHON3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def compute_bids(compute_p_m, compute_a, A, B, dp, half_spread, max_num_orders, **kwargs):
    # Compute the marginal price.
    p_m = compute_p_m(A, B, **kwargs)

    # Set the iterator's starting condition.
    p = p_m * (1 - half_spread)
    a = 0
    da = 0
    b = 0
    db = 0

    arr_p = [p_m]
    arr_a = [a]
    arr_da = [da]
    arr_b = [b]
    arr_db = [db]

    for n in range(1, max_num_orders + 1):
        # Terminate if price is less or equal to zero.
        if p <= 0:
            break

        # Compute the total order size (in base asset) at this price.
        a = compute_a(A, B, p, **kwargs)

        # Compute the order size (in base asset) at this price.
        da = a - arr_a[n - 1]

        # Compute the total order size (in quote asset) at this price.
        db = da * p
        b = arr_b[n - 1] + db

        # If total order size (in quote asset) is greater than the reserve, cap it to the reserve size.
        if b > B:
            b = B
            db = b - arr_b[n - 1]
            da = db * p
            a = arr_a[n - 1] + da

        # If order size rounds to zero, we have ran out of liquidity. Terminate the iterator.
        # Here we assume the base asset has 6 decimals, so < 1e-6 means rounding to zero.
        if da < 1e-6:
            break

        # Update the iterator state.
        arr_p.append(p)
        arr_a.append(a)
        arr_da.append(da)
        arr_b.append(b)
        arr_db.append(db)

        p -= dp

    return np.array(arr_p), np.array(arr_a), np.array(arr_da), np.array(arr_b), np.array(arr_db)


def compute_asks(compute_p_m, compute_a, A, B, dp, half_spread, max_num_orders, **kwargs):
    # Compute the marginal price.
    p_m = compute_p_m(A, B, **kwargs)

    # Set the iterator's starting condition.
    p = p_m * (1 + half_spread)
    a = 0
    da = 0
    b = 0
    db = 0

    arr_p = [p_m]
    arr_a = [a]
    arr_da = [da]
    arr_b = [b]
    arr_db = [db]

    for n in range(1, max_num_orders + 1):
        # Compute the total order size (in base asset) at this price.
        a = compute_a(A, B, p, **kwargs)

        # If total order size (in base asset) exceeds the base asset reserve, cap it to the reserve size.
        if a >= A:
            a = A

        # Compute the order size (in base asset) at this price.
        da = a - arr_a[n - 1]

        # If order size rounds to zero, we have ran out of liquidity. Terminate the iterator.
        # Here we assume the base asset has 6 decimals, so < 1e-6 means rounding to zero.
        if da < 1e-6:
            break

        # Compute the order size (in quote asset) at this price.
        # This isn't used in the smart contract logic. Just for plotting the graphs.
        db = da * p

        # Compute the total order size (in quote asset) at this price.
        b = arr_b[n - 1] + db

        # Update the iterator state.
        arr_p.append(p)
        arr_a.append(a)
        arr_da.append(da)
        arr_b.append(b)
        arr_db.append(db)

        p += dp

    return np.array(arr_p), np.array(arr_a), np.array(arr_da), np.array(arr_b), np.array(arr_db)


def plot(compute_bids, compute_asks, A, B, dp, half_spread, max_num_orders=25, filename="", **kwargs):
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 6))
    # fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, figsize=(12, 12))

    # Compute and plot bids
    arr_p, arr_a, arr_da, arr_b, arr_db = compute_bids(A, B, dp, half_spread, max_num_orders, **kwargs)
    ax1.bar(arr_p, arr_da, color="green", width=dp * 0.8)
    ax2.step(arr_p, arr_a, color="green", where="post")
    # ax3.bar(arr_p, arr_db, color="green", width=dp * 0.8)
    # ax4.step(arr_p, arr_b, color="green", where="post")

    print("---------------------- Bids -----------------------")
    print(pd.DataFrame(data={"p": arr_p, "a": arr_a, "da": arr_da, "b": arr_b, "db": arr_db}))

    # Compute and plot asks
    arr_p, arr_a, arr_da, arr_b, arr_db = compute_asks(A, B, dp, half_spread, max_num_orders, **kwargs)
    ax1.bar(arr_p, arr_da, color="red", width=dp * 0.8)
    ax2.step(arr_p, arr_a, color="red", where="post")
    # ax3.bar(arr_p, arr_db, color="red", width=dp * 0.8)
    # ax4.step(arr_p, arr_b, color="red", where="post")

    print("---------------------- Asks -----------------------")
    print(pd.DataFrame(data={"p": arr_p, "a": arr_a, "da": arr_da, "b": arr_b, "db": arr_db}))

    ax1.set_ylabel("order size (SOL)")
    ax2.set_ylabel("order depth (SOL)")
    # ax3.set_ylabel("order size (USD)")
    # ax4.set_ylabel("order depth (USD)")
    ax1.set_ylim(0)
    ax2.set_ylim(0)
    # ax3.set_ylim(0)
    # ax4.set_ylim(0)
    ax2.set_xlabel("price (USD per SOL)")
    # ax4.set_xlabel("price (USD per SOL)")

    plt.tight_layout()
    if filename != "":
        plt.savefig(filename)
    plt.show()

def compute_xyk_f(A, B):
    return A * B


def compute_xyk_p_m(A, B):
    return B / A


def compute_xyk_ask_a(A, B, p):
    return A - B / p


def compute_xyk_bid_a(A, B, p):
    return B / p - A


def compute_xyk_ask_a_fixed(A, B, p):
    return A - (compute_xyk_f(A, B) / p) ** 0.5


def compute_xyk_bid_a_fixed(A, B, p):
    return (compute_xyk_f(A, B) / p) ** 0.5 - A


def compute_xyk_bids(A, B, dp, half_spread, max_num_orders):
    return compute_bids(compute_xyk_p_m, compute_xyk_bid_a_fixed, A, B, dp, half_spread, max_num_orders)


def compute_xyk_asks(A, B, dp, half_spread, max_num_orders):
    return compute_asks(compute_xyk_p_m, compute_xyk_ask_a_fixed, A, B, dp, half_spread, max_num_orders)


plot(compute_xyk_bids,
     compute_xyk_asks,
     A=1,
     B=200,
     dp=1,
     half_spread=0.003, # 0.3%
     max_num_orders=30,
     filename="")
     # filename="1-xyk.png")

We obtain the following result:

Text
---------------------- Bids -----------------------
        p         a        da          b        db
0   200.0  0.000000  0.000000   0.000000  0.000000
1   199.4  0.001503  0.001503   0.299775  0.299775
2   198.4  0.004024  0.002521   0.799897  0.500122
3   197.4  0.006564  0.002540   1.301275  0.501378
4   196.4  0.009123  0.002559   1.803918  0.502643
5   195.4  0.011702  0.002579   2.307836  0.503918
6   194.4  0.014301  0.002599   2.813038  0.505202
7   193.4  0.016920  0.002619   3.319535  0.506497
8   192.4  0.019559  0.002639   3.827336  0.507801
9   191.4  0.022219  0.002660   4.336451  0.509115
10  190.4  0.024900  0.002681   4.846891  0.510440
...

Doing a comparative analysis again,

Using passive orders, the pool exchanges 4.846891 USDC for 0.024900 SOL,

For a swap, the pool exchanges 4.84443 USDC for 0.024900 SOL.

The pool still loses a tinier amount if it uses the passive order rather than a regular swap, but this is due to the incorrect application of the fee that is discussed in another submission.

However, if we were to calculate the K invariant, K = 1.024900 * 195.153109 = 200.012421, the K-invariant increases instead of decreasing, so at least LP providers are making money instead of losing like earlier.

Impact

K value decreases over time from passive orders, leading to loss of funds for LP providers.

PoC

No response

Mitigation

No response

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

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 passive order sizing formula uses the initial quote reserve divided by price instead of the square root of K divided by price, which incorrectly assumes the quote reserve stays constant as price moves.

Impact

The K invariant decreases over time from passive orders, leading to a loss of funds for LP providers.

What the attacker needed

None

The fix

The order size calculation should use the square root of K divided by price instead of the initial quote reserve divided by price.

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 an automated market maker (AMM), the product of the two token reserves (K) should stay the same or grow with each trade; if it shrinks, the pool is leaking value. Here, the code that places passive orders used a wrong formula, so traders got slightly better prices than they should, and the pool's K slowly dropped. That means people who provided liquidity lost a small amount of money over time.

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 0xc0ffEE

View all

27 more disclosed reports, best first.

More from Dango DEX

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.