Skip to main content

tycho_simulation/book/
sim.rs

1//! Shared pieces of the `ProtocolSim` implementations of level-based book states: which way a
2//! swap runs through a pair, conversion between atomic and human amounts, and the results a
3//! fill against a ladder turns into.
4
5use num_bigint::BigUint;
6use num_traits::{FromPrimitive, ToPrimitive, Zero};
7use tycho_common::{
8    models::token::Token,
9    simulation::{
10        errors::SimulationError,
11        protocol_sim::{GetAmountOutResult, ProtocolSim},
12    },
13    Bytes,
14};
15
16use crate::book::levels::{Fill, Levels};
17
18/// The direction of a swap relative to a pair's `base`/`quote` orientation.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum SwapDirection {
21    /// Sell base, receive quote.
22    BaseToQuote,
23    /// Sell quote, receive base.
24    QuoteToBase,
25}
26
27impl SwapDirection {
28    /// Which way `token_in -> token_out` runs through the `base`/`quote` pair; `None` when the
29    /// tokens are not that pair.
30    fn detect(base: &Bytes, quote: &Bytes, token_in: &Bytes, token_out: &Bytes) -> Option<Self> {
31        if token_in == base && token_out == quote {
32            Some(SwapDirection::BaseToQuote)
33        } else if token_in == quote && token_out == base {
34            Some(SwapDirection::QuoteToBase)
35        } else {
36            None
37        }
38    }
39
40    /// The direction, or the error every book state reports for tokens outside its pair.
41    pub fn require(
42        base: &Token,
43        quote: &Token,
44        token_in: &Bytes,
45        token_out: &Bytes,
46    ) -> Result<Self, SimulationError> {
47        let (base, quote) = (&base.address, &quote.address);
48        Self::detect(base, quote, token_in, token_out).ok_or_else(|| {
49            SimulationError::InvalidInput(
50                format!(
51                    "Invalid token addresses. Got in={token_in}, out={token_out}, expected {base} / {quote}"
52                ),
53                None,
54            )
55        })
56    }
57
58    /// For books that price one direction only: `Ok` when `token_in -> token_out` sells base
59    /// for quote, the same error as [`Self::require`] otherwise.
60    pub fn require_base_to_quote(
61        base: &Token,
62        quote: &Token,
63        token_in: &Bytes,
64        token_out: &Bytes,
65    ) -> Result<(), SimulationError> {
66        let (base, quote) = (&base.address, &quote.address);
67        match Self::detect(base, quote, token_in, token_out) {
68            Some(SwapDirection::BaseToQuote) => Ok(()),
69            _ => Err(SimulationError::InvalidInput(
70                format!(
71                    "Invalid token addresses. Got in={token_in}, out={token_out}, expected in={base}, out={quote}"
72                ),
73                None,
74            )),
75        }
76    }
77
78    /// The decimals of the token sold and the token bought by a swap in this direction through
79    /// the `base`/`quote` pair.
80    pub fn decimals(self, base: &Token, quote: &Token) -> (u32, u32) {
81        match self {
82            SwapDirection::BaseToQuote => (base.decimals, quote.decimals),
83            SwapDirection::QuoteToBase => (quote.decimals, base.decimals),
84        }
85    }
86}
87
88/// The client a state asks for a binding quote, or the error one that came out of a recording
89/// reports: a state is serialized without the venue's client, so a replayed book still prices
90/// but has nothing to quote through.
91pub fn quoting_client<'a, C>(
92    client: Option<&'a std::sync::Arc<C>>,
93    venue: &str,
94) -> Result<&'a C, SimulationError> {
95    client
96        .map(|client| client.as_ref())
97        .ok_or_else(|| {
98            SimulationError::FatalError(format!(
99                "This {venue} state carries no client, so it cannot request a quote"
100            ))
101        })
102}
103
104/// The directions of a book that quotes both ways round, as `(token sold, token bought)`: it
105/// buys base where it bids and sells base where it asks, and a side with nothing on it prices
106/// neither way.
107pub fn directions(base: &Token, quote: &Token, bids: bool, asks: bool) -> Vec<(Bytes, Bytes)> {
108    let mut directions = Vec::with_capacity(2);
109    if bids {
110        directions.push((base.address.clone(), quote.address.clone()));
111    }
112    if asks {
113        directions.push((quote.address.clone(), base.address.clone()));
114    }
115    directions
116}
117
118/// An atomic amount in human units, the units price levels are quoted in. An amount past
119/// `f64::MAX` becomes infinity, which no ladder absorbs, so its fill reports the whole amount as
120/// unfilled.
121pub fn to_human(amount: &BigUint, decimals: u32) -> f64 {
122    let amount = amount
123        .to_f64()
124        .expect("BigUint::to_f64 saturates to infinity instead of failing");
125    amount / 10f64.powi(decimals as i32)
126}
127
128/// A human amount back in atomic units. Fails for amounts a `BigUint` cannot hold (negative,
129/// non-finite).
130pub fn to_atomic(amount: f64, decimals: u32) -> Result<BigUint, SimulationError> {
131    BigUint::from_f64(amount * 10f64.powi(decimals as i32))
132        .ok_or_else(|| SimulationError::RecoverableError("Can't convert amount to BigUint".into()))
133}
134
135/// Turns a fill of `amount_in` (human units) into the swap result, with the partially filled
136/// result attached to the `InvalidInput` error when the ladder ran out of liquidity. A fill
137/// that took nothing is an `InvalidInput` with no partial result attached.
138pub fn fill_result(
139    fill: Fill,
140    amount_in: f64,
141    out_decimals: u32,
142    gas: u64,
143    state: &dyn ProtocolSim,
144) -> Result<GetAmountOutResult, SimulationError> {
145    // A ladder that took none of the amount has nothing on this side to take it with: no
146    // amount is servable, and there is no part of one to hand back.
147    if fill.remaining_in == amount_in {
148        return Err(SimulationError::InvalidInput(
149            format!("Pool has no liquidity on this side, so {amount_in} cannot be filled"),
150            None,
151        ));
152    }
153    let result = GetAmountOutResult {
154        amount: to_atomic(fill.amount_out, out_decimals)?,
155        gas: BigUint::from(gas),
156        new_state: state.clone_box(),
157    };
158    if fill.is_complete() {
159        Ok(result)
160    } else {
161        Err(SimulationError::InvalidInput(
162            format!(
163                "Pool has not enough liquidity to support complete swap. Input amount: {amount_in}, consumed amount: {}",
164                amount_in - fill.remaining_in
165            ),
166            Some(result),
167        ))
168    }
169}
170
171/// The price of the next input unit of `levels` once `filled` atomic units went in, or the
172/// recoverable error of a ladder with nothing left.
173pub fn marginal_price(
174    levels: &Levels,
175    filled: &BigUint,
176    in_decimals: u32,
177) -> Result<f64, SimulationError> {
178    levels
179        .marginal_price(to_human(filled, in_decimals))
180        .ok_or_else(|| SimulationError::RecoverableError("No liquidity".into()))
181}
182
183/// Refuses a swap of nothing, which a ladder would otherwise report as an amount fully
184/// consumed — a fill of zero that reads as a swap that worked.
185pub fn require_positive_amount(amount_in: &BigUint) -> Result<(), SimulationError> {
186    if amount_in.is_zero() {
187        return Err(SimulationError::InvalidInput(
188            "Swap amount must be greater than zero".to_string(),
189            None,
190        ));
191    }
192    Ok(())
193}
194
195/// The swap limits of a ladder: the input it absorbs in total and the output that buys, in atomic
196/// units of the respective tokens.
197pub fn limits(
198    levels: &Levels,
199    in_decimals: u32,
200    out_decimals: u32,
201) -> Result<(BigUint, BigUint), SimulationError> {
202    let (total_in, total_out) = levels.totals();
203    Ok((to_atomic(total_in, in_decimals)?, to_atomic(total_out, out_decimals)?))
204}
205
206#[cfg(test)]
207mod tests {
208    use std::str::FromStr;
209
210    use rstest::rstest;
211    use tycho_common::models::Chain;
212
213    use super::*;
214    use crate::{book::levels::PriceLevel, evm::decoder::MockProtocolSim};
215
216    fn addr(last: u8) -> Bytes {
217        Bytes::from(vec![last; 20])
218    }
219
220    fn token(last: u8, decimals: u32) -> Token {
221        Token::new(&addr(last), &format!("T{last}"), decimals, 0, &[], Chain::Ethereum, 100)
222    }
223
224    #[test]
225    fn detects_both_directions_and_rejects_other_tokens() {
226        let (base, quote, other) = (token(1, 18), token(2, 6), addr(3));
227
228        assert_eq!(
229            SwapDirection::require(&base, &quote, &base.address, &quote.address).unwrap(),
230            SwapDirection::BaseToQuote
231        );
232        assert_eq!(
233            SwapDirection::require(&base, &quote, &quote.address, &base.address).unwrap(),
234            SwapDirection::QuoteToBase
235        );
236        assert!(matches!(
237            SwapDirection::require(&base, &quote, &base.address, &other),
238            Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")
239        ));
240        assert!(matches!(
241            SwapDirection::require_base_to_quote(&base, &quote, &quote.address, &base.address),
242            Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")
243        ));
244    }
245
246    #[test]
247    fn the_direction_says_which_decimals_are_sold_and_bought() {
248        let (base, quote) = (token(1, 18), token(2, 6));
249
250        assert_eq!(SwapDirection::BaseToQuote.decimals(&base, &quote), (18, 6));
251        assert_eq!(SwapDirection::QuoteToBase.decimals(&base, &quote), (6, 18));
252    }
253
254    #[test]
255    fn converts_between_atomic_and_human_units() {
256        let atomic = BigUint::from_str("1500000").unwrap();
257
258        assert_eq!(to_human(&atomic, 6), 1.5);
259        assert_eq!(to_atomic(1.5, 6).unwrap(), atomic);
260        assert!(to_atomic(-1.0, 6).is_err());
261        assert!(to_atomic(f64::NAN, 6).is_err());
262    }
263
264    /// Two levels of one unit each at 2000; the fill of 2 units is complete, the fill of 3 stops
265    /// at the ladder's depth.
266    fn ladder() -> Levels {
267        Levels::new(vec![
268            PriceLevel { quantity: 1.0, price: 2_000.0 },
269            PriceLevel { quantity: 1.0, price: 2_000.0 },
270        ])
271        .unwrap()
272    }
273
274    fn new_state() -> Box<dyn ProtocolSim> {
275        let mut state = MockProtocolSim::new();
276        state
277            .expect_clone_box()
278            .returning(|| Box::new(MockProtocolSim::new()));
279        Box::new(state)
280    }
281
282    #[test]
283    fn fill_result_attaches_the_partial_result_when_the_ladder_runs_out() {
284        let ladder = ladder();
285
286        let state = new_state();
287        let complete = fill_result(ladder.fill(2.0), 2.0, 6, 100, state.as_ref()).unwrap();
288        assert_eq!(complete.amount, BigUint::from(4_000_000_000u64));
289        assert_eq!(complete.gas, BigUint::from(100u64));
290
291        let partial = fill_result(ladder.fill(3.0), 3.0, 6, 100, state.as_ref());
292        match partial {
293            Err(SimulationError::InvalidInput(message, Some(result))) => {
294                assert!(message.contains("consumed amount: 2"));
295                assert_eq!(result.amount, BigUint::from(4_000_000_000u64));
296            }
297            other => panic!("expected the partially filled result, got {other:?}"),
298        }
299    }
300
301    /// What `get_limits` promises, `get_amount_out` must be able to fill: the limit goes out in
302    /// atomic units and comes back through `to_human`, and neither conversion may leave the
303    /// caller a hair short of a complete fill.
304    ///
305    /// The single level is a measured case where the round trip alone overshoots: 75559.18038262217
306    /// atomic-ises and comes back as 75559.18038262219, just under one ulp high.
307    #[rstest]
308    #[case::eighteen_decimals(18, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
309    #[case::six_decimals(6, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
310    #[case::two_decimals(2, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
311    #[case::round_trip_overshoots(18, &[75559.18038262217])]
312    fn the_reported_limit_fills_completely(#[case] decimals: u32, #[case] quantities: &[f64]) {
313        let ladder = Levels::new(
314            quantities
315                .iter()
316                .map(|&quantity| PriceLevel { price: 1.5, quantity })
317                .collect(),
318        )
319        .unwrap();
320
321        let (sell_limit, _) = limits(&ladder, decimals, 6).unwrap();
322        let fill = ladder.fill(to_human(&sell_limit, decimals));
323
324        assert!(fill.is_complete(), "{decimals} decimals left {} unfilled", fill.remaining_in);
325    }
326
327    #[test]
328    fn limits_are_the_ladder_totals_in_atomic_units() {
329        let ladder = Levels::new(vec![
330            PriceLevel { price: 2.0, quantity: 1.5 },
331            PriceLevel { price: 3.0, quantity: 0.5 },
332        ])
333        .unwrap();
334
335        let (sell, buy) = limits(&ladder, 6, 2).unwrap();
336
337        assert_eq!(sell, BigUint::from(2_000_000u64));
338        assert_eq!(buy, BigUint::from(450u64));
339    }
340}