Skip to content
Business logic Audit finding Intermediate

query_reverse_simulation doesn’t account for extra fees when simulating stable reversed swaps

The reverse simulation query for stable swaps ignored extra fees, so it returned an offer amount that was too low. A trader using that amount would receive less than the desired output, potentially causing unexpected reverts in dependent contracts.

0xAlix2 Follow

Originally disclosed on Code4rena

Submitted by 0xAlix2

/contracts/pool-manager/src/queries.rs#L117-L120

Finding description and impact

Mantra only allows exact-in swaps; however, it provides a way for traders to compute a required amount to get an exact amount out. This could be done using query_reverse_simulation, from the code comments:

/// Queries a swap reverse simulation. Used to derive the number of source tokens returned for

/// the number of target tokens.

query_reverse_simulation considers all the variable factors that affect the amounts in and out, most importantly fees. However, the issue is that for stable swaps it doesn’t consider extra fees, it just account swap, protocol, and burn fees:

let before_fees = (Decimal256::one()
    .checked_sub(pool_fees.protocol_fee.to_decimal_256())?
    .checked_sub(pool_fees.swap_fee.to_decimal_256())?
    .checked_sub(pool_fees.burn_fee.to_decimal_256())?)
.inv()
.unwrap_or_else(Decimal256::one)
.checked_mul(Decimal256::decimal_with_precision(
    ask_asset.amount,
    ask_decimal,
)?)?;

This leads to a wrong offer_amount returned, leading to a wrong ask return_amount, ultimately leading to unexpected results for traders and unexpected reverts to contracts built on top of this.

Proof of Concept

Add the following test in contracts/pool-manager/src/tests/integration_tests.rs:

#[test]
fn stableswap_not_accouting_extra_fees() {
    let mut suite = TestingSuite::default_with_balances(
        vec![
            coin(100_000_000u128 * 10u128.pow(6), "uluna".to_string()),
            coin(100_000_000u128 * 10u128.pow(6), "uusd".to_string()),
            coin(10_000u128, "uom".to_string()),
        ],
        StargateMock::new("uom".to_string(), "8888".to_string()),
    );
    let creator = suite.creator();
    let pool_id = "o.uluna.uusd".to_string();
    let amp = 85;

    suite
        .instantiate_default()
        .add_one_epoch()
        .create_pool(
            &creator,
            vec!["uluna".to_string(), "uusd".to_string()],
            vec![6u8, 6u8],
            PoolFee {
                protocol_fee: Fee {
                    share: Decimal::zero(),
                },
                swap_fee: Fee {
                    share: Decimal::zero(),
                },
                burn_fee: Fee {
                    share: Decimal::zero(),
                },
                extra_fees: vec![Fee {
                    share: Decimal::percent(1),
                }],
            },
            PoolType::StableSwap { amp },
            Some("uluna.uusd".to_string()),
            vec![coin(1000, "uusd"), coin(8888, "uom")],
            |result| {
                result.unwrap();
            },
        )
        .provide_liquidity(
            &creator,
            pool_id.clone(),
            None,
            None,
            None,
            None,
            vec![
                Coin {
                    denom: "uluna".to_string(),
                    amount: Uint128::from(100_000u128 * 10u128.pow(6)),
                },
                Coin {
                    denom: "uusd".to_string(),
                    amount: Uint128::from(100_000u128 * 10u128.pow(6)),
                },
            ],
            |result| {
                result.unwrap();
            },
        );

    // Need uusd amount (amount out)
    let needed_uusd = Uint128::from(98_998_849u128);
    let offer_uluna = std::cell::RefCell::new(Uint128::zero());

    suite
        .query_reverse_simulation(
            pool_id.clone(),
            Coin {
                denom: "uusd".to_string(),
                amount: needed_uusd,
            },
            "uluna".to_string(),
            |result| {
                // Computed the amount of uluna (amount in)
                *offer_uluna.borrow_mut() = result.unwrap().offer_amount;
            },
        )
        // Swap using the computed amount in
        .swap(
            &creator,
            "uusd".to_string(),
            None,
            None,
            None,
            pool_id.clone(),
            vec![coin((*offer_uluna.borrow()).into(), "uluna".to_string())],
            |result| {
                for event in result.unwrap().events {
                    if event.ty == "wasm" {
                        for attribute in event.attributes {
                            match attribute.key.as_str() {
                                "return_amount" => {
                                    let return_amount = attribute.value.parse::<Uint128>().unwrap();
                                    // Amount out is less than what's needed
                                    assert!(return_amount < needed_uusd);
                                }
                                _ => {}
                            }
                        }
                    }
                }
            },
        );
}

Recommended mitigation steps

Make sure extra fees are accounted for in the before_fees calculation:

let before_fees = (Decimal256::one()
    .checked_sub(pool_fees.protocol_fee.to_decimal_256())?
    .checked_sub(pool_fees.swap_fee.to_decimal_256())?
    .checked_sub(pool_fees.burn_fee.to_decimal_256())?
    .checked_sub(pool_fees.extra_fees.iter().fold(
        Decimal256::zero(),
        |acc, fee| {
            acc.checked_add(fee.to_decimal_256())
                .unwrap_or(Decimal256::zero())
        },
    ))?)
.inv()
.unwrap_or_else(Decimal256::one)
.checked_mul(Decimal256::decimal_with_precision(
    ask_asset.amount,
    ask_decimal,
)?)?;

3docSec (judge) commented:

Looks valid, can be intended behavior though.

jvr0x (MANTRA) disputed and commented:

This is a valid issue; however, the extra fees were quickly added in one of the subsequent commits after the v1.0.0 tag was done.

This is how the current code on chain looks like:

 let mut extra_fees = Decimal256::zero();
            for extra_fee in pool_fees.extra_fees.iter() {
                extra_fees = extra_fees.checked_add(extra_fee.to_decimal_256())?;
            }

            let before_fees = (Decimal256::one()
                .checked_sub(pool_fees.protocol_fee.to_decimal_256())?
                .checked_sub(pool_fees.swap_fee.to_decimal_256())?
                .checked_sub(pool_fees.burn_fee.to_decimal_256())?)
            .checked_sub(extra_fees)?
            .inv()
            .unwrap_or_else(Decimal256::one)
            .checked_mul(Decimal256::decimal_with_precision(
                ask_asset.amount,
                ask_decimal,
            )?)?;

3docSec (judge) commented:

I consider this valid because we have to base on the commit where scope was frozen.


The original report as published on Code4rena, by 0xAlix2. 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 reverse simulation calculation for stable swaps omitted the extra fees from the fee deduction step.

Impact

Traders could receive less than the desired output when using the reverse simulation, and contracts relying on it may revert unexpectedly.

What the attacker needed

Stable swap pool with extra fees; use of reverse simulation

The fix

The code was fixed to include extra fees in the before_fees calculation.

How it was found

  1. Create a stable swap pool with an extra fee set.
  2. Provide liquidity to the pool.
  3. Call query_reverse_simulation to compute the required offer amount for a desired ask amount.
  4. Perform a swap using the computed offer amount.
  5. Observe that the actual return amount is less than the desired ask amount.

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 reverse simulation helps you find how much you need to put in to get a certain amount out. The bug meant that for stable swaps, the simulation forgot to include some extra fees, so it told you to put in too little. When you actually swapped, you got less than you wanted.

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

View all

39 more disclosed reports, best first.

More from MANTRA 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.