tycho-simulation 0.486.0

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
use num_bigint::BigUint;
use num_traits::{ToPrimitive, Zero};
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DefaultOnNull, DisplayFromStr};
use tycho_common::Bytes;

use crate::{serde_helpers::evm_address, snapshot_feed::errors::FeedError};

const Q64_FLOAT: f64 = 18_446_744_073_709_551_616.0;

/// The body Metric answers a request it will not serve with.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct MetricApiError {
    pub error: String,
}

impl MetricApiError {
    /// Whether this is Metric stating it does not serve the chain its path named. A pool it
    /// does not know answers with the same status, so the chain is named in the message.
    pub fn refuses_the_chain(&self) -> bool {
        self.error
            .starts_with("Unknown chainId")
    }
}

/// The `PaginatedMetadataResponse` envelope returned by `GET /public/v1/evm/{chain_id}/metadata`.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaginatedMetadataResponse {
    pub data: Vec<MetricMetadata>,
    /// `offset` for the next page, or `None` on the last page.
    pub next_offset: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricMetadata {
    #[serde(deserialize_with = "evm_address::deserialize")]
    pub pool_address: Bytes,
    #[serde(deserialize_with = "evm_address::deserialize")]
    pub token0: Bytes,
    #[serde(deserialize_with = "evm_address::deserialize")]
    pub token1: Bytes,
    /// Total value locked in the requested fiat currency, used directly as the component TVL.
    /// Absent when Metric has no price for the pool.
    pub tvl_fiat: Option<f64>,
    /// `0` trades normally; anything higher refuses some or all swaps. `None` when the response
    /// omits the field.
    #[serde(default)]
    pub pause_level: Option<u8>,
}

impl MetricMetadata {
    /// Whether the pool accepts swaps. Metric routes only to pools at pause level `0`; a pool
    /// whose metadata carries no pause level is treated as unpaused.
    pub fn is_unpaused(&self) -> bool {
        self.pause_level.unwrap_or(0) == 0
    }
}

/// The body `POST /public/v1/evm/{chain_id}/bid_ask/batch` is sent with.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct MetricBatchBidAskRequest {
    /// Checksummed pool addresses, at most 100.
    pub pools: Vec<String>,
}

/// The answer of `POST /public/v1/evm/{chain_id}/bid_ask/batch`: one result per requested pool.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct MetricBatchBidAskResponse {
    pub results: Vec<MetricBatchBidAskResult>,
}

/// One pool's entry in a batch bid/ask answer: its quote, or the error the single-pool endpoint
/// would have answered for it.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricBatchBidAskResult {
    #[serde(deserialize_with = "evm_address::deserialize")]
    pub pool_address: Bytes,
    #[serde(default)]
    pub quote: Option<MetricBidAskResponse>,
    #[serde(default)]
    pub error: Option<MetricBatchBidAskError>,
}

impl MetricBatchBidAskResult {
    /// The pool's quote, or why Metric did not quote it.
    pub fn into_quote(self) -> Result<MetricBidAskResponse, FeedError> {
        match (self.quote, self.error) {
            (Some(quote), _) => Ok(quote),
            (None, Some(error)) => Err(error.into()),
            (None, None) => Err(FeedError::Parsing(format!(
                "Metric batch bid/ask answered neither a quote nor an error for pool {}",
                self.pool_address
            ))),
        }
    }
}

/// A pool a batch bid/ask request could not quote.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct MetricBatchBidAskError {
    /// The HTTP status the single-pool endpoint would have answered with.
    pub status: u16,
    pub error: String,
}

impl From<MetricBatchBidAskError> for FeedError {
    /// Classified as a failed single-pool request would be: fatal only when Metric names the
    /// chain as one it does not serve.
    fn from(error: MetricBatchBidAskError) -> Self {
        let message = format!("Metric bid/ask HTTP error {}: {}", error.status, error.error);
        if (MetricApiError { error: error.error }).refuses_the_chain() {
            FeedError::Fatal(message)
        } else {
            FeedError::Connection(message)
        }
    }
}

