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