casper_rust_wasm_sdk/sdk/rpcs/
get_auction_info.rs

1#[cfg(target_arch = "wasm32")]
2use crate::types::identifier::block_identifier::BlockIdentifier;
3use crate::{
4    types::{
5        identifier::block_identifier::BlockIdentifierInput, sdk_error::SdkError,
6        verbosity::Verbosity,
7    },
8    SDK,
9};
10use casper_client::{
11    cli::get_auction_info as get_auction_info_cli, get_auction_info as get_auction_info_lib,
12    rpcs::results::GetAuctionInfoResult as _GetAuctionInfoResult, JsonRpcId, SuccessResponse,
13};
14#[cfg(target_arch = "wasm32")]
15use gloo_utils::format::JsValueSerdeExt;
16use rand::Rng;
17#[cfg(target_arch = "wasm32")]
18use serde::{Deserialize, Serialize};
19#[cfg(target_arch = "wasm32")]
20use wasm_bindgen::prelude::*;
21
22// Define a struct to wrap the GetAuctionInfoResult
23#[cfg(target_arch = "wasm32")]
24#[derive(Debug, Deserialize, Clone, Serialize)]
25#[wasm_bindgen]
26pub struct GetAuctionInfoResult(_GetAuctionInfoResult);
27
28#[cfg(target_arch = "wasm32")]
29impl From<GetAuctionInfoResult> for _GetAuctionInfoResult {
30    fn from(result: GetAuctionInfoResult) -> Self {
31        result.0
32    }
33}
34
35#[cfg(target_arch = "wasm32")]
36impl From<_GetAuctionInfoResult> for GetAuctionInfoResult {
37    fn from(result: _GetAuctionInfoResult) -> Self {
38        GetAuctionInfoResult(result)
39    }
40}
41
42#[cfg(target_arch = "wasm32")]
43#[wasm_bindgen]
44impl GetAuctionInfoResult {
45    /// Gets the API version as a JsValue.
46    #[wasm_bindgen(getter)]
47    pub fn api_version(&self) -> JsValue {
48        JsValue::from_serde(&self.0.api_version).unwrap()
49    }
50
51    /// Gets the auction state as a JsValue.
52    #[wasm_bindgen(getter)]
53    pub fn auction_state(&self) -> JsValue {
54        JsValue::from_serde(&self.0.auction_state).unwrap()
55    }
56
57    /// Converts the GetAuctionInfoResult to a JsValue.
58    #[wasm_bindgen(js_name = "toJson")]
59    pub fn to_json(&self) -> JsValue {
60        JsValue::from_serde(&self.0).unwrap_or(JsValue::null())
61    }
62}
63
64/// Options for the `get_auction_info` method.
65#[derive(Debug, Deserialize, Clone, Default, Serialize)]
66#[cfg(target_arch = "wasm32")]
67#[wasm_bindgen(js_name = "getAuctionInfoOptions", getter_with_clone)]
68pub struct GetAuctionInfoOptions {
69    pub maybe_block_id_as_string: Option<String>,
70    pub maybe_block_identifier: Option<BlockIdentifier>,
71    pub rpc_address: Option<String>,
72    pub verbosity: Option<Verbosity>,
73}
74
75#[cfg(target_arch = "wasm32")]
76#[wasm_bindgen]
77impl SDK {
78    /// Parses auction info options from a JsValue.
79    ///
80    /// # Arguments
81    ///
82    /// * `options` - A JsValue containing auction info options to be parsed.
83    ///
84    /// # Returns
85    ///
86    /// Result containing parsed auction info options as a `GetAuctionInfoOptions` struct,
87    /// or a `JsError` if deserialization fails.
88    pub fn get_auction_info_options(
89        &self,
90        options: JsValue,
91    ) -> Result<GetAuctionInfoOptions, JsError> {
92        options
93            .into_serde::<GetAuctionInfoOptions>()
94            .map_err(|err| JsError::new(&format!("Error deserializing options: {:?}", err)))
95    }
96
97    /// Retrieves auction information using the provided options.
98    ///
99    /// # Arguments
100    ///
101    /// * `options` - An optional `GetAuctionInfoOptions` struct containing retrieval options.
102    ///
103    /// # Returns
104    ///
105    /// A `Result` containing either a `GetAuctionInfoResult` or a `JsError` in case of an error.
106    ///
107    /// # Errors
108    ///
109    /// Returns a `JsError` if there is an error during the retrieval process.
110    #[wasm_bindgen(js_name = "get_auction_info")]
111    pub async fn get_auction_info_js_alias(
112        &self,
113        options: Option<GetAuctionInfoOptions>,
114    ) -> Result<GetAuctionInfoResult, JsError> {
115        let GetAuctionInfoOptions {
116            maybe_block_id_as_string,
117            maybe_block_identifier,
118            verbosity,
119            rpc_address,
120        } = options.unwrap_or_default();
121
122        let maybe_block_identifier = if let Some(maybe_block_identifier) = maybe_block_identifier {
123            Some(BlockIdentifierInput::BlockIdentifier(
124                maybe_block_identifier,
125            ))
126        } else {
127            maybe_block_id_as_string.map(BlockIdentifierInput::String)
128        };
129
130        let result = self
131            .get_auction_info(maybe_block_identifier, verbosity, rpc_address)
132            .await;
133        match result {
134            Ok(data) => Ok(data.result.into()),
135            Err(err) => {
136                let err = &format!("Error occurred with {:?}", err);
137                Err(JsError::new(err))
138            }
139        }
140    }
141
142    // JavaScript alias for `get_auction_info`
143    #[wasm_bindgen(js_name = "state_get_auction_info_js_alias")]
144    pub async fn state_get_auction_info(
145        &self,
146        options: Option<GetAuctionInfoOptions>,
147    ) -> Result<GetAuctionInfoResult, JsError> {
148        self.get_auction_info_js_alias(options).await
149    }
150}
151
152impl SDK {
153    /// Retrieves auction information based on the provided options.
154    ///
155    /// # Arguments
156    ///
157    /// * `maybe_block_identifier` - An optional `BlockIdentifierInput` for specifying a block identifier.
158    /// * `verbosity` - An optional `Verbosity` level for controlling the output verbosity.
159    /// * `rpc_address` - An optional string specifying the rpc address to use for the request.
160    ///
161    /// # Returns
162    ///
163    /// A `Result` containing either a `_GetAuctionInfoResult` or a `SdkError` in case of an error.
164    ///
165    /// # Errors
166    ///
167    /// Returns a `SdkError` if there is an error during the retrieval process.
168    pub async fn get_auction_info(
169        &self,
170        maybe_block_identifier: Option<BlockIdentifierInput>,
171        verbosity: Option<Verbosity>,
172        rpc_address: Option<String>,
173    ) -> Result<SuccessResponse<_GetAuctionInfoResult>, SdkError> {
174        //log("get_auction_info!");
175
176        if let Some(BlockIdentifierInput::String(maybe_block_id)) = maybe_block_identifier {
177            get_auction_info_cli(
178                &rand::thread_rng().gen::<u64>().to_string(),
179                &self.get_rpc_address(rpc_address),
180                self.get_verbosity(verbosity).into(),
181                &maybe_block_id,
182            )
183            .await
184            .map_err(SdkError::from)
185        } else {
186            let maybe_block_identifier =
187                if let Some(BlockIdentifierInput::BlockIdentifier(maybe_block_identifier)) =
188                    maybe_block_identifier
189                {
190                    Some(maybe_block_identifier)
191                } else {
192                    None
193                };
194            get_auction_info_lib(
195                JsonRpcId::from(rand::thread_rng().gen::<u64>().to_string()),
196                &self.get_rpc_address(rpc_address),
197                self.get_verbosity(verbosity).into(),
198                maybe_block_identifier.map(Into::into),
199            )
200            .await
201            .map_err(SdkError::from)
202        }
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use crate::types::{
210        hash::block_hash::BlockHash, identifier::block_identifier::BlockIdentifier,
211    };
212    use sdk_tests::tests::helpers::get_network_constants;
213
214    #[tokio::test]
215    async fn test_get_auction_info_with_none_values() {
216        // Arrange
217        let sdk = SDK::new(None, None, None);
218        let error_message = "failed to parse node address as valid URL";
219
220        // Act
221        let result = sdk.get_auction_info(None, None, None).await;
222
223        // Assert
224        assert!(result.is_err());
225        let err_string = result.err().unwrap().to_string();
226        assert!(err_string.contains(error_message));
227    }
228
229    #[ignore = "currently failing on node"]
230    #[tokio::test]
231    async fn test_get_auction_info_with_block_id_string() {
232        // Arrange
233        let sdk = SDK::new(None, None, None);
234        let verbosity = Some(Verbosity::High);
235        let (rpc_address, _, _, _, _) = get_network_constants();
236        let result = sdk
237            .get_block(None, verbosity, Some(rpc_address.clone()))
238            .await;
239        let block_hash = BlockHash::from(
240            *result
241                .unwrap()
242                .result
243                .block_with_signatures
244                .unwrap()
245                .block
246                .hash(),
247        )
248        .to_string();
249        let block_identifier = BlockIdentifierInput::String(block_hash.to_string());
250
251        // Act
252        let result = sdk
253            .get_auction_info(Some(block_identifier), verbosity, Some(rpc_address))
254            .await;
255
256        // Assert
257        assert!(result.is_ok());
258    }
259
260    #[ignore = "currently failing on node"]
261    #[tokio::test]
262    async fn test_get_auction_info_with_block_identifier() {
263        // Arrange
264        let sdk = SDK::new(None, None, None);
265        let block_identifier =
266            BlockIdentifierInput::BlockIdentifier(BlockIdentifier::from_height(1));
267        let verbosity = Some(Verbosity::High);
268        let (rpc_address, _, _, _, _) = get_network_constants();
269
270        // Act
271        let result = sdk
272            .get_auction_info(Some(block_identifier), verbosity, Some(rpc_address))
273            .await;
274
275        // Assert
276        assert!(result.is_ok());
277    }
278
279    #[tokio::test]
280    async fn test_get_auction_info_with_error() {
281        let sdk = SDK::new(Some("http://localhost".to_string()), None, None);
282
283        let error_message = "error sending request for url (http://localhost/rpc)";
284
285        // Act
286        let result = sdk.get_auction_info(None, None, None).await;
287
288        // Assert
289        assert!(result.is_err());
290        let err_string = result.err().unwrap().to_string();
291        assert!(err_string.contains(error_message));
292    }
293}