casper_rust_wasm_sdk/sdk/rpcs/
get_era_summary.rs

1#[cfg(target_arch = "wasm32")]
2use crate::types::identifier::block_identifier::BlockIdentifier;
3use crate::{
4    types::{
5        identifier::block_identifier::BlockIdentifierInput, sdk_error::SdkError,
6        verbosity::Verbosity,
7    },
8    SDK,
9};
10use casper_client::{
11    cli::get_era_summary as get_era_summary_cli, get_era_summary as get_era_summary_lib,
12    rpcs::results::GetEraSummaryResult as _GetEraSummaryResult, JsonRpcId, SuccessResponse,
13};
14#[cfg(target_arch = "wasm32")]
15use gloo_utils::format::JsValueSerdeExt;
16use rand::Rng;
17#[cfg(target_arch = "wasm32")]
18use serde::{Deserialize, Serialize};
19#[cfg(target_arch = "wasm32")]
20use wasm_bindgen::prelude::*;
21
22/// Wrapper struct for the `GetEraSummaryResult` from casper_client.
23#[cfg(target_arch = "wasm32")]
24#[derive(Debug, Deserialize, Clone, Serialize)]
25#[wasm_bindgen]
26pub struct GetEraSummaryResult(_GetEraSummaryResult);
27
28#[cfg(target_arch = "wasm32")]
29impl From<GetEraSummaryResult> for _GetEraSummaryResult {
30    fn from(result: GetEraSummaryResult) -> Self {
31        result.0
32    }
33}
34
35#[cfg(target_arch = "wasm32")]
36impl From<_GetEraSummaryResult> for GetEraSummaryResult {
37    fn from(result: _GetEraSummaryResult) -> Self {
38        GetEraSummaryResult(result)
39    }
40}
41
42#[cfg(target_arch = "wasm32")]
43#[wasm_bindgen]
44impl GetEraSummaryResult {
45    /// Gets the API version as a JsValue.
46    #[wasm_bindgen(getter)]
47    pub fn api_version(&self) -> JsValue {
48        JsValue::from_serde(&self.0.api_version).unwrap()
49    }
50
51    /// Gets the era summary as a JsValue.
52    #[wasm_bindgen(getter)]
53    pub fn era_summary(&self) -> JsValue {
54        JsValue::from_serde(&self.0.era_summary).unwrap()
55    }
56
57    /// Converts the GetEraSummaryResult to a JsValue.
58    #[wasm_bindgen(js_name = "toJson")]
59    pub fn to_json(&self) -> JsValue {
60        JsValue::from_serde(&self.0).unwrap_or(JsValue::null())
61    }
62}
63
64/// Options for the `get_era_summary` method.
65#[derive(Debug, Deserialize, Clone, Default, Serialize)]
66#[cfg(target_arch = "wasm32")]
67#[wasm_bindgen(js_name = "getEraSummaryOptions", getter_with_clone)]
68pub struct GetEraSummaryOptions {
69    pub maybe_block_id_as_string: Option<String>,
70    pub maybe_block_identifier: Option<BlockIdentifier>,
71    pub rpc_address: Option<String>,
72    pub verbosity: Option<Verbosity>,
73}
74
75#[cfg(target_arch = "wasm32")]
76#[wasm_bindgen]
77impl SDK {
78    /// Parses era summary options from a JsValue.
79    ///
80    /// # Arguments
81    ///
82    /// * `options` - A JsValue containing era summary options to be parsed.
83    ///
84    /// # Returns
85    ///
86    /// Parsed era summary options as a `GetEraSummaryOptions` struct.
87    pub fn get_era_summary_options(
88        &self,
89        options: JsValue,
90    ) -> Result<GetEraSummaryOptions, JsError> {
91        options
92            .into_serde::<GetEraSummaryOptions>()
93            .map_err(|err| JsError::new(&format!("Error deserializing options: {:?}", err)))
94    }
95
96    /// Retrieves era summary information using the provided options.
97    ///
98    /// # Arguments
99    ///
100    /// * `options` - An optional `GetEraSummaryOptions` struct containing retrieval options.
101    ///
102    /// # Returns
103    ///
104    /// A `Result` containing either a `GetEraSummaryResult` or a `JsError` in case of an error.
105    ///
106    /// # Errors
107    ///
108    /// Returns a `JsError` if there is an error during the retrieval process.
109    #[wasm_bindgen(js_name = "get_era_summary")]
110    pub async fn get_era_summary_js_alias(
111        &self,
112        options: Option<GetEraSummaryOptions>,
113    ) -> Result<GetEraSummaryResult, JsError> {
114        let GetEraSummaryOptions {
115            maybe_block_id_as_string,
116            maybe_block_identifier,
117            verbosity,
118            rpc_address,
119        } = options.unwrap_or_default();
120
121        let maybe_block_identifier = if let Some(maybe_block_identifier) = maybe_block_identifier {
122            Some(BlockIdentifierInput::BlockIdentifier(
123                maybe_block_identifier,
124            ))
125        } else {
126            maybe_block_id_as_string.map(BlockIdentifierInput::String)
127        };
128
129        let result = self
130            .get_era_summary(maybe_block_identifier, verbosity, rpc_address)
131            .await;
132        match result {
133            Ok(data) => Ok(data.result.into()),
134            Err(err) => {
135                let err = &format!("Error occurred with {:?}", err);
136                Err(JsError::new(err))
137            }
138        }
139    }
140
141    // JavaScript alias for `get_era_summary`
142    #[wasm_bindgen(js_name = "chain_get_era_summary")]
143    #[deprecated(note = "This function is an alias. Please use `get_era_summary` instead.")]
144    #[allow(deprecated)]
145    pub async fn chain_get_era_summary(
146        &self,
147        options: Option<GetEraSummaryOptions>,
148    ) -> Result<GetEraSummaryResult, JsError> {
149        self.get_era_summary_js_alias(options).await
150    }
151}
152
153impl SDK {
154    /// Retrieves era summary information based on the provided options.
155    ///
156    /// # Arguments
157    ///
158    /// * `maybe_block_identifier` - An optional `BlockIdentifierInput` for specifying a block identifier.
159    /// * `verbosity` - An optional `Verbosity` level for controlling the output verbosity.
160    /// * `rpc_address` - An optional string specifying the rpc address to use for the request.
161    ///
162    /// # Returns
163    ///
164    /// A `Result` containing either a `_GetEraSummaryResult` or a `SdkError` in case of an error.
165    ///
166    /// # Errors
167    ///
168    /// Returns a `SdkError` if there is an error during the retrieval process.
169    pub async fn get_era_summary(
170        &self,
171        maybe_block_identifier: Option<BlockIdentifierInput>,
172        verbosity: Option<Verbosity>,
173        rpc_address: Option<String>,
174    ) -> Result<SuccessResponse<_GetEraSummaryResult>, SdkError> {
175        //log("get_era_summary!");
176        if let Some(BlockIdentifierInput::String(maybe_block_id)) = maybe_block_identifier {
177            get_era_summary_cli(
178                &rand::thread_rng().gen::<u64>().to_string(),
179                &self.get_rpc_address(rpc_address),
180                self.get_verbosity(verbosity).into(),
181                &maybe_block_id,
182            )
183            .await
184            .map_err(SdkError::from)
185        } else {
186            let maybe_block_identifier =
187                if let Some(BlockIdentifierInput::BlockIdentifier(maybe_block_identifier)) =
188                    maybe_block_identifier
189                {
190                    Some(maybe_block_identifier)
191                } else {
192                    None
193                };
194            get_era_summary_lib(
195                JsonRpcId::from(rand::thread_rng().gen::<u64>().to_string()),
196                &self.get_rpc_address(rpc_address),
197                self.get_verbosity(verbosity).into(),
198                maybe_block_identifier.map(Into::into),
199            )
200            .await
201            .map_err(SdkError::from)
202        }
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use crate::types::{
210        hash::block_hash::BlockHash, identifier::block_identifier::BlockIdentifier,
211    };
212    use sdk_tests::tests::helpers::get_network_constants;
213
214    #[tokio::test]
215    async fn test_get_era_summary_with_none_values() {
216        // Arrange
217        let sdk = SDK::new(None, None, None);
218        let error_message = "failed to parse node address as valid URL";
219
220        // Act
221        let result = sdk.get_era_summary(None, None, None).await;
222
223        // Assert
224        assert!(result.is_err());
225        let err_string = result.err().unwrap().to_string();
226        assert!(err_string.contains(error_message));
227    }
228
229    #[tokio::test]
230    async fn test_get_era_summary_with_block_id_string() {
231        // Arrange
232        let sdk = SDK::new(None, None, None);
233        let verbosity = Some(Verbosity::High);
234        let (rpc_address, _, _, _, _) = get_network_constants();
235        let result = sdk
236            .get_block(None, verbosity, Some(rpc_address.clone()))
237            .await;
238        let block_hash = BlockHash::from(
239            *result
240                .unwrap()
241                .result
242                .block_with_signatures
243                .unwrap()
244                .block
245                .hash(),
246        )
247        .to_string();
248
249        let block_identifier = BlockIdentifierInput::String(block_hash.to_string());
250
251        // Act
252        let result = sdk
253            .get_era_summary(Some(block_identifier), verbosity, Some(rpc_address))
254            .await;
255
256        // Assert
257        assert!(result.is_ok());
258    }
259
260    #[tokio::test]
261    async fn test_get_era_summary_with_block_identifier() {
262        // Arrange
263        let sdk = SDK::new(None, None, None);
264        let block_identifier =
265            BlockIdentifierInput::BlockIdentifier(BlockIdentifier::from_height(11));
266        let verbosity = Some(Verbosity::High);
267        let (rpc_address, _, _, _, _) = get_network_constants();
268
269        // Act
270        let result = sdk
271            .get_era_summary(Some(block_identifier), verbosity, Some(rpc_address.clone()))
272            .await;
273        // Assert
274        assert!(result.is_ok());
275    }
276
277    #[tokio::test]
278    async fn test_get_era_summary_with_error() {
279        let sdk = SDK::new(Some("http://localhost".to_string()), None, None);
280
281        let error_message = "error sending request for url (http://localhost/rpc)";
282
283        // Act
284        let result = sdk.get_era_summary(None, None, None).await;
285
286        // Assert
287        assert!(result.is_err());
288        let err_string = result.err().unwrap().to_string();
289        assert!(err_string.contains(error_message));
290    }
291}