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("x-api-key"),
108 header,
109 );
110 client = client.default_headers(headers);
111 };
112 Ok(near_openapi_client::Client::new_with_client(
113 self.url.as_ref().trim_end_matches('/'),
114 client.build().unwrap(),
115 ))
116 }
117}
118
119#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
120pub struct NetworkConfig {
141 pub network_name: String,
143 pub rpc_endpoints: Vec<RPCEndpoint>,
145 pub linkdrop_account_id: Option<AccountId>,
147 pub near_social_db_contract_account_id: Option<AccountId>,
149 pub faucet_url: Option<url::Url>,
151 pub meta_transaction_relayer_url: Option<url::Url>,
153 pub fastnear_url: Option<url::Url>,
157 pub staking_pools_factory_account_id: Option<AccountId>,
159}
160
161impl NetworkConfig {
162 pub fn mainnet() -> Self {
164 Self {
165 network_name: "mainnet".to_string(),
166 rpc_endpoints: vec![RPCEndpoint::mainnet()],
167 linkdrop_account_id: Some("near".parse().unwrap()),
168 near_social_db_contract_account_id: Some("social.near".parse().unwrap()),
169 faucet_url: None,
170 meta_transaction_relayer_url: None,
171 fastnear_url: Some("https://api.fastnear.com/".parse().unwrap()),
172 staking_pools_factory_account_id: Some("poolv1.near".parse().unwrap()),
173 }
174 }
175
176 pub fn testnet() -> Self {
178 Self {
179 network_name: "testnet".to_string(),
180 rpc_endpoints: vec![RPCEndpoint::testnet()],
181 linkdrop_account_id: Some("testnet".parse().unwrap()),
182 near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
183 faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
184 meta_transaction_relayer_url: None,
185 fastnear_url: None,
186 staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
187 }
188 }
189
190 pub fn from_rpc_url(name: &str, rpc_url: Url) -> Self {
191 Self {
192 network_name: name.to_string(),
193 rpc_endpoints: vec![RPCEndpoint::new(rpc_url)],
194 linkdrop_account_id: None,
195 near_social_db_contract_account_id: None,
196 faucet_url: None,
197 fastnear_url: None,
198 meta_transaction_relayer_url: None,
199 staking_pools_factory_account_id: None,
200 }
201 }
202}
203
204#[derive(Debug)]
205pub enum RetryResponse<R, E> {
207 Ok(R),
209 Retry(E),
211 Critical(E),
213}
214
215impl<R, E> From<Result<R, E>> for RetryResponse<R, E> {
216 fn from(value: Result<R, E>) -> Self {
217 match value {
218 Ok(value) => Self::Ok(value),
219 Err(value) => Self::Retry(value),
220 }
221 }
222}
223
224pub async fn retry<R, E, T, F>(network: NetworkConfig, mut task: F) -> Result<R, RetryError<E>>
230where
231 F: FnMut(Client) -> T + Send,
232 T: core::future::Future<Output = RetryResponse<R, E>> + Send,
233 T::Output: Send,
234 E: Send,
235{
236 if network.rpc_endpoints.is_empty() {
237 return Err(RetryError::NoRpcEndpoints);
238 }
239
240 let mut last_error = None;
241 for endpoint in network.rpc_endpoints.iter() {
242 let client = endpoint
243 .client()
244 .map_err(|e| RetryError::InvalidApiKey(e))?;
245 for retry in 0..endpoint.retries {
246 let result = task(client.clone()).await;
247 match result {
248 RetryResponse::Ok(result) => return Ok(result),
249 RetryResponse::Retry(error) => {
250 last_error = Some(error);
251 tokio::time::sleep(endpoint.get_sleep_duration(retry as usize)).await;
252 }
253 RetryResponse::Critical(result) => return Err(RetryError::Critical(result)),
254 }
255 }
256 }
257 Err(RetryError::RetriesExhausted(last_error.expect(
258 "Logic error: last_error should be Some when all retries are exhausted",
259 )))
260}