tycho-simulation 0.527.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
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use tycho_common::{models::Chain, Bytes};

use crate::book::{
    levels::{Levels, PriceLevel},
    wire::SkipInvalidEntries,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NativeOrderbookSide {
    /// The market maker buys base; the taker sells base and receives quote.
    Bid,
    /// The market maker sells base; the taker sells quote and receives base.
    Ask,
}

/// Native's wire form of a ladder: `[quantity, price]` number pairs, with `[0, 0]` placeholders.
fn deserialize_levels<'de, D>(deserializer: D) -> Result<Levels, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let levels = Vec::<[f64; 2]>::deserialize(deserializer)?
        .into_iter()
        .map(|[quantity, price]| PriceLevel { quantity, price })
        .collect();
    Levels::new(levels).map_err(serde::de::Error::custom)
}

fn deserialize_non_negative_f64<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = f64::deserialize(deserializer)?;
    if !value.is_finite() || value < 0.0 {
        return Err(serde::de::Error::custom("expected a non-negative finite number"))
    }
    Ok(value)
}

/// Native's aggregated orderbook: one entry per pair, side and orientation its makers quote.
#[serde_as]
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct NativeOrderbook(
    #[serde_as(deserialize_as = "SkipInvalidEntries")] pub Vec<NativeOrderbookEntry>,
);

#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct NativeOrderbookEntry {
    pub base_address: Bytes,
    pub quote_address: Bytes,
    /// Minimum base-token amount in atomic units.
    ///
    /// Unlike `levels`, whose quantities are expressed in normal token units, Native Relay's
    /// aggregated orderbook returns this field in atomic units. It constrains input for a bid and
    /// output for an ask.
    #[serde(deserialize_with = "deserialize_non_negative_f64")]
    pub minimum_in_base: f64,
    pub side: NativeOrderbookSide,
    #[serde(deserialize_with = "deserialize_levels")]
    pub levels: Levels,
}

/// One side of a book: the ladder a fill walks, and the trade sizes the side requires. A side
/// comes from a single orderbook entry, which states its minimum on one end of the trade — the
/// input for a bid, the output for an ask — so the end it does not constrain stays `0.0`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct NativeBookSide {
    pub levels: Levels,
    /// Minimum a taker must sell into this side, in atomic units of the token it takes in.
    pub minimum_in: f64,
    /// Minimum a taker must receive from this side, in atomic units of the token it pays out.
    pub minimum_out: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NativePriceData {
    pub base_address: Bytes,
    pub quote_address: Bytes,
    /// The makers' bids: a taker fills them by selling base and receiving quote.
    pub bids: NativeBookSide,
    /// The makers' asks: a taker fills them by selling quote and receiving base.
    pub asks: NativeBookSide,
}

impl NativePriceData {
    /// Returns `None` when the book cannot be valued or the calculation is non-finite.
    pub fn calculate_tvl(&self, quote_price_data: Option<&NativePriceData>) -> Option<f64> {
        let bid_tvl = self.bids.levels.notional();
        let ask_tvl = self.asks.levels.notional();
        let total_tvl = match (self.bids.levels.is_empty(), self.asks.levels.is_empty()) {
            (false, false) => bid_tvl.midpoint(ask_tvl),
            (false, true) => bid_tvl,
            (true, false) => ask_tvl,
            (true, true) => 0.0,
        };
        if !total_tvl.is_finite() {
            return None
        }
        if let Some(quote_data) = quote_price_data {
            let price_of_quote_token = quote_data.get_mid_price(total_tvl, &self.quote_address)?;
            let converted_tvl = total_tvl * price_of_quote_token;
            return converted_tvl
                .is_finite()
                .then_some(converted_tvl)
        }
        Some(total_tvl)
    }

