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
use ethers_core::types::U256;

use async_trait::async_trait;
use reqwest::Client;
use serde::Deserialize;
use url::Url;

use crate::gas_oracle::{GasCategory, GasOracle, GasOracleError};

const GAS_NOW_URL: &str = "https://www.gasnow.org/api/v1/gas/price";

/// A client over HTTP for the [GasNow](https://www.gasnow.org/api/v1/gas/price) gas tracker API
/// that implements the `GasOracle` trait
#[derive(Debug)]
pub struct GasNow {
    client: Client,
    url: Url,
    gas_category: GasCategory,
}

impl Default for GasNow {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Deserialize)]
struct GasNowResponse {
    data: GasNowResponseInner,
}

#[derive(Deserialize)]
struct GasNowResponseInner {
    #[serde(rename = "top50")]
    top_50: u64,
    #[serde(rename = "top200")]
    top_200: u64,
    #[serde(rename = "top400")]
    top_400: u64,
}

impl GasNow {
    /// Creates a new [GasNow](https://gasnow.org) gas price oracle.
    pub fn new() -> Self {
        let url = Url::parse(GAS_NOW_URL).expect("invalid url");

        Self {
            client: Client::new(),
            url,
            gas_category: GasCategory::Standard,
        }
    }

    /// Sets the gas price category to be used when fetching the gas price.
    pub fn category(mut self, gas_category: GasCategory) -> Self {
        self.gas_category = gas_category;
        self
    }
}

#[async_trait]
impl GasOracle for GasNow {
    async fn fetch(&self) -> Result<U256, GasOracleError> {
        let res = self
            .client
            .get(self.url.as_ref())
            .send()
            .await?
            .json::<GasNowResponse>()
            .await?;

        let gas_price = match self.gas_category {
            GasCategory::SafeLow => U256::from(res.data.top_400),
            GasCategory::Standard => U256::from(res.data.top_200),
            _ => U256::from(res.data.top_50),
        };

        Ok(gas_price)
    }
}