use std::{any::Any, collections::HashMap};
use alloy::primitives::{address, Address, I128, U256};
use tycho_common::{
dto::ProtocolStateDelta,
models::token::Token,
simulation::{
errors::{SimulationError, TransitionError},
protocol_sim::{Balances, BlockContext},
},
Bytes,
};
use super::{
super::launchpad::{exact_input, swap_bound, INT128_MAX},
math::{
add, fill_price, mul_div_ceil, mul_div_floor, observe, refuse, size_fill, sub_invariant,
Fill, FillRequest, PoolPrice, WINDOW_SECONDS,
},
AscendPoolState, Bid, Observation, POOL_ATTRIBUTES,
};
use crate::evm::protocol::{
uniswap_v4::{
hooks::{
hook_handler::HookHandler,
models::{
AfterSwapDelta, AfterSwapParameters, BalanceDelta, BeforeSwapDelta,
BeforeSwapOutput, BeforeSwapParameters, HookSpotFees, StateContext, SwapOutcome,
SwapParams, WithGasEstimate,
},
},
state::UniswapV4State,
},
utils::uniswap::FEE_PIPS_DENOMINATOR,
};
pub const ASCEND_HOOK_ELYSIUM: Address = address!("e0def4221b9840a610d4e7d55812a79a6431a8ec");
const ASCEND_BUY_BEFORE_SWAP_GAS: u64 = 50_203;
const ASCEND_BUY_AFTER_SWAP_GAS: u64 = 5_402;
const ASCEND_SELL_BEFORE_SWAP_GAS: u64 = 17_388;
const ASCEND_SELL_CONSIDERED_BEFORE_SWAP_GAS: u64 = 47_094;
const ASCEND_FILL_BEFORE_SWAP_GAS: u64 = 171_820;
const ASCEND_SELL_AFTER_SWAP_GAS: u64 = 20_319;
const ASCEND_FILL_AFTER_SWAP_GAS: u64 = 10_475;
const ASCEND_WHOLE_INPUT_FILL_AFTER_SWAP_GAS: u64 = 5_728;
const ASCEND_WHOLE_INPUT_ROUTE_GAS: u64 = 164_000;
const ASCEND_HOOK_DISPATCH_GAS: u64 = 1_689;
const ASCEND_BUY_SAME_SECOND_BEFORE_SWAP_GAS: u64 = 41_436;
const ASCEND_SELL_SAME_SECOND_BEFORE_SWAP_GAS: u64 = 8_995;
const ASCEND_SELL_CONSIDERED_SAME_SECOND_BEFORE_SWAP_GAS: u64 = 23_171;
const ASCEND_BUY_REPEAT_BEFORE_SWAP_GAS: u64 = 21_743;
const ASCEND_SELL_REPEAT_BEFORE_SWAP_GAS: u64 = 8_994;
const ASCEND_SELL_CONSIDERED_REPEAT_BEFORE_SWAP_GAS: u64 = 9_171;
const ASCEND_SELL_REPEAT_AFTER_SWAP_GAS: u64 = 10_660;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AscendHookHandler {
address: Address,
pub(super) state: AscendPoolState,
pub(super) block_timestamp: u64,
follows_swap_in_route: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Timing {
Elapsed,
SameSecond,
Repeat,
}
#[derive(Debug, Clone, Copy)]
enum SwapPath {
Buy,
SellNotConsidered,
SellDeclined,
SellFilled(Fill),
}
#[derive(Debug, Clone, Copy)]
struct SwapPlan {
path: SwapPath,
timing: Timing,
observation: Observation,
bid: Bid,
}
impl SwapPlan {
fn fill_tokens(&self) -> U256 {
match self.path {
SwapPath::SellFilled(fill) => fill.tokens_in,
SwapPath::Buy | SwapPath::SellNotConsidered | SwapPath::SellDeclined => U256::ZERO,
}
}
fn fills_whole_input(&self, amount_in: U256) -> bool {
matches!(self.path, SwapPath::SellFilled(fill) if fill.tokens_in == amount_in)
}
fn before_swap_gas(&self, amount_in: U256) -> u64 {
match (self.path, self.timing) {
(SwapPath::Buy, Timing::Elapsed) => ASCEND_BUY_BEFORE_SWAP_GAS,
(SwapPath::Buy, Timing::SameSecond) => ASCEND_BUY_SAME_SECOND_BEFORE_SWAP_GAS,
(SwapPath::Buy, Timing::Repeat) => ASCEND_BUY_REPEAT_BEFORE_SWAP_GAS,
(SwapPath::SellNotConsidered, Timing::Elapsed) => ASCEND_SELL_BEFORE_SWAP_GAS,
(SwapPath::SellNotConsidered, Timing::SameSecond) => {
ASCEND_SELL_SAME_SECOND_BEFORE_SWAP_GAS
}
(SwapPath::SellNotConsidered, Timing::Repeat) => ASCEND_SELL_REPEAT_BEFORE_SWAP_GAS,
(SwapPath::SellDeclined, Timing::Elapsed) => ASCEND_SELL_CONSIDERED_BEFORE_SWAP_GAS,
(SwapPath::SellDeclined, Timing::SameSecond) => {
ASCEND_SELL_CONSIDERED_SAME_SECOND_BEFORE_SWAP_GAS
}
(SwapPath::SellDeclined, Timing::Repeat) => {
ASCEND_SELL_CONSIDERED_REPEAT_BEFORE_SWAP_GAS
}
(SwapPath::SellFilled(_), _) if self.fills_whole_input(amount_in) => {
ASCEND_FILL_BEFORE_SWAP_GAS + ASCEND_WHOLE_INPUT_ROUTE_GAS
}
(SwapPath::SellFilled(_), _) => ASCEND_FILL_BEFORE_SWAP_GAS,
}
}
fn after_swap_gas(&self, amount_in: U256) -> u64 {
match (self.path, self.timing) {
(SwapPath::Buy, _) => ASCEND_BUY_AFTER_SWAP_GAS,
(SwapPath::SellNotConsidered | SwapPath::SellDeclined, Timing::Repeat) => {
ASCEND_SELL_REPEAT_AFTER_SWAP_GAS
}
(SwapPath::SellNotConsidered | SwapPath::SellDeclined, _) => ASCEND_SELL_AFTER_SWAP_GAS,
(SwapPath::SellFilled(_), _) if self.fills_whole_input(amount_in) => {
ASCEND_WHOLE_INPUT_FILL_AFTER_SWAP_GAS
}
(SwapPath::SellFilled(_), _) => ASCEND_FILL_AFTER_SWAP_GAS,
}
}
}
fn fill_net(fill: &Fill, fee_pips: u32) -> Result<U256, SimulationError> {
sub_invariant(fill.quote_out, fee_floor(fill.quote_out, fee_pips)?, "the fill's net")
}
pub(super) fn fee_floor(amount: U256, fee_pips: u32) -> Result<U256, SimulationError> {
mul_div_floor(amount, U256::from(fee_pips), U256::from(FEE_PIPS_DENOMINATOR))
}
pub(super) fn fee_ceil(amount: U256, fee_pips: u32) -> Result<U256, SimulationError> {
mul_div_ceil(amount, U256::from(fee_pips), U256::from(FEE_PIPS_DENOMINATOR))
}
fn to_i128(value: U256, what: &str) -> Result<I128, SimulationError> {
u128::try_from(value)
.ok()
.and_then(|v| I128::try_from(v).ok())
.ok_or_else(|| {
SimulationError::FatalError(format!("ascend hook: {what} {value} does not fit int128"))
})
}
pub(super) fn max_gross_buy(max_net: U256, fee_pips: u32) -> Result<U256, SimulationError> {
let kept = U256::from(FEE_PIPS_DENOMINATOR - fee_pips);
let bound = add(max_net, U256::from(1), "the buy limit")?
.checked_mul(U256::from(FEE_PIPS_DENOMINATOR))
.ok_or_else(|| refuse("the buy limit overflows"))?;
Ok((bound - U256::from(1)) / kept)
}
fn price_of(context: &StateContext) -> PoolPrice {
PoolPrice { sqrt_price: context.sqrt_price_x96, tick: context.tick }
}
impl AscendHookHandler {
pub fn new(address: Address, state: AscendPoolState, block_timestamp: u64) -> Self {
Self { address, state, block_timestamp, follows_swap_in_route: false }
}
fn timing(&self) -> Timing {
if self.follows_swap_in_route {
Timing::Repeat
} else if self.state.observation.updated_at == self.block_timestamp {
Timing::SameSecond
} else {
Timing::Elapsed
}
}
fn is_buy(&self, zero_for_one: bool) -> bool {
zero_for_one != self.state.token_is_currency0()
}
fn refuses_every_swap(&self) -> bool {
self.state
.observation
.is_ahead_of(self.block_timestamp)
}
fn plan_swap(
&self,
context: &StateContext,
swap_params: &SwapParams,
) -> Result<(U256, SwapPlan), SimulationError> {
let amount_in = exact_input(swap_params.amount_specified).map_err(refuse)?;
let plan = self.plan(price_of(context), swap_params.zero_for_one, amount_in)?;
Ok((amount_in, plan))
}
fn plan(
&self,
price: PoolPrice,
zero_for_one: bool,
amount_in: U256,
) -> Result<SwapPlan, SimulationError> {
let curve = &self.state.curve;
let now = self.block_timestamp;
let PoolPrice { sqrt_price: spot, tick } = price;
let mut observation = observe(curve, &self.state.observation, price, now)?;
let is_buy = self.is_buy(zero_for_one);
let mut bid = self.state.bid;
let path = if is_buy {
SwapPath::Buy
} else if bid.inventory.is_zero() || observation.tick != tick {
SwapPath::SellNotConsidered
} else {
let window_reset = bid
.window_start
.saturating_add(WINDOW_SECONDS) <=
now;
let filled = if window_reset { U256::ZERO } else { bid.filled };
let x = fill_price(curve, observation.ema, observation.discount)?;
let fill = size_fill(
curve,
&FillRequest {
spot,
fill_price: x,
ema: observation.ema,
amount_in,
inventory: bid.inventory,
max_clip: U256::from(bid.max_clip),
filled,
},
)?;
match fill {
Some(fill) => {
observation.discount = fill.discount;
bid.inventory =
sub_invariant(bid.inventory, fill.quote_out, "the bid inventory")?;
bid.filled = add(filled, fill.quote_out, "the bid's filled amount")?;
if window_reset {
bid.window_start = now;
}
SwapPath::SellFilled(fill)
}
None => SwapPath::SellDeclined,
}
};
Ok(SwapPlan { path, timing: self.timing(), observation, bid })
}
fn settle_output(
&self,
plan: &SwapPlan,
amm_out: U256,
) -> Result<SettledOutput, SimulationError> {
let fee_pips = self.state.fee_pips;
let filled_net = match plan.path {
SwapPath::Buy => {
return Ok(SettledOutput { fee: U256::ZERO, swapper_output: amm_out });
}
SwapPath::SellFilled(fill) => fill_net(&fill, fee_pips)?,
SwapPath::SellNotConsidered | SwapPath::SellDeclined => U256::ZERO,
};
let fee = fee_ceil(amm_out, fee_pips)?;
let amm_net = sub_invariant(amm_out, fee, "the pool's output net of the fee")?;
let swapper_output = add(filled_net, amm_net, "the swapper's output")?;
Ok(SettledOutput { fee, swapper_output })
}
}
#[derive(Debug, Clone, Copy)]
struct SettledOutput {
fee: U256,
swapper_output: U256,
}
impl HookHandler for AscendHookHandler {
fn address(&self) -> Address {
self.address
}
fn apply_block(&mut self, block: &BlockContext) -> bool {
self.follows_swap_in_route = false;
let moved = self.block_timestamp != block.timestamp();
let was_refusing = self.refuses_every_swap();
self.block_timestamp = block.timestamp();
let amounts_depend_on_time = !self.state.bid.inventory.is_zero();
let refusal_changed = was_refusing != self.refuses_every_swap();
moved && (amounts_depend_on_time || refusal_changed)
}
fn swaps_from_empty_range(&self) -> bool {
true
}
fn pool_manager_call_overhead(&self) -> u64 {
if self.follows_swap_in_route {
0
} else {
ASCEND_HOOK_DISPATCH_GAS
}
}
fn before_swap(
&self,
params: BeforeSwapParameters,
_overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
_transient_storage: Option<HashMap<Address, HashMap<U256, U256>>>,
) -> Result<WithGasEstimate<BeforeSwapOutput>, SimulationError> {
let (amount_in, plan) = self.plan_swap(¶ms.context, ¶ms.swap_params)?;
let delta = match plan.path {
SwapPath::Buy => {
let fee = fee_ceil(amount_in, self.state.fee_pips)?;
BalanceDelta::new(to_i128(fee, "the buy's fee")?, I128::ZERO)
}
SwapPath::SellFilled(fill) => {
let net = fill_net(&fill, self.state.fee_pips)?;
BalanceDelta::new(
to_i128(fill.tokens_in, "the fill's tokens")?,
-to_i128(net, "the fill's net quote")?,
)
}
SwapPath::SellNotConsidered | SwapPath::SellDeclined => {
BalanceDelta::new(I128::ZERO, I128::ZERO)
}
};
Ok(WithGasEstimate {
gas_estimate: plan.before_swap_gas(amount_in),
result: BeforeSwapOutput {
amount_delta: BeforeSwapDelta(delta.as_i256()),
fee: Default::default(),
overwrites: HashMap::new(),
transient_storage: HashMap::new(),
},
})
}
fn after_swap(
&self,
params: AfterSwapParameters,
_overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
_transient_storage_params: Option<HashMap<Address, HashMap<U256, U256>>>,
) -> Result<WithGasEstimate<AfterSwapDelta>, SimulationError> {
let (amount_in, plan) = self.plan_swap(¶ms.context, ¶ms.swap_params)?;
let amm_out = U256::from(
if params.swap_params.zero_for_one {
params.delta.amount1()
} else {
params.delta.amount0()
}
.unsigned_abs(),
);
let settled = self.settle_output(&plan, amm_out)?;
if settled.swapper_output.is_zero() {
return Err(refuse("the swap's output is 0, which no minimum output accepts"));
}
Ok(WithGasEstimate {
gas_estimate: plan.after_swap_gas(amount_in),
result: to_i128(settled.fee, "the sell's fee")?,
})
}
fn check_swap_outcome(
&self,
_zero_for_one: bool,
outcome: &SwapOutcome,
) -> Result<(), SimulationError> {
if outcome.amount_unfilled != U256::ZERO {
return Err(refuse(format!(
"the pool could not swap {} of the input, and unlock reverts CurrencyNotSettled \
on the credit",
outcome.amount_unfilled
)));
}
Ok(())
}
fn fee(&self, _context: &UniswapV4State, _params: SwapParams) -> Result<f64, SimulationError> {
Ok(f64::from(self.state.fee_pips) / f64::from(FEE_PIPS_DENOMINATOR))
}
fn spot_fees(&self, _zero_for_one: bool) -> Result<Option<HookSpotFees>, SimulationError> {
if self.refuses_every_swap() {
return Err(refuse(format!(
"the block timestamp {} is before the last observation {}",
self.block_timestamp, self.state.observation.updated_at
)));
}
Ok(Some(HookSpotFees { lp_fee_override: None, hook_fee_pips: self.state.fee_pips }))
}
fn max_amount_in(
&self,
state: &UniswapV4State,
zero_for_one: bool,
) -> Result<Option<U256>, SimulationError> {
let curve = &self.state.curve;
let (sqrt_price, tick) = state.price_and_tick();
let price = PoolPrice { sqrt_price, tick };
if self.is_buy(zero_for_one) {
observe(curve, &self.state.observation, price, self.block_timestamp)?;
let target = swap_bound(curve.far_end, zero_for_one);
let walk = state.amount_in_to_price(zero_for_one, target, None)?;
if walk.amount_in.is_zero() || walk.amount_out.is_zero() {
return Ok(Some(U256::ZERO));
}
return Ok(Some(max_gross_buy(walk.amount_in, self.state.fee_pips)?.min(INT128_MAX)));
}
let target = swap_bound(curve.curve_end, zero_for_one);
let walk = state.amount_in_to_price(zero_for_one, target, None)?;
let saturated = self
.plan(price, zero_for_one, INT128_MAX)?
.fill_tokens();
let mut limit = add(walk.amount_in, saturated, "the sell limit")?.min(INT128_MAX);
let mut plan = self.plan(price, zero_for_one, limit)?;
if plan.fill_tokens() != saturated {
limit = walk.amount_in.min(INT128_MAX);
plan = self.plan(price, zero_for_one, limit)?;
}
if limit.is_zero() ||
self.settle_output(&plan, walk.amount_out)?
.swapper_output
.is_zero()
{
return Ok(Some(U256::ZERO));
}
Ok(Some(limit))
}
fn handler_after_swap(
&self,
context: &StateContext,
swap_params: &SwapParams,
) -> Result<Option<Box<dyn HookHandler>>, SimulationError> {
let (_, plan) = self.plan_swap(context, swap_params)?;
let mut next = self.clone();
next.state.observation = plan.observation;
next.state.bid = plan.bid;
next.follows_swap_in_route = true;
Ok(Some(Box::new(next)))
}
fn delta_transition(
&mut self,
delta: ProtocolStateDelta,
_tokens: &HashMap<Bytes, Token>,
_balances: &Balances,
) -> Result<(), TransitionError> {
if let Some(deleted) = POOL_ATTRIBUTES.iter().find(|name| {
delta
.deleted_attributes
.contains(**name)
}) {
return Err(TransitionError::DecodeError(format!(
"ascend hook {}: {deleted} was deleted, so the pool's terms are unknown",
self.address
)));
}
self.state = self
.state
.with_updates(&delta.updated_attributes)
.map_err(|e| TransitionError::DecodeError(e.to_string()))?;
self.follows_swap_in_route = false;
Ok(())
}
fn clone_box(&self) -> Box<dyn HookHandler> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn is_equal(&self, other: &dyn HookHandler) -> bool {
other.as_any().downcast_ref::<Self>() == Some(self)
}
}