    /// The midpoint of the bid-side and ask-side average prices for selling `amount` of
    /// `sell_token`, or the one side that has liquidity. `None` when `sell_token` is neither side
    /// of the pair or nothing can be priced.
    pub fn get_mid_price(&self, amount: f64, sell_token: &Bytes) -> Option<f64> {
        if sell_token != &self.base_address && sell_token != &self.quote_address {
            return None;
        }
        let (bids, asks) = (&self.bids.levels, &self.asks.levels);
        let (bids_price, asks_price) = if sell_token == &self.quote_address {
            (bids.invert().average_price(amount), asks.invert().average_price(amount))
        } else {
            (bids.average_price(amount), asks.average_price(amount))
        };
        match (bids_price, asks_price) {
            (Some(bid), Some(ask)) => Some(bid.midpoint(ask)),
            (Some(bid), None) => Some(bid),
            (None, Some(ask)) => Some(ask),
            (None, None) => None,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct FirmQuoteRequest {
    pub from_address: String,
    pub src_chain: NativeSupportedChain,
    pub dst_chain: NativeSupportedChain,
    pub token_in: String,
    pub token_out: String,
    pub amount_wei: String,
    pub version: u32,
    pub allow_multihop: bool,
}

// --- Response ---
//
// The firm-quote response is deserialized in its documented shape so a change on Native's side
// fails loudly at parse time; only the fields the quote validation reads are used afterwards.

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[expect(
    dead_code,
    reason = "fields are deserialized to validate the response shape but never read"
)]
pub struct WidgetFee {
    pub signer: String,
    pub fee_recipient: String,
    pub fee_rate: f64,
}

#[derive(Debug, Clone, Deserialize)]
pub struct TxRequest {
    pub target: String,
    pub calldata: String,
    pub value: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[expect(
    dead_code,
    reason = "fields are deserialized to validate the response shape but never read"
)]
pub struct FirmQuoteOrder {
    pub pool: String,
    pub signer: String,
    pub recipient: String,
    pub seller_token: String,
    pub buyer_token: String,
    pub effective_seller_token_amount: String,
    pub seller_token_amount: String,
    pub buyer_token_amount: String,
    pub deadline_timestamp: u64,
    pub nonce: u64,
    pub quote_id: String,
    pub multi_hop: bool,
    pub signature: String,
    pub external_swap_calldata: String,
    pub amount_out_minimum: String,
    pub widget_fee: WidgetFee,
    pub widget_fee_signature: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[expect(
    dead_code,
    reason = "fields are deserialized to validate the response shape but never read"
)]
pub struct FirmQuoteResponse {
    pub success: bool,
    pub orders: Vec<FirmQuoteOrder>,
    pub widget_fee: WidgetFee,
    pub widget_fee_signature: String,
    pub recipient: String,
    pub amount_in: String,
    pub amount_out: String,
    pub amount_out_before_fee: String,
    pub fallback_swap_data_array: Option<serde_json::Value>,
    pub token_transfer_fee_on_percent: f64,
    pub tx_request: TxRequest,
    pub source: Vec<u32>,
    pub error_message: String,
    #[serde(rename = "router_version")]
    pub router_version: String,
    pub amount_in_offset: u32,
    pub amount_out_minimum_offset: u32,
}

#[derive(Debug, Clone, Deserialize)]
pub struct NativeApiErrorResponse {
    pub code: u64,
    pub message: String,
}

/// A chain Native Relay's swap API serves, resolved from the configured [`Chain`] when a feed is
/// built.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NativeSupportedChain {
    Ethereum,
    Bsc,
    Arbitrum,
    Base,
    Robinhood,
}

impl TryFrom<Chain> for NativeSupportedChain {
    type Error = String;

    fn try_from(chain: Chain) -> Result<Self, Self::Error> {
        match chain {
            Chain::Ethereum => Ok(NativeSupportedChain::Ethereum),
            Chain::Bsc => Ok(NativeSupportedChain::Bsc),
            Chain::Arbitrum => Ok(NativeSupportedChain::Arbitrum),
            Chain::Base => Ok(NativeSupportedChain::Base),
            Chain::Robinhood => Ok(NativeSupportedChain::Robinhood),
            unserved @ (Chain::Starknet |
            Chain::ZkSync |
            Chain::Unichain |
            Chain::Polygon |
            Chain::Plasma |
            Chain::Arc |
            Chain::Custom(_) |
            _) => Err(format!("Native does not serve {unserved}")),
        }
    }
}

impl NativeSupportedChain {
    /// How Native spells the chain: `?chain=` on the orderbook poll, `src_chain` and
    /// `dst_chain` in a firm quote's body.
    pub fn as_str(self) -> &'static str {
        match self {
            NativeSupportedChain::Ethereum => "ethereum",
            NativeSupportedChain::Bsc => "bsc",
            NativeSupportedChain::Arbitrum => "arbitrum",
            NativeSupportedChain::Base => "base",
            NativeSupportedChain::Robinhood => "robinhood",
        }
    }
}

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

    use super::*;

    fn addr(address: &str) -> Bytes {
        Bytes::from_str(address).unwrap()
    }

    /// A book side priced by `levels` and open to any trade size: valuing and pricing a book
    /// read its ladders only.
    fn side(levels: Vec<PriceLevel>) -> NativeBookSide {
        NativeBookSide { levels: Levels::new(levels).unwrap(), minimum_in: 0.0, minimum_out: 0.0 }
    }

    /// An entry Native got wrong costs that pair alone; the orderbook's other entries publish.
    #[test]
    fn an_entry_native_got_wrong_leaves_the_orderbook_standing() {
        let json = r#"[
                {"base_address":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","quote_address":"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48","minimum_in_base":0,"side":"bid","levels":[[1,0]]},
                {"base_address":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","quote_address":"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48","minimum_in_base":0,"side":"ask","levels":[[2,3000]]}
            ]"#;

        let NativeOrderbook(entries) = serde_json::from_str(json).unwrap();

        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].side, NativeOrderbookSide::Ask);
    }

    /// Nothing readable in the orderbook is a parsing failure, not an empty book: a published
    /// snapshot is complete, so an empty one withdraws every pair the venue had.
    #[test]
    fn an_orderbook_with_no_readable_entry_is_an_error() {
        let json = r#"[{"base_address":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","quote_address":"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48","minimum_in_base":0,"side":"bid","levels":[[1,0]]}]"#;

        assert!(serde_json::from_str::<NativeOrderbook>(json).is_err());
    }

    #[test]
    fn deserializes_native_relay_orderbook_entry() {
        let json = r#"{
            "base_symbol": "WETH",
            "quote_symbol": "USDT",
            "base_address": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
            "quote_address": "0xdac17f958d2ee523a2206206994597c13d831ec7",
            "minimum_in_base": 0,
            "side": "bid",
            "levels": [[0, 0], [0.0001, 3213.12345], [12.75786733219471, 3210.15]]
        }"#;

        let entry: NativeOrderbookEntry = serde_json::from_str(json).unwrap();
        assert_eq!(entry.side, NativeOrderbookSide::Bid);
        // The `[0, 0]` placeholder is dropped.
        assert_eq!(entry.levels.len(), 2);
        assert_eq!(entry.levels[0].quantity, 0.0001);
        assert_eq!(entry.levels[0].price, 3213.12345);
    }

