Skip to main content

casper_rust_wasm_sdk/sdk/rpcs/
list_rpcs.rs

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