Stablepools return wrong price when they do not converge
The StableSwap pool's price calculation using Newton's method may not converge in unbalanced pools, returning a wrong price instead of reverting. An attacker could swap at this incorrect price, potentially profiting at the expense of the pool.
Submitted by DadeKuma
/contracts/pool-manager/src/helpers.rs#L751
Finding description and impact
A StableSwap pool calculates the price using Newton’s method to approximate the D value. This calculation might not converge in unbalanced pools, resulting in a wrong price, and in this case, it shouldn’t be possible to swap.
However, this scenario is not prevented as the transaction will not revert even when the function does not converge.
Proof of Concept
The computation of D converges when the result is either 1 or 0; otherwise, it diverges. In the latter case, the pool is considered nonfunctional, as the StableSwap math will not work as intended.
In case a pool diverges, it shouldn’t be possible to swap, but only to withdraw liquidity. This is implemented correctly in the original Curve implementation.
But in Mantra this is not the case, as the result is returned even if the computation did not converge:
pub fn compute_d(amp_factor: &u64, deposits: &[Coin]) -> Option<Uint512> {
let n_coins = Uint128::from(deposits.len() as u128);
// sum(x_i), a.k.a S
let sum_x = deposits
.iter()
.fold(Uint128::zero(), |acc, x| acc.checked_add(x.amount).unwrap());
if sum_x == Uint128::zero() {
Some(Uint512::zero())
} else {
// do as below but for a generic number of assets
let amount_times_coins: Vec<Uint128> = deposits
.iter()
.map(|coin| coin.amount.checked_mul(n_coins).unwrap())
.collect();
// Newton's method to approximate D
let mut d_prev: Uint512;
let mut d: Uint512 = sum_x.into();
for _ in 0..256 {
let mut d_prod = d;
for amount in amount_times_coins.clone().into_iter() {
d_prod = d_prod
.checked_mul(d)
.unwrap()
.checked_div(amount.into())
.unwrap();
}
d_prev = d;
d = compute_next_d(amp_factor, d, d_prod, sum_x, n_coins).unwrap();
// Equality with the precision of 1
if d > d_prev {
if d.checked_sub(d_prev).unwrap() <= Uint512::one() {
break;
}
} else if d_prev.checked_sub(d).unwrap() <= Uint512::one() {
break;
}
}
-> Some(d)
}
}
/contracts/pool-manager/src/helpers.rs#L751
Recommended mitigation steps
Consider the following fix:
d = compute_next_d(amp_factor, d, d_prod, sum_x, n_coins).unwrap();
// Equality with the precision of 1
if d > d_prev {
if d.checked_sub(d_prev).unwrap() <= Uint512::one() {
- break;
+ return Some(d);
}
} else if d_prev.checked_sub(d).unwrap() <= Uint512::one() {
- break;
+ return Some(d);
}
}
- Some(d)
+ Err(ContractError::ConvergeError)
Abdessamed (warden) commented:
In case a pool diverges, it shouldn’t be possible to swap, but only to withdraw liquidity.
This is incorrect, due to the StableSwap math, there is no straightforward algebraic formula to compute D and instead, Newton’s method is used to estimate the value. In case the pool is highly imbalanced and Newton’s method does not converge, the latest estimated value should be returned rather than reverting the transaction. The pool can easily be balanced again by adding balanced liquidity in subsequent transactions.
The StableSwap pool referenced by the warden is
Zapspool and it is a non-standard pool. You can see that in3poolwhich is one of the most used pools in Curve, theget_Ddoes NOT revert and instead returns the best-estimated value
If Newton’s method does not converge, it will return the wrong price; this is simply how an iterative algorithm works. You shared a specific pool implementation: a 3-token pool designed for DAI/USDC/USDT, as seen in this comment.
What I shared is a normal 2-token stable pool that requires this check, which is definitely standard. For example EURS/sEUR or the pool template from the same repository you have shared.
jvr0x (MANTRA) confirmed and commented:
DadeKuma - does it mean there has to be two cases for when the pool has 2 vs 3 assets?
@jvr0x - it’s not related to the number of assets but rather to the expected stability of the pool. For example, with DAI/USDC/USDT, it’s basically impossible for the algorithm to diverge, making this check unnecessary (unlike UST/DAI/USDC/USDT which also has this check).
However, since this function can be used with any asset in 2, 3, or 4-asset combinations, I recommend implementing this check in any case.
Seems reasonable.
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 compute_d function returns the last estimated value even when Newton's method fails to converge, instead of reverting or returning an error.
Impact
Swaps could occur at an incorrect price when the pool is unbalanced, potentially allowing an attacker to profit at the pool's expense.
What the attacker needed
Pool is highly unbalanced; swap transaction
The fix
The code should return an error when the computation does not converge, as suggested in the recommended mitigation.
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 StableSwap pool is a type of cryptocurrency exchange that uses a mathematical formula to keep prices stable. The formula uses an approximation method that sometimes fails to give an accurate result when the pool's assets are very unbalanced. The code returns this inaccurate result anyway, allowing trades at a wrong price.
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.