Skip to content

Commit

Permalink
Balancer Stable Math: calculate_invariant_v2 (#368)
Browse files Browse the repository at this point in the history
There has been a change to the calculateInvariant method in Balancer's stable math. Previously they had a boolean indicator for rounding up or down on division and now they only support rounding up.

The Balancer team have assured us that this computation will always return the same results as the previous implementation of the contract (also confirmed by out unit tests still agreeing), and that the only difference is better convergence. This means we can simply adjust the implementation and use it for all stable pools going forward.
  • Loading branch information
bh2smith authored Jul 19, 2022
1 parent f801f37 commit 94239cc
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 88 deletions.
30 changes: 0 additions & 30 deletions crates/shared/src/sources/balancer_v2/swap/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,40 +41,10 @@ impl BalU256 for U256 {
}
}

pub fn rounded_div(numerator: U256, denominator: U256, round_up: bool) -> Result<U256, Error> {
if round_up {
numerator.bdiv_up(denominator)
} else {
numerator.bdiv_down(denominator)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn rounded_div_ok() {
assert_eq!(rounded_div(1.into(), 2.into(), true).unwrap(), 1.into());
assert_eq!(rounded_div(1.into(), 2.into(), false).unwrap(), 0.into());
}

#[test]
fn rounded_div_err() {
assert_eq!(
rounded_div(1.into(), 0.into(), true)
.unwrap_err()
.to_string(),
"BAL#004: ZeroDivision"
);
assert_eq!(
rounded_div(1.into(), 0.into(), false)
.unwrap_err()
.to_string(),
"BAL#004: ZeroDivision"
);
}

#[test]
fn bmul_tests() {
let zero = U256::zero();
Expand Down
93 changes: 35 additions & 58 deletions crates/shared/src/sources/balancer_v2/swap/stable_math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,16 @@
//! https://github.com/balancer-labs/balancer-v2-monorepo/blob/stable-deployment/pkg/pool-stable/contracts/StableMath.sol
use super::error::Error;
use crate::sources::balancer_v2::swap::{
fixed_point::Bfp,
math::{rounded_div, BalU256},
};
use crate::sources::balancer_v2::swap::{fixed_point::Bfp, math::BalU256};
use ethcontract::U256;
use lazy_static::lazy_static;

lazy_static! {
static ref AMP_PRECISION: U256 = U256::from(1000);
}

/// https://github.com/balancer-labs/balancer-v2-monorepo/blob/ad1442113b26ec22081c2047e2ec95355a7f12ba/pkg/pool-stable/contracts/StableMath.sol#L49-L105
fn calculate_invariant(
amplification_parameter: U256,
balances: &[Bfp],
round_up: bool,
) -> Result<U256, Error> {
/// https://github.com/balancer-labs/balancer-v2-monorepo/blob/9eb7e44a4e9ebbadfe3c6242a086118298cadc9f/pkg/pool-stable-phantom/contracts/StableMath.sol#L57-L119
fn calculate_invariant(amplification_parameter: U256, balances: &[Bfp]) -> Result<U256, Error> {
let mut sum = U256::zero();
let num_tokens_usize = balances.len();
for balance_i in balances.iter() {
Expand All @@ -36,50 +29,33 @@ fn calculate_invariant(
let amp_times_total = amplification_parameter.bmul(num_tokens)?;
for _ in 0..255 {
// If balances were empty, we would have returned on sum.is_zero()
let mut p_d = balances[0].as_uint256().bmul(num_tokens)?;
for balance in &balances[1..] {
// P_D = Math.div(Math.mul(Math.mul(P_D, balances[j]), numTokens), invariant, roundUp);
p_d = rounded_div(
p_d.bmul(balance.as_uint256())?.bmul(num_tokens)?,
invariant,
round_up,
)?
let mut d_p = invariant;
for balance in balances {
// (d_p * invariant) / (balance * numTokens)
d_p = d_p
.bmul(invariant)?
.bdiv_down(balance.as_uint256().bmul(num_tokens)?)?;
}
let prev_invariant = invariant;

invariant = rounded_div(
// invariant = Math.div(
// Math.mul(Math.mul(numTokens, invariant), invariant).add(
// Math.div(Math.mul(Math.mul(ampTimesTotal, sum), P_D), _AMP_PRECISION, roundUp)
// ),
num_tokens
.bmul(invariant)?
.bmul(invariant)?
.badd(rounded_div(
amp_times_total.bmul(sum)?.bmul(p_d)?,
*AMP_PRECISION,
round_up,
)?)?,
// Math.mul(numTokens + 1, invariant).add(
// // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1
// Math.div(Math.mul(ampTimesTotal - _AMP_PRECISION, P_D), _AMP_PRECISION, !roundUp)
// ),
(num_tokens.badd(1.into())?)
.bmul(invariant)?
.badd(rounded_div(
(amp_times_total.bsub(*AMP_PRECISION)?).bmul(p_d)?,
*AMP_PRECISION,
!round_up,
)?)?,
round_up,
)?;

// ((ampTimesTotal * sum) / AMP_PRECISION + D_P * numTokens) * invariant
let numerator = amp_times_total
.bmul(sum)?
.bdiv_down(*AMP_PRECISION)?
.badd(d_p.bmul(num_tokens)?)?
.bmul(invariant)?;
// ((ampTimesTotal - _AMP_PRECISION) * invariant) / _AMP_PRECISION + (numTokens + 1) * D_P
let denominator = amp_times_total
.bsub(*AMP_PRECISION)?
.bmul(invariant)?
.bdiv_down(*AMP_PRECISION)?
.badd(num_tokens.badd(1.into())?.bmul(d_p)?)?;
invariant = numerator.bdiv_down(denominator)?;
match convergence_criteria(invariant, prev_invariant) {
None => continue,
Some(invariant) => return Ok(invariant),
}
}

Err(Error::StableInvariantDidntConverge)
}

Expand All @@ -95,7 +71,7 @@ pub fn calc_out_given_in(
if token_index_out >= balances.len() || token_index_in >= balances.len() {
return Err(Error::InvalidToken);
}
let invariant = calculate_invariant(amplification_parameter, balances, true)?;
let invariant = calculate_invariant(amplification_parameter, balances)?;
balances[token_index_in] = balances[token_index_in].add(token_amount_in)?;

let final_balance_out = get_token_balance_given_invariant_and_all_other_balances(
Expand Down Expand Up @@ -127,7 +103,7 @@ pub fn calc_in_given_out(
if token_index_out >= balances.len() || token_index_in >= balances.len() {
return Err(Error::InvalidToken);
}
let invariant = calculate_invariant(amplification_parameter, balances, true)?;
let invariant = calculate_invariant(amplification_parameter, balances)?;
balances[token_index_out] = balances[token_index_out].sub(token_amount_out)?;

let final_balance_in = get_token_balance_given_invariant_and_all_other_balances(
Expand Down Expand Up @@ -356,32 +332,33 @@ mod tests {
let amp = 100.;
let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy());
let balances = vec![Bfp::from(10), Bfp::from(12)];
let result = calculate_invariant(amplification_parameter, &balances, true).unwrap();
let max_relative_error = 0.001;
let expected = calculate_analytic_invariant_two_tokens(
balances[0].to_f64_lossy(),
balances[1].to_f64_lossy(),
amp,
);
let max_relative_error = 0.001;
let result = calculate_invariant(amplification_parameter, &balances).unwrap();
assert!((result.to_f64_lossy() / 1e18 - expected)
.abs()
.le(&max_relative_error));
}

#[test]
fn invariant_two_tokens_err() {
fn invariant_converges_at_extreme_values() {
let amp = 5000.;
let balances: Vec<Bfp> = vec!["0.00001", "1200000", "300"]
.iter()
.map(|x| Bfp::from_str(x).unwrap())
.collect();
let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy());
assert_eq!(
calculate_invariant(amplification_parameter, balances.as_slice(), true)
.unwrap_err()
.to_string(),
"BAL#321: StableInvariantDidntConverge"
);
let result = calculate_invariant(amplification_parameter, balances.as_slice()).unwrap();
let float_balances = balances.iter().map(|x| x.to_f64_lossy()).collect();
let expected = calculate_invariant_approx(float_balances, amp);
let max_relative_error = 0.001;
assert!((result.to_f64_lossy() / 1e18 - expected)
.abs()
.le(&max_relative_error));
}

#[test]
Expand All @@ -390,9 +367,9 @@ mod tests {
let amplification_parameter = U256::from_f64_lossy(amp * AMP_PRECISION.to_f64_lossy());
let balances = vec![Bfp::from(10), Bfp::from(12), Bfp::from(14)];
let float_balances = balances.iter().map(|x| x.to_f64_lossy()).collect();
let result = calculate_invariant(amplification_parameter, &balances, true).unwrap();
let expected = calculate_invariant_approx(float_balances, amp);
let max_relative_error = 0.001;
let result = calculate_invariant(amplification_parameter, &balances).unwrap();
assert!((result.to_f64_lossy() / 1e18 - expected)
.abs()
.le(&max_relative_error));
Expand Down

0 comments on commit 94239cc

Please sign in to comment.