tycho-simulation 0.504.1

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
use std::{any::Any, borrow::Cow, collections::HashMap, sync::Arc};

use async_trait::async_trait;
use num_bigint::BigUint;
use num_traits::FromPrimitive;
use serde::{Deserialize, Serialize};
use tycho_common::{
    dto::ProtocolStateDelta,
    models::{protocol::GetAmountOutParams, token::Token},
    simulation::{
        errors::{SimulationError, TransitionError},
        indicatively_priced::{IndicativelyPriced, SignedQuote},
        protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
    },
    Bytes,
};

use crate::{
    book::{
        all_pairs::{all_pairs_state, PricesAfterFill, RefusesQuote, SignedByVenue},
        component::PairState,
        levels::Levels,
        sim::{self, SwapDirection},
    },
    rfq::protocols::native::{
        client::NativeClient,
        models::{NativeBookSide, NativePriceData},
    },
};

/// Approximate gas for one Native Relay swap.
const NATIVE_SWAP_GAS: u64 = 134_000;

#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
pub struct NativeState {
    pub(super) base_token: Token,
    pub(super) quote_token: Token,
    #[debug(skip)]
    pub(super) book: NativePriceData,
    #[serde(skip)]
    #[debug(skip)]
    client: Option<Arc<NativeClient>>,
}

impl NativeState {
    /// A book this venue prices, with the client its binding quotes go to.
    pub(super) fn new(
        base_token: Token,
        quote_token: Token,
        book: NativePriceData,
        client: Arc<NativeClient>,
    ) -> Self {
        NativeState { base_token, quote_token, book, client: Some(client) }
    }

    fn enforce_minimum(
        amount: &BigUint,
        minimum: f64,
        amount_kind: &str,
    ) -> Result<(), SimulationError> {
        if minimum == 0.0 {
            return Ok(())
        }
        // Native Relay reports minimums in atomic units, matching `amount`. Round up defensively
        // because the JSON number is deserialized into an f64 by the orderbook model.
        let minimum = BigUint::from_f64(minimum.ceil()).ok_or_else(|| {
            SimulationError::FatalError(format!(
                "Can't convert Native minimum {amount_kind} amount to BigUint"
            ))
        })?;
        if amount < &minimum {
            return Err(SimulationError::RecoverableError(format!(
                "Amount below minimum {amount_kind}. Amount: {amount}, min amount: {minimum}"
            )))
        }
        Ok(())
    }

    /// The side of the book a swap in `direction` fills, which carries both the ladder and the
    /// trade sizes that side requires.
    fn side(&self, direction: SwapDirection) -> &NativeBookSide {
        match direction {
            SwapDirection::BaseToQuote => &self.book.bids,
            SwapDirection::QuoteToBase => &self.book.asks,
        }
    }

    /// The ladder a swap in `direction` consumes, in the units of the token sold: the bids as
    /// published for selling base, the asks re-expressed per quote unit for selling quote.
    fn ladder(&self, direction: SwapDirection) -> Cow<'_, Levels> {
        match direction {
            SwapDirection::BaseToQuote => Cow::Borrowed(&self.book.bids.levels),
            SwapDirection::QuoteToBase => Cow::Owned(self.book.asks.levels.invert()),
        }
    }
}

impl PairState for NativeState {
    fn base_token(&self) -> &Token {
        &self.base_token
    }

    fn quote_token(&self) -> &Token {
        &self.quote_token
    }

    fn directions(&self) -> Vec<(Bytes, Bytes)> {
        sim::directions(
            &self.base_token,
            &self.quote_token,
            !self.book.bids.levels.is_empty(),
            !self.book.asks.levels.is_empty(),
        )
    }
}

