-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
mod.rs
331 lines (289 loc) · 9.99 KB
/
mod.rs
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
//! Provider-related instantiation and usage utilities.
pub mod retry;
pub mod runtime_transport;
pub mod tower;
use crate::{
provider::runtime_transport::RuntimeTransportBuilder, ALCHEMY_FREE_TIER_CUPS, REQUEST_TIMEOUT,
};
use alloy_provider::{
fillers::{ChainIdFiller, FillProvider, GasFiller, JoinFill, NonceFiller, SignerFiller},
network::{AnyNetwork, EthereumSigner},
Identity, ProviderBuilder as AlloyProviderBuilder, RootProvider,
};
use alloy_rpc_client::ClientBuilder;
use eyre::{Result, WrapErr};
use foundry_config::NamedChain;
use reqwest::Url;
use runtime_transport::RuntimeTransport;
use std::{
net::SocketAddr,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
use tower::{RetryBackoffLayer, RetryBackoffService};
use url::ParseError;
/// Helper type alias for a retry provider
pub type RetryProvider<N = AnyNetwork> = RootProvider<RetryBackoffService<RuntimeTransport>, N>;
/// Helper type alias for a retry provider with a signer
pub type RetryProviderWithSigner<N = AnyNetwork> = FillProvider<
JoinFill<
JoinFill<JoinFill<JoinFill<Identity, GasFiller>, NonceFiller>, ChainIdFiller>,
SignerFiller<EthereumSigner>,
>,
RootProvider<RetryBackoffService<RuntimeTransport>, N>,
RetryBackoffService<RuntimeTransport>,
N,
>;
/// Helper type alias for a rpc url
pub type RpcUrl = String;
/// Constructs a provider with a 100 millisecond interval poll if it's a localhost URL (most likely
/// an anvil or other dev node) and with the default, or 7 second otherwise.
///
/// See [`try_get_http_provider`] for more details.
///
/// # Panics
///
/// Panics if the URL is invalid.
///
/// # Examples
///
/// ```
/// use foundry_common::provider::get_http_provider;
///
/// let retry_provider = get_http_provider("http://localhost:8545");
/// ```
#[inline]
#[track_caller]
pub fn get_http_provider(builder: impl AsRef<str>) -> RetryProvider {
try_get_http_provider(builder).unwrap()
}
/// Constructs a provider with a 100 millisecond interval poll if it's a localhost URL (most likely
/// an anvil or other dev node) and with the default, or 7 second otherwise.
#[inline]
pub fn try_get_http_provider(builder: impl AsRef<str>) -> Result<RetryProvider> {
ProviderBuilder::new(builder.as_ref()).build()
}
/// Helper type to construct a `RetryProvider`
#[derive(Debug)]
pub struct ProviderBuilder {
// Note: this is a result, so we can easily chain builder calls
url: Result<Url>,
chain: NamedChain,
max_retry: u32,
timeout_retry: u32,
initial_backoff: u64,
timeout: Duration,
/// available CUPS
compute_units_per_second: u64,
/// JWT Secret
jwt: Option<String>,
headers: Vec<String>,
}
// === impl ProviderBuilder ===
impl ProviderBuilder {
/// Creates a new builder instance
pub fn new(url_str: &str) -> Self {
// a copy is needed for the next lines to work
let mut url_str = url_str;
// invalid url: non-prefixed URL scheme is not allowed, so we prepend the default http
// prefix
let storage;
if url_str.starts_with("localhost:") {
storage = format!("http://{url_str}");
url_str = storage.as_str();
}
let url = Url::parse(url_str)
.or_else(|err| match err {
ParseError::RelativeUrlWithoutBase => {
if SocketAddr::from_str(url_str).is_ok() {
Url::parse(&format!("http://{}", url_str))
} else {
let path = Path::new(url_str);
if let Ok(path) = resolve_path(path) {
Url::parse(&format!("file://{}", path.display()))
} else {
Err(err)
}
}
}
_ => Err(err),
})
.wrap_err_with(|| format!("invalid provider URL: {url_str:?}"));
Self {
url,
chain: NamedChain::Mainnet,
max_retry: 8,
timeout_retry: 8,
initial_backoff: 800,
timeout: REQUEST_TIMEOUT,
// alchemy max cpus <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
compute_units_per_second: ALCHEMY_FREE_TIER_CUPS,
jwt: None,
headers: vec![],
}
}
/// Enables a request timeout.
///
/// The timeout is applied from when the request starts connecting until the
/// response body has finished.
///
/// Default is no timeout.
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
/// Sets the chain of the node the provider will connect to
pub fn chain(mut self, chain: NamedChain) -> Self {
self.chain = chain;
self
}
/// How often to retry a failed request
pub fn max_retry(mut self, max_retry: u32) -> Self {
self.max_retry = max_retry;
self
}
/// How often to retry a failed request. If `None`, defaults to the already-set value.
pub fn maybe_max_retry(mut self, max_retry: Option<u32>) -> Self {
self.max_retry = max_retry.unwrap_or(self.max_retry);
self
}
/// The starting backoff delay to use after the first failed request. If `None`, defaults to
/// the already-set value.
pub fn maybe_initial_backoff(mut self, initial_backoff: Option<u64>) -> Self {
self.initial_backoff = initial_backoff.unwrap_or(self.initial_backoff);
self
}
/// How often to retry a failed request due to connection issues
pub fn timeout_retry(mut self, timeout_retry: u32) -> Self {
self.timeout_retry = timeout_retry;
self
}
/// The starting backoff delay to use after the first failed request
pub fn initial_backoff(mut self, initial_backoff: u64) -> Self {
self.initial_backoff = initial_backoff;
self
}
/// Sets the number of assumed available compute units per second
///
/// See also, <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
pub fn compute_units_per_second(mut self, compute_units_per_second: u64) -> Self {
self.compute_units_per_second = compute_units_per_second;
self
}
/// Sets the number of assumed available compute units per second
///
/// See also, <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
pub fn compute_units_per_second_opt(mut self, compute_units_per_second: Option<u64>) -> Self {
if let Some(cups) = compute_units_per_second {
self.compute_units_per_second = cups;
}
self
}
/// Sets aggressive `max_retry` and `initial_backoff` values
///
/// This is only recommend for local dev nodes
pub fn aggressive(self) -> Self {
self.max_retry(100).initial_backoff(100)
}
/// Sets the JWT secret
pub fn jwt(mut self, jwt: impl Into<String>) -> Self {
self.jwt = Some(jwt.into());
self
}
/// Sets http headers
pub fn headers(mut self, headers: Vec<String>) -> Self {
self.headers = headers;
self
}
/// Constructs the `RetryProvider` taking all configs into account.
pub fn build(self) -> Result<RetryProvider> {
let ProviderBuilder {
url,
chain: _,
max_retry,
timeout_retry,
initial_backoff,
timeout,
compute_units_per_second,
jwt,
headers,
} = self;
let url = url?;
let retry_layer = RetryBackoffLayer::new(
max_retry,
timeout_retry,
initial_backoff,
compute_units_per_second,
);
let transport = RuntimeTransportBuilder::new(url.clone())
.with_timeout(timeout)
.with_headers(headers)
.with_jwt(jwt)
.build();
let client = ClientBuilder::default().layer(retry_layer).transport(transport, false);
let provider = AlloyProviderBuilder::<_, _, AnyNetwork>::default()
.on_provider(RootProvider::new(client));
Ok(provider)
}
/// Constructs the `RetryProvider` with a signer
pub fn build_with_signer(self, signer: EthereumSigner) -> Result<RetryProviderWithSigner> {
let ProviderBuilder {
url,
chain: _,
max_retry,
timeout_retry,
initial_backoff,
timeout,
compute_units_per_second,
jwt,
headers,
} = self;
let url = url?;
let retry_layer = RetryBackoffLayer::new(
max_retry,
timeout_retry,
initial_backoff,
compute_units_per_second,
);
let transport = RuntimeTransportBuilder::new(url.clone())
.with_timeout(timeout)
.with_headers(headers)
.with_jwt(jwt)
.build();
let client = ClientBuilder::default().layer(retry_layer).transport(transport, false);
let provider = AlloyProviderBuilder::<_, _, AnyNetwork>::default()
.with_recommended_fillers()
.signer(signer)
.on_provider(RootProvider::new(client));
Ok(provider)
}
}
#[cfg(not(windows))]
fn resolve_path(path: &Path) -> Result<PathBuf, ()> {
if path.is_absolute() {
Ok(path.to_path_buf())
} else {
std::env::current_dir().map(|d| d.join(path)).map_err(drop)
}
}
#[cfg(windows)]
fn resolve_path(path: &Path) -> Result<PathBuf, ()> {
if let Some(s) = path.to_str() {
if s.starts_with(r"\\.\pipe\") {
return Ok(path.to_path_buf());
}
}
Err(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn can_auto_correct_missing_prefix() {
let builder = ProviderBuilder::new("localhost:8545");
assert!(builder.url.is_ok());
let url = builder.url.unwrap();
assert_eq!(url, Url::parse("http://localhost:8545").unwrap());
}
}