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    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)]
124/// Configuration for a NEAR network including RPC endpoints and network-specific settings.
125///
126/// # Multiple RPC endpoints
127///
128/// This struct is used to configure multiple RPC endpoints for a NEAR network.
129/// It allows for failover between endpoints in case of a failure.
130///
131///
132/// ## Example
133/// ```rust,no_run
134/// use near_api::*;
135///
136/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
137/// let config = NetworkConfig {
138///     rpc_endpoints: vec![RPCEndpoint::mainnet(), RPCEndpoint::new("https://near.lava.build".parse()?)],
139///     ..NetworkConfig::mainnet()
140/// };
141/// # Ok(())
142/// # }
143/// ```
144pub struct NetworkConfig {
145    /// Human readable name of the network (e.g. "mainnet", "testnet")
146    pub network_name: String,
147    /// List of [RPC endpoints](https://docs.near.org/api/rpc/providers) to use with failover
148    pub rpc_endpoints: Vec<RPCEndpoint>,
149    /// Account ID used for [linkdrop functionality](https://docs.near.org/build/primitives/linkdrop)
150    pub linkdrop_account_id: Option<AccountId>,
151    /// Account ID of the [NEAR Social contract](https://docs.near.org/social/contract)
152    pub near_social_db_contract_account_id: Option<AccountId>,
153    /// URL of the network's faucet service
154    pub faucet_url: Option<url::Url>,
155    /// URL for the [meta transaction relayer](https://docs.near.org/concepts/abstraction/relayers) service
156    pub meta_transaction_relayer_url: Option<url::Url>,
157    /// URL for the [fastnear](https://docs.near.org/tools/ecosystem-apis/fastnear-api) service.
158    ///
159    /// Currently, unused. See [#30](https://github.com/near/near-api-rs/issues/30)
160    pub fastnear_url: Option<url::Url>,
161    /// Account ID of the [staking pools factory](https://github.com/NearSocial/social-db)
162    pub staking_pools_factory_account_id: Option<AccountId>,
163}
164
165impl NetworkConfig {
166    /// Constructs default mainnet configuration.
167    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    /// Constructs default testnet configuration.
181    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)]
209/// Represents the possible outcomes of a retry-able operation.
210pub enum RetryResponse<R, E> {
211    /// Operation succeeded with result R
212    Ok(R),
213    /// Operation failed with error E, should be retried
214    Retry(E),
215    /// Operation failed with critical error E, should not be retried
216    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
228/// Retry a task with exponential backoff and failover.
229///
230/// # Arguments
231/// * `network` - The network configuration to use for the retry-able operation.
232/// * `task` - The task to retry.
233pub 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}