tycho-simulation 0.482.4

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
//! Metric book feed for the `api.metric.xyz` v1 API.
//!
//! Endpoint reference: <https://docs.metric.xyz>

use std::{future::Future, num::NonZeroUsize, time::Duration};

use reqwest::Url;

use crate::{
    book::{BookFeedConfig, BookSnapshot, ReceivedAt},
    pamm::protocols::metric::{
        client::{MetricClient, DEFAULT_BID_ASK_CONCURRENCY},
        source::MetricBookSource,
        FALLBACK_PROTOCOL_SYSTEM, PROTOCOL_SYSTEM,
    },
    snapshot_feed::{
        errors::FeedError,
        http::{default_http_feed_config, run_http_poll_feed, HttpFeedConfig},
        Publisher, SnapshotFeed,
    },
};

/// Metric's book feed: polls the metadata and batch bid/ask endpoints and publishes every poll
/// as a complete [`BookSnapshot`]. Built through [`MetricFeedBuilder`]. `Debug` output omits the
/// API key.
#[derive(Debug, Clone)]
pub struct MetricFeed {
    feed_config: HttpFeedConfig,
    source: MetricBookSource,
}

/// Builds a [`MetricFeed`] from the shared [`BookFeedConfig`] and the Bearer trading key. The feed
/// talks to Metric's public API unless [`base_url`](Self::base_url) says otherwise.
pub struct MetricFeedBuilder {
    protocol_system: &'static str,
    book_config: BookFeedConfig,
    base_url: Option<String>,
    api_key: String,
    bid_ask_concurrency: NonZeroUsize,
    feed_config: HttpFeedConfig,
}

impl MetricFeedBuilder {
    /// `api_key` is the Bearer trading key the batch bid/ask endpoint requires; without a
    /// valid one no pool is quotable and the feed publishes empty books.
    pub fn new(book_config: BookFeedConfig, api_key: String) -> Self {
        Self {
            book_config,
            base_url: None,
            api_key,
            bid_ask_concurrency: DEFAULT_BID_ASK_CONCURRENCY,
            feed_config: Self::default_feed_config(),
            protocol_system: PROTOCOL_SYSTEM,
        }
    }

    /// Points the feed at another Metric deployment; [`build`](Self::build) rejects a value
    /// that is not a URL.
    pub fn base_url(mut self, base_url: String) -> Self {
        self.base_url = Some(base_url);
        self
    }

    /// How many of a poll's batch bid/ask requests run at once.
    ///
    /// Each request quotes up to 100 pools, so this only matters for a venue serving more than
    /// that: it keeps a poll's duration flat as the venue adds pools instead of growing until the
    /// loop's `request_timeout` discards the whole poll. Lower it to be gentler on the API.
    pub fn bid_ask_concurrency(mut self, requests_in_flight: NonZeroUsize) -> Self {
        self.bid_ask_concurrency = requests_in_flight;
        self
    }

    /// The feed tuning a new builder starts from.
    ///
    /// Measured live, Metric's quotes change about every 2 s, and a poll — a page of pool
    /// metadata, then a batch of bid/asks — answers in 0.6-1.5 s, so it is polled every 2 s:
    /// once per quote change, and longer than a slow poll, which a shorter interval would follow
    /// with the next poll straight away. A poll that hangs gives up after 5 s, and a book is
    /// withdrawn once 15 s pass without a refresh: longer than one hung poll and its retry, so a
    /// single slow poll does not blank the book.
    ///
    /// Spread from it to change one field:
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use tycho_simulation::pamm::protocols::metric::feed::MetricFeedBuilder;
    /// # use tycho_simulation::snapshot_feed::http::HttpFeedConfig;
    /// let tuned = HttpFeedConfig {
    ///     poll_interval: Duration::from_secs(10),
    ///     ..MetricFeedBuilder::default_feed_config()
    /// };
    /// ```
    pub fn default_feed_config() -> HttpFeedConfig {
        HttpFeedConfig {
            poll_interval: Duration::from_secs(2),
            request_timeout: Duration::from_secs(5),
            max_snapshot_age: Some(Duration::from_secs(15)),
            ..default_http_feed_config()
        }
    }

