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/// Refuses a swap of nothing, which a ladder would otherwise report as an amount fully
172/// consumed — a fill of zero that reads as a swap that worked.
173pub fn require_positive_amount(amount_in: &BigUint) -> Result<(), SimulationError> {
174    if amount_in.is_zero() {
175        return Err(SimulationError::InvalidInput(
176            "Swap amount must be greater than zero".to_string(),
177            None,
178        ));
179    }
180    Ok(())
181}
182
183/// The swap limits of a ladder: the input it absorbs in total and the output that buys, in atomic
184/// units of the respective tokens.
185pub fn limits(
186    levels: &Levels,
187    in_decimals: u32,
188    out_decimals: u32,
189) -> Result<(BigUint, BigUint), SimulationError> {
190    let (total_in, total_out) = levels.totals();
191    Ok((to_atomic(total_in, in_decimals)?, to_atomic(total_out, out_decimals)?))
192}
193
194#[cfg(test)]
195mod tests {
196    use std::str::FromStr;
197
198    use rstest::rstest;
199    use tycho_common::models::Chain;
200
201    use super::*;
202    use crate::{book::levels::PriceLevel, evm::decoder::MockProtocolSim};
203
204    fn addr(last: u8) -> Bytes {
205        Bytes::from(vec![last; 20])
206    }
207
208    fn token(last: u8, decimals: u32) -> Token {
209        Token::new(&addr(last), &format!("T{last}"), decimals, 0, &[], Chain::Ethereum, 100)
210    }
211
212    #[test]
213    fn detects_both_directions_and_rejects_other_tokens() {
214        let (base, quote, other) = (token(1, 18), token(2, 6), addr(3));
215
216        assert_eq!(
217            SwapDirection::require(&base, &quote, &base.address, &quote.address).unwrap(),
218            SwapDirection::BaseToQuote
219        );
220        assert_eq!(
221            SwapDirection::require(&base, &quote, &quote.address, &base.address).unwrap(),
222            SwapDirection::QuoteToBase
223        );
224        assert!(matches!(
225            SwapDirection::require(&base, &quote, &base.address, &other),
226            Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")
227        ));
228        assert!(matches!(
229            SwapDirection::require_base_to_quote(&base, &quote, &quote.address, &base.address),
230            Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")
231        ));
232    }
233
234    #[test]
235    fn the_direction_says_which_decimals_are_sold_and_bought() {
236        let (base, quote) = (token(1, 18), token(2, 6));
237
238        assert_eq!(SwapDirection::BaseToQuote.decimals(&base, &quote), (18, 6));
239        assert_eq!(SwapDirection::QuoteToBase.decimals(&base, &quote), (6, 18));
240    }
241
242    #[test]
243    fn converts_between_atomic_and_human_units() {
244        let atomic = BigUint::from_str("1500000").unwrap();
245
246        assert_eq!(to_human(&atomic, 6), 1.5);
247        assert_eq!(to_atomic(1.5, 6).unwrap(), atomic);
248        assert!(to_atomic(-1.0, 6).is_err());
249        assert!(to_atomic(f64::NAN, 6).is_err());
250    }
251
252    /// Two levels of one unit each at 2000; the fill of 2 units is complete, the fill of 3 stops
253    /// at the ladder's depth.
254    fn ladder() -> Levels {
255        Levels::new(vec![
256            PriceLevel { quantity: 1.0, price: 2_000.0 },
257            PriceLevel { quantity: 1.0, price: 2_000.0 },
258        ])
259        .unwrap()
260    }
261
262    fn new_state() -> Box<dyn ProtocolSim> {
263        let mut state = MockProtocolSim::new();
264        state
265            .expect_clone_box()
266            .returning(|| Box::new(MockProtocolSim::new()));
267        Box::new(state)
268    }
269
270    #[test]
271    fn fill_result_attaches_the_partial_result_when_the_ladder_runs_out() {
272        let ladder = ladder();
273
274        let state = new_state();
275        let complete = fill_result(ladder.fill(2.0), 2.0, 6, 100, state.as_ref()).unwrap();
276        assert_eq!(complete.amount, BigUint::from(4_000_000_000u64));
277        assert_eq!(complete.gas, BigUint::from(100u64));
278
279        let partial = fill_result(ladder.fill(3.0), 3.0, 6, 100, state.as_ref());
280        match partial {
281            Err(SimulationError::InvalidInput(message, Some(result))) => {
282                assert!(message.contains("consumed amount: 2"));
283                assert_eq!(result.amount, BigUint::from(4_000_000_000u64));
284            }
285            other => panic!("expected the partially filled result, got {other:?}"),
286        }
287    }
288
289    /// What `get_limits` promises, `get_amount_out` must be able to fill: the limit goes out in
290    /// atomic units and comes back through `to_human`, and neither conversion may leave the
291    /// caller a hair short of a complete fill.
292    ///
293    /// The single level is a measured case where the round trip alone overshoots: 75559.18038262217
294    /// atomic-ises and comes back as 75559.18038262219, just under one ulp high.
295    #[rstest]
296    #[case::eighteen_decimals(18, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
297    #[case::six_decimals(6, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
298    #[case::two_decimals(2, &[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 48.508172])]
299    #[case::round_trip_overshoots(18, &[75559.18038262217])]
300    fn the_reported_limit_fills_completely(#[case] decimals: u32, #[case] quantities: &[f64]) {
301        let ladder = Levels::new(
302            quantities
303                .iter()
304                .map(|&quantity| PriceLevel { price: 1.5, quantity })
305                .collect(),
306        )
307        .unwrap();
308
309        let (sell_limit, _) = limits(&ladder, decimals, 6).unwrap();
310        let fill = ladder.fill(to_human(&sell_limit, decimals));
311
312        assert!(fill.is_complete(), "{decimals} decimals left {} unfilled", fill.remaining_in);
313    }
314
315    #[test]
316    fn limits_are_the_ladder_totals_in_atomic_units() {
317        let ladder = Levels::new(vec![
318            PriceLevel { price: 2.0, quantity: 1.5 },
319            PriceLevel { price: 3.0, quantity: 0.5 },
320        ])
321        .unwrap();
322
323        let (sell, buy) = limits(&ladder, 6, 2).unwrap();
324
325        assert_eq!(sell, BigUint::from(2_000_000u64));
326        assert_eq!(buy, BigUint::from(450u64));
327    }
328}