/// Metric returns its numeric fields as decimal strings; they are parsed once at deserialization
/// (`DisplayFromStr`) so the pricing paths never re-parse, and serialize back to the same form.
#[serde_as]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricBidAskResponse {
    /// Fee-adjusted bid price, Q64.64.
    #[serde_as(as = "DisplayFromStr")]
    pub bid_adj: BigUint,
    /// Fee-adjusted ask price, Q64.64.
    #[serde_as(as = "DisplayFromStr")]
    pub ask_adj: BigUint,
    /// Token0 available for the quote (raw units). `None` when the pool cannot currently quote.
    #[serde_as(as = "Option<DisplayFromStr>")]
    pub total_token0_available: Option<BigUint>,
    /// Token1 available for the quote (raw units). `None` when the pool cannot currently quote.
    #[serde_as(as = "Option<DisplayFromStr>")]
    pub total_token1_available: Option<BigUint>,
    /// Server Unix timestamp (seconds) when the quote was produced.
    pub server_ts: u64,
    /// Price-provider health for this quote: `healthy`, `feed_down` (no valid price right now),
    /// or `internal_error`. `None` when the response omits the field.
    pub price_provider_status: Option<String>,
    /// Per-side depth bins. Absent on older responses and explicitly `null` when the endpoint is
    /// queried with `depth=false`; both decode to an empty book.
    #[serde_as(as = "DefaultOnNull")]
    #[serde(default)]
    pub depth: MetricDepth,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct MetricDepth {
    #[serde(default)]
    pub asks: Vec<MetricDepthBin>,
    #[serde(default)]
    pub bids: Vec<MetricDepthBin>,
}

#[serde_as]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricDepthBin {
    pub bin_idx: i64,
    /// Fee-adjusted price at this bin boundary, Q64.64.
    #[serde_as(as = "DisplayFromStr")]
    pub price: BigUint,
    /// Cumulative output-token volume from the current position to this boundary (raw units).
    #[serde_as(as = "DisplayFromStr")]
    pub cumulative_volume: BigUint,
    /// Cumulative input-token amount required to reach this boundary (raw units). Used to drive
    /// the input-based depth walk so pricing matches Metric's own accounting.
    #[serde_as(as = "DisplayFromStr")]
    pub cumulative_input_volume: BigUint,
}

impl MetricBidAskResponse {
    /// The bid price, or `None` when the pool quotes no bid: the API then sends `bidAdj = 0`.
    pub fn bid_price(&self) -> Result<Option<f64>, FeedError> {
        if self.bid_adj.is_zero() {
            return Ok(None);
        }
        q64_to_f64(&self.bid_adj).map(Some)
    }

    /// The ask price, or `None` when the pool quotes no ask: the API then sends
    /// `askAdj = 2^128 - 1`.
    pub fn ask_price(&self) -> Result<Option<f64>, FeedError> {
        if self.ask_adj == BigUint::from(u128::MAX) {
            return Ok(None);
        }
        q64_to_f64(&self.ask_adj).map(Some)
    }

    pub fn total_token0_available(&self) -> Result<BigUint, FeedError> {
        self.total_token0_available
            .clone()
            .ok_or_else(|| FeedError::Parsing("totalToken0Available is null".to_string()))
    }

    pub fn total_token1_available(&self) -> Result<BigUint, FeedError> {
        self.total_token1_available
            .clone()
            .ok_or_else(|| FeedError::Parsing("totalToken1Available is null".to_string()))
    }

    /// Whether the pool can currently be quoted.
    ///
    /// The API's own `priceProviderStatus` is the primary gate: anything other than `healthy`
    /// (e.g. `feed_down`, `internal_error`) is not quotable. When the field is absent the
    /// structural checks below decide alone; they are always applied as defence in depth:
    /// both availability figures must be non-null and the order book non-empty. Pools with empty
    /// depth (e.g. `bidAdj=0` / `askAdj` sentinel and no bins) are treated as not quotable, since
    /// depth-based pricing has no bins to walk.
    pub fn is_quotable(&self) -> bool {
        if let Some(status) = self.price_provider_status.as_deref() {
            if status != "healthy" {
                return false;
            }
        }
        self.total_token0_available.is_some() &&
            self.total_token1_available.is_some() &&
            !(self.depth.bids.is_empty() && self.depth.asks.is_empty())
    }
}

