Skip to main content

casper_rust_wasm_sdk/sdk/rpcs/
get_node_status.rs

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