use alloy::primitives::U256;
use tycho_common::simulation::errors::SimulationError;
use super::{
constants::{BASIS_POINT_MAX, REAL_ID_SHIFT, SCALE, SCALE_OFFSET},
fee::{get_fee_amount, get_fee_amount_from},
uint128x128::pow,
uint256x256::{
mul_shift_round_down, mul_shift_round_up, shift_div_round_down, shift_div_round_up,
},
};
pub fn get_base(bin_step: u16) -> U256 {
SCALE + (U256::from(bin_step) << SCALE_OFFSET) / U256::from(BASIS_POINT_MAX)
}
pub fn get_price_from_id(id: u32, bin_step: u16) -> Result<U256, SimulationError> {
let exponent =
i32::try_from(i64::from(id) - i64::from(REAL_ID_SHIFT)).map_err(|_wider_than_u24| {
SimulationError::InvalidInput(format!("bin id {id} exceeds u24"), None)
})?;
pow(get_base(bin_step), exponent)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BinAmounts {
pub amount_in_with_fee: u128,
pub amount_out: u128,
pub fee_amount: u128,
}
pub fn get_amounts_out(
bin_reserve_out: u128,
swap_fee_pips: u32,
price: U256,
swap_for_y: bool,
amount_in_left: u128,
) -> Result<BinAmounts, SimulationError> {
let drained = get_drain_amounts(bin_reserve_out, swap_fee_pips, price, swap_for_y)?
.ok_or_else(|| {
SimulationError::InvalidInput(
format!("max amount in for the bin at price {price} exceeds u128"),
None,
)
})?;
if amount_in_left >= drained.amount_in_with_fee {
return Ok(drained);
}
let fee_amount = get_fee_amount_from(amount_in_left, swap_fee_pips)?;
let net_amount_in = U256::from(amount_in_left - fee_amount);
let amount_out = if swap_for_y {
mul_shift_round_down(net_amount_in, price, SCALE_OFFSET)?
} else {
shift_div_round_down(net_amount_in, SCALE_OFFSET, price)?
};
let amount_out = to_u128(amount_out, "amount out")?;
Ok(BinAmounts {
amount_in_with_fee: amount_in_left,
amount_out: amount_out.min(bin_reserve_out),
fee_amount,
})
}
pub fn get_drain_amounts(
bin_reserve_out: u128,
swap_fee_pips: u32,
price: U256,
swap_for_y: bool,
) -> Result<Option<BinAmounts>, SimulationError> {
let reserve_out = U256::from(bin_reserve_out);
let max_amount_in = if swap_for_y {
shift_div_round_up(reserve_out, SCALE_OFFSET, price)?
} else {
mul_shift_round_up(reserve_out, price, SCALE_OFFSET)?
};
let Ok(max_amount_in) = u128::try_from(max_amount_in) else {
return Ok(None);
};
let fee_amount = get_fee_amount(max_amount_in, swap_fee_pips)?;
let Some(amount_in_with_fee) = max_amount_in.checked_add(fee_amount) else {
return Ok(None);
};
Ok(Some(BinAmounts { amount_in_with_fee, amount_out: bin_reserve_out, fee_amount }))
}
pub fn get_liquidity(x: u128, y: u128, price: U256) -> Result<U256, SimulationError> {
let mut liquidity = U256::ZERO;
if x > 0 {
liquidity = price
.checked_mul(U256::from(x))
.ok_or_else(|| {
SimulationError::InvalidInput(
format!("bin liquidity overflow: price {price} * x {x}"),
None,
)
})?;
}
if y > 0 {
let shifted_y = U256::from(y) << SCALE_OFFSET;
liquidity = liquidity
.checked_add(shifted_y)
.ok_or_else(|| {
SimulationError::InvalidInput(
format!("bin liquidity overflow: {liquidity} + y {y} << 128"),
None,
)
})?;
}
Ok(liquidity)
}
fn to_u128(value: U256, what: &str) -> Result<u128, SimulationError> {
u128::try_from(value).map_err(|_wider_than_u128| {
SimulationError::InvalidInput(format!("{what} exceeds u128: {value}"), None)
})
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::{super::uint128x128::pow, *};
use crate::evm::protocol::pancakeswap_infinity_bin::math::constants::SCALE;
#[test]
fn test_get_drain_amounts_is_none_past_u128() {
let price = get_price_from_id(REAL_ID_SHIFT + 7_000, 100).unwrap();
assert_eq!(get_drain_amounts(10u128.pow(18), 100, price, false).unwrap(), None);
}
#[test]
fn test_get_drain_amounts_propagates_bad_fee() {
assert!(get_drain_amounts(1_000, 1_000_000, SCALE, true).is_err());
}
#[rstest]
#[case::partial_swap_for_y(
1_000_000_000, 100, true, REAL_ID_SHIFT, 1_000_000,
BinAmounts { amount_in_with_fee: 1_000_000, amount_out: 999_900, fee_amount: 100 }
)]
#[case::drains_bin(
1_000_000_000, 100, true, REAL_ID_SHIFT, 10_000_000_000,
BinAmounts {
amount_in_with_fee: 1_000_100_011,
amount_out: 1_000_000_000,
fee_amount: 100_011,
}
)]
#[case::partial_one_for_zero(
1_000_000_000, 100, false, REAL_ID_SHIFT + 5, 1_000_000,
BinAmounts { amount_in_with_fee: 1_000_000, amount_out: 994_915, fee_amount: 100 }
)]
#[case::max_fee(
1_000_000_000, 100_000, true, REAL_ID_SHIFT, 1_000_000,
BinAmounts { amount_in_with_fee: 1_000_000, amount_out: 900_000, fee_amount: 100_000 }
)]
#[case::below_shift(
1_000_000_000, 100, true, REAL_ID_SHIFT - 8, 1_000_000,
BinAmounts { amount_in_with_fee: 1_000_000, amount_out: 991_936, fee_amount: 100 }
)]
fn test_get_amounts_out(
#[case] bin_reserve_out: u128,
#[case] swap_fee_pips: u32,
#[case] swap_for_y: bool,
#[case] active_id: u32,
#[case] amount_in_left: u128,
#[case] expected: BinAmounts,
) {
let price = get_price_from_id(active_id, 10).unwrap();
let amounts =
get_amounts_out(bin_reserve_out, swap_fee_pips, price, swap_for_y, amount_in_left)
.unwrap();
assert_eq!(amounts, expected);
}
#[test]
fn test_price_at_id_shift_is_one() {
assert_eq!(get_price_from_id(REAL_ID_SHIFT, 25).unwrap(), SCALE);
assert_eq!(pow(get_base(25), 0).unwrap(), SCALE);
}
#[test]
fn test_price_one_bin_above_shift_is_base() {
let base_25 = U256::from_str_radix("341133072838240809622033043950347631984", 10).unwrap();
let base_10 = U256::from_str_radix("340622649287859401926837982039199979667", 10).unwrap();
assert_eq!(get_base(25), base_25);
assert_eq!(get_price_from_id(REAL_ID_SHIFT + 1, 25).unwrap(), base_25);
assert_eq!(get_price_from_id(REAL_ID_SHIFT + 1, 10).unwrap(), base_10);
}
#[rstest]
#[case::step_10(10, "ffbe878b6170458ffbe878b617045900")]
#[case::step_25(25, "ff5c918e5d34fcced7c7d208f00a36e7")]
fn test_price_one_bin_below_shift(#[case] bin_step: u16, #[case] expected: &str) {
assert_eq!(
get_price_from_id(REAL_ID_SHIFT - 1, bin_step).unwrap(),
U256::from_str_radix(expected, 16).unwrap()
);
}
#[test]
fn test_pow_errors_outside_the_loop_range() {
assert!(
pow(get_base(10), 1 << 20).is_err(),
"exponents past the loop range underflow to zero on chain"
);
}
#[rstest]
#[case::step_1_far_above(REAL_ID_SHIFT + 880_000, 1,
"57896044618658097711785492504343953926634992332820282019728792003956564819967")]
#[case::step_1_far_below(REAL_ID_SHIFT - 880_000, 1, "2")]
fn test_price_at_far_ids(#[case] id: u32, #[case] bin_step: u16, #[case] expected: &str) {
assert_eq!(
get_price_from_id(id, bin_step).unwrap(),
U256::from_str_radix(expected, 10).unwrap()
);
}
#[rstest]
#[case::step_1_largest_exponent_above(REAL_ID_SHIFT + (1 << 20) - 1, 1)]
#[case::step_1_largest_exponent_below(REAL_ID_SHIFT - (1 << 20) + 1, 1)]
#[case::step_100_above(REAL_ID_SHIFT + 10_000, 100)]
#[case::step_100_below(REAL_ID_SHIFT - 10_000, 100)]
fn test_price_errors_where_pow_underflows(#[case] id: u32, #[case] bin_step: u16) {
assert!(
get_price_from_id(id, bin_step).is_err(),
"bin {id} at step {bin_step} reverts on chain"
);
}
#[rstest]
#[case::both_sides_at_price_one(7, 11, SCALE, "6125082604576892342340742933771827806208")]
#[case::x_only_at_base_price(
1_000_000,
0,
get_base(10),
"340622649287859401926837982039199979667000000"
)]
fn test_get_liquidity(
#[case] x: u128,
#[case] y: u128,
#[case] price: U256,
#[case] expected: &str,
) {
assert_eq!(
get_liquidity(x, y, price).unwrap(),
U256::from_str_radix(expected, 10).unwrap()
);
}
#[test]
fn test_liquidity_errors_on_overflow() {
assert!(
get_liquidity(2, 0, U256::MAX).is_err(),
"price * x overflowing must error, not wrap"
);
}
}