Skip to content
Business logic Audit finding Intermediate

Wrong simulation function used in reverse operation path

The reverse simulation function for multi-hop swaps incorrectly used forward simulation instead of reverse simulation, leading to incorrect price quotes for users trying to determine required input tokens for a desired output amount.

Rhaydden Follow with Tigerfrake

Originally disclosed on Code4rena

Submitted by Rhaydden, also found by Tigerfrake

reverse_simulate_swap_operations function incorrectly uses query_simulation instead of query_reverse_simulation when calculating multi-hop trades in reverse. As a result, users will get incorrect price calculations when they attempt to determine how many input tokens they need for a desired output amount.

In summary:

  1. Users receive incorrect price quotes for trades.
  2. The error compounds in multi-hop trades, causing issues.

Proof of Concept

/contracts/pool-manager/src/queries.rs#L275

The bug is in the reverse_simulate_swap_operations function:

pub fn reverse_simulate_swap_operations(
    deps: Deps,
    ask_amount: Uint128,
    operations: Vec<SwapOperation>,
) -> Result<SimulateSwapOperationsResponse, ContractError> {
    let operations_len = operations.len();
    if operations_len == 0 {
        return Err(ContractError::NoSwapOperationsProvided);
    }

    let mut amount = ask_amount;

    for operation in operations.into_iter().rev() {
        match operation {
            SwapOperation::MantraSwap {
                token_in_denom,
                token_out_denom,
                pool_identifier,
            } => {
>>>             let res = query_simulation(
                    deps,
                    coin(amount.u128(), token_out_denom),
                    token_in_denom,
                    pool_identifier,
                )?;
                amount = res.return_amount;
            }
        }
    }

    Ok(SimulateSwapOperationsResponse { amount })
}

According to the docs and the example given in it:

We have a QUERY:

{
  "reverse_simulation": {
    "ask_asset": {
      "denom": "uusdc",
      "amount": "990000"
    },
    "offer_asset_denom": "uom",
    "pool_identifier": "om-usdc-1"
  }
}

And a RESPONSE (ReverseSimulationResponse):

{
  "offer_amount": "1000000",
  "spread_amount": "5000",
  "swap_fee_amount": "3000",
  "protocol_fee_amount": "2000",
  "burn_fee_amount": "0",
  "extra_fees_amount": "0"
}

The doc also clearly states that offer_amount in the response is “The amount of the offer asset needed to get the ask amount.”

Now, let’s compare again with the implementation:

let res = query_simulation(  <--- This is WRONG! Its using forward simulation
    deps,
    coin(amount.u128(), token_out_denom),
    token_in_denom,
    pool_identifier,
)?;

The bug is clear because it’s using query_simulation instead of query_reverse_simulation.

Also consider a multi-hop trade A -> B -> C where a user wants 100 C tokens:

  1. The fn calculates how many B tokens you get for X C tokens (forward).
  2. Then calculates how many A tokens you get for Y B tokens (forward).
  3. This is incorrect for reverse price discovery.

It shoould actually be:

  1. Calculate how many B tokens you need to get 100 C tokens (reverse).
  2. Then calculate how many A tokens you need to get the required B tokens (reverse).

The contract already has a correct query_reverse_simulation function that handles proper price calculation for reverse operations, but it’s not being used.

Recommended mitigation steps

pub fn reverse_simulate_swap_operations(
    deps: Deps,
    ask_amount: Uint128,
    operations: Vec<SwapOperation>,
) -> Result<SimulateSwapOperationsResponse, ContractError> {
    let operations_len = operations.len();
    if operations_len == 0 {
        return Err(ContractError::NoSwapOperationsProvided);
    }

    let mut amount = ask_amount;

    for operation in operations.into_iter().rev() {
        match operation {
            SwapOperation::MantraSwap {
                token_in_denom,
                token_out_denom,
                pool_identifier,
            } => {
-                let res = query_simulation(
+                let res = query_reverse_simulation(
                    deps,
                    coin(amount.u128(), token_out_denom),
                    token_in_denom,

                    pool_identifier,
                )?;
-                amount = res.return_amount;
+                amount = res.offer_amount;
            }
        }
    }

    Ok(SimulateSwapOperationsResponse { amount })
}

jvr0x (MANTRA) disputed and commented:

This is something that was fixed in a subsequent commit after the v1.0.0 tag was created. The current (live) reverse query code is the following:

pub fn reverse_simulate_swap_operations(
    deps: Deps,
    ask_amount: Uint128,
    operations: Vec<SwapOperation>,
) -> Result<ReverseSimulateSwapOperationsResponse, ContractError> {
    let operations_len = operations.len();
    if operations_len == 0 {
        return Err(ContractError::NoSwapOperationsProvided);
    }

    let mut offer_in_needed = ask_amount;
    let mut spreads: Vec<Coin> = vec![];
    let mut swap_fees: Vec<Coin> = vec![];
    let mut protocol_fees: Vec<Coin> = vec![];
    let mut burn_fees: Vec<Coin> = vec![];
    let mut extra_fees: Vec<Coin> = vec![];

    for operation in operations.into_iter().rev() {
        match operation {
            SwapOperation::MantraSwap {
                token_in_denom,
                token_out_denom,
                pool_identifier,
            } => {
                let res = query_reverse_simulation(
                    deps,
                    coin(offer_in_needed.u128(), token_out_denom.clone()),
                    token_in_denom,
                    pool_identifier,
                )?;

                if res.spread_amount > Uint128::zero() {
                    spreads.push(coin(res.spread_amount.u128(), &token_out_denom));
                }
                if res.swap_fee_amount > Uint128::zero() {
                    swap_fees.push(coin(res.swap_fee_amount.u128(), &token_out_denom));
                }
                if res.protocol_fee_amount > Uint128::zero() {
                    protocol_fees.push(coin(res.protocol_fee_amount.u128(), &token_out_denom));
                }
                if res.burn_fee_amount > Uint128::zero() {
                    burn_fees.push(coin(res.burn_fee_amount.u128(), &token_out_denom));
                }
                if res.extra_fees_amount > Uint128::zero() {
                    extra_fees.push(coin(res.extra_fees_amount.u128(), &token_out_denom));
                }

                offer_in_needed = res.offer_amount;
            }
        }
    }

    spreads = aggregate_coins(spreads)?;
    swap_fees = aggregate_coins(swap_fees)?;
    protocol_fees = aggregate_coins(protocol_fees)?;
    burn_fees = aggregate_coins(burn_fees)?;
    extra_fees = aggregate_coins(extra_fees)?;

    Ok(ReverseSimulateSwapOperationsResponse {
        offer_amount: offer_in_needed,
        spreads,
        swap_fees,
        protocol_fees,
        burn_fees,
        extra_fees,
    })
}

3docSec (judge) commented:

For judging, we base on the commit frozen for the audit scope; so while it’s good to see the team found and fixed the issue independently, it wouldn’t be fair to wardens to not reward a valid finding.


The original report as published on Code4rena, by Rhaydden. 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 function called query_simulation (forward simulation) instead of query_reverse_simulation when computing the required input amount for a desired output.

What the attacker needed

None

The fix

The function should call query_reverse_simulation and use the offer_amount from its response instead of query_simulation and return_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 want to swap tokens, you might ask the system how many tokens you need to put in to get a certain amount out. This function is supposed to answer that, but it used the wrong calculation method, so the answer was wrong. That means users could get bad price estimates.

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 Rhaydden

View all

36 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.