Skip to main content

casper_rust_wasm_sdk/sdk/rpcs/
get_chainspec.rs

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