use alloy::primitives::{uint, U256};
use tycho_common::simulation::errors::SimulationError;
use super::{super::launchpad::INT128_MAX, Observation};
use crate::evm::protocol::utils::{
solidity_math::{mul_div, mul_div_rounding_up},
uniswap::{
sqrt_price_math::{get_amount0_delta, get_amount1_delta, Q96},
tick_math::get_sqrt_ratio_at_tick,
},
};
const CURVE_WIDTH_TICKS: i32 = 200_000;
const TICK_SPACING: i32 = 200;
const LAUNCH_SUPPLY: U256 = uint!(1_000_000_000_000_000_000_000_000_000_U256);
const EMA_STEP_SECONDS: u64 = 600;
const EMA_MAX_STEPS: u32 = 8;
const DECAY_SECONDS: u64 = 43_200;
const BAND_NUMERATOR: u64 = 500;
const BAND_DENOMINATOR: u64 = 20_000;
pub(super) const WINDOW_SECONDS: u64 = 600;
const Q32: U256 = uint!(4_294_967_296_U256);
pub(super) fn refuse(reason: impl Into<String>) -> SimulationError {
SimulationError::InvalidInput(format!("ascend hook: {}", reason.into()), None)
}
pub(super) fn mul_div_floor(a: U256, b: U256, denominator: U256) -> Result<U256, SimulationError> {
mul_div(a, b, denominator).map_err(|e| refuse(format!("{a} * {b} / {denominator}: {e}")))
}
pub(super) fn mul_div_ceil(a: U256, b: U256, denominator: U256) -> Result<U256, SimulationError> {
mul_div_rounding_up(a, b, denominator)
.map_err(|e| refuse(format!("{a} * {b} / {denominator} rounded up: {e}")))
}
pub(super) fn sub(a: U256, b: U256, what: &str) -> Result<U256, SimulationError> {
a.checked_sub(b)
.ok_or_else(|| refuse(format!("{what}: {a} - {b} underflows")))
}
pub(super) fn add(a: U256, b: U256, what: &str) -> Result<U256, SimulationError> {
a.checked_add(b)
.ok_or_else(|| refuse(format!("{what}: {a} + {b} overflows")))
}
fn sqrt_ratio_at(tick: i32) -> Result<U256, SimulationError> {
get_sqrt_ratio_at_tick(tick).map_err(|e| refuse(format!("the tick {tick}: {e}")))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Curve {
pub(super) token_is_currency0: bool,
pub(super) start_tick: i32,
pub(super) liquidity: u128,
pub(super) curve_end: U256,
pub(super) far_end: U256,
pub(super) start_side_bound: U256,
pub(super) clamp: (U256, U256),
}
impl Curve {
pub(super) fn try_new(
token_is_currency0: bool,
start_tick: i32,
) -> Result<Self, SimulationError> {
let (lower_tick, upper_tick) = if token_is_currency0 {
(start_tick, start_tick + CURVE_WIDTH_TICKS)
} else {
(-(start_tick + CURVE_WIDTH_TICKS), -start_tick)
};
let lower = sqrt_ratio_at(lower_tick)?;
let upper = sqrt_ratio_at(upper_tick)?;
let width = sub_invariant(upper, lower, "the position's width")?;
let liquidity = if token_is_currency0 {
let product = mul_div_floor(lower, upper, Q96)?;
mul_div_floor(LAUNCH_SUPPLY, product, width)?
} else {
mul_div_floor(LAUNCH_SUPPLY, Q96, width)?
};
let liquidity = u128::try_from(liquidity)
.ok()
.filter(|liquidity| *liquidity > 0)
.ok_or_else(|| {
refuse(format!(
"the launch liquidity {liquidity} of start tick {start_tick} is 0 or does not \
fit uint128"
))
})?;
let start_side_bound = sqrt_ratio_at(if token_is_currency0 {
start_tick - TICK_SPACING
} else {
-start_tick + TICK_SPACING
})?;
Ok(if token_is_currency0 {
Self {
token_is_currency0,
start_tick,
liquidity,
curve_end: lower,
far_end: upper,
start_side_bound,
clamp: (start_side_bound, upper),
}
} else {
Self {
token_is_currency0,
start_tick,
liquidity,
curve_end: upper,
far_end: lower,
start_side_bound,
clamp: (lower, start_side_bound),
}
})
}
}
pub(super) fn amount0_delta_down(
a: U256,
b: U256,
liquidity: u128,
) -> Result<U256, SimulationError> {
let (lower, upper) = if a > b { (b, a) } else { (a, b) };
if lower.is_zero() {
return Err(broken_invariant("a price of 0"));
}
let spread = sub_invariant(upper, lower, "the price spread")?;
Ok(mul_div_floor(U256::from(liquidity) << 96usize, spread, upper)? / lower)
}
fn band(x: U256) -> Result<U256, SimulationError> {
mul_div_floor(x, U256::from(BAND_NUMERATOR), U256::from(BAND_DENOMINATOR))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct PoolPrice {
pub(super) sqrt_price: U256,
pub(super) tick: i32,
}
pub(super) fn observe(
curve: &Curve,
observation: &Observation,
price: PoolPrice,
now: u64,
) -> Result<Observation, SimulationError> {
let PoolPrice { sqrt_price: spot, tick } = price;
if observation.is_ahead_of(now) {
return Err(refuse(format!(
"the block timestamp {now} is before the last observation {}",
observation.updated_at
)));
}
let dt = now - observation.updated_at;
if dt == 0 {
return Ok(*observation);
}
let old_ema = observation.ema;
let spot = spot.clamp(curve.clamp.0, curve.clamp.1);
let mut ema = old_ema;
let mut remaining = dt;
for _ in 0..EMA_MAX_STEPS {
if remaining == 0 {
break;
}
let step = remaining.min(EMA_STEP_SECONDS);
let distance = spot.abs_diff(ema);
let moved = mul_div_floor(distance, U256::from(step), U256::from(step + EMA_STEP_SECONDS))?;
ema = if spot > ema { ema + moved } else { ema - moved };
remaining -= step;
}
let decayed = mul_div_ceil(
U256::from(observation.discount),
U256::from(DECAY_SECONDS),
U256::from(dt) + U256::from(DECAY_SECONDS),
)?;
let kept = sub_invariant(Q32, decayed, "the decayed discount")?;
let anchored = if curve.token_is_currency0 {
mul_div_floor(kept, old_ema, ema)?
} else {
mul_div_floor(kept, ema, old_ema)?
};
let discount = Q32.saturating_sub(anchored);
let discount = u32::try_from(discount).map_err(|_overflow| {
refuse(format!("the re-anchored discount {discount} does not fit uint32"))
})?;
Ok(Observation { ema, updated_at: now, tick, discount })
}
pub(super) fn fill_price(curve: &Curve, ema: U256, discount: u32) -> Result<U256, SimulationError> {
let kept = Q32 - U256::from(discount);
if curve.token_is_currency0 {
Ok(mul_div_floor(ema, kept, Q32)?.max(curve.start_side_bound))
} else {
Ok(mul_div_ceil(ema, Q32, kept)?.min(curve.start_side_bound))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Fill {
pub(super) tokens_in: U256,
pub(super) quote_out: U256,
pub(super) discount: u32,
}
pub(super) struct FillRequest {
pub(super) spot: U256,
pub(super) fill_price: U256,
pub(super) ema: U256,
pub(super) amount_in: U256,
pub(super) inventory: U256,
pub(super) max_clip: U256,
pub(super) filled: U256,
}
fn end_price_and_quote(
curve: &Curve,
x0: U256,
tokens: U256,
) -> Result<(U256, U256), SimulationError> {
let liquidity = U256::from(curve.liquidity);
let scaled_liquidity = liquidity << 96usize;
if curve.token_is_currency0 {
let new_denominator = add(scaled_liquidity / x0, tokens, "the fill's price denominator")?;
let end_price = scaled_liquidity.div_ceil(new_denominator);
let quote = mul_div_floor(liquidity, sub(x0, end_price, "the fill's price move")?, Q96)?;
Ok((end_price, quote))
} else {
let end_price = add(x0, (tokens << 96usize) / liquidity, "the fill's end price")?;
let moved = sub(end_price, x0, "the fill's price move")?;
let quote = mul_div_floor(scaled_liquidity, moved, end_price)? / x0;
Ok((end_price, quote))
}
}
pub(super) fn broken_invariant(what: &str) -> SimulationError {
SimulationError::FatalError(format!("ascend hook: {what}"))
}
pub(super) fn sub_invariant(a: U256, b: U256, what: &str) -> Result<U256, SimulationError> {
a.checked_sub(b)
.ok_or_else(|| broken_invariant(&format!("{what}: {a} - {b} underflows")))
}
pub(super) fn tokens_for_capped_quote(
curve: &Curve,
x0: U256,
cap: U256,
) -> Result<U256, SimulationError> {
let liquidity = U256::from(curve.liquidity);
let scaled_liquidity = liquidity << 96usize;
if curve.token_is_currency0 {
let d_sqrt = (cap << 96usize) / liquidity;
let scaled = mul_div_floor(scaled_liquidity, d_sqrt, x0)?;
let remaining_price = sub_invariant(x0, d_sqrt, "the capped fill's price move")?;
if remaining_price.is_zero() {
return Err(broken_invariant("the capped fill reaches a price of 0"));
}
Ok(scaled / remaining_price)
} else {
let capped_inverse =
sub_invariant(scaled_liquidity.div_ceil(x0), cap, "the capped fill's inverse price")?;
if capped_inverse.is_zero() {
return Err(broken_invariant("the capped fill reaches an infinite price"));
}
let capped_price = scaled_liquidity / capped_inverse;
mul_div_floor(
liquidity,
sub_invariant(capped_price, x0, "the capped fill's price move")?,
Q96,
)
}
}
pub(super) fn size_fill(
curve: &Curve,
request: &FillRequest,
) -> Result<Option<Fill>, SimulationError> {
let FillRequest { spot, fill_price: x, ema, amount_in, inventory, max_clip, filled } = *request;
let liquidity = U256::from(curve.liquidity);
let tokens_is_0 = curve.token_is_currency0;
let past_curve_end = if tokens_is_0 { x <= curve.curve_end } else { x >= curve.curve_end };
if past_curve_end {
return Ok(None);
}
let ema_band = band(ema)?;
if spot < sub_invariant(ema, ema_band, "the band below the EMA")? ||
spot > add(ema, ema_band, "the band above the EMA")?
{
return Ok(None);
}
let (x0, to_fill_price, qmax) = if tokens_is_0 {
let t = if spot > x {
add(
get_amount0_delta(x, spot, curve.liquidity, true)?,
U256::ONE,
"the tokens to the fill price",
)?
} else {
U256::ZERO
};
let x0 = x.min(spot);
let qmax = mul_div_floor(liquidity, band(x0)?, Q96)?;
(x0, t, qmax)
} else {
let t = if x > spot {
add(
get_amount1_delta(spot, x, curve.liquidity, true)?,
U256::ONE,
"the tokens to the fill price",
)?
} else {
U256::ZERO
};
let x0 = x.max(spot);
let band_x0 = band(x0)?;
let x_high = add(x0, band_x0, "the band above the fill price")?;
let inner = mul_div_floor(liquidity << 96usize, band_x0, x_high)?;
(x0, t, inner / x0)
};
if amount_in <= to_fill_price {
return Ok(None);
}
let mut tokens_in = amount_in - to_fill_price;
let per_window = qmax.min(max_clip);
if filled >= per_window {
return Ok(None);
}
let cap = (per_window - filled)
.min(inventory)
.min(INT128_MAX);
if cap <= U256::ONE {
return Ok(None);
}
let cap = cap - U256::ONE;
let to_curve_end = if tokens_is_0 {
if x0 < curve.curve_end {
return Ok(None);
}
amount0_delta_down(curve.curve_end, x0, curve.liquidity)?
} else {
if x0 > curve.curve_end {
return Ok(None);
}
mul_div_floor(liquidity, curve.curve_end - x0, Q96)?
};
tokens_in = tokens_in.min(to_curve_end);
if tokens_in.is_zero() {
return Ok(None);
}
let (mut end_price, mut quote) = end_price_and_quote(curve, x0, tokens_in)?;
if quote > cap {
tokens_in = tokens_for_capped_quote(curve, x0, cap)?;
(end_price, quote) = end_price_and_quote(curve, x0, tokens_in)?;
}
if quote.is_zero() {
return Ok(None);
}
let ratio = if tokens_is_0 {
mul_div_floor(end_price, Q32, ema)?
} else {
mul_div_floor(ema, Q32, end_price)?
};
let discount = sub(Q32, ratio, "the new discount")?;
let discount = u32::try_from(discount).map_err(|_overflow| {
refuse(format!("the fill's discount {discount} does not fit uint32"))
})?;
Ok(Some(Fill { tokens_in, quote_out: add(quote, U256::ONE, "the fill's quote")?, discount }))
}