|
| 1 | +use async_trait::async_trait; |
| 2 | +use rust_decimal::Decimal; |
| 3 | +use serde::Deserialize; |
| 4 | +use std::time::Duration; |
| 5 | +use thiserror::Error; |
| 6 | + |
| 7 | +#[derive(Error, Debug)] |
| 8 | +pub enum PriceFetcherError { |
| 9 | + #[error("Request error: {0}")] |
| 10 | + Request(#[from] reqwest::Error), |
| 11 | + #[error("Rate limit exceeded (429)")] |
| 12 | + RateLimit, |
| 13 | + #[error("Response status error: {0}")] |
| 14 | + Status(u16), |
| 15 | + #[error("Parse error: {0}")] |
| 16 | + Parse(String), |
| 17 | + #[error("Client build error: {0}")] |
| 18 | + Build(String), |
| 19 | +} |
| 20 | + |
| 21 | +#[derive(Deserialize)] |
| 22 | +struct BitcoinResponse { |
| 23 | + bitcoin: BitcoinPrice, |
| 24 | +} |
| 25 | + |
| 26 | +#[derive(Deserialize)] |
| 27 | +struct BitcoinPrice { |
| 28 | + usd: Decimal, |
| 29 | +} |
| 30 | + |
| 31 | +#[async_trait] |
| 32 | +pub trait PriceFetcher { |
| 33 | + async fn fetch_price(&self) -> Result<Decimal, PriceFetcherError>; |
| 34 | +} |
| 35 | + |
| 36 | +pub struct CoingeckoPriceFetcher { |
| 37 | + client: reqwest::Client, |
| 38 | +} |
| 39 | + |
| 40 | +impl CoingeckoPriceFetcher { |
| 41 | + const URL: &'static str = "https://api.coingecko.com/api/v3"; |
| 42 | + const REQUEST_TIMEOUT: Duration = Duration::from_secs(5); |
| 43 | + |
| 44 | + pub fn new() -> Result<Self, PriceFetcherError> { |
| 45 | + let client = reqwest::Client::builder() |
| 46 | + .user_agent("simplicity-dex/1.0") |
| 47 | + .timeout(Self::REQUEST_TIMEOUT) |
| 48 | + .build() |
| 49 | + .map_err(|e| PriceFetcherError::Build(e.to_string()))?; |
| 50 | + |
| 51 | + Ok(Self { client }) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +#[async_trait] |
| 56 | +impl PriceFetcher for CoingeckoPriceFetcher { |
| 57 | + async fn fetch_price(&self) -> Result<Decimal, PriceFetcherError> { |
| 58 | + let url = format!("{}/simple/price", Self::URL); |
| 59 | + |
| 60 | + let resp = self |
| 61 | + .client |
| 62 | + .get(&url) |
| 63 | + .query(&[("ids", "bitcoin"), ("vs_currencies", "usd"), ("precision", "8")]) |
| 64 | + .send() |
| 65 | + .await?; |
| 66 | + |
| 67 | + match resp.status() { |
| 68 | + reqwest::StatusCode::OK => { |
| 69 | + let data: BitcoinResponse = resp.json().await.map_err(|e| PriceFetcherError::Parse(e.to_string()))?; |
| 70 | + Ok(data.bitcoin.usd) |
| 71 | + } |
| 72 | + reqwest::StatusCode::TOO_MANY_REQUESTS => Err(PriceFetcherError::RateLimit), |
| 73 | + status => Err(PriceFetcherError::Status(status.as_u16())), |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments