Skip to content
Audit finding Intermediate

compute_offer_amount floors the offer_amount when simulating constant product reversed swaps, leading to unexpected results

The reverse simulation function floors the computed offer amount, so a trader who uses it to determine the input needed for an exact output will receive slightly less than requested. This can cause unexpected reverts for contracts relying on the simulation.

0xAlix2 Follow

Originally disclosed on Code4rena

Submitted by 0xAlix2

/contracts/pool-manager/src/helpers.rs#L355-L364

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 calls compute_offer_amount, which computes offer_amount but floors the result:

let cp: Uint256 = offer_asset_in_pool * ask_asset_in_pool;
let offer_amount: Uint256 = Uint256::one()
    .multiply_ratio(
        cp,
        ask_asset_in_pool.checked_sub(
            Decimal256::from_ratio(ask_amount, Uint256::one())
                .checked_mul(inv_one_minus_commission)?
                .to_uint_floor(),
        )?,
    )
    .checked_sub(offer_asset_in_pool)?;

The calculation here differs a bit from the calculation in compute_swap, this results in some dust differences. The main issue in the above is that it rounds the result down, which could result in underpayment, ultimately leading to unexpected results for traders and unexpected reverts to contracts built on top of this.

NB: It is better to pay some extra dust amount and get an expected amount out, rather than paying dust amount less and getting an amount less than expected.

Proof of Concept

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

#[test]
fn compute_offer_amount_floor() {
    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 user = suite.senders[1].clone();
    let pool_id = "o.uluna.uusd".to_string();

    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::percent(0),
                },
                swap_fee: Fee {
                    share: Decimal::percent(0),
                },
                burn_fee: Fee {
                    share: Decimal::percent(0),
                },
                extra_fees: vec![],
            },
            PoolType::ConstantProduct,
            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(99_900_099u128);
    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(
            &user,
            "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

Round the offer_amount up, to make sure that the user is receiving the expected amount:

  pub fn compute_offer_amount(
    offer_asset_in_pool: Uint128,
    ask_asset_in_pool: Uint128,
    ask_amount: Uint128,
    pool_fees: PoolFee,
  ) -> StdResult<OfferAmountComputation> {
    // ...

    let offer_amount: Uint256 = Uint256::one()
        .multiply_ratio(
            cp,
            ask_asset_in_pool.checked_sub(
                Decimal256::from_ratio(ask_amount, Uint256::one())
                    .checked_mul(inv_one_minus_commission)?
                    .to_uint_floor(),
-           )?,
+           )?.checked_sub(Uint256::one())?,
        )
        .checked_sub(offer_asset_in_pool)?;

    // ...
  }

jvr0x (MANTRA) acknowledged and commented:

Known issue. However, to convert from Decimal to Uint there’s a sacrifice to pay, you can either floor or round up. Rounding up, what you suggest with paying some more dust, could lead to the contract leaking value and eventually leak value from pools which should not happen.

3docSec (judge) decreased severity to Low and commented:

Marked low because the impact is limited to dust.

a_kalout (warden) commented:

@jvr0x - I agree that there’s a tradeoff here; however, we have 2 options:

  1. Round down, and return wrong results to the user. For example, I want X amount of T1 out, I simulate that swap by calling query_reverse_simulation, and I get an amount Y needed of T2. The catch is that swapping Y of T2 for T1 gives me X-Z, which could easily lead to unexpected reverts for swappers, but no dust left in the contract.
  2. Roundup, and have the needed amount of T2 as Y+Z (where Z is dust), in that case when I swap Y+Z of T2 in return for T1, I get exactly what I want of T1 X (and maybe some dust), but some dust could end up on the contract.

These are the only 2 options we have here with their tradeoffs, the protocol is going with the first, which I disagree with, as it has worse consequences than the second. I believe the second option is what should be followed in this case.

jvr0x (MANTRA) commented:

Ah, I had misinterpreted your point. Probably better to round up on the reverse simulation to be on the safe side, you are right.

3docSec (judge) increased severity to Medium and commented:

I’d stick with valid Medium here, because the use-case for the very reasonable “exact output” flow is off-by-one.


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 floors the offer amount instead of rounding up, causing a small shortfall.

Impact

Traders may receive slightly less than the exact amount they requested, potentially causing unexpected reverts in contracts that rely on the simulation; the impact is limited to dust.

What the attacker needed

A constant product pool with liquidity; ability to call query_reverse_simulation

The fix

The offer amount should be rounded up to ensure the user receives the expected amount, though the protocol initially chose to keep rounding down.

How it was found

  1. Create a pool and provide liquidity.
  2. Call query_reverse_simulation to compute the required input for a desired output.
  3. Perform a swap using the computed input amount.
  4. Observe that the actual output is less than the desired 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.

When you swap tokens, you often want to know how much you need to put in to get a specific amount out. The function that calculates this rounds down, so you end up putting in slightly too little and getting less than you asked for. This can break other programs that rely on getting the exact amount.

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

Same bug class and techniques, clearest first.