Amplifiers can’t be ramped allowing loss of funds from the pool
The Mantra DEX stableswap pools have a fixed amplification coefficient (A) that cannot be changed after pool creation, unlike Curve's implementation. This lack of ramping means the pool cannot adapt to changing market conditions, potentially allowing traders to exploit the pool during events like a stablecoin depeg and cause losses to liquidity providers.
Originally disclosed on Code4rena
Submitted by Bauchibred
The Mantra DEX stableswap implementation lacks the ability to modify the amplification coefficient (A) after pool creation, which is a critical feature present even in the original Curve implementation. While the focus was on reducing Newton-Raphson iterations from 256 to 32, the absence of amplifier ramping breaks the logic.
In Mantra’s implementation, the amplification factor is static:
/packages/amm/src/pool_manager.rs#L85-L94
pub enum PoolType {
StableSwap {
/// The amount of amplification to perform on the constant product part of the swap formula.
amp: u64,
},
ConstantProduct,
}
Once set during pool creation, there is no mechanism to modify this value. In contrast, Curve’s implementation includes comprehensive amplifier management, this can be seen here:
def ramp_A(_future_A: uint256, _future_time: uint256):
assert msg.sender == self.owner # dev: only owner
assert block.timestamp >= self.initial_A_time + MIN_RAMP_TIME
assert _future_time >= block.timestamp + MIN_RAMP_TIME # dev: insufficient time
initial_A: uint256 = self._A()
future_A_p: uint256 = _future_A * A_PRECISION
assert _future_A > 0 and _future_A < MAX_A
if future_A_p < initial_A:
assert future_A_p * MAX_A_CHANGE >= initial_A
else:
assert future_A_p <= initial_A * MAX_A_CHANGE
self.initial_A = initial_A
self.future_A = future_A_p
self.initial_A_time = block.timestamp
self.future_A_time = _future_time
Note that the Amplification Coefficient is a crucial feature for managing the pool’s behavior and adapting to changing market conditions.
Before going further we understand that the stableswap invariant is enforced by the equation: An∑xi + D = ADⁿ + (D^(n+1))/(n^n∏xi), this can be seen in compute_y_raw(), that gets called from compute_y().
Then, this directly translates to how we mint the amount of liquidity say when a user is making a stable swap deposit when providing liquidity:
/contracts/pool-manager/src/liquidity/commands.rs#L256-L267
pub fn provide_liquidity() {
// ..snip
//@audit below we route the call when providing the liquidity to the stableswap implementation
} else {
compute_lp_mint_amount_for_stableswap_deposit(
amp_factor,
// pool_assets hold the balances before the deposit was made
&pool_assets,
// add the deposit to the pool_assets to calculate the new balances
&add_coins(pool_assets.clone(), deposits.clone())?,
total_share,
)?
.ok_or(ContractError::StableLpMintError)?
}
// ..snip
}
/contracts/pool-manager/src/helpers.rs#L790-L812
pub fn compute_lp_mint_amount_for_stableswap_deposit(
amp_factor: &u64,
old_pool_assets: &[Coin],
new_pool_assets: &[Coin],
pool_lp_token_total_supply: Uint128,
) -> Result<Option<Uint128>, ContractError> {
// Initial invariant
let d_0 = compute_d(amp_factor, old_pool_assets).ok_or(ContractError::StableInvariantError)?;
// Invariant after change, i.e. after deposit
// notice that new_pool_assets already added the new deposits to the pool
let d_1 = compute_d(amp_factor, new_pool_assets).ok_or(ContractError::StableInvariantError)?;
// If the invariant didn't change, return None
if d_1 <= d_0 {
Ok(None)
} else {
let amount = Uint512::from(pool_lp_token_total_supply)
.checked_mul(d_1.checked_sub(d_0)?)?
.checked_div(d_0)?;
Ok(Some(Uint128::try_from(amount)?))
}
}
That’s to say essentially when we are trying to calculate the swap amount, see here:
pub fn compute_y_raw(
n_coins: u8,
amp_factor: &u64,
swap_in: Uint128,
//swap_out: Uint128,
no_swap: Uint128,
d: Uint512,
) -> Option<Uint512> {
let ann = amp_factor.checked_mul(n_coins.into())?; // A * n ** n
// sum' = prod' = x
// c = D ** (n + 1) / (n ** (2 * n) * prod' * A)
let mut c = d;
c = c
.checked_mul(d)
.unwrap()
.checked_div(swap_in.checked_mul(n_coins.into()).unwrap().into())
.unwrap();
c = c
.checked_mul(d)
.unwrap()
.checked_div(no_swap.checked_mul(n_coins.into()).unwrap().into())
.unwrap();
c = c
.checked_mul(d)
.unwrap()
.checked_div(ann.checked_mul(n_coins.into()).unwrap().into())
.unwrap();
// b = sum(swap_in, no_swap) + D // Ann - D
// not subtracting D here because that could result in a negative.
let b = d
.checked_div(ann.into())
.unwrap()
.checked_add(swap_in.into())
.unwrap()
.checked_add(no_swap.into())
.unwrap();
// Solve for y by approximating: y**2 + b*y = c
let mut y_prev: Uint512;
let mut y = d;
for _ in 0..1000 {
y_prev = y;
// y = (y * y + c) / (2 * y + b - d);
let y_numerator = y.checked_mul(y).unwrap().checked_add(c).unwrap();
let y_denominator = y
.checked_mul(Uint512::from(2u8))
.unwrap()
.checked_add(b)
.unwrap()
.checked_sub(d)
.unwrap();
y = y_numerator.checked_div(y_denominator).unwrap();
if y > y_prev {
if y.checked_sub(y_prev).unwrap() <= Uint512::one() {
break;
}
} else if y_prev.checked_sub(y).unwrap() <= Uint512::one() {
break;
}
}
Some(y)
}
To explain the bug case more, let’s examine how different A (Amplifier) values affect a 2-token stableswap pool with DAI and USDC (n=2):
Initial Balanced State:
- x₁ = 1000 DAI
- x₂ = 1000 USDC
- D = 2000 (invariant)
With Optimal A = 85:, concluding this as optimal considering this was also hinted in the original Curve implementation:
Left side: An∑xi + D
= 85 * 2 * (1000 + 1000) + 2000
= 85 * 2 * 2000 + 2000
= 340,000 + 2000
= 342,000
Right side: ADⁿ + (D^(n+1))/(n^n∏xi)
= 85 * 2000² + 2000³/(2² * 1000 * 1000)
= 340,000 + 2000
= 342,000
Price impact for 10% imbalance trade ≈ 0.3%
With Too High A = 1000:
Left side: An∑xi + D
= 1000 * 2 * (1000 + 1000) + 2000
= 1000 * 2 * 2000 + 2000
= 4,000,000 + 2000
= 4,002,000
Right side: ADⁿ + (D^(n+1))/(n^n∏xi)
= 1000 * 2000² + 2000³/(2² * 1000 * 1000)
= 4,000,000 + 2000
= 4,002,000
Price impact for 10% imbalance trade ≈ 0.025%
With Too Low A = 10:
Left side: An∑xi + D
= 10 * 2 * (1000 + 1000) + 2000
= 10 * 2 * 2000 + 2000
= 40,000 + 2000
= 42,000
Right side: ADⁿ + (D^(n+1))/(n^n∏xi)
= 10 * 2000² + 2000³/(2² * 1000 * 1000)
= 40,000 + 2000
= 42,000
Price impact for 10% imbalance ≈ 2.5%
This demonstrates how:
- Optimal A (85) balances stability with safety.
- Too high A (1000) makes the pool vulnerable to manipulation due to minimal price impact.
- Too low A (10) causes excessive slippage even for small trades.
Impact
As already slightly hinted under Proof of Concept, we can see how having a static amplification value causes lack of flexibility in managing the pool’s behavior, and would immensely affect the minting lps logic when we are providing liquidity to a stableswap pool, building up on the swap details already hinted:
Note that market conditions are not constant and deviate quite, which means we can’t have a constant “amp” for all condition of the pool for it’s lifetime, just like we can’t have say a constant “slippage” for all market conditions. Even at that, assume we end up with an amp value that works 80% of the time, the implementation is still broken for 20% of the time. And blackswan events unfortunately occur from time to time which would even cause the breach to be way higher.
To build up on the scenario already hinted at, we can see that in the case we have a very high amplifier (A) The curve is flatter, meaning the price wrongly remains relatively stable even with significant imbalances. Whereas this is desirable for stablecoins or pegged assets where maintaining a tight peg is paramount, we still have to take into account that a blackswan event could be occurring. As such, the price of one of the assets in the pool is heavily dropping due to some sort of freefall. We can’t just keep the price stable or enforce the equilibrium; otherwise, we then allow for anyone with the now “fall dropping” asset to come steal the other assets since the the prices are ~same; i.e., assume when Terra’s UST was on a free fall, with a very high Amp value, holders of Terra’s UST can come steal the other stablecoined assets in the pool, assume USDC for this report.
For example, during UST’s depeg:
- Pool state: 1M UST (
$0.95) and 1M USDC ($1.00). - With A=1000: A trader could still swap
~950kUST for~950kUSDC (only~0.025%price impact). - With proper ramping, A could be decreased to protect the pool, causing larger price impacts.
- Loss to pool:
~$47,500(5% of 950k) due to inability to adjust A.
Now with a low amplifier, the case is even exacerbated, considering the curve is even more curved, leading to even greater price fluctuations with even small imbalances. In this case, we just open up the window for malicious actors to front/back run trades and scoop up the asset that’s cheaper in price at the time.
Recommended Mitigation Steps
Implement amplifier ramping functionality similar to Curve:
pub enum ExecuteMsg {
RampAmplifier {
future_amp: u64,
future_time: u64,
},
StopRamp {},
}
And add safety constraints:
const MAX_A: u64 = 1_000_000; // 10^6
const MAX_A_CHANGE: u64 = 10;
const MIN_RAMP_TIME: u64 = 3600; // 1 hour
Looks reasonable but more of a missing feature than a bug.
jvr0x (MANTRA) confirmed and commented:
This is a valid point, and indeed a feature that’s missing in the contract. Need to think about it. The reason pools are immutable after creation is to prevent bad actors from creating a pool with favorable conditions/fees to attract liquidity to then change the parameters and manipulate things on their favor, effectively harming the LPs.
Not a high issue, potentially medium.
3docSec (judge) decreased severity to Medium and commented:
I agree Medium makes sense, because pools can
leak value with a hypothetical attack path with stated assumptions, but external requirementslike market conditions.
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 pool's amplification coefficient is set at creation and cannot be modified, missing the ramping mechanism that allows dynamic adjustment.
Impact
During a stablecoin depeg, a high fixed A could let a trader swap the depegged asset for others with minimal price impact, causing losses to the pool; the judge noted this requires specific market conditions.
What the attacker needed
Pool created with fixed A; market conditions like a depeg
The fix
Implement amplifier ramping functionality similar to Curve, with functions to ramp and stop ramping, and safety constraints.
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 a stableswap pool, the amplification coefficient (A) controls how closely the pool tries to keep prices of assets equal. If A is too high, the pool stays very stable even when one asset's real-world price drops, letting traders swap the falling asset for others at almost no loss. If A is too low, small trades cause big price swings. The bug is that this A value is fixed forever, so the pool can't adjust when markets change, which could let attackers drain value from liquidity providers.
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.