    /// Settles this venue's swaps through Tycho's `MetricFallbackRouter`, which retries
    /// against a solver-named fallback pool when the venue reverts. Components then carry
    /// [`FALLBACK_PROTOCOL_SYSTEM`] rather than [`PROTOCOL_SYSTEM`], which is what selects
    /// the fallback encoder. Off by default.
    pub fn with_fallback_router(mut self) -> Self {
        self.protocol_system = FALLBACK_PROTOCOL_SYSTEM;
        self
    }

    /// Tune the price feed loop (poll cadence, request timeout, failure limit)
    pub fn feed_config(mut self, feed_config: HttpFeedConfig) -> Self {
        self.feed_config = feed_config;
        self
    }

    /// Fails for an empty trading key, for a base URL that is not one, and for a chain with no
    /// numeric chain id, which is all Metric's API is addressed by. Whether the venue serves
    /// that chain is Metric's own answer, and the first poll carries it.
    pub fn build(self) -> Result<MetricFeed, FeedError> {
        // Metric answers an empty bearer token with the same `Unknown chainId` it refuses an
        // unserved chain with, where a key it rejects is a plain 401. A key that authenticates
        // nothing would therefore read as a refusal and end the feed, so it stops here.
        if self.api_key.is_empty() {
            return Err(FeedError::InvalidInput("Metric trading key is empty".to_string()));
        }
        let chain_id = self.book_config.chain_id()?;
        // A base URL that is not one fails every poll the same way, so the feed does not start.
        if let Some(base_url) = &self.base_url {
            Url::parse(base_url).map_err(|error| {
                FeedError::InvalidInput(format!("Metric base URL {base_url}: {error}"))
            })?;
        }
        Ok(MetricFeed {
            feed_config: self.feed_config,
            source: MetricBookSource {
                protocol_system: self.protocol_system,
                book_config: self.book_config,
                client: MetricClient::new(
                    self.base_url.as_deref(),
                    chain_id,
                    self.api_key,
                    self.bid_ask_concurrency,
                ),
            },
        })
    }
}

impl SnapshotFeed for MetricFeed {
    type Snapshot = BookSnapshot<ReceivedAt>;
    type Error = FeedError;

    fn run(
        self,
        publisher: Publisher<Self::Snapshot>,
    ) -> impl Future<Output = Result<(), FeedError>> + Send + 'static {
        run_http_poll_feed(self.feed_config, publisher, self.source)
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, sync::Arc};

    use tycho_common::models::Chain;

    use super::*;

    fn builder(chain: Chain) -> MetricFeedBuilder {
        MetricFeedBuilder::new(
            BookFeedConfig { chain, tokens: Arc::new(HashMap::new()), min_tvl_usd: 0.0 },
            "secret_key".to_string(),
        )
    }

    #[test]
    fn debug_output_omits_the_api_key() {
        let feed = builder(Chain::Ethereum)
            .base_url("https://metric.example".to_string())
            .build()
            .unwrap();
        let rendered = format!("{feed:?}");

        assert!(!rendered.contains("secret_key"));
        assert!(rendered.contains("metric.example"));
    }

    /// A base URL the venue cannot be reached at would fail every poll alike, so the feed does
    /// not start.
    #[test]
    fn a_base_url_that_is_not_one_is_rejected() {
        let error = builder(Chain::Ethereum)
            .base_url("api.metric.xyz".to_string())
            .build()
            .unwrap_err();

        assert!(matches!(error, FeedError::InvalidInput(_)), "{error}");
    }

    /// Metric answers an empty bearer token the way it refuses a chain, which no retry would
    /// recover from, so the feed does not start without a key.
    #[test]
    fn an_empty_trading_key_is_rejected() {
        let config = BookFeedConfig {
            chain: Chain::Ethereum,
            tokens: Arc::new(HashMap::new()),
            min_tvl_usd: 0.0,
        };

        let error = MetricFeedBuilder::new(config, String::new())
            .build()
            .unwrap_err();

        assert!(matches!(error, FeedError::InvalidInput(_)), "{error}");
    }
}