gmsol/utils/rpc/
context.rs

1use anchor_client::solana_client::rpc_response::{Response, RpcApiVersion, RpcResponseContext};
2
3pub use gmsol_solana_utils::utils::WithSlot;
4
5/// With Context.
6#[derive(Debug, Clone)]
7pub struct WithContext<T> {
8    /// Context.
9    context: RpcResponseContext,
10    /// Value.
11    value: T,
12}
13
14impl<T> WithContext<T> {
15    /// Apply a function on the value.
16    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> WithContext<U> {
17        WithContext {
18            context: self.context,
19            value: (f)(self.value),
20        }
21    }
22
23    /// Into value.
24    pub fn into_value(self) -> T {
25        self.value
26    }
27
28    /// Get a refercne to the value.
29    pub fn value(&self) -> &T {
30        &self.value
31    }
32
33    /// Get a mutable reference to the value.
34    pub fn value_mut(&mut self) -> &mut T {
35        &mut self.value
36    }
37
38    /// Get response slot.
39    pub fn slot(&self) -> u64 {
40        self.context.slot
41    }
42
43    /// Get API version.
44    pub fn api_version(&self) -> Option<&RpcApiVersion> {
45        self.context.api_version.as_ref()
46    }
47}
48
49impl<T, E> WithContext<Result<T, E>> {
50    /// Transpose.
51    pub fn transpose(self) -> Result<WithContext<T>, E> {
52        match self.value {
53            Ok(value) => Ok(WithContext {
54                context: self.context,
55                value,
56            }),
57            Err(err) => Err(err),
58        }
59    }
60}
61
62impl<T> From<Response<T>> for WithContext<T> {
63    fn from(res: Response<T>) -> Self {
64        Self {
65            context: res.context,
66            value: res.value,
67        }
68    }
69}
70
71impl<T> From<WithContext<T>> for WithSlot<T> {
72    fn from(value: WithContext<T>) -> Self {
73        Self::new(value.slot(), value.value)
74    }
75}