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
use std::collections::HashMap;
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, GWEI_TO_WEI};
const ETH_GAS_STATION_URL_PREFIX: &str = "https://ethgasstation.info/api/ethgasAPI.json";
#[derive(Clone, Debug)]
pub struct EthGasStation {
client: Client,
url: Url,
gas_category: GasCategory,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct EthGasStationResponse {
pub safe_low: f64,
pub average: u64,
pub fast: u64,
pub fastest: u64,
#[serde(rename = "block_time")]
pub block_time: f64,
pub block_num: u64,
pub speed: f64,
pub safe_low_wait: f64,
pub avg_wait: f64,
pub fast_wait: f64,
pub fastest_wait: f64,
pub gas_price_range: HashMap<u64, f64>,
}
impl EthGasStation {
pub fn new(api_key: Option<&'static str>) -> Self {
let url = match api_key {
Some(key) => format!("{}?api-key={}", ETH_GAS_STATION_URL_PREFIX, key),
None => ETH_GAS_STATION_URL_PREFIX.to_string(),
};
let url = Url::parse(&url).expect("invalid url");
EthGasStation { client: Client::new(), url, gas_category: GasCategory::Standard }
}
pub fn category(mut self, gas_category: GasCategory) -> Self {
self.gas_category = gas_category;
self
}
pub async fn query(&self) -> Result<EthGasStationResponse, GasOracleError> {
Ok(self.client.get(self.url.as_ref()).send().await?.json::<EthGasStationResponse>().await?)
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl GasOracle for EthGasStation {
async fn fetch(&self) -> Result<U256, GasOracleError> {
let res = self.query().await?;
let gas_price = match self.gas_category {
GasCategory::SafeLow => U256::from((res.safe_low.ceil() as u64 * GWEI_TO_WEI) / 10),
GasCategory::Standard => U256::from((res.average * GWEI_TO_WEI) / 10),
GasCategory::Fast => U256::from((res.fast * GWEI_TO_WEI) / 10),
GasCategory::Fastest => U256::from((res.fastest * GWEI_TO_WEI) / 10),
};
Ok(gas_price)
}
async fn estimate_eip1559_fees(&self) -> Result<(U256, U256), GasOracleError> {
Err(GasOracleError::Eip1559EstimationNotSupported)
}
}