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
#[macro_use]
extern crate derive_setters;
#[macro_use]
extern crate fomat_macros;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate thiserror;

mod coin_info;
mod simple_price;
mod utils;

use const_format::concatcp;

use isahc::HttpClient;

pub use crate::coin_info::*;
pub use crate::simple_price::*;

const API: &str = "https://api.coingecko.com/api/v3/";

pub struct Client {
    http: HttpClient,
}

impl Client {
    pub fn new(http: HttpClient) -> Self {
        Self { http }
    }

    /// Check if CoinGecko is reachable
    pub async fn ping(&self) -> Result<Ping, Error> {
        const PING: &str = concatcp!(crate::API, "/ping");

        utils::get_json(&self.http, PING).await
    }

    /// Fetches the current price of any cryptocurrencies in any other supported currencies you need.
    pub async fn simple_price(&self, req: SimplePriceReq) -> Result<SimplePrices, Error> {
        const SIMPLE: &str = concatcp!(crate::API, "/simple/price");

        let uri = fomat!((SIMPLE) "?" (req.query()));

        utils::get_json(&self.http, &uri).await
    }

    /// Fetches detailed information about a particular coin by its ID.
    pub async fn coin_info(&self, coin: &str) -> Result<CoinInfo, Error> {
        const COINS: &str = concatcp!(crate::API, "/coins");

        let uri = fomat!((COINS) "/" (coin));

        utils::get_json(&self.http, &uri).await
    }

    /// Fetches a list of coins supported by CoinGecko
    pub async fn coins_list(&self) -> Result<Vec<Coin>, Error> {
        const COINS_LIST: &str = concatcp!(crate::API, "/coins/list");

        utils::get_json(&self.http, COINS_LIST).await
    }
}

#[derive(Error, Debug)]
pub enum Error {
    #[error("HTTP error")]
    Http(#[from] isahc::Error),
    #[error("IO error")]
    Io(#[from] std::io::Error),
    #[error("Deserialization error")]
    Deserialization(#[from] serde_json::Error),
}

#[derive(Debug, Deserialize)]
pub struct Coin {
    pub id: String,
    pub symbol: String,
    pub name: String,
}

#[derive(Debug, Deserialize)]
pub struct Ping {
    gecko_says: String,
}