1use near_api_types::AccountId;
2use near_openapi_client::Client;
3use reqwest::header::{HeaderValue, InvalidHeaderValue};
4use url::Url;
5
6use crate::errors::RetryError;
7
8#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
9pub enum RetryMethod {
11 ExponentialBackoff {
14 initial_sleep: std::time::Duration,
16 factor: u8,
18 },
19 Fixed {
21 sleep: std::time::Duration,
23 },
24}
25
26#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
27pub struct RPCEndpoint {
29 pub url: url::Url,
31 pub bearer_header: Option<String>,
33 pub retries: u8,
35 pub retry_method: RetryMethod,
37}
38
39impl RPCEndpoint {
40 pub const fn new(url: url::Url) -> Self {
45 Self {
46 url,
47 bearer_header: None,
48 retries: 5,
49 retry_method: RetryMethod::ExponentialBackoff {
51 initial_sleep: std::time::Duration::from_millis(10),
52 factor: 2,
53 },
54 }
55 }
56
57 pub fn mainnet() -> Self {
59 Self::new("https://free.rpc.fastnear.com".parse().unwrap())
60 }
61
62 pub fn testnet() -> Self {
64 Self::new("https://test.rpc.fastnear.com".parse().unwrap())
65 }
66
67 pub fn with_api_key(mut self, api_key: String) -> Self {
69 self.bearer_header = Some(format!("Bearer {api_key}"));
70 self
71 }
72
73 pub const fn with_retries(mut self, retries: u8) -> Self {
75 self.retries = retries;
76 self
77 }
78
79 pub const fn with_retry_method(mut self, retry_method: RetryMethod) -> Self {
80 self.retry_method = retry_method;
81 self
82 }
83
84 pub fn get_sleep_duration(&self, retry: usize) -> std::time::Duration {
85 match self.retry_method {
86 RetryMethod::ExponentialBackoff {
87 initial_sleep,
88 factor,
89 } => initial_sleep * ((factor as u32).pow(retry as u32)),
90 RetryMethod::Fixed { sleep } => sleep,
91 }
92 }
93
94 pub(crate) fn client(&self) -> Result<Client, InvalidHeaderValue> {
95 let dur = std::time::Duration::from_secs(15);
96 let mut client = reqwest::ClientBuilder::new()
97 .connect_timeout(dur)
98 .timeout(dur);
99
100 if let Some(rpc_api_key) = &self.bearer_header {
101 let mut headers = reqwest::header::HeaderMap::new();
102
103 let mut header = HeaderValue::from_str(rpc_api_key)?;
104 header.set_sensitive(true);
105
106 headers.insert(
107 reqwest::header::HeaderName::from_static("authorization"),
108 header.clone(),
109 );
110 headers.insert(
111 reqwest::header::HeaderName::from_static("x-api-key"),
112 header,
113 );
114 client = client.default_headers(headers);
115 };
116 Ok(near_openapi_client::Client::new_with_client(
117 self.url.as_ref().trim_end_matches('/'),
118 client.build().unwrap(),
119 ))
120 }
121}
122
123#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
124pub struct NetworkConfig {
145 pub network_name: String,
147 pub rpc_endpoints: Vec<RPCEndpoint>,
149 pub linkdrop_account_id: Option<AccountId>,
151 pub near_social_db_contract_account_id: Option<AccountId>,
153 pub faucet_url: Option<url::Url>,
155 pub meta_transaction_relayer_url: Option<url::Url>,
157 pub fastnear_url: Option<url::Url>,
161 pub staking_pools_factory_account_id: Option<AccountId>,
163}
164
165impl NetworkConfig {
166 pub fn mainnet() -> Self {
168 Self {
169 network_name: "mainnet".to_string(),
170 rpc_endpoints: vec![RPCEndpoint::mainnet()],
171 linkdrop_account_id: Some("near".parse().unwrap()),
172 near_social_db_contract_account_id: Some("social.near".parse().unwrap()),
173 faucet_url: None,
174 meta_transaction_relayer_url: None,
175 fastnear_url: Some("https://api.fastnear.com/".parse().unwrap()),
176 staking_pools_factory_account_id: Some("poolv1.near".parse().unwrap()),
177 }
178 }
179
180 pub fn testnet() -> Self {
182 Self {
183 network_name: "testnet".to_string(),
184 rpc_endpoints: vec![RPCEndpoint::testnet()],
185 linkdrop_account_id: Some("testnet".parse().unwrap()),
186 near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
187 faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
188 meta_transaction_relayer_url: None,
189 fastnear_url: None,
190 staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
191 }
192 }
193
194 pub fn from_rpc_url(name: &str, rpc_url: Url) -> Self {
195 Self {
196 network_name: name.to_string(),
197 rpc_endpoints: vec![RPCEndpoint::new(rpc_url)],
198 linkdrop_account_id: None,
199 near_social_db_contract_account_id: None,
200 faucet_url: None,
201 fastnear_url: None,
202 meta_transaction_relayer_url: None,
203 staking_pools_factory_account_id: None,
204 }
205 }
206}
207
208#[derive(Debug)]
209pub enum RetryResponse<R, E> {
211 Ok(R),
213 Retry(E),
215 Critical(E),
217}
218
219impl<R, E> From<Result<R, E>> for RetryResponse<R, E> {
220 fn from(value: Result<R, E>) -> Self {
221 match value {
222 Ok(value) => Self::Ok(value),
223 Err(value) => Self::Retry(value),
224 }
225 }
226}
227
228pub async fn retry<R, E, T, F>(network: NetworkConfig, mut task: F) -> Result<R, RetryError<E>>
234where
235 F: FnMut(Client) -> T + Send,
236 T: core::future::Future<Output = RetryResponse<R, E>> + Send,
237 T::Output: Send,
238 E: Send,
239{
240 if network.rpc_endpoints.is_empty() {
241 return Err(RetryError::NoRpcEndpoints);
242 }
243
244 let mut last_error = None;
245 for endpoint in network.rpc_endpoints.iter() {
246 let client = endpoint
247 .client()
248 .map_err(|e| RetryError::InvalidApiKey(e))?;
249 for retry in 0..endpoint.retries {
250 let result = task(client.clone()).await;
251 match result {
252 RetryResponse::Ok(result) => return Ok(result),
253 RetryResponse::Retry(error) => {
254 last_error = Some(error);
255 tokio::time::sleep(endpoint.get_sleep_duration(retry as usize)).await;
256 }
257 RetryResponse::Critical(result) => return Err(RetryError::Critical(result)),
258 }
259 }
260 }
261 Err(RetryError::RetriesExhausted(last_error.expect(
262 "Logic error: last_error should be Some when all retries are exhausted",
263 )))
264}