Skip to main content

casper_rust_wasm_sdk/sdk/rpcs/
get_validator_changes.rs

1use crate::{
2    types::{sdk_error::SdkError, verbosity::Verbosity},
3    SDK,
4};
5use casper_client::{
6    get_validator_changes, rpcs::results::GetValidatorChangesResult as _GetValidatorChangesResult,
7    JsonRpcId, SuccessResponse,
8};
9#[cfg(all(feature = "js", target_arch = "wasm32"))]
10use gloo_utils::format::JsValueSerdeExt;
11use rand::RngExt;
12#[cfg(all(feature = "js", target_arch = "wasm32"))]
13use serde::{Deserialize, Serialize};
14#[cfg(all(feature = "js", target_arch = "wasm32"))]
15use wasm_bindgen::prelude::*;
16
17/// Wrapper struct for the `GetValidatorChangesResult` from casper_client.
18#[cfg(all(feature = "js", target_arch = "wasm32"))]
19#[derive(Debug, Deserialize, Clone, Serialize)]
20#[cfg_attr(feature = "js", wasm_bindgen)]
21pub struct GetValidatorChangesResult(_GetValidatorChangesResult);
22
23#[cfg(all(feature = "js", target_arch = "wasm32"))]
24impl From<GetValidatorChangesResult> for _GetValidatorChangesResult {
25    fn from(result: GetValidatorChangesResult) -> Self {
26        result.0
27    }
28}
29
30#[cfg(all(feature = "js", target_arch = "wasm32"))]
31impl From<_GetValidatorChangesResult> for GetValidatorChangesResult {
32    fn from(result: _GetValidatorChangesResult) -> Self {
33        GetValidatorChangesResult(result)
34    }
35}
36
37#[cfg(all(feature = "js", target_arch = "wasm32"))]
38#[cfg_attr(feature = "js", wasm_bindgen)]
39impl GetValidatorChangesResult {
40    /// Gets the API version as a JsValue.
41    #[cfg_attr(feature = "js", wasm_bindgen(getter))]
42    #[cfg(feature = "js")]
43    pub fn api_version(&self) -> JsValue {
44        JsValue::from_serde(&self.0.api_version).unwrap()
45    }
46
47    /// Gets the validator changes as a JsValue.
48    #[cfg_attr(feature = "js", wasm_bindgen(getter))]
49    #[cfg(feature = "js")]
50    pub fn changes(&self) -> JsValue {
51        JsValue::from_serde(&self.0.changes).unwrap()
52    }
53
54    /// Converts the GetValidatorChangesResult to a JsValue.
55    #[cfg_attr(feature = "js", wasm_bindgen(js_name = "toJson"))]
56    #[cfg(feature = "js")]
57    pub fn to_json(&self) -> JsValue {
58        JsValue::from_serde(&self.0).unwrap_or(JsValue::null())
59    }
60}
61
62/// SDK methods for working with validator changes.
63#[cfg(all(feature = "js", target_arch = "wasm32"))]
64#[cfg_attr(feature = "js", wasm_bindgen)]
65impl SDK {
66    /// Retrieves validator changes using the provided options.
67    ///
68    /// # Arguments
69    ///
70    /// * `verbosity` - An optional `Verbosity` level for controlling the output verbosity.
71    /// * `rpc_address` - An optional string specifying the rpc address to use for the request.
72    ///
73    /// # Returns
74    ///
75    /// A `Result` containing either a `GetValidatorChangesResult` or a `JsError` in case of an error.
76    ///
77    /// # Errors
78    ///
79    /// Returns a `JsError` if there is an error during the retrieval process.
80    #[cfg_attr(feature = "js", wasm_bindgen(js_name = "get_validator_changes"))]
81    #[cfg(feature = "js")]
82    pub async fn get_validator_changes_js_alias(
83        &self,
84        verbosity: Option<Verbosity>,
85        rpc_address: Option<String>,
86    ) -> Result<GetValidatorChangesResult, JsError> {
87        let result = self.get_validator_changes(verbosity, rpc_address).await;
88        match result {
89            Ok(data) => Ok(data.result.into()),
90            Err(err) => {
91                let err = &format!("Error occurred with {err:?}");
92                Err(JsError::new(err))
93            }
94        }
95    }
96
97    // JavaScript alias for `get_validator_changes`
98    #[deprecated(note = "This function is an alias. Please use `get_validator_changes` instead.")]
99    #[allow(deprecated)]
100    #[cfg(feature = "js")]
101    pub async fn info_get_validator_change(
102        &self,
103        verbosity: Option<Verbosity>,
104        rpc_address: Option<String>,
105    ) -> Result<GetValidatorChangesResult, JsError> {
106        self.get_validator_changes_js_alias(verbosity, rpc_address)
107            .await
108    }
109}
110
111impl SDK {
112    /// Retrieves validator changes based on the provided options.
113    ///
114    /// # Arguments
115    ///
116    /// * `verbosity` - An optional `Verbosity` level for controlling the output verbosity.
117    /// * `rpc_address` - An optional string specifying the rpc address to use for the request.
118    ///
119    /// # Returns
120    ///
121    /// A `Result` containing either a `_GetValidatorChangesResult` or an `Error` in case of an error.
122    ///
123    /// # Errors
124    ///
125    /// Returns an `Error` if there is an error during the retrieval process.
126    pub async fn get_validator_changes(
127        &self,
128        verbosity: Option<Verbosity>,
129        rpc_address: Option<String>,
130    ) -> Result<SuccessResponse<_GetValidatorChangesResult>, SdkError> {
131        //log("get_validator_changes!");
132        let random_id = JsonRpcId::from(rand::rng().random::<u64>().to_string());
133        get_validator_changes(
134            random_id,
135            &self.get_rpc_address(rpc_address),
136            self.get_verbosity(verbosity).into(),
137        )
138        .await
139        .map_err(Into::into)
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use sdk_tests::tests::helpers::get_network_constants;
147
148    #[tokio::test]
149    async fn test_get_validator_changes_with_none_values() {
150        // Arrange
151        let sdk = SDK::new(None, None, None);
152        let error_message = "failed to parse node address as valid URL";
153
154        // Act
155        let result = sdk.get_validator_changes(None, None).await;
156
157        // Assert
158        assert!(result.is_err());
159        let err_string = result.err().unwrap().to_string();
160        assert!(err_string.contains(error_message));
161    }
162
163    #[tokio::test]
164    async fn test_get_validator_changes_with_specific_arguments() {
165        // Arrange
166        let sdk = SDK::new(None, None, None);
167        let verbosity = Some(Verbosity::High);
168        let (rpc_address, _, _, _, _) = get_network_constants();
169
170        // Act
171        let result = sdk
172            .get_validator_changes(verbosity, Some(rpc_address))
173            .await;
174
175        // Assert
176        assert!(result.is_ok());
177    }
178
179    #[tokio::test]
180    async fn test_get_validator_changes_with_error() {
181        let sdk = SDK::new(Some("http://localhost".to_string()), None, None);
182
183        let error_message = "error sending request";
184
185        // Act
186        let result = sdk.get_validator_changes(None, None).await;
187
188        // Assert
189        assert!(result.is_err());
190        let err_string = result.err().unwrap().to_string();
191        assert!(err_string.contains(error_message));
192    }
193}