near_api/
fastnear.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::collections::BTreeSet;

use near_primitives::types::AccountId;
use serde::de::DeserializeOwned;

use crate::errors::FastNearError;

#[derive(Debug, serde::Deserialize)]
pub struct StakingPool {
    pool_id: near_primitives::types::AccountId,
}

#[derive(Debug, serde::Deserialize)]
pub struct StakingResponse {
    pools: Vec<StakingPool>,
}

pub struct FastNearBuilder<T: DeserializeOwned + Send + Sync, PostProcessed> {
    query: String,
    post_process: Box<dyn Fn(T) -> PostProcessed + Send + Sync>,
    _response: std::marker::PhantomData<T>,
}

impl<T: DeserializeOwned + Send + Sync> FastNearBuilder<T, T> {
    pub fn new(query: String) -> Self {
        Self {
            query,
            post_process: Box::new(|response| response),
            _response: Default::default(),
        }
    }
}

impl<T, PostProcessed> FastNearBuilder<T, PostProcessed>
where
    T: DeserializeOwned + Send + Sync,
{
    pub fn with_postprocess<F>(query: String, func: F) -> Self
    where
        F: Fn(T) -> PostProcessed + Send + Sync + 'static,
    {
        Self {
            query,
            post_process: Box::new(func),
            _response: Default::default(),
        }
    }

    pub async fn fetch_from_url(self, url: url::Url) -> Result<PostProcessed, FastNearError> {
        let request = reqwest::get(url.join(&self.query)?).await?;
        Ok((self.post_process)(request.json().await?))
    }

    pub async fn fetch_from_mainnet(self) -> Result<PostProcessed, FastNearError> {
        match crate::config::NetworkConfig::mainnet().fastnear_url {
            Some(url) => self.fetch_from_url(url).await,
            None => Err(FastNearError::FastNearUrlIsNotDefined),
        }
    }
}

#[derive(Clone, Debug)]
pub struct FastNear {}

impl FastNear {
    pub async fn pools_delegated_by(
        &self,
        account_id: &AccountId,
    ) -> Result<FastNearBuilder<StakingResponse, BTreeSet<AccountId>>, FastNearError> {
        let query_builder = FastNearBuilder::with_postprocess(
            format!("v1/account/{}/staking", account_id),
            |response: StakingResponse| {
                response
                    .pools
                    .into_iter()
                    .map(|pool| pool.pool_id)
                    .collect()
            },
        );

        Ok(query_builder)
    }
}