impl PricesAfterFill for NativeState {
    fn marginal_price(
        &self,
        token_in: &Bytes,
        token_out: &Bytes,
        filled: &BigUint,
    ) -> Result<f64, SimulationError> {
        let direction =
            SwapDirection::require(&self.base_token, &self.quote_token, token_in, token_out)?;
        let (sell_decimals, _) = direction.decimals(&self.base_token, &self.quote_token);
        sim::marginal_price(&self.ladder(direction), filled, sell_decimals)
    }
}

#[typetag::serde]
impl ProtocolSim for NativeState {
    fn fee(&self) -> f64 {
        0.0
    }

    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
        let direction = SwapDirection::require(
            &self.base_token,
            &self.quote_token,
            &base.address,
            &quote.address,
        )?;
        let best_bid = self
            .book
            .bids
            .levels
            .first()
            .map(|lvl| lvl.price);
        let best_ask = self
            .book
            .asks
            .levels
            .first()
            .map(|lvl| lvl.price);
        let average_price = match (best_bid, best_ask) {
            (Some(bid), Some(ask)) => bid.midpoint(ask),
            (Some(bid), None) => bid,
            (None, Some(ask)) => ask,
            (None, None) => {
                return Err(SimulationError::RecoverableError("No liquidity".to_string()))
            }
        };
        let spot_price = match direction {
            SwapDirection::BaseToQuote => average_price,
            SwapDirection::QuoteToBase => average_price.recip(),
        };
        if !spot_price.is_finite() || spot_price <= 0.0 {
            return Err(SimulationError::RecoverableError(
                "Native spot price is not positive and finite".to_string(),
            ))
        }
        Ok(spot_price)
    }

    fn get_amount_out(
        &self,
        amount_in: BigUint,
        token_in: &Token,
        token_out: &Token,
    ) -> Result<GetAmountOutResult, SimulationError> {
        // Native refuses a zero amount with `131004 invalid parameter`; an amount under the
        // side's published minimum is its separate `171055`.
        sim::require_positive_amount(&amount_in)?;

        let direction = SwapDirection::require(
            &self.base_token,
            &self.quote_token,
            &token_in.address,
            &token_out.address,
        )?;
        let side = self.side(direction);
        Self::enforce_minimum(&amount_in, side.minimum_in, "input")?;

        let ladder = self.ladder(direction);

        let amount_in = sim::to_human(&amount_in, token_in.decimals);
        let fill = ladder.fill(amount_in);
        let result = sim::fill_result(fill, amount_in, token_out.decimals, NATIVE_SWAP_GAS, self)?;
        Self::enforce_minimum(&result.amount, side.minimum_out, "output")?;
        Ok(result)
    }

    fn get_limits(
        &self,
        sell_token: Bytes,
        buy_token: Bytes,
    ) -> Result<(BigUint, BigUint), SimulationError> {
        let direction =
            SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
        let ladder = self.ladder(direction);
        // Nothing on this side is no swap at any size, so there is no limit to report.
        if ladder.is_empty() {
            return Err(SimulationError::RecoverableError("No liquidity".into()));
        }
        let (sell_decimals, buy_decimals) = direction.decimals(&self.base_token, &self.quote_token);
        sim::limits(&ladder, sell_decimals, buy_decimals)
    }

    fn delta_transition(
        &mut self,
        _delta: ProtocolStateDelta,
        _tokens: &HashMap<Bytes, Token>,
        _balances: &Balances,
    ) -> Result<(), TransitionError> {
        Err(TransitionError::DecodeError("Not implemented".into()))
    }

    fn clone_box(&self) -> Box<dyn ProtocolSim> {
        Box::new(self.clone())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn eq(&self, other: &dyn ProtocolSim) -> bool {
        if let Some(other_state) = other
            .as_any()
            .downcast_ref::<NativeState>()
        {
            self.base_token == other_state.base_token &&
                self.quote_token == other_state.quote_token &&
                self.book == other_state.book
        } else {
            false
        }
    }

    fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
        Ok(self)
    }
}