    #[test]
    fn rejects_negative_orderbook_minimum() {
        let result = serde_json::from_value::<NativeOrderbookEntry>(serde_json::json!({
            "base_address": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
            "quote_address": "0xdac17f958d2ee523a2206206994597c13d831ec7",
            "minimum_in_base": -1,
            "side": "bid",
            "levels": [[1, 2_000]],
        }));

        assert!(result.is_err());
    }

    #[test]
    fn calculates_tvl_as_average_bid_ask_quote_value() {
        let price_data = NativePriceData {
            base_address: addr("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            quote_address: addr("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
            bids: side(vec![
                PriceLevel { quantity: 1.0, price: 2000.0 },
                PriceLevel { quantity: 2.0, price: 1999.0 },
            ]),
            asks: side(vec![
                PriceLevel { quantity: 1.5, price: 2001.0 },
                PriceLevel { quantity: 1.0, price: 2002.0 },
            ]),
        };

        let tvl = price_data
            .calculate_tvl(None)
            .expect("TVL should be finite");
        assert!((tvl - 5500.75).abs() < 0.01);
    }

    #[test]
    fn normalizes_tvl_through_quote_token_market() {
        let tamara = addr("0x1234567890123456789012345678901234567890");
        let usdc = addr("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
        let price_data_eth_tamara = NativePriceData {
            base_address: addr("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            quote_address: tamara.clone(),
            bids: side(vec![PriceLevel { quantity: 3.0, price: 100.0 }]),
            asks: side(vec![PriceLevel { quantity: 3.0, price: 100.0 }]),
        };
        let price_data_tamara_usdc = NativePriceData {
            base_address: tamara,
            quote_address: usdc,
            bids: side(vec![PriceLevel { quantity: 300.0, price: 9.0 }]),
            asks: side(vec![PriceLevel { quantity: 300.0, price: 11.0 }]),
        };

        assert_eq!(
            price_data_eth_tamara.calculate_tvl(Some(&price_data_tamara_usdc)),
            Some(3000.0)
        );
    }

    #[test]
    fn calculates_and_normalizes_tvl_for_one_sided_bid_books() {
        let tamara = addr("0x1234567890123456789012345678901234567890");
        let price_data_eth_tamara = NativePriceData {
            base_address: addr("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
            quote_address: tamara.clone(),
            bids: side(vec![PriceLevel { quantity: 3.0, price: 100.0 }]),
            asks: NativeBookSide::default(),
        };
        let price_data_tamara_usdc = NativePriceData {
            base_address: tamara,
            quote_address: addr("0xA0b86991c6218b36c1d19d4a2e9Eb0cE3606eB48"),
            bids: side(vec![PriceLevel { quantity: 300.0, price: 10.0 }]),
            asks: NativeBookSide::default(),
        };

        assert_eq!(price_data_eth_tamara.calculate_tvl(None), Some(300.0));
        assert_eq!(
            price_data_eth_tamara.calculate_tvl(Some(&price_data_tamara_usdc)),
            Some(3000.0)
        );
    }

    #[test]
    fn rejects_non_finite_derived_tvl() {
        let weth = addr("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2");
        let tamara = addr("0x1234567890123456789012345678901234567890");
        let usdc = addr("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
        let book = |base_address, quote_address, quantity, price| NativePriceData {
            base_address,
            quote_address,
            bids: side(vec![PriceLevel { quantity, price }]),
            asks: NativeBookSide::default(),
        };
        let overflowing_book = book(weth.clone(), usdc.clone(), 1e308, 2.0);
        let finite_book = book(weth, tamara.clone(), 1.0, 2.0);
        let overflowing_conversion = book(tamara, usdc, 2.0, 1e308);

        assert_eq!(overflowing_book.calculate_tvl(None), None);
        assert_eq!(finite_book.calculate_tvl(Some(&overflowing_conversion)), None);
    }
}