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