use std::{any::Any, collections::HashMap};
use alloy::primitives::{address, aliases::U24, Address, I128, I256, U256, U512};
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},
decode_paused, MontraPoolConfig, PAUSED_ATTRIBUTE, POOL_CONFIG_ATTRIBUTES,
};
use crate::evm::protocol::{
uniswap_v4::{
hooks::{
hook_handler::HookHandler,
models::{
AfterSwapDelta, AfterSwapParameters, BeforeSwapDelta, BeforeSwapOutput,
BeforeSwapParameters, HookSpotFees, SwapOutcome, SwapParams, WithGasEstimate,
},
},
state::UniswapV4State,
},
utils::{
solidity_math::{mul_div, truncate_to_u256},
uniswap::{
lp_fee::OVERRIDE_FEE_FLAG, tick_math::get_sqrt_ratio_at_tick, FEE_PIPS_DENOMINATOR,
},
},
};
pub const MONTRA_HOOK_ELYSIUM: Address = address!("6b1216a40b65c83e9c9e18a562c446697b8cf8ec");
pub(crate) const MONTRA_LP_LINE_HOLD_SECONDS_ELYSIUM: u64 = 600;
pub(crate) const MONTRA_BUY_BEFORE_SWAP_GAS: u64 = 22_491;
pub(crate) const MONTRA_BUY_AFTER_SWAP_GAS: u64 = 5_570;
pub(crate) const MONTRA_SELL_BEFORE_SWAP_GAS: u64 = 3_913;
pub(crate) const MONTRA_SELL_AFTER_SWAP_GAS: u64 = 24_818;
pub(crate) const MONTRA_HOOK_DISPATCH_GAS: u64 = 2_680;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MontraHookHandler {
address: Address,
config: MontraPoolConfig,
paused: bool,
block_timestamp: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct QuotingTerms {
buy_fee_pips: u32,
lp_fee_pips: Option<u32>,
}
impl MontraHookHandler {
pub fn new(
address: Address,
config: MontraPoolConfig,
paused: bool,
block_timestamp: u64,
) -> Self {
Self { address, config, paused, block_timestamp }
}
fn quoting_terms(&self) -> Result<QuotingTerms, SimulationError> {
Ok(QuotingTerms {
buy_fee_pips: self
.config
.buy_fee_pips(self.block_timestamp)?,
lp_fee_pips: self
.config
.lp_fee_in_force_pips(self.block_timestamp),
})
}
fn is_buy(&self, zero_for_one: bool) -> bool {
zero_for_one == self.config.quote_is_currency0()
}
fn fees(&self, zero_for_one: bool) -> Result<HookSpotFees, SimulationError> {
let terms = self.quoting_terms()?;
let rate = if self.is_buy(zero_for_one) {
terms.buy_fee_pips
} else {
self.config.total_fee_pips()
};
Ok(HookSpotFees {
lp_fee_override: terms.lp_fee_pips,
hook_fee_pips: rate.saturating_sub(terms.lp_fee_pips.unwrap_or(0)),
})
}
fn refuse(&self, reason: &str) -> SimulationError {
SimulationError::InvalidInput(format!("montra hook {}: {reason}", self.address), None)
}
fn split_output(
&self,
zero_for_one: bool,
gross_out: U256,
) -> Result<OutputSplit, SimulationError> {
let fee = if self.is_buy(zero_for_one) {
U256::ZERO
} else {
hook_fee(gross_out, self.fees(zero_for_one)?.hook_fee_pips)?
};
Ok(OutputSplit { hook_fee: fee, swapper_out: gross_out.saturating_sub(fee) })
}
}
struct OutputSplit {
hook_fee: U256,
swapper_out: U256,
}
fn hook_fee(amount: U256, fee_pips: u32) -> Result<U256, SimulationError> {
mul_div(amount, U256::from(fee_pips), U256::from(FEE_PIPS_DENOMINATOR)).map_err(|e| {
SimulationError::FatalError(format!(
"montra hook: the fee of {fee_pips} pips on {amount}: {e}"
))
})
}
fn kept_pips(fee_pips: u32) -> Result<u32, SimulationError> {
FEE_PIPS_DENOMINATOR
.checked_sub(fee_pips)
.filter(|kept| *kept > 0)
.ok_or_else(|| {
SimulationError::FatalError(format!(
"montra hook: a fee of {fee_pips} pips leaves nothing to swap"
))
})
}
pub(super) fn max_gross_buy(max_net: U256, hook_fee_pips: u32) -> Result<U256, SimulationError> {
let kept_pips = kept_pips(hook_fee_pips)?;
mul_div(max_net, U256::from(FEE_PIPS_DENOMINATOR), U256::from(kept_pips)).map_err(|e| {
SimulationError::FatalError(format!(
"montra hook: the gross buy for a net of {max_net} at {hook_fee_pips} pips: {e}"
))
})
}
fn swap_bound_sqrt_price(tick: i32, zero_for_one: bool) -> Result<U256, SimulationError> {
Ok(swap_bound(get_sqrt_ratio_at_tick(tick)?, zero_for_one))
}
pub(super) fn input_absorbed_at_price(
sqrt_price: U256,
liquidity: u128,
zero_for_one: bool,
fee_pips: u32,
) -> Result<U256, SimulationError> {
if liquidity == 0 {
return Ok(U256::ZERO);
}
let liquidity = U512::from(liquidity);
let max_unmoving: U512 = if zero_for_one {
let scaled_liquidity: U512 = liquidity << 96usize;
let sqrt_price = U512::from(sqrt_price);
let per_unit = (sqrt_price - U512::from(1)) * sqrt_price;
(scaled_liquidity - U512::from(1)) / per_unit
} else {
(liquidity - U512::from(1)) >> 96usize
};
let denominator = U512::from(FEE_PIPS_DENOMINATOR);
let kept = U512::from(kept_pips(fee_pips)?);
let absorbed: U512 = ((max_unmoving + U512::from(1)) * denominator - U512::from(1)) / kept;
truncate_to_u256(absorbed)
}
impl HookHandler for MontraHookHandler {
fn address(&self) -> Address {
self.address
}
fn apply_block(&mut self, block: &BlockContext) -> bool {
let before = self.quoting_terms();
self.block_timestamp = block.timestamp();
!matches!((before, self.quoting_terms()), (Ok(before), Ok(after)) if before == after)
}
fn swaps_enabled(&self) -> bool {
!self.paused
}
fn swaps_from_empty_range(&self) -> bool {
true
}
fn pool_manager_call_overhead(&self) -> u64 {
MONTRA_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 zero_for_one = params.swap_params.zero_for_one;
let fees = self.fees(zero_for_one)?;
if self.paused {
return Err(self.refuse("the pool is paused"));
}
let amount_in = exact_input(params.swap_params.amount_specified)
.map_err(|reason| self.refuse(reason))?;
let (fee, gas_estimate) = if self.is_buy(zero_for_one) {
(hook_fee(amount_in, fees.hook_fee_pips)?, MONTRA_BUY_BEFORE_SWAP_GAS)
} else {
(U256::ZERO, MONTRA_SELL_BEFORE_SWAP_GAS)
};
let amount_delta = BeforeSwapDelta(I256::from_raw(fee) << 128);
let fee_override = fees
.lp_fee_override
.map_or(U24::ZERO, |lp_fee_override| U24::from(lp_fee_override | OVERRIDE_FEE_FLAG));
Ok(WithGasEstimate {
gas_estimate,
result: BeforeSwapOutput {
amount_delta,
fee: fee_override,
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 zero_for_one = params.swap_params.zero_for_one;
let gross_out = if zero_for_one { params.delta.amount1() } else { params.delta.amount0() };
let split = self.split_output(zero_for_one, U256::from(gross_out.unsigned_abs()))?;
if split.swapper_out.is_zero() {
return Err(self.refuse("the swap's output is 0, which no minimum output accepts"));
}
let gas_estimate = if self.is_buy(zero_for_one) {
MONTRA_BUY_AFTER_SWAP_GAS
} else {
MONTRA_SELL_AFTER_SWAP_GAS
};
let fee = split.hook_fee;
let result = u128::try_from(fee)
.ok()
.and_then(|fee| I128::try_from(fee).ok())
.ok_or_else(|| {
SimulationError::FatalError(format!(
"montra hook {}: the fee {fee} is below the swap's int128 output, yet does \
not fit int128",
self.address
))
})?;
Ok(WithGasEstimate { gas_estimate, result })
}
fn check_swap_outcome(
&self,
zero_for_one: bool,
outcome: &SwapOutcome,
) -> Result<(), SimulationError> {
if outcome.amount_unfilled != U256::ZERO {
return Err(self.refuse(&format!(
"PartialFillRejected: the pool could not swap {} of the input",
outcome.amount_unfilled
)));
}
if self.is_buy(zero_for_one) {
return Ok(());
}
let opening = get_sqrt_ratio_at_tick(self.config.opening_tick())?;
let past_opening = if zero_for_one {
outcome.sqrt_price_x96 < opening
} else {
outcome.sqrt_price_x96 > opening
};
if past_opening {
return Err(self.refuse("PastOpening: the sell takes the price past the opening tick"));
}
Ok(())
}
fn fee(&self, _context: &UniswapV4State, params: SwapParams) -> Result<f64, SimulationError> {
let hook_fee_pips = self
.fees(params.zero_for_one)?
.hook_fee_pips;
Ok(f64::from(hook_fee_pips) / f64::from(FEE_PIPS_DENOMINATOR))
}
fn spot_fees(&self, zero_for_one: bool) -> Result<Option<HookSpotFees>, SimulationError> {
Ok(Some(self.fees(zero_for_one)?))
}
fn max_amount_in(
&self,
state: &UniswapV4State,
zero_for_one: bool,
) -> Result<Option<U256>, SimulationError> {
let fees = self.fees(zero_for_one)?;
let lp_fee_override = fees.lp_fee_override;
let bound_tick = if self.is_buy(zero_for_one) {
self.config.seed_extreme_tick()
} else {
self.config.opening_tick()
};
let target = swap_bound_sqrt_price(bound_tick, zero_for_one)?;
let walk = state.amount_in_to_price(zero_for_one, target, lp_fee_override)?;
if self
.split_output(zero_for_one, walk.amount_out)?
.swapper_out
.is_zero()
{
return Ok(Some(U256::ZERO));
}
let limit = if self.is_buy(zero_for_one) {
max_gross_buy(walk.amount_in, fees.hook_fee_pips)?
} else {
let swap_fee = state.swap_fee_pips(zero_for_one, lp_fee_override)?;
let absorbed = input_absorbed_at_price(target, walk.liquidity, zero_for_one, swap_fee)?;
walk.amount_in
.checked_add(absorbed)
.ok_or_else(|| {
SimulationError::FatalError(format!(
"montra hook {}: sell limit overflows",
self.address
))
})?
};
Ok(Some(limit.min(INT128_MAX)))
}
fn delta_transition(
&mut self,
delta: ProtocolStateDelta,
_tokens: &HashMap<Bytes, Token>,
_balances: &Balances,
) -> Result<(), TransitionError> {
if let Some(deleted) = POOL_CONFIG_ATTRIBUTES
.iter()
.find(|name| {
delta
.deleted_attributes
.contains(**name)
})
{
return Err(TransitionError::DecodeError(format!(
"montra hook {}: {deleted} was deleted, so the pool's terms are unknown",
self.address
)));
}
let config = self
.config
.with_updates(&delta.updated_attributes)
.map_err(|e| TransitionError::DecodeError(e.to_string()))?;
let paused = match delta
.updated_attributes
.get(PAUSED_ATTRIBUTE)
{
Some(value) => decode_paused(value),
None if delta
.deleted_attributes
.contains(PAUSED_ATTRIBUTE) =>
{
false
}
None => self.paused,
};
self.config = config;
self.paused = paused;
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)
}
}