Skip to main content

casper_rust_wasm_sdk/sdk/rpcs/
put_transaction.rs

1#[cfg(all(feature = "js", target_arch = "wasm32"))]
2use crate::transaction::transaction::PutTransactionResult;
3use crate::{
4    types::{sdk_error::SdkError, transaction::Transaction, verbosity::Verbosity},
5    SDK,
6};
7use casper_client::{
8    put_transaction, rpcs::results::PutTransactionResult as _PutTransactionResult, JsonRpcId,
9    SuccessResponse,
10};
11use rand::RngExt;
12#[cfg(all(feature = "js", target_arch = "wasm32"))]
13use wasm_bindgen::prelude::*;
14
15/// SDK methods for putting a transaction.
16#[cfg(all(feature = "js", target_arch = "wasm32"))]
17#[cfg_attr(feature = "js", wasm_bindgen)]
18impl SDK {
19    /// Puts a transaction using the provided options.
20    ///
21    /// # Arguments
22    ///
23    /// * `transaction` - The `Transaction` object to be sent.
24    /// * `verbosity` - An optional `Verbosity` level for controlling the output verbosity.
25    /// * `rpc_address` - An optional string specifying the rpc address to use for the request.
26    ///
27    /// # Returns
28    ///
29    /// A `Result` containing either a `PutTransactionResult` or a `JsError` in case of an error.
30    ///
31    /// # Errors
32    ///
33    /// Returns a `JsError` if there is an error during the transaction process.
34    #[cfg_attr(feature = "js", wasm_bindgen(js_name = "put_transaction"))]
35    #[cfg(feature = "js")]
36    pub async fn put_transaction_js_alias(
37        &self,
38        transaction: Transaction,
39        verbosity: Option<Verbosity>,
40        rpc_address: Option<String>,
41    ) -> Result<PutTransactionResult, JsError> {
42        let result = self
43            .put_transaction(transaction, verbosity, rpc_address)
44            .await;
45        match result {
46            Ok(data) => Ok(data.result.into()),
47            Err(err) => {
48                let err = &format!("Error occurred with {err:?}");
49                Err(JsError::new(err))
50            }
51        }
52    }
53
54    /// JavaScript Alias for `put_transaction`.
55    #[deprecated(note = "This function is an alias. Please use `put_transaction` instead.")]
56    #[allow(deprecated)]
57    #[cfg(feature = "js")]
58    pub async fn account_put_transaction(
59        &self,
60        transaction: Transaction,
61        verbosity: Option<Verbosity>,
62        rpc_address: Option<String>,
63    ) -> Result<PutTransactionResult, JsError> {
64        self.put_transaction_js_alias(transaction, verbosity, rpc_address)
65            .await
66    }
67}
68
69impl SDK {
70    /// Puts a transaction based on the provided options.
71    ///
72    /// # Arguments
73    ///
74    /// * `transaction` - The `Transaction` object to be sent.
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 `_PutTransactionResult` or an `Error` in case of an error.
81    ///
82    /// # Errors
83    ///
84    /// Returns an `Error` if there is an error during the transaction process.
85    pub async fn put_transaction(
86        &self,
87        transaction: Transaction,
88        verbosity: Option<Verbosity>,
89        rpc_address: Option<String>,
90    ) -> Result<SuccessResponse<_PutTransactionResult>, SdkError> {
91        let random_id = JsonRpcId::from(rand::rng().random::<u64>().to_string());
92        //log("account_put_transaction!");
93        put_transaction(
94            random_id,
95            &self.get_rpc_address(rpc_address),
96            self.get_verbosity(verbosity).into(),
97            transaction.into(),
98        )
99        .await
100        .map_err(Into::into)
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use crate::{
108        helpers::public_key_from_secret_key,
109        types::transaction_params::transaction_str_params::TransactionStrParams,
110    };
111    use sdk_tests::{
112        config::TRANSFER_AMOUNT,
113        tests::helpers::{get_network_constants, get_user_secret_key},
114    };
115
116    fn get_transaction() -> Transaction {
117        let secret_key = get_user_secret_key(None).unwrap();
118        let initiator_addr = public_key_from_secret_key(&secret_key).unwrap();
119        let (_, _, _, _, chain_name) = get_network_constants();
120
121        let transaction_params = TransactionStrParams::default();
122        transaction_params.set_secret_key(&secret_key);
123        transaction_params.set_chain_name(&chain_name);
124        transaction_params.set_payment_amount(TRANSFER_AMOUNT);
125
126        Transaction::new_transfer(
127            None,
128            &initiator_addr, // self transfer
129            TRANSFER_AMOUNT,
130            transaction_params,
131            None,
132        )
133        .unwrap()
134    }
135
136    #[tokio::test]
137    async fn test_put_transaction_with_none_values() {
138        // Arrange
139        let sdk = SDK::new(None, None, None);
140        let error_message = "failed to parse node address as valid URL";
141        let transaction = get_transaction();
142
143        // Act
144        let result = sdk.put_transaction(transaction, None, None).await;
145
146        // Assert
147        assert!(result.is_err());
148        let err_string = result.err().unwrap().to_string();
149        assert!(err_string.contains(error_message));
150    }
151
152    #[tokio::test]
153    async fn test_put_transaction() {
154        // Arrange
155        let sdk = SDK::new(None, None, None);
156        let verbosity = Some(Verbosity::High);
157        let (rpc_address, _, _, _, _) = get_network_constants();
158        let transaction = get_transaction();
159
160        // Act
161        let result = sdk
162            .put_transaction(transaction, verbosity, Some(rpc_address))
163            .await;
164
165        // Assert
166        assert!(result.is_ok());
167    }
168
169    #[tokio::test]
170    async fn test_put_transaction_with_error() {
171        // Arrange
172        let sdk = SDK::new(Some("http://localhost".to_string()), None, None);
173        let error_message = "error sending request";
174        let transaction = get_transaction();
175
176        // Act
177        let result = sdk.put_transaction(transaction, 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}