/// Converts a Q64.64 fixed-point value to an f64 price.
fn q64_to_f64(value: &BigUint) -> Result<f64, FeedError> {
    let raw = value
        .to_f64()
        .ok_or_else(|| FeedError::Parsing(format!("Q64 price does not fit in f64: {value}")))?;
    Ok(raw / Q64_FLOAT)
}

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

    use rstest::rstest;

    use super::*;

    #[test]
    fn sentinel_sides_have_no_price() {
        let quote = |bid: String, ask: String| MetricBidAskResponse {
            bid_adj: bid.parse().unwrap(),
            ask_adj: ask.parse().unwrap(),
            total_token0_available: None,
            total_token1_available: None,
            server_ts: 0,
            price_provider_status: None,
            depth: MetricDepth::default(),
        };

        let unquoted = quote("0".to_string(), u128::MAX.to_string());
        assert_eq!(unquoted.bid_price().unwrap(), None);
        assert_eq!(unquoted.ask_price().unwrap(), None);

        // One below the no-ask sentinel is still a price.
        let quoted = quote("1".to_string(), (u128::MAX - 1).to_string());
        assert!(quoted.bid_price().unwrap().is_some());
        assert!(quoted.ask_price().unwrap().is_some());
    }

    #[test]
    fn bid_ask_deserializes_depth_bins() {
        let response: MetricBidAskResponse = serde_json::from_value(serde_json::json!({
            "bidAdj": "55340232221128654848000",
            "askAdj": "55524699661865750400000",
            "totalToken0Available": "1000000000000000000",
            "totalToken1Available": "3000000000",
            "serverTs": 0,
            "depth": {
                "asks": [{
                    "binIdx": 0,
                    "price": "57184906628499610009600",
                    "cumulativeVolume": "1000000000000000000",
                    "cumulativeInputVolume": "3100000000",
                    "priceImpactE6": "33333"
                }],
                "bids": [{
                    "binIdx": -1,
                    "price": "53495557813757699686400",
                    "cumulativeVolume": "3000000000",
                    "cumulativeInputVolume": "1000000000000000000",
                    "priceImpactE6": "33333"
                }]
            }
        }))
        .unwrap();

        assert_eq!(response.depth.asks.len(), 1);
        assert_eq!(response.depth.bids[0].bin_idx, -1);
        assert_eq!(q64_to_f64(&response.depth.asks[0].price).unwrap(), 3100.0);
        assert_eq!(response.depth.bids[0].cumulative_volume, BigUint::from(3_000_000_000u64));
        assert_eq!(
            response.depth.bids[0].cumulative_input_volume,
            BigUint::from(1_000_000_000_000_000_000u64)
        );

        // Numeric fields round-trip back to the same decimal-string JSON form.
        let serialized = serde_json::to_value(&response).unwrap();
        assert_eq!(serialized["bidAdj"], "55340232221128654848000");
        assert_eq!(serialized["totalToken1Available"], "3000000000");
        assert_eq!(serialized["depth"]["asks"][0]["cumulativeInputVolume"], "3100000000");
    }

    #[test]
    fn bid_ask_null_totals_are_not_quotable() {
        let response: MetricBidAskResponse = serde_json::from_value(serde_json::json!({
            "bidAdj": "55340232221128654848000",
            "askAdj": "55524699661865750400000",
            "totalToken0Available": null,
            "totalToken1Available": null,
            "serverTs": 1_770_053_095u64,
        }))
        .unwrap();

        assert_eq!(response.total_token0_available, None);
        assert!(!response.is_quotable());
    }

    #[test]
    fn bid_ask_absent_totals_decode_as_none() {
        let response: MetricBidAskResponse = serde_json::from_value(serde_json::json!({
            "bidAdj": "55340232221128654848000",
            "askAdj": "55524699661865750400000",
            "serverTs": 1_770_053_095u64,
        }))
        .unwrap();

        assert_eq!(response.total_token0_available, None);
        assert_eq!(response.total_token1_available, None);
        assert_eq!(response.price_provider_status, None);
    }

    #[test]
    fn bid_ask_null_depth_decodes_as_empty() {
        // `depth=false` makes the endpoint return an explicit null rather than omitting the key.
        let response: MetricBidAskResponse = serde_json::from_value(serde_json::json!({
            "bidAdj": "55340232221128654848000",
            "askAdj": "55524699661865750400000",
            "totalToken0Available": "1000000000000000000",
            "totalToken1Available": "3000000000",
            "serverTs": 0,
            "depth": null,
        }))
        .unwrap();

        assert_eq!(response.depth, MetricDepth::default());
        assert!(!response.is_quotable());
    }

    #[test]
    fn bid_ask_empty_depth_is_not_quotable() {
        // Real degenerate pool observed on Base: bidAdj=0, askAdj=uint128 max sentinel, no depth.
        let response: MetricBidAskResponse = serde_json::from_value(serde_json::json!({
            "bidAdj": "0",
            "askAdj": "340282366920938463463374607431768211455",
            "totalToken0Available": "11419581536531814910",
            "totalToken1Available": "12935676138",
            "serverTs": 1_784_611_959u64,
        }))
        .unwrap();

        assert!(response.depth.bids.is_empty() && response.depth.asks.is_empty());
        assert!(!response.is_quotable());
    }

    #[test]
    fn bid_ask_unhealthy_provider_status_is_not_quotable() {
        // Structurally complete quote, but the API reports the price provider as down: the
        // explicit status must veto quotability regardless of the structural checks.
        let quotable = serde_json::json!({
            "bidAdj": "55340232221128654848000",
            "askAdj": "55524699661865750400000",
            "totalToken0Available": "1000000000000000000",
            "totalToken1Available": "3000000000",
            "serverTs": 1_787_710_476u64,
            "depth": {
                "asks": [{
                    "binIdx": 0,
                    "price": "57184906628499610009600",
                    "cumulativeVolume": "1000000000000000000",
                    "cumulativeInputVolume": "3100000000"
                }],
                "bids": []
            }
        });

        for (status, expected) in
            [("healthy", true), ("feed_down", false), ("internal_error", false)]
        {
            let mut payload = quotable.clone();
            payload["priceProviderStatus"] = serde_json::json!(status);
            let response: MetricBidAskResponse = serde_json::from_value(payload).unwrap();
            assert_eq!(response.is_quotable(), expected, "status {status}");
        }

        // Absent status (older responses): structural checks decide.
        let response: MetricBidAskResponse = serde_json::from_value(quotable).unwrap();
        assert_eq!(response.price_provider_status, None);
        assert!(response.is_quotable());
    }

    #[test]
    fn paginated_metadata_deserializes_tvl_fiat() {
        let response: PaginatedMetadataResponse = serde_json::from_value(serde_json::json!({
            "data": [{
                "pair": "ethusdc",
                "poolAddress": "0xbF48bCf474d57fF82A3215319229e0DE1476A557",
                "token0": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
                "token1": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
                "tvlFiat": 1234.56
            }],
            "total": 1,
            "nextOffset": null
        }))
        .unwrap();

        assert_eq!(response.next_offset, None);
        assert_eq!(response.data[0].tvl_fiat, Some(1234.56));
    }

    fn metadata_with_pause_level(pause_level: Option<u8>) -> MetricMetadata {
        let mut pool = serde_json::json!({
            "poolAddress": "0xbF48bCf474d57fF82A3215319229e0DE1476A557",
            "token0": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
            "token1": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
        });
        if let Some(level) = pause_level {
            pool["pauseLevel"] = serde_json::json!(level);
        }
        serde_json::from_value(pool).unwrap()
    }

    #[rstest]
    #[case::trading(Some(0), true)]
    #[case::partly_paused(Some(1), false)]
    #[case::fully_paused(Some(2), false)]
    #[case::no_pause_level(None, true)]
    fn only_pause_level_zero_is_unpaused(#[case] pause_level: Option<u8>, #[case] unpaused: bool) {
        let pool = metadata_with_pause_level(pause_level);

        assert_eq!(pool.pause_level, pause_level);
        assert_eq!(pool.is_unpaused(), unpaused);
    }

    #[test]
    fn batch_bid_ask_carries_quotes_and_per_pool_errors() {
        let response: MetricBatchBidAskResponse = serde_json::from_value(serde_json::json!({
            "results": [
                {
                    "poolAddress": "0xf85afbadecc7f23dd173ed706f07d9c7e2473e24",
                    "quote": {
                        "pair": "WETH/USDC",
                        "poolAddress": "0xF85AfbADeCC7F23Dd173ed706f07d9C7e2473e24",
                        "priceProviderStatus": "healthy",
                        "bidAdj": "49940417631045696435290",
                        "askAdj": "49945012360825322506424",
                        "totalToken0Available": "24503618827789131821",
                        "totalToken1Available": "49785157539",
                        "serverTs": 1790508850,
                        "depth": null
                    }
                },
                {
                    "poolAddress": "0x0000000000000000000000000000000000000001",
                    "error": { "status": 404, "error": "Pair metadata not found" }
                },
                { "poolAddress": "0x0000000000000000000000000000000000000002" }
            ]
        }))
        .unwrap();

        let [quoted, failed, empty] = <[_; 3]>::try_from(response.results).unwrap();
        // Addresses decode to bytes, whatever casing the venue answers in.
        assert_eq!(
            quoted.pool_address,
            Bytes::from_str("0xF85AfbADeCC7F23Dd173ed706f07d9C7e2473e24").unwrap()
        );
        assert_eq!(quoted.into_quote().unwrap().server_ts, 1790508850);
        let error = failed.into_quote().unwrap_err();
        assert!(matches!(error, FeedError::Connection(_)), "{error}");
        assert!(
            error
                .to_string()
                .contains("Pair metadata not found"),
            "{error}"
        );
        assert!(matches!(empty.into_quote(), Err(FeedError::Parsing(_))));
    }

    #[rstest]
    #[case::an_unknown_pool("Pair metadata not found", false)]
    #[case::an_unserved_chain("Unknown chainId: 130", true)]
    fn only_a_batch_entry_refusing_the_chain_is_fatal(#[case] message: &str, #[case] fatal: bool) {
        let error: FeedError =
            MetricBatchBidAskError { status: 404, error: message.to_string() }.into();

        assert_eq!(error.is_fatal(), fatal, "{error}");
    }
}