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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
pub mod contract;
pub mod errors;
mod transaction;
use errors::EtherscanError;
use ethers_core::{abi::Address, types::Chain};
use reqwest::{header, Url};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::borrow::Cow;
pub type Result<T> = std::result::Result<T, EtherscanError>;
#[derive(Clone, Debug)]
pub struct Client {
client: reqwest::Client,
api_key: String,
etherscan_api_url: Url,
etherscan_url: Url,
}
impl Client {
pub fn new(chain: Chain, api_key: impl Into<String>) -> Result<Self> {
let (etherscan_api_url, etherscan_url) = match chain {
Chain::Mainnet => {
(Url::parse("https://api.etherscan.io/api"), Url::parse("https://etherscan.io"))
}
Chain::Ropsten | Chain::Kovan | Chain::Rinkeby | Chain::Goerli => {
let chain_name = chain.to_string().to_lowercase();
(
Url::parse(&format!("https://api-{}.etherscan.io/api", chain_name)),
Url::parse(&format!("https://{}.etherscan.io", chain_name)),
)
}
Chain::Polygon => (
Url::parse("https://api.polygonscan.com/api"),
Url::parse("https://polygonscan.com"),
),
Chain::PolygonMumbai => (
Url::parse("https://api-testnet.polygonscan.com/api"),
Url::parse("https://mumbai.polygonscan.com"),
),
Chain::Avalanche => {
(Url::parse("https://api.snowtrace.io/api"), Url::parse("https://snowtrace.io"))
}
Chain::AvalancheFuji => (
Url::parse("https://api-testnet.snowtrace.io/api"),
Url::parse("https://testnet.snowtrace.io"),
),
chain => return Err(EtherscanError::ChainNotSupported(chain)),
};
Ok(Self {
client: Default::default(),
api_key: api_key.into(),
etherscan_api_url: etherscan_api_url.expect("is valid http"),
etherscan_url: etherscan_url.expect("is valid http"),
})
}
pub fn new_from_env(chain: Chain) -> Result<Self> {
let api_key = match chain {
Chain::Avalanche | Chain::AvalancheFuji => std::env::var("SNOWTRACE_API_KEY")?,
Chain::Polygon | Chain::PolygonMumbai => std::env::var("POLYGONSCAN_API_KEY")?,
Chain::Mainnet | Chain::Ropsten | Chain::Kovan | Chain::Rinkeby | Chain::Goerli => {
std::env::var("ETHERSCAN_API_KEY")?
}
Chain::XDai => String::default(),
};
Self::new(chain, api_key)
}
pub fn etherscan_api_url(&self) -> &Url {
&self.etherscan_api_url
}
pub fn etherscan_url(&self) -> &Url {
&self.etherscan_url
}
pub fn block_url(&self, block: u64) -> String {
format!("{}/block/{}", self.etherscan_url, block)
}
pub fn address_url(&self, address: Address) -> String {
format!("{}/address/{}", self.etherscan_url, address)
}
pub fn transaction_url(&self, tx_hash: impl AsRef<str>) -> String {
format!("{}/tx/{}", self.etherscan_url, tx_hash.as_ref())
}
pub fn token_url(&self, token_hash: impl AsRef<str>) -> String {
format!("{}/token/{}", self.etherscan_url, token_hash.as_ref())
}
async fn post_form<T: DeserializeOwned, Form: Serialize>(
&self,
form: &Form,
) -> Result<Response<T>> {
Ok(self
.client
.post(self.etherscan_api_url.clone())
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.form(form)
.send()
.await?
.json()
.await?)
}
async fn get_json<T: DeserializeOwned, Q: Serialize>(&self, query: &Q) -> Result<Response<T>> {
Ok(self
.client
.get(self.etherscan_api_url.clone())
.header(header::ACCEPT, "application/json")
.query(query)
.send()
.await?
.json()
.await?)
}
fn create_query<T: Serialize>(
&self,
module: &'static str,
action: &'static str,
other: T,
) -> Query<T> {
Query {
apikey: Cow::Borrowed(&self.api_key),
module: Cow::Borrowed(module),
action: Cow::Borrowed(action),
other,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Response<T> {
pub status: String,
pub message: String,
pub result: T,
}
#[derive(Debug, Serialize)]
struct Query<'a, T: Serialize> {
apikey: Cow<'a, str>,
module: Cow<'a, str>,
action: Cow<'a, str>,
#[serde(flatten)]
other: T,
}
#[cfg(test)]
mod tests {
use crate::{Client, EtherscanError};
use ethers_core::types::Chain;
#[test]
fn chain_not_supported() {
let err = Client::new_from_env(Chain::XDai).unwrap_err();
assert!(matches!(err, EtherscanError::ChainNotSupported(_)));
assert_eq!(err.to_string(), "chain XDai not supported");
}
}