#[async_trait]
impl IndicativelyPriced for NativeState {
    async fn request_signed_quote(
        &self,
        params: GetAmountOutParams,
    ) -> Result<SignedQuote, SimulationError> {
        Ok(sim::quoting_client(self.client.as_ref(), "Native")?
            .request_binding_quote(&params)
            .await?)
    }
}

all_pairs_state! {
    /// Native's books on one chain behind one component.
    ///
    /// Native signs its quotes itself and names no market maker, so all of its books share one
    /// turn: a route takes one quote from the venue, and the swap that takes it spends every
    /// book behind the component.
    NativeAllPairsState(NativeState, SignedByVenue);
}

impl RefusesQuote for NativeAllPairsState {}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use rstest::rstest;
    use tokio::time::Duration;
    use tycho_common::models::Chain;

    use super::*;
    use crate::{book::levels::PriceLevel, rfq::protocols::native::models::NativeSupportedChain};

    fn token(address: &str, symbol: &str, decimals: u32) -> Token {
        Token::new(
            &Bytes::from_str(address).unwrap(),
            symbol,
            decimals,
            0,
            &[],
            Chain::Ethereum,
            100,
        )
    }

    fn state() -> NativeState {
        let base_token = token("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "WETH", 18);
        let quote_token = token("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "USDC", 6);
        let book = NativePriceData {
            base_address: base_token.address.clone(),
            quote_address: quote_token.address.clone(),
            bids: NativeBookSide {
                levels: Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_000.0 }]).unwrap(),
                minimum_in: 100_000_000_000.0,
                minimum_out: 0.0,
            },
            asks: NativeBookSide {
                levels: Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_000.0 }]).unwrap(),
                minimum_in: 100.0,
                minimum_out: 0.0,
            },
        };
        let client = Arc::new(NativeClient::new(
            None,
            NativeSupportedChain::Ethereum,
            String::new(),
            Duration::from_secs(5),
        ));

        NativeState { base_token, quote_token, book, client: Some(client) }
    }

    /// Selling base at the atomic input minimum is accepted, one unit below it is not; the same
    /// for selling quote against its own minimum.
    #[rstest]
    #[case::base_sell_at_minimum(true, 100_000_000_000, true)]
    #[case::base_sell_below_minimum(true, 99_999_999_999, false)]
    #[case::quote_sell_at_minimum(false, 100, true)]
    #[case::quote_sell_below_minimum(false, 99, false)]
    fn enforces_atomic_input_minimums(
        #[case] sell_base: bool,
        #[case] amount_in: u64,
        #[case] expect_ok: bool,
    ) {
        let state = state();
        let (token_in, token_out) = if sell_base {
            (&state.base_token, &state.quote_token)
        } else {
            (&state.quote_token, &state.base_token)
        };

        let result = state.get_amount_out(BigUint::from(amount_in), token_in, token_out);

        if expect_ok {
            assert!(result.is_ok());
        } else {
            assert!(matches!(result, Err(SimulationError::RecoverableError(_))));
        }
    }

    #[test]
    fn calculates_midpoint_spot_price_in_both_directions() {
        let mut state = state();
        state.book.bids.levels =
            Levels::new(vec![PriceLevel { quantity: 1.0, price: 1_900.0 }]).unwrap();
        state.book.asks.levels =
            Levels::new(vec![PriceLevel { quantity: 1.0, price: 2_100.0 }]).unwrap();

        let direct = state
            .spot_price(&state.base_token, &state.quote_token)
            .unwrap();
        let inverse = state
            .spot_price(&state.quote_token, &state.base_token)
            .unwrap();

        assert_eq!(direct, 2_000.0);
        assert_eq!(inverse, direct.recip());
    }

    /// The spot price must be positive and finite: a huge finite midpoint passes in the direct
    /// direction, a subnormal one overflows to infinity when inverted and is rejected.
    #[test]
    fn requires_a_finite_spot_price() {
        let mut state = state();
        let extreme = Levels::new(vec![PriceLevel { quantity: 1e-306, price: 1e308 }]).unwrap();
        state.book.bids.levels = extreme.clone();
        state.book.asks.levels = extreme;
        assert_eq!(
            state
                .spot_price(&state.base_token, &state.quote_token)
                .unwrap(),
            1e308
        );

        let subnormal =
            Levels::new(vec![PriceLevel { quantity: 1.0, price: f64::from_bits(1) }]).unwrap();
        state.book.bids.levels = subnormal.clone();
        state.book.asks.levels = subnormal;
        assert!(matches!(
            state.spot_price(&state.quote_token, &state.base_token),
            Err(SimulationError::RecoverableError(message))
                if message.contains("not positive and finite")
        ));
    }

    /// After some input went in, the next unit is priced at the level where the fill stopped, on
    /// the side of the book a swap in that direction fills.
    #[rstest]
    #[case::selling_base_in_the_level(true, 500_000_000_000_000_000, Some(2_000.0))]
    #[case::selling_base_past_the_depth(true, 1_000_000_000_000_000_000, None)]
    #[case::selling_quote_in_the_level(false, 1_000_000_000, Some(1.0 / 2_000.0))]
    fn the_price_after_a_fill_is_the_level_where_it_stopped(
        #[case] sell_base: bool,
        #[case] filled: u64,
        #[case] expected: Option<f64>,
    ) {
        let state = state();
        let (token_in, token_out) = if sell_base {
            (&state.base_token, &state.quote_token)
        } else {
            (&state.quote_token, &state.base_token)
        };

        let price =
            state.marginal_price(&token_in.address, &token_out.address, &BigUint::from(filled));

        match (price, expected) {
            (Ok(price), Some(expected)) => assert_eq!(price, expected),
            (Err(SimulationError::RecoverableError(message)), None) => {
                assert_eq!(message, "No liquidity")
            }
            (price, _) => panic!("expected {expected:?}, got {price:?}"),
        }
    }

    #[rstest]
    #[case::sell_base(true, 2_500_000_000_000_000_000, 3_500_000_000)]
    #[case::sell_quote(false, 8_192_000_000, 2_500_000_000_000_000_000)]
    fn consumes_multiple_price_levels(
        #[case] sell_base: bool,
        #[case] amount_in: u64,
        #[case] expected_amount_out: u64,
    ) {
        let mut state = state();
        state.book.bids.levels = Levels::new(vec![
            PriceLevel { quantity: 1.0, price: 2_000.0 },
            PriceLevel { quantity: 2.0, price: 1_000.0 },
        ])
        .unwrap();
        state.book.asks.levels = Levels::new(vec![
            PriceLevel { quantity: 1.0, price: 2_048.0 },
            PriceLevel { quantity: 2.0, price: 4_096.0 },
        ])
        .unwrap();
        // Sell base: 1 * 2000 + 1.5 * 1000 = 3500 USDC.
        // Sell quote: 2048 buys the first WETH; the remaining 6144 buys 1.5 WETH.
        let (token_in, token_out) = if sell_base {
            (&state.base_token, &state.quote_token)
        } else {
            (&state.quote_token, &state.base_token)
        };

        let result = state
            .get_amount_out(BigUint::from(amount_in), token_in, token_out)
            .unwrap();

        assert_eq!(result.amount, BigUint::from(expected_amount_out));
    }

    #[test]
    fn enforces_base_sell_atomic_output_minimum() {
        let mut state = state();
        state.book.bids.minimum_out = 1_000_000_000.0;
        let amount_in = BigUint::from(500_000_000_000_000_000u64);

        assert!(state
            .get_amount_out(amount_in.clone(), &state.base_token, &state.quote_token)
            .is_ok());

        state.book.bids.minimum_out = 1_000_000_001.0;
        assert!(matches!(
            state.get_amount_out(amount_in, &state.base_token, &state.quote_token),
            Err(SimulationError::RecoverableError(message)) if message.contains("minimum output")
        ));
    }

    #[test]
    fn enforces_quote_sell_atomic_output_minimum() {
        let mut state = state();
        state.book.asks.minimum_out = 500_000_000_000_000.0;
        let amount_in = BigUint::from(1_000_000u64);

        assert!(state
            .get_amount_out(amount_in.clone(), &state.quote_token, &state.base_token)
            .is_ok());

        state.book.asks.minimum_out = 500_000_000_000_001.0;
        assert!(matches!(
            state.get_amount_out(amount_in, &state.quote_token, &state.base_token),
            Err(SimulationError::RecoverableError(message)) if message.contains("minimum output")
        ));
    }

    #[test]
    fn rejects_sub_unit_partial_fill() {
        let mut state = state();
        state.book.bids.minimum_in = 0.0;
        state.book.bids.levels =
            Levels::new(vec![PriceLevel { quantity: 0.5e-18, price: 2_000.0 }]).unwrap();

        let result =
            state.get_amount_out(BigUint::from(1u64), &state.base_token, &state.quote_token);

        assert!(matches!(result, Err(SimulationError::InvalidInput(_, Some(_)))));
    }

    /// Limits follow the ladder of the swap direction and the decimals of the tokens on each side.
    #[rstest]
    #[case::sell_base(true, 1_000_000_000_000_000_000, 2_000_000_000)]
    #[case::sell_quote(false, 2_000_000_000, 1_000_000_000_000_000_000)]
    fn gets_limits_in_both_directions(
        #[case] sell_base: bool,
        #[case] expected_sell_limit: u64,
        #[case] expected_buy_limit: u64,
    ) {
        let state = state();
        let (token_in, token_out) = if sell_base {
            (&state.base_token, &state.quote_token)
        } else {
            (&state.quote_token, &state.base_token)
        };

        let limits = state
            .get_limits(token_in.address.clone(), token_out.address.clone())
            .unwrap();

        assert_eq!(limits, (BigUint::from(expected_sell_limit), BigUint::from(expected_buy_limit)));
    }

    #[test]
    fn rejects_invalid_pair() {
        let mut state = state();
        let other = token("0x1111111111111111111111111111111111111111", "OTHER", 18);

        assert!(matches!(
            state.get_amount_out(BigUint::from(1u64), &other, &state.quote_token),
            Err(SimulationError::InvalidInput(_, None))
        ));
        assert!(matches!(
            state.get_limits(other.address.clone(), state.quote_token.address.clone()),
            Err(SimulationError::InvalidInput(_, None))
        ));

        // Direction validation must win even when the book has no liquidity.
        state.book.bids.levels = Levels::default();
        state.book.asks.levels = Levels::default();
        assert!(matches!(
            state.spot_price(&other, &state.quote_token),
            Err(SimulationError::InvalidInput(message, None))
                if message.contains("Invalid token addresses")
        ));
    }

    #[test]
    /// A side the venue is not quoting has no depth to report and no swap to price.
    fn a_side_with_no_levels_has_nothing_to_offer() {
        let mut state = state();
        state.book.bids.levels = Levels::default();

        assert!(matches!(
            state.get_amount_out(
                BigUint::from(500_000_000_000_000_000u64),
                &state.base_token,
                &state.quote_token,
            ),
            Err(SimulationError::InvalidInput(_, None))
        ));
        assert!(matches!(
            state.get_limits(state.base_token.address.clone(), state.quote_token.address.clone()),
            Err(SimulationError::RecoverableError(_))
        ));
    }

    /// The venue refuses a swap of nothing, so simulating one must not report a fill.
    #[test]
    fn rejects_a_zero_amount() {
        let state = state();

        let result = state.get_amount_out(
            BigUint::ZERO,
            &state.base_token.clone(),
            &state.quote_token.clone(),
        );

        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
    }
}