tycho_common/simulation/protocol_sim.rs
1use std::{any::Any, collections::HashMap, fmt};
2
3use num_bigint::BigUint;
4
5use crate::{
6 dto::ProtocolStateDelta,
7 models::token::Token,
8 simulation::{
9 errors::{SimulationError, TransitionError},
10 indicatively_priced::IndicativelyPriced,
11 },
12 Bytes,
13};
14
15#[derive(Default)]
16pub struct Balances {
17 pub component_balances: HashMap<String, HashMap<Bytes, Bytes>>,
18 pub account_balances: HashMap<Bytes, HashMap<Bytes, Bytes>>,
19}
20
21/// GetAmountOutResult struct represents the result of getting the amount out of a trading pair
22///
23/// # Fields
24///
25/// * `amount`: BigUint, the amount of the trading pair
26/// * `gas`: BigUint, the gas of the trading pair
27#[derive(Debug)]
28pub struct GetAmountOutResult {
29 pub amount: BigUint,
30 pub gas: BigUint,
31 pub new_state: Box<dyn ProtocolSim>,
32}
33
34impl GetAmountOutResult {
35 /// Constructs a new GetAmountOutResult struct with the given amount and gas
36 pub fn new(amount: BigUint, gas: BigUint, new_state: Box<dyn ProtocolSim>) -> Self {
37 GetAmountOutResult { amount, gas, new_state }
38 }
39
40 /// Aggregates the given GetAmountOutResult struct to the current one.
41 /// It updates the amount with the other's amount and adds the other's gas to the current one's
42 /// gas.
43 pub fn aggregate(&mut self, other: &Self) {
44 self.amount = other.amount.clone();
45 self.gas += &other.gas;
46 }
47}
48
49impl fmt::Display for GetAmountOutResult {
50 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 write!(f, "amount = {}, gas = {}", self.amount, self.gas)
52 }
53}
54
55/// Represents a price as a fraction in the token_in -> token_out direction with units
56/// `[token_out/token_in]`.
57///
58/// # Fields
59///
60/// * `numerator` - The amount of token_out (what you receive) in atomic units (wei)
61/// * `denominator` - The amount of token_in (what you pay) in atomic units (wei)
62///
63/// A fraction struct is used for price to have flexibility in precision independent of the
64/// decimal precisions of the numerator and denominator tokens. This allows for:
65/// - Exact price representation without floating-point errors
66/// - Handling tokens with different decimal places without loss of precision
67///
68/// # Example
69/// If we want to represent that token A is worth 2.5 units of token B:
70///
71/// ```
72/// use num_bigint::BigUint;
73/// use tycho_common::simulation::protocol_sim::Price;
74///
75/// let numerator = BigUint::from(25u32); // Represents 25 units of token B
76/// let denominator = BigUint::from(10u32); // Represents 10 units of token A
77/// let price = Price::new(numerator, denominator);
78/// ```
79///
80/// If you want to define a limit price for a trade, where you expect to get at least 120 T1 for
81/// 50 T2:
82/// ```
83/// use num_bigint::BigUint;
84/// use tycho_common::simulation::protocol_sim::Price;
85///
86/// let min_amount_out = BigUint::from(120u32); // The minimum amount of T1 you expect
87/// let amount_in = BigUint::from(50u32); // The amount of T2 you are selling
88/// let limit_price = Price::new(min_amount_out, amount_in);
89/// ```
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Price {
92 pub numerator: BigUint,
93 pub denominator: BigUint,
94}
95
96impl Price {
97 pub fn new(numerator: BigUint, denominator: BigUint) -> Self {
98 if denominator == BigUint::ZERO {
99 // Division by zero is not possible
100 panic!("Price denominator cannot be zero");
101 } else if numerator == BigUint::ZERO {
102 // Zero pool price is not valid in our context
103 panic!("Price numerator cannot be zero");
104 }
105 Self { numerator, denominator }
106 }
107}
108
109/// Represents a pool swap between two tokens at a given price on a pool.
110#[derive(Debug, Clone)]
111pub struct PoolSwap {
112 /// The amount of token_in sold to the pool
113 amount_in: BigUint,
114 /// The amount of token_out bought from the pool
115 amount_out: BigUint,
116 /// The new state of the pool after the swap
117 new_state: Box<dyn ProtocolSim>,
118 /// Optional price points that the pool was transitioned through while computing this swap.
119 /// The values are tuples of (amount_in, amount_out, price). This is useful for repeated calls
120 /// by providing good bounds for the next call.
121 price_points: Option<Vec<(BigUint, BigUint, f64)>>,
122}
123
124impl PoolSwap {
125 pub fn new(
126 amount_in: BigUint,
127 amount_out: BigUint,
128 new_state: Box<dyn ProtocolSim>,
129 price_points: Option<Vec<(BigUint, BigUint, f64)>>,
130 ) -> Self {
131 Self { amount_in, amount_out, new_state, price_points }
132 }
133
134 pub fn amount_in(&self) -> &BigUint {
135 &self.amount_in
136 }
137
138 pub fn amount_out(&self) -> &BigUint {
139 &self.amount_out
140 }
141
142 pub fn new_state(&self) -> &dyn ProtocolSim {
143 self.new_state.as_ref()
144 }
145
146 pub fn price_points(&self) -> &Option<Vec<(BigUint, BigUint, f64)>> {
147 &self.price_points
148 }
149}
150
151/// Options on how to constrain the pool swap query.
152///
153/// All prices use units `[token_out/token_in]` with amounts in atomic units (wei). When selling
154/// token_in into a pool, prices decrease due to slippage.
155#[derive(Debug, Clone, PartialEq)]
156pub enum SwapConstraint {
157 /// Calculates the maximum trade while respecting a minimum trade price.
158 TradeLimitPrice {
159 /// The minimum acceptable trade price. The resulting `amount_out / amount_in >= limit`.
160 limit: Price,
161 /// Fraction to raise the acceptance threshold above `limit`. Loosens the search criteria
162 /// but will never allow violating the trade limit price itself.
163 tolerance: f64,
164 /// The minimum amount of token_in that must be used for this trade.
165 min_amount_in: Option<BigUint>,
166 /// The maximum amount of token_in that can be used for this trade.
167 max_amount_in: Option<BigUint>,
168 },
169
170 /// Calculates the swap required to move the pool's marginal price down to a target.
171 ///
172 /// # Edge Cases and Limitations
173 ///
174 /// Computing the exact amount to move a pool's marginal price to a target has several
175 /// challenges:
176 /// - The definition of marginal price varies between protocols. It is usually not an attribute
177 /// of the pool but a consequence of its liquidity distribution and current state.
178 /// - For protocols with concentrated liquidity, the marginal price is discrete, meaning we
179 /// can't always find an exact trade amount to reach the target price.
180 /// - Not all protocols support analytical solutions for this problem, requiring numerical
181 /// methods.
182 PoolTargetPrice {
183 /// The target marginal price for the pool after the trade. The pool's price decreases
184 /// toward this target as token_in is sold into it.
185 target: Price,
186 /// Fraction above `target` considered acceptable. After trading, the pool's marginal
187 /// price will be in `[target, target * (1 + tolerance)]`.
188 tolerance: f64,
189 /// The lower bound for searching algorithms.
190 min_amount_in: Option<BigUint>,
191 /// The upper bound for searching algorithms.
192 max_amount_in: Option<BigUint>,
193 },
194}
195
196/// Represents the parameters for [ProtocolSim::query_pool_swap].
197///
198/// # Fields
199///
200/// * `token_in` - The token being sold (swapped into the pool)
201/// * `token_out` - The token being bought (swapped out of the pool)
202/// * `swap_constraint` - Type of price constraint to be applied. See [SwapConstraint].
203#[derive(Debug, Clone, PartialEq)]
204pub struct QueryPoolSwapParams {
205 token_in: Token,
206 token_out: Token,
207 swap_constraint: SwapConstraint,
208}
209
210impl QueryPoolSwapParams {
211 pub fn new(token_in: Token, token_out: Token, swap_constraint: SwapConstraint) -> Self {
212 Self { token_in, token_out, swap_constraint }
213 }
214
215 /// Returns a reference to the input token (token being sold into the pool)
216 pub fn token_in(&self) -> &Token {
217 &self.token_in
218 }
219
220 /// Returns a reference to the output token (token being bought out of the pool)
221 pub fn token_out(&self) -> &Token {
222 &self.token_out
223 }
224
225 /// Returns a reference to the price constraint
226 pub fn swap_constraint(&self) -> &SwapConstraint {
227 &self.swap_constraint
228 }
229}
230
231/// ProtocolSim trait
232/// This trait defines the methods that a protocol state must implement in order to be used
233/// in the trade simulation.
234pub trait ProtocolSim: fmt::Debug + Send + Sync + 'static {
235 /// Returns the fee of the protocol as ratio
236 ///
237 /// E.g. if the fee is 1%, the value returned would be 0.01.
238 ///
239 /// # Panics
240 ///
241 /// Currently panic for protocols with asymmetric fees (e.g. Rocketpool, Uniswap V4),
242 /// where a single fee value cannot represent the protocol's fee structure.
243 fn fee(&self) -> f64;
244
245 /// Returns the protocol's current spot buy price for `base` in units of `quote`.
246 ///
247 /// The returned price is the amount of `quote` required to buy exactly 1 unit of `base`,
248 /// accounting for the protocol fee (i.e. `price = pre_fee_price / (1.0 - fee)`)
249 /// and assuming zero slippage (i.e., a negligibly small trade size).
250 ///
251 /// # Arguments
252 /// * `base` - the token being priced (what you buy). For BTC/USDT, BTC is the base token.
253 /// * `quote` - the token used to price (pay) for `base`. For BTC/USDT, USDT is the quote token.
254 ///
255 /// # Examples
256 /// If the BTC/USDT is trading at 1000 with a 20% fee, this returns `1000 / (1.0 - 0.20) = 1250`
257 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError>;
258
259 /// Returns the amount out given an amount in and input/output tokens.
260 ///
261 /// # Arguments
262 ///
263 /// * `amount_in` - The amount in of the input token.
264 /// * `token_in` - The input token ERC20 token.
265 /// * `token_out` - The output token ERC20 token.
266 ///
267 /// # Returns
268 ///
269 /// A `Result` containing a `GetAmountOutResult` struct on success or a
270 /// `SimulationError` on failure.
271 fn get_amount_out(
272 &self,
273 amount_in: BigUint,
274 token_in: &Token,
275 token_out: &Token,
276 ) -> Result<GetAmountOutResult, SimulationError>;
277
278 /// Computes the maximum amount that can be traded between two tokens.
279 ///
280 /// This function calculates the maximum possible trade amount between two tokens,
281 /// taking into account the protocol's specific constraints and mechanics.
282 /// The implementation details vary by protocol - for example:
283 /// - For constant product AMMs (like Uniswap V2), this is based on available reserves
284 /// - For concentrated liquidity AMMs (like Uniswap V3), this considers liquidity across tick
285 /// ranges
286 ///
287 /// Note: if there are no limits, the returned amount will be a "soft" limit,
288 /// meaning that the actual amount traded could be higher but it's advised to not
289 /// exceed it.
290 ///
291 /// # Arguments
292 /// * `sell_token` - The address of the token being sold
293 /// * `buy_token` - The address of the token being bought
294 ///
295 /// # Returns
296 /// * `Ok((BigUint, BigUint))` - A tuple containing:
297 /// - First element: The maximum input amount (sell_token)
298 /// - Second element: The maximum output amount (buy_token)
299 ///
300 /// For `let res = get_limits(...)`, the valid input domain for `get_amount_out` is `[0,
301 /// res.0]`.
302 ///
303 /// * `Err(SimulationError)` - If any unexpected error occurs
304 fn get_limits(
305 &self,
306 sell_token: Bytes,
307 buy_token: Bytes,
308 ) -> Result<(BigUint, BigUint), SimulationError>;
309
310 /// Decodes and applies a protocol state delta to the state
311 ///
312 /// Will error if the provided delta is missing any required attributes or if any of the
313 /// attribute values cannot be decoded.
314 ///
315 /// # Arguments
316 ///
317 /// * `delta` - A `ProtocolStateDelta` from the tycho indexer
318 ///
319 /// # Returns
320 ///
321 /// * `Result<(), TransitionError<String>>` - A `Result` containing `()` on success or a
322 /// `TransitionError` on failure.
323 fn delta_transition(
324 &mut self,
325 delta: ProtocolStateDelta,
326 tokens: &HashMap<Bytes, Token>,
327 balances: &Balances,
328 ) -> Result<(), TransitionError<String>>;
329
330 /// Calculates the swap volume required to achieve the provided goal when trading against this
331 /// pool.
332 ///
333 /// This method will branch towards different behaviors based on [SwapConstraint] enum. Please
334 /// refer to its documentation for further details on each behavior.
335 ///
336 /// In short, the current two options are:
337 /// - Maximize your trade while respecting a trade limit price:
338 /// [SwapConstraint::TradeLimitPrice]
339 /// - Move the pool price to a target price: [SwapConstraint::PoolTargetPrice]
340 ///
341 /// # Arguments
342 ///
343 /// * `params` - A [QueryPoolSwapParams] struct containing the inputs for this method.
344 ///
345 /// # Returns
346 ///
347 /// * `Ok(PoolSwap)` - A `PoolSwap` struct containing the amounts to be traded and the state of
348 /// the pool after trading.
349 /// * `Err(SimulationError)` - If:
350 /// - The calculation encounters numerical issues
351 /// - The method is not implemented for this protocol
352 #[allow(unused)]
353 fn query_pool_swap(&self, params: &QueryPoolSwapParams) -> Result<PoolSwap, SimulationError> {
354 Err(SimulationError::FatalError("query_pool_swap not implemented".into()))
355 }
356
357 /// Clones the protocol state as a trait object.
358 /// This allows the state to be cloned when it is being used as a `Box<dyn ProtocolSim>`.
359 fn clone_box(&self) -> Box<dyn ProtocolSim>;
360
361 /// Allows downcasting of the trait object to its underlying type.
362 fn as_any(&self) -> &dyn Any;
363
364 /// Allows downcasting of the trait object to its mutable underlying type.
365 fn as_any_mut(&mut self) -> &mut dyn Any;
366
367 /// Compares two protocol states for equality.
368 /// This method must be implemented to define how two protocol states are considered equal
369 /// (used for tests).
370 fn eq(&self, other: &dyn ProtocolSim) -> bool;
371
372 /// Cast as IndicativelyPriced. This is necessary for RFQ protocols
373 fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
374 Err(SimulationError::FatalError("Pool State does not implement IndicativelyPriced".into()))
375 }
376}
377
378impl Clone for Box<dyn ProtocolSim> {
379 fn clone(&self) -> Box<dyn ProtocolSim> {
380 self.clone_box()
381 }
382}