Skip to main content

tycho_simulation/evm/protocol/aero_basic/
state.rs

1use std::{any::Any, collections::HashMap};
2
3use alloy::primitives::{address, Address, U256};
4use num_bigint::BigUint;
5use serde::{Deserialize, Serialize};
6use tycho_common::{
7    dto::ProtocolStateDelta,
8    models::token::Token,
9    simulation::{
10        errors::{SimulationError, TransitionError},
11        protocol_sim::{Balances, GetAmountOutResult, PoolSwap, ProtocolSim, QueryPoolSwapParams},
12    },
13    Bytes,
14};
15
16use crate::evm::{
17    protocol::{
18        aerodrome_v1::{
19            solidly_stable::{StableMath, StablePool},
20            state::volatile_get_amount_out,
21        },
22        cpmm::protocol::{cpmm_fee, cpmm_get_limits, cpmm_spot_price},
23        safe_math::{safe_add_u256, safe_div_u256, safe_mul_u256, safe_sub_u256},
24        u256_num::{biguint_to_u256, u256_to_biguint, u256_to_f64},
25        utils::add_fee_markup,
26    },
27    query_pool_swap::query_pool_swap,
28};
29
30const FEE_PRECISION_BPS: u32 = 10_000;
31/// `CustomFeeModule` stores 420 to mean "this pool trades at 0 bps".
32const ZERO_FEE_INDICATOR_BPS: u32 = 420;
33/// The factory ignores fee-module results above this and falls back to its default fee.
34const MAX_BASE_FEE_BPS: u32 = 1_000;
35/// The `CustomFeeModule` deployments AERO basic factories use; identical on every chain.
36const VOLATILE_CUSTOM_FEE_MODULE: Address = address!("7949DE8d67E4F6b8509Bdbb43FF0503aF1247a7A");
37const STABLE_CUSTOM_FEE_MODULE: Address = address!("0195fC76Da986D66B2A468133a1be41E90893Da6");
38/// Gas of `pool.swap`, from `eth_simulateV1` of a cold WETH/USDC swap on Base (231_751 including
39/// the 21_000 intrinsic cost). The swap only checks the invariant, so stable pools cost the same.
40const SWAP_GAS: u32 = 210_000;
41
42/// State of an AERO v1.1 basic pool: a Solidly volatile (`x * y = k`) or stable
43/// (`x^3 * y + y^3 * x = k`) pool whose fee comes from its factory's fee module.
44///
45/// Quotes assume the swap pays no MEV tax: the factory's MEV tax module only charges transactions
46/// whose priority fee exceeds its threshold, which depends on the executing transaction.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub struct AeroBasicState {
49    reserve0: U256,
50    reserve1: U256,
51    stable: bool,
52    /// Raw `CustomFeeModule.customFee(pool)` in bps: 0 means unset, 420 means zero fee.
53    custom_fee: u32,
54    /// The factory's `defaultFee` in bps.
55    default_fee: u32,
56    /// The factory's fee module; fees are only modelled for the known `CustomFeeModule`s.
57    fee_module: Bytes,
58    paused: bool,
59    decimals0: u8,
60    decimals1: u8,
61}
62
63/// Inputs of [`AeroBasicState::new`] that come from the pool's factory.
64#[derive(Clone, Debug, PartialEq, Eq)]
65pub struct AeroBasicFees {
66    pub custom_fee: u32,
67    pub default_fee: u32,
68    pub fee_module: Bytes,
69    pub paused: bool,
70}
71
72impl AeroBasicState {
73    pub fn new(
74        reserves: (U256, U256),
75        stable: bool,
76        fees: AeroBasicFees,
77        decimals: (u8, u8),
78    ) -> Result<Self, String> {
79        let state = Self {
80            reserve0: reserves.0,
81            reserve1: reserves.1,
82            stable,
83            custom_fee: fees.custom_fee,
84            default_fee: fees.default_fee,
85            fee_module: fees.fee_module,
86            paused: fees.paused,
87            decimals0: decimals.0,
88            decimals1: decimals.1,
89        };
90        state.validate()?;
91        Ok(state)
92    }
93
94    fn validate(&self) -> Result<(), String> {
95        if self.default_fee >= FEE_PRECISION_BPS {
96            return Err(format!(
97                "default fee {} bps must be below {FEE_PRECISION_BPS}",
98                self.default_fee
99            ));
100        }
101        Ok(())
102    }
103
104    fn supported_fee_module(&self) -> Address {
105        if self.stable {
106            STABLE_CUSTOM_FEE_MODULE
107        } else {
108            VOLATILE_CUSTOM_FEE_MODULE
109        }
110    }
111
112    /// The swap fee in bps, as the factory's `getBaseFee`. Errors when the pool cannot be quoted:
113    /// the factory is paused or uses a fee module whose fees are not modelled.
114    fn fee_bps(&self) -> Result<u32, SimulationError> {
115        if self.paused {
116            return Err(SimulationError::RecoverableError("Pool factory is paused".to_string()));
117        }
118        if self
119            .fee_module
120            .iter()
121            .all(|byte| *byte == 0)
122        {
123            return Ok(self.default_fee);
124        }
125        if self.fee_module.as_ref() != self.supported_fee_module().as_slice() {
126            return Err(SimulationError::FatalError(format!(
127                "Unsupported AERO fee module {}",
128                self.fee_module
129            )));
130        }
131        // `CustomFeeModule.getFee` reverts for an unset fee; the factory then uses its default,
132        // as it does for any result above the maximum base fee.
133        Ok(match self.custom_fee {
134            ZERO_FEE_INDICATOR_BPS => 0,
135            0 => self.default_fee,
136            fee if fee > MAX_BASE_FEE_BPS => self.default_fee,
137            fee => fee,
138        })
139    }
140
141    fn stable_pool(&self) -> StablePool {
142        StablePool {
143            reserve0: self.reserve0,
144            reserve1: self.reserve1,
145            decimals0: self.decimals0,
146            decimals1: self.decimals1,
147            math: StableMath::FullPrecision,
148        }
149    }
150
151    /// Marginal price of token1 in token0 on the stable curve, in whole-token units:
152    /// `dy/dx = (3x²y + y³) / (x³ + 3xy²)`.
153    fn stable_spot_price(&self, zero2one: bool) -> Result<f64, SimulationError> {
154        let x = u256_to_f64(self.reserve0)? / 10f64.powi(self.decimals0 as i32);
155        let y = u256_to_f64(self.reserve1)? / 10f64.powi(self.decimals1 as i32);
156        if x == 0.0 || y == 0.0 {
157            return Err(SimulationError::RecoverableError("No liquidity".to_string()));
158        }
159        let quote_per_base = (3.0 * x * x * y + y * y * y) / (x * x * x + 3.0 * x * y * y);
160        Ok(if zero2one { quote_per_base } else { 1.0 / quote_per_base })
161    }
162}
163
164#[typetag::serde]
165impl ProtocolSim for AeroBasicState {
166    fn fee(&self) -> f64 {
167        cpmm_fee(
168            self.fee_bps()
169                .unwrap_or(self.default_fee),
170        )
171    }
172
173    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
174        let fee = cpmm_fee(self.fee_bps()?);
175        let price = if self.stable {
176            self.stable_spot_price(base.address < quote.address)?
177        } else {
178            cpmm_spot_price(base, quote, self.reserve0, self.reserve1)?
179        };
180        Ok(add_fee_markup(price, fee))
181    }
182
183    fn get_amount_out(
184        &self,
185        amount_in: BigUint,
186        token_in: &Token,
187        token_out: &Token,
188    ) -> Result<GetAmountOutResult, SimulationError> {
189        let fee_bps = self.fee_bps()?;
190        let amount_in = biguint_to_u256(&amount_in);
191        let zero2one = token_in.address < token_out.address;
192        let (reserve_in, reserve_out) =
193            if zero2one { (self.reserve0, self.reserve1) } else { (self.reserve1, self.reserve0) };
194
195        let amount_out = if self.stable {
196            self.stable_pool()
197                .get_amount_out(amount_in, zero2one, fee_bps)?
198        } else {
199            volatile_get_amount_out(amount_in, reserve_in, reserve_out, fee_bps)?
200        };
201        if amount_out.is_zero() {
202            return Err(SimulationError::InvalidInput(
203                "Amount in is too small to buy any output".to_string(),
204                None,
205            ));
206        }
207
208        // The fee leaves the pool: the swap sends it to the pool's fee contract before `Sync`.
209        let fee_amount = safe_div_u256(
210            safe_mul_u256(amount_in, U256::from(fee_bps))?,
211            U256::from(FEE_PRECISION_BPS),
212        )?;
213        let new_reserve_in = safe_add_u256(reserve_in, safe_sub_u256(amount_in, fee_amount)?)?;
214        let new_reserve_out = safe_sub_u256(reserve_out, amount_out)?;
215        let mut new_state = self.clone();
216        if zero2one {
217            new_state.reserve0 = new_reserve_in;
218            new_state.reserve1 = new_reserve_out;
219        } else {
220            new_state.reserve0 = new_reserve_out;
221            new_state.reserve1 = new_reserve_in;
222        }
223
224        Ok(GetAmountOutResult::new(
225            u256_to_biguint(amount_out),
226            BigUint::from(SWAP_GAS),
227            Box::new(new_state),
228        ))
229    }
230
231    fn get_limits(
232        &self,
233        sell_token: Bytes,
234        buy_token: Bytes,
235    ) -> Result<(BigUint, BigUint), SimulationError> {
236        let fee_bps = self.fee_bps()?;
237        if self.stable {
238            self.stable_pool()
239                .get_limits(sell_token, buy_token)
240        } else {
241            cpmm_get_limits(sell_token, buy_token, self.reserve0, self.reserve1, fee_bps)
242        }
243    }
244
245    fn delta_transition(
246        &mut self,
247        delta: ProtocolStateDelta,
248        _tokens: &HashMap<Bytes, Token>,
249        _balances: &Balances,
250    ) -> Result<(), TransitionError> {
251        let attributes = &delta.updated_attributes;
252        if let Some(value) = attributes.get("reserve0") {
253            self.reserve0 = U256::from_be_slice(value);
254        }
255        if let Some(value) = attributes.get("reserve1") {
256            self.reserve1 = U256::from_be_slice(value);
257        }
258        if let Some(value) = attributes.get("custom_fee") {
259            self.custom_fee = u32::try_from(value.clone())?;
260        }
261        if let Some(value) = attributes.get("default_fee") {
262            self.default_fee = u32::try_from(value.clone())?;
263        }
264        if let Some(value) = attributes.get("fee_module") {
265            self.fee_module = value.clone();
266        }
267        if let Some(value) = attributes.get("paused") {
268            self.paused = value.iter().any(|byte| *byte != 0);
269        }
270        self.validate()
271            .map_err(TransitionError::DecodeError)
272    }
273
274    fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
275        query_pool_swap(self, params)
276    }
277
278    fn clone_box(&self) -> Box<dyn ProtocolSim> {
279        Box::new(self.clone())
280    }
281
282    fn as_any(&self) -> &dyn Any {
283        self
284    }
285
286    fn as_any_mut(&mut self) -> &mut dyn Any {
287        self
288    }
289
290    fn eq(&self, other: &dyn ProtocolSim) -> bool {
291        other
292            .as_any()
293            .downcast_ref::<Self>()
294            .is_some_and(|other| self == other)
295    }
296}
297
298#[cfg(test)]
299#[path = "state_tests.rs"]
300mod tests;