near_api/
config.rs

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)]
9/// Specifies the retry strategy for RPC endpoint requests.
10pub enum RetryMethod {
11    /// Exponential backoff strategy with configurable initial delay and multiplication factor.
12    /// The delay is calculated as: `initial_sleep * factor^retry_number`
13    ExponentialBackoff {
14        /// The initial delay duration before the first retry
15        initial_sleep: std::time::Duration,
16        /// The multiplication factor for calculating subsequent delays
17        factor: u8,
18    },
19    /// Fixed delay strategy with constant sleep duration
20    Fixed {
21        /// The constant delay duration between retries
22        sleep: std::time::Duration,
23    },
24}
25
26#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
27/// Configuration for a [NEAR RPC](https://docs.near.org/api/rpc/providers) endpoint with retry and backoff settings.
28pub struct RPCEndpoint {
29    /// The URL of the RPC endpoint
30    pub url: url::Url,
31    /// Optional API key for authenticated requests
32    pub bearer_header: Option<String>,
33    /// Number of consecutive failures to move on to the next endpoint.
34    pub retries: u8,
35    /// The retry method to use
36    pub retry_method: RetryMethod,
37}
38
39impl RPCEndpoint {
40    /// Constructs a new RPC endpoint configuration with default settings.
41    ///
42    /// The default retry method is `ExponentialBackoff` with an initial sleep of 10ms and a factor of 2.
43    /// The delays will be 10ms, 20ms, 40ms, 80ms, 160ms.
44    pub const fn new(url: url::Url) -> Self {
45        Self {
46            url,
47            bearer_header: None,
48            retries: 5,
49            // 10ms, 20ms, 40ms, 80ms, 160ms
50            retry_method: RetryMethod::ExponentialBackoff {
51                initial_sleep: std::time::Duration::from_millis(10),
52                factor: 2,
53            },
54        }
55    }
56
57    /// Constructs default mainnet configuration.
58    pub fn mainnet() -> Self {
59        Self::new("https://free.rpc.fastnear.com".parse().unwrap())
60    }
61
62    /// Constructs default testnet configuration.
63    pub fn testnet() -> Self {
64        Self::new("https://test.rpc.fastnear.com".parse().unwrap())
65    }
66
67    /// Set API key for the endpoint.
68    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    /// Set number of retries for the endpoint before moving on to the next one.
74    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
95#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
96/// Configuration for a NEAR network including RPC endpoints and network-specific settings.
97///
98/// # Multiple RPC endpoints
99///
100/// This struct is used to configure multiple RPC endpoints for a NEAR network.
101/// It allows for failover between endpoints in case of a failure.
102///
103///
104/// ## Example
105/// ```rust,no_run
106/// use near_api::*;
107///
108/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
109/// let config = NetworkConfig {
110///     rpc_endpoints: vec![RPCEndpoint::mainnet(), RPCEndpoint::new("https://near.lava.build".parse()?)],
111///     ..NetworkConfig::mainnet()
112/// };
113/// # Ok(())
114/// # }
115/// ```
116pub struct NetworkConfig {
117    /// Human readable name of the network (e.g. "mainnet", "testnet")
118    pub network_name: String,
119    /// List of [RPC endpoints](https://docs.near.org/api/rpc/providers) to use with failover
120    pub rpc_endpoints: Vec<RPCEndpoint>,
121    /// Account ID used for [linkdrop functionality](https://docs.near.org/build/primitives/linkdrop)
122    pub linkdrop_account_id: Option<AccountId>,
123    /// Account ID of the [NEAR Social contract](https://docs.near.org/social/contract)
124    pub near_social_db_contract_account_id: Option<AccountId>,
125    /// URL of the network's faucet service
126    pub faucet_url: Option<url::Url>,
127    /// URL for the [meta transaction relayer](https://docs.near.org/concepts/abstraction/relayers) service
128    pub meta_transaction_relayer_url: Option<url::Url>,
129    /// URL for the [fastnear](https://docs.near.org/tools/ecosystem-apis/fastnear-api) service.
130    ///
131    /// Currently, unused. See [#30](https://github.com/near/near-api-rs/issues/30)
132    pub fastnear_url: Option<url::Url>,
133    /// Account ID of the [staking pools factory](https://github.com/NearSocial/social-db)
134    pub staking_pools_factory_account_id: Option<AccountId>,
135}
136
137impl NetworkConfig {
138    /// Constructs default mainnet configuration.
139    pub fn mainnet() -> Self {
140        Self {
141            network_name: "mainnet".to_string(),
142            rpc_endpoints: vec![RPCEndpoint::mainnet()],
143            linkdrop_account_id: Some("near".parse().unwrap()),
144            near_social_db_contract_account_id: Some("social.near".parse().unwrap()),
145            faucet_url: None,
146            meta_transaction_relayer_url: None,
147            fastnear_url: Some("https://api.fastnear.com/".parse().unwrap()),
148            staking_pools_factory_account_id: Some("poolv1.near".parse().unwrap()),
149        }
150    }
151
152    /// Constructs default testnet configuration.
153    pub fn testnet() -> Self {
154        Self {
155            network_name: "testnet".to_string(),
156            rpc_endpoints: vec![RPCEndpoint::testnet()],
157            linkdrop_account_id: Some("testnet".parse().unwrap()),
158            near_social_db_contract_account_id: Some("v1.social08.testnet".parse().unwrap()),
159            faucet_url: Some("https://helper.nearprotocol.com/account".parse().unwrap()),
160            meta_transaction_relayer_url: None,
161            fastnear_url: None,
162            staking_pools_factory_account_id: Some("pool.f863973.m0".parse().unwrap()),
163        }
164    }
165
166    pub fn from_rpc_url(name: &str, rpc_url: Url) -> Self {
167        Self {
168            network_name: name.to_string(),
169            rpc_endpoints: vec![RPCEndpoint::new(rpc_url)],
170            linkdrop_account_id: None,
171            near_social_db_contract_account_id: None,
172            faucet_url: None,
173            fastnear_url: None,
174            meta_transaction_relayer_url: None,
175            staking_pools_factory_account_id: None,
176        }
177    }
178
179    pub(crate) fn client(&self, index: usize) -> Result<Client, InvalidHeaderValue> {
180        let rpc_endpoint = &self.rpc_endpoints[index];
181
182        let dur = std::time::Duration::from_secs(15);
183        let mut client = reqwest::ClientBuilder::new()
184            .connect_timeout(dur)
185            .timeout(dur);
186
187        if let Some(rpc_api_key) = &rpc_endpoint.bearer_header {
188            let mut headers = reqwest::header::HeaderMap::new();
189
190            let mut header = HeaderValue::from_str(rpc_api_key)?;
191            header.set_sensitive(true);
192
193            headers.insert(
194                reqwest::header::HeaderName::from_static("x-api-key"),
195                header,
196            );
197            client = client.default_headers(headers);
198        };
199        Ok(near_openapi_client::Client::new_with_client(
200            rpc_endpoint.url.as_ref().trim_end_matches('/'),
201            client.build().unwrap(),
202        ))
203    }
204}
205
206#[derive(Debug)]
207/// Represents the possible outcomes of a retry-able operation.
208pub enum RetryResponse<R, E> {
209    /// Operation succeeded with result R
210    Ok(R),
211    /// Operation failed with error E, should be retried
212    Retry(E),
213    /// Operation failed with critical error E, should not be retried
214    Critical(E),
215}
216
217impl<R, E> From<Result<R, E>> for RetryResponse<R, E> {
218    fn from(value: Result<R, E>) -> Self {
219        match value {
220            Ok(value) => Self::Ok(value),
221            Err(value) => Self::Retry(value),
222        }
223    }
224}
225
226/// Retry a task with exponential backoff and failover.
227///
228/// # Arguments
229/// * `network` - The network configuration to use for the retry-able operation.
230/// * `task` - The task to retry.
231pub async fn retry<R, E, T, F>(network: NetworkConfig, mut task: F) -> Result<R, RetryError<E>>
232where
233    F: FnMut(Client) -> T + Send,
234    T: core::future::Future<Output = RetryResponse<R, E>> + Send,
235    T::Output: Send,
236    E: Send,
237{
238    if network.rpc_endpoints.is_empty() {
239        return Err(RetryError::NoRpcEndpoints);
240    }
241
242    let mut last_error = None;
243    for (index, endpoint) in network.rpc_endpoints.iter().enumerate() {
244        let client = network
245            .client(index)
246            .map_err(|e| RetryError::InvalidApiKey(e))?;
247        for retry in 0..endpoint.retries {
248            let result = task(client.clone()).await;
249            match result {
250                RetryResponse::Ok(result) => return Ok(result),
251                RetryResponse::Retry(error) => {
252                    last_error = Some(error);
253                    tokio::time::sleep(endpoint.get_sleep_duration(retry as usize)).await;
254                }
255                RetryResponse::Critical(result) => return Err(RetryError::Critical(result)),
256            }
257        }
258    }
259    Err(RetryError::RetriesExhausted(last_error.expect(
260        "Logic error: last_error should be Some when all retries are exhausted",
261    )))
262}