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        let random_id = rand::thread_rng().gen::<u64>().to_string();
177        if let Some(BlockIdentifierInput::String(maybe_block_id)) = maybe_block_identifier {
178            get_era_summary_cli(
179                &random_id,
180                &self.get_rpc_address(rpc_address),
181                self.get_verbosity(verbosity).into(),
182                &maybe_block_id,
183            )
184            .await
185            .map_err(SdkError::from)
186        } else {
187            let maybe_block_identifier =
188                if let Some(BlockIdentifierInput::BlockIdentifier(maybe_block_identifier)) =
189                    maybe_block_identifier
190                {
191                    Some(maybe_block_identifier)
192                } else {
193                    None
194                };
195            get_era_summary_lib(
196                JsonRpcId::from(random_id),
197                &self.get_rpc_address(rpc_address),
198                self.get_verbosity(verbosity).into(),
199                maybe_block_identifier.map(Into::into),
200            )
201            .await
202            .map_err(SdkError::from)
203        }
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use crate::types::{
211        hash::block_hash::BlockHash, identifier::block_identifier::BlockIdentifier,
212    };
213    use sdk_tests::tests::helpers::get_network_constants;
214
215    #[tokio::test]
216    async fn test_get_era_summary_with_none_values() {
217        // Arrange
218        let sdk = SDK::new(None, None, None);
219        let error_message = "failed to parse node address as valid URL";
220
221        // Act
222        let result = sdk.get_era_summary(None, None, None).await;
223
224        // Assert
225        assert!(result.is_err());
226        let err_string = result.err().unwrap().to_string();
227        assert!(err_string.contains(error_message));
228    }
229
230    #[tokio::test]
231    async fn test_get_era_summary_with_block_id_string() {
232        // Arrange
233        let sdk = SDK::new(None, None, None);
234        let verbosity = Some(Verbosity::High);
235        let (rpc_address, _, _, _, _) = get_network_constants();
236        let result = sdk
237            .get_block(None, verbosity, Some(rpc_address.clone()))
238            .await;
239        let block_hash = BlockHash::from(
240            *result
241                .unwrap()
242                .result
243                .block_with_signatures
244                .unwrap()
245                .block
246                .hash(),
247        )
248        .to_string();
249
250        let block_identifier = BlockIdentifierInput::String(block_hash.to_string());
251
252        // Act
253        let result = sdk
254            .get_era_summary(Some(block_identifier), verbosity, Some(rpc_address))
255            .await;
256
257        // Assert
258        assert!(result.is_ok());
259    }
260
261    #[tokio::test]
262    async fn test_get_era_summary_with_block_identifier() {
263        // Arrange
264        let sdk = SDK::new(None, None, None);
265        let block_identifier =
266            BlockIdentifierInput::BlockIdentifier(BlockIdentifier::from_height(11));
267        let verbosity = Some(Verbosity::High);
268        let (rpc_address, _, _, _, _) = get_network_constants();
269
270        // Act
271        let result = sdk
272            .get_era_summary(Some(block_identifier), verbosity, Some(rpc_address.clone()))
273            .await;
274        // Assert
275        assert!(result.is_ok());
276    }
277
278    #[tokio::test]
279    async fn test_get_era_summary_with_error() {
280        let sdk = SDK::new(Some("http://localhost".to_string()), None, None);
281
282        let error_message = "error sending request";
283
284        // Act
285        let result = sdk.get_era_summary(None, None, None).await;
286
287        // Assert
288        assert!(result.is_err());
289        let err_string = result.err().unwrap().to_string();
290        assert!(err_string.contains(error_message));
291    }
292}