casper_rust_wasm_sdk/sdk/rpcs/
get_node_status.rs

1#[cfg(target_arch = "wasm32")]
2use crate::types::{digest::Digest, public_key::PublicKey};
3use crate::{types::verbosity::Verbosity, SDK};
4use casper_client::{
5    get_node_status, rpcs::results::GetNodeStatusResult as _GetNodeStatusResult, Error, JsonRpcId,
6    SuccessResponse,
7};
8#[cfg(target_arch = "wasm32")]
9use gloo_utils::format::JsValueSerdeExt;
10use rand::Rng;
11#[cfg(target_arch = "wasm32")]
12use serde::{Deserialize, Serialize};
13#[cfg(target_arch = "wasm32")]
14use wasm_bindgen::prelude::*;
15
16/// Wrapper struct for the `GetNodeStatusResult` from casper_client.
17#[cfg(target_arch = "wasm32")]
18#[derive(Debug, Deserialize, Clone, Serialize)]
19#[wasm_bindgen]
20pub struct GetNodeStatusResult(_GetNodeStatusResult);
21
22#[cfg(target_arch = "wasm32")]
23impl From<GetNodeStatusResult> for _GetNodeStatusResult {
24    fn from(result: GetNodeStatusResult) -> Self {
25        result.0
26    }
27}
28
29#[cfg(target_arch = "wasm32")]
30impl From<_GetNodeStatusResult> for GetNodeStatusResult {
31    fn from(result: _GetNodeStatusResult) -> Self {
32        GetNodeStatusResult(result)
33    }
34}
35
36#[cfg(target_arch = "wasm32")]
37#[wasm_bindgen]
38impl GetNodeStatusResult {
39    /// Gets the API version as a JsValue.
40    #[wasm_bindgen(getter)]
41    pub fn api_version(&self) -> JsValue {
42        JsValue::from_serde(&self.0.api_version).unwrap()
43    }
44
45    /// Gets the chainspec name as a String.
46    #[wasm_bindgen(getter)]
47    pub fn chainspec_name(&self) -> String {
48        self.0.chainspec_name.clone()
49    }
50
51    /// Gets the starting state root hash as a Digest.
52    #[allow(deprecated)]
53    #[wasm_bindgen(getter)]
54    pub fn starting_state_root_hash(&self) -> Digest {
55        self.0.starting_state_root_hash.into()
56    }
57
58    /// Gets the list of peers as a JsValue.
59    #[wasm_bindgen(getter)]
60    pub fn peers(&self) -> JsValue {
61        JsValue::from_serde(&self.0.peers).unwrap()
62    }
63
64    /// Gets information about the last added block as a JsValue.
65    #[wasm_bindgen(getter)]
66    pub fn last_added_block_info(&self) -> JsValue {
67        JsValue::from_serde(&self.0.last_added_block_info).unwrap()
68    }
69
70    /// Gets the public signing key as an Option<PublicKey>.
71    #[wasm_bindgen(getter)]
72    pub fn our_public_signing_key(&self) -> Option<PublicKey> {
73        self.0.our_public_signing_key.clone().map(Into::into)
74    }
75
76    /// Gets the round length as a JsValue.
77    #[wasm_bindgen(getter)]
78    pub fn round_length(&self) -> JsValue {
79        JsValue::from_serde(&self.0.round_length).unwrap()
80    }
81
82    /// Gets information about the next upgrade as a JsValue.
83    #[wasm_bindgen(getter)]
84    pub fn next_upgrade(&self) -> JsValue {
85        JsValue::from_serde(&self.0.next_upgrade).unwrap()
86    }
87
88    /// Gets the build version as a String.
89    #[wasm_bindgen(getter)]
90    pub fn build_version(&self) -> String {
91        self.0.build_version.clone()
92    }
93
94    /// Gets the uptime information as a JsValue.
95    #[wasm_bindgen(getter)]
96    pub fn uptime(&self) -> JsValue {
97        JsValue::from_serde(&self.0.uptime).unwrap()
98    }
99
100    /// Gets the reactor state information as a JsValue.
101    #[wasm_bindgen(getter)]
102    pub fn reactor_state(&self) -> JsValue {
103        JsValue::from_serde(&self.0.reactor_state).unwrap()
104    }
105
106    /// Gets the last progress information as a JsValue.
107    #[wasm_bindgen(getter)]
108    pub fn last_progress(&self) -> JsValue {
109        JsValue::from_serde(&self.0.last_progress).unwrap()
110    }
111
112    /// Gets the available block range as a JsValue.
113    #[wasm_bindgen(getter)]
114    pub fn available_block_range(&self) -> JsValue {
115        JsValue::from_serde(&self.0.available_block_range).unwrap()
116    }
117
118    /// Gets the block sync information as a JsValue.
119    #[wasm_bindgen(getter)]
120    pub fn block_sync(&self) -> JsValue {
121        JsValue::from_serde(&self.0.block_sync).unwrap()
122    }
123
124    /// Converts the GetNodeStatusResult to a JsValue.
125    #[wasm_bindgen(js_name = "toJson")]
126    pub fn to_json(&self) -> JsValue {
127        JsValue::from_serde(&self.0).unwrap_or(JsValue::null())
128    }
129}
130
131/// SDK methods related to retrieving node status information.
132#[cfg(target_arch = "wasm32")]
133#[wasm_bindgen]
134impl SDK {
135    /// Retrieves node status information using the provided options.
136    ///
137    /// # Arguments
138    ///
139    /// * `verbosity` - An optional `Verbosity` level for controlling the output verbosity.
140    /// * `rpc_address` - An optional string specifying the rpc address to use for the request.
141    ///
142    /// # Returns
143    ///
144    /// A `Result` containing either a `GetNodeStatusResult` or a `JsError` in case of an error.
145    ///
146    /// # Errors
147    ///
148    /// Returns a `JsError` if there is an error during the retrieval process.
149    #[wasm_bindgen(js_name = "get_node_status")]
150    pub async fn get_node_status_js_alias(
151        &self,
152        verbosity: Option<Verbosity>,
153        rpc_address: Option<String>,
154    ) -> Result<GetNodeStatusResult, JsError> {
155        let result = self.get_node_status(verbosity, rpc_address).await;
156        match result {
157            Ok(data) => Ok(data.result.into()),
158            Err(err) => {
159                let err = &format!("Error occurred with {:?}", err);
160                Err(JsError::new(err))
161            }
162        }
163    }
164
165    // JavaScript alias for `get_node_status`
166    #[deprecated(note = "This function is an alias. Please use `get_node_status` instead.")]
167    #[allow(deprecated)]
168    pub async fn info_get_status(
169        &self,
170        verbosity: Option<Verbosity>,
171        rpc_address: Option<String>,
172    ) -> Result<GetNodeStatusResult, JsError> {
173        self.get_node_status_js_alias(verbosity, rpc_address).await
174    }
175}
176
177impl SDK {
178    /// Retrieves node status information based on the provided options.
179    ///
180    /// # Arguments
181    ///
182    /// * `verbosity` - An optional `Verbosity` level for controlling the output verbosity.
183    /// * `rpc_address` - An optional string specifying the rpc address to use for the request.
184    ///
185    /// # Returns
186    ///
187    /// A `Result` containing either a `_GetNodeStatusResult` or an `Error` in case of an error.
188    ///
189    /// # Errors
190    ///
191    /// Returns an `Error` if there is an error during the retrieval process.
192    pub async fn get_node_status(
193        &self,
194        verbosity: Option<Verbosity>,
195        rpc_address: Option<String>,
196    ) -> Result<SuccessResponse<_GetNodeStatusResult>, Error> {
197        //log("get_node_status!");
198        get_node_status(
199            JsonRpcId::from(rand::thread_rng().gen::<u64>().to_string()),
200            &self.get_rpc_address(rpc_address),
201            self.get_verbosity(verbosity).into(),
202        )
203        .await
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use sdk_tests::tests::helpers::get_network_constants;
211
212    #[tokio::test]
213    async fn test_get_node_status_with_none_values() {
214        // Arrange
215        let sdk = SDK::new(None, None, None);
216        let error_message = "failed to parse node address as valid URL";
217
218        // Act
219        let result = sdk.get_node_status(None, None).await;
220
221        // Assert
222        assert!(result.is_err());
223        let err_string = result.err().unwrap().to_string();
224        assert!(err_string.contains(error_message));
225    }
226
227    #[tokio::test]
228    async fn test_get_node_status_with_specific_arguments() {
229        // Arrange
230        let sdk = SDK::new(None, None, None);
231        let verbosity = Some(Verbosity::High);
232        let (rpc_address, _, _, _, _) = get_network_constants();
233
234        // Act
235        let result = sdk.get_node_status(verbosity, Some(rpc_address)).await;
236
237        // Assert
238        assert!(result.is_ok());
239    }
240
241    #[tokio::test]
242    async fn test_get_node_status_with_error() {
243        let sdk = SDK::new(Some("http://localhost".to_string()), None, None);
244
245        let error_message = "error sending request for url (http://localhost/rpc)";
246
247        // Act
248        let result = sdk.get_node_status(None, None).await;
249
250        // Assert
251        assert!(result.is_err());
252        let err_string = result.err().unwrap().to_string();
253        assert!(err_string.contains(error_message));
254    }
255}