Skip to main content

casper_rust_wasm_sdk/helpers/
mod.rs

1use crate::types::hash::account_hash::AccountHash;
2use crate::types::transaction_params::transaction_str_params::{DEFAULT_GAS_PRICE, DEFAULT_TTL};
3use crate::types::{key::Key, public_key::PublicKey, sdk_error::SdkError, verbosity::Verbosity};
4use base64::engine::general_purpose;
5use base64::Engine;
6use bigdecimal::BigDecimal;
7use blake2::{Blake2b256, Digest};
8use casper_client::cli::JsonArg;
9use casper_types::{
10    bytesrepr::ToBytes, cl_value_to_json as cl_value_to_json_from_casper_types, CLValue,
11    Key as CasperTypesKey, NamedArg, PublicKey as CasperTypesPublicKey, RuntimeArgs, SecretKey,
12    TimeDiff, Timestamp,
13};
14use chrono::{DateTime, SecondsFormat, Utc};
15#[cfg(all(feature = "js", target_arch = "wasm32"))]
16use gloo_utils::format::JsValueSerdeExt;
17use serde::Serialize;
18use serde_json::Value;
19use std::str::FromStr;
20#[cfg(all(feature = "js", target_arch = "wasm32"))]
21use wasm_bindgen::{JsCast, JsValue};
22
23/// Converts a CLValue to a JSON Value.
24///
25/// # Arguments
26///
27/// * `cl_value` - The CLValue to convert.
28///
29/// # Returns
30///
31/// A JSON Value representing the CLValue data.
32pub fn cl_value_to_json(cl_value: &CLValue) -> Option<Value> {
33    cl_value_to_json_from_casper_types(cl_value)
34}
35
36/// Gets the current timestamp.
37///
38/// # Arguments
39///
40/// * `timestamp` - An optional timestamp value in milliseconds since the Unix epoch.
41///
42/// # Returns
43///
44/// A string containing the current timestamp in RFC3339 format.
45pub fn get_current_timestamp(timestamp: Option<String>) -> String {
46    let parsed_timestamp = timestamp.as_ref().and_then(|ts| ts.parse::<i64>().ok());
47    let current_timestamp = parsed_timestamp
48        .map(|parsed_time| DateTime::from_timestamp(parsed_time / 1000, 0).unwrap_or_else(Utc::now))
49        .unwrap_or_else(Utc::now);
50    current_timestamp.to_rfc3339_opts(SecondsFormat::Secs, true)
51}
52
53/// Computes the Blake2b hash of the provided metadata.
54///
55/// # Arguments
56///
57/// * `meta_data` - A reference to a string containing the metadata to be hashed.
58///
59/// # Returns
60///
61/// A hexadecimal string representing the Blake2b hash of the input metadata.
62pub fn get_blake2b_hash(meta_data: &str) -> String {
63    hex::encode(Blake2b256::digest(meta_data.as_bytes()))
64}
65
66/// Creates a dictionary item key by concatenating the serialized bytes of the key and value.
67///
68/// # Arguments
69///
70/// * `key` - The key to be serialized.
71/// * `value` - The value to be serialized.
72///
73/// # Returns
74///
75/// A hexadecimal-encoded string representing the dictionary item key.
76///
77/// # Panics
78///
79/// Panics if the hasher cannot be created.
80///
81/// # Example
82///
83/// ```rust
84/// use casper_types::{U256, U512};
85/// use casper_rust_wasm_sdk::helpers::make_dictionary_item_key;
86/// use casper_rust_wasm_sdk::types::key::Key;
87/// // Key / Value as U256
88/// let key = Key::from_formatted_str( "account-hash-e11bfffe63bf899ea07117af8a2bb43ef0078c0e38ebee6b6cb0b0e39c233538").unwrap();
89/// let value = U256::from(1);
90/// let dictionary_item_key = make_dictionary_item_key(&key, &value);
91/// println!("Dictionary Item Key (Key/Value as U256): {}", dictionary_item_key);
92/// assert_eq!(dictionary_item_key,"145f6211a24c0a8af16b47e7aa58431ea25172eb402903b3c25ac92b9784c7a9".to_string());
93/// // Key / Value as Key
94/// let key = Key::from_formatted_str( "account-hash-813428ce1a9805f1087db07e6017c6c4f5af0ee78a05591bb6577763e89b4f1f").unwrap();
95/// let value = Key::from_formatted_str("account-hash-e11bfffe63bf899ea07117af8a2bb43ef0078c0e38ebee6b6cb0b0e39c233538").unwrap();
96/// let dictionary_item_key = make_dictionary_item_key(&key, &value);
97/// println!("Dictionary Item Key (Key/Value as Key): {}", dictionary_item_key);
98/// assert_eq!(dictionary_item_key,"1e26dc82db208943c3785c0e11b9d78b9c408fee748c78dda5a5d016840dedca".to_string());
99/// ```
100pub fn make_dictionary_item_key<V: ToBytes>(key: &Key, value: &V) -> String {
101    let key: CasperTypesKey = CasperTypesKey::from(key.clone());
102    let mut bytes = key.to_bytes().unwrap_or_default();
103    bytes.extend(value.to_bytes().unwrap_or_default());
104    hex::encode(Blake2b256::digest(&bytes))
105}
106
107/// Convert a formatted account hash to a base64-encoded Key as string (cep-18 key encoding).
108///
109/// # Arguments
110///
111/// * `formatted_account_hash` - A hex-formatted string representing the account hash.
112///
113/// Example: "account-hash-b485c074cef7ccaccd0302949d2043ab7133abdb14cfa87e8392945c0bd80a5f"
114///
115/// # Returns
116///
117/// Returns a `Result` with the base64-encoded string on success, or a `SdkError` on failure.
118/// Example: "ALSFwHTO98yszQMClJ0gQ6txM6vbFM+ofoOSlFwL2Apf"
119pub fn get_base64_key_from_account_hash(account_hash: &str) -> Result<String, Box<SdkError>> {
120    let account_hash = AccountHash::from_formatted_str(account_hash)?;
121    let key = Key::from_account(account_hash).to_bytes().unwrap();
122    Ok(general_purpose::STANDARD.encode(key)) // base64.encode
123}
124
125/// Converts a formatted key hash to a base64-encoded string (CEP-18 key encoding).
126///
127/// # Arguments
128///
129/// * `formatted_hash` - A hex-formatted string representing the key hash.
130///   Example: "hash-b485c074cef7ccaccd0302949d2043ab7133abdb14cfa87e8392945c0bd80a5f"
131///
132/// # Returns
133///
134/// Returns a `Result` containing the base64-encoded string on success.
135/// Example: "AbSFwHTO98yszQMClJ0gQ6txM6vbFM+ofoOSlFwL2Apf"
136///
137/// # Errors
138///
139/// This function returns an error if:
140/// - The input string is not a valid formatted key hash.
141/// - The conversion to bytes or base64 encoding fails.
142pub fn get_base64_key_from_key_hash(formatted_hash: &str) -> Result<String, Box<SdkError>> {
143    let key = Key::from_formatted_str(formatted_hash)?;
144    let key = key.to_bytes().unwrap();
145    Ok(general_purpose::STANDARD.encode(key)) // base64.encode
146}
147
148/// Prefix used when addressable entities are enabled for contract-shaped named keys.
149pub const ENTITY_CONTRACT_PREFIX: &str = "entity-contract-";
150/// Prefix expected by `query_global_state` for classic `StoredValue::Contract` keys.
151pub const HASH_PREFIX: &str = "hash-";
152
153/// Maps a contract-shaped formatted key to the `hash-…` form used when AE is off.
154///
155/// With addressable entities disabled, account named keys often still store
156/// `entity-contract-<hex>`, but `query_global_state` and contract-info identifiers
157/// resolve `hash-<hex>` to `StoredValue::Contract`. Pass the named-key string
158/// through this helper before those queries.
159///
160/// - `entity-contract-<hex>` → `hash-<hex>`
161/// - already `hash-…` → unchanged
162/// - bare hex (no prefix) → `hash-<hex>`
163/// - any other prefix → unchanged
164pub fn contract_hash_key_for_global_state(formatted: &str) -> String {
165    if let Some(hex) = formatted.strip_prefix(ENTITY_CONTRACT_PREFIX) {
166        format!("{HASH_PREFIX}{hex}")
167    } else if formatted.starts_with(HASH_PREFIX) {
168        formatted.to_string()
169    } else if formatted.contains('-') {
170        // account-hash-, uref-, package-, addressable-entity-, …
171        formatted.to_string()
172    } else {
173        format!("{HASH_PREFIX}{formatted}")
174    }
175}
176
177/// Strips `hash-` or `entity-contract-` for hex-only comparisons.
178pub fn strip_contract_key_prefix(formatted: &str) -> &str {
179    formatted
180        .strip_prefix(HASH_PREFIX)
181        .or_else(|| formatted.strip_prefix(ENTITY_CONTRACT_PREFIX))
182        .unwrap_or(formatted)
183}
184
185/// Gets the time to live (TTL) value or returns the default value if not provided.
186///
187/// # Arguments
188///
189/// * `ttl` - An optional TTL value as a string.
190///
191/// # Returns
192///
193/// A string containing the TTL value or the default TTL if not provided.
194pub fn get_ttl_or_default(ttl: Option<&str>) -> String {
195    if let Some(ttl) = ttl {
196        ttl.to_string()
197    } else {
198        DEFAULT_TTL.to_string()
199    }
200}
201
202/// Parses a timestamp string into a `Timestamp` object.
203///
204/// # Arguments
205///
206/// * `value` - The timestamp string to parse.
207///
208/// # Returns
209///
210/// A `Result` containing the parsed `Timestamp` or an error if parsing fails.
211pub fn parse_timestamp(value: &str) -> Result<Timestamp, Box<SdkError>> {
212    Timestamp::from_str(value).map_err(|error| {
213        Box::new(SdkError::FailedToParseTimestamp {
214            context: "timestamp",
215            error,
216        })
217    })
218}
219
220/// Parses a TTL (time to live) string into a `TimeDiff` object.
221///
222/// # Arguments
223///
224/// * `value` - The TTL string to parse.
225///
226/// # Returns
227///
228/// A `Result` containing the parsed `TimeDiff` or an error if parsing fails.
229pub fn parse_ttl(value: &str) -> Result<TimeDiff, Box<SdkError>> {
230    TimeDiff::from_str(value).map_err(|error| {
231        Box::new(SdkError::FailedToParseTimeDiff {
232            context: "ttl",
233            error,
234        })
235    })
236}
237
238/// Gets the gas price or returns the default value if not provided.
239///
240/// # Arguments
241///
242/// * `gas_price` - An optional gas price value.
243///
244/// # Returns
245///
246/// The gas price or the default gas price if not provided.
247pub fn get_gas_price_or_default(gas_price: Option<u64>) -> u64 {
248    gas_price.unwrap_or(DEFAULT_GAS_PRICE)
249}
250
251/// Gets the value as a string or returns an empty string if not provided.
252///
253/// # Arguments
254///
255/// * `opt_str` - An optional string value.
256///
257/// # Returns
258///
259/// The string value or an empty string if not provided.
260pub(crate) fn get_str_or_default(opt_str: Option<&String>) -> &str {
261    opt_str.map(String::as_str).unwrap_or_default()
262}
263
264/// Generates a secret key using the Ed25519 algorithm.
265///
266/// # Returns
267///
268/// A `Result` containing the generated secret key or an error if the generation fails.
269///
270/// # Errors
271///
272/// Returns an `SdkError` if the secret key generation fails.
273pub fn secret_key_generate() -> Result<SecretKey, Box<SdkError>> {
274    SecretKey::generate_ed25519().map_err(|err| {
275        Box::new(SdkError::FailedToGenerateSecretKey {
276            context: "secret_key_from_pem".to_string(),
277            error: err,
278        })
279    })
280}
281
282/// Generates a secret key using the secp256k1 algorithm.
283///
284/// # Returns
285///
286/// A `Result` containing the generated secret key or an error if the generation fails.
287///
288/// # Errors
289///
290/// Returns an `SdkError` if the secret key generation fails.
291pub fn secret_key_secp256k1_generate() -> Result<SecretKey, Box<SdkError>> {
292    SecretKey::generate_secp256k1().map_err(|err| {
293        Box::new(SdkError::FailedToGenerateSecretKey {
294            context: "secret_key_from_pem".to_string(),
295            error: err,
296        })
297    })
298}
299
300/// Parses a secret key in PEM format into a `SecretKey` object.
301///
302/// # Arguments
303///
304/// * `secret_key` - The secret key in PEM format.
305///
306/// # Returns
307///
308/// A `Result` containing the parsed `SecretKey` or an error if parsing fails.
309pub fn secret_key_from_pem(secret_key: &str) -> Result<SecretKey, Box<SdkError>> {
310    SecretKey::from_pem(secret_key).map_err(|err| {
311        Box::new(SdkError::FailedToParseSecretKey {
312            context: "secret_key_from_pem".to_string(),
313            error: err,
314        })
315    })
316}
317
318/// Converts a secret key in PEM format to its corresponding public key as a string.
319///
320/// # Arguments
321///
322/// * `secret_key` - The secret key in PEM format.
323///
324/// # Returns
325///
326/// A `Result` containing the public key as a string or an error if the conversion fails.
327pub fn public_key_from_secret_key(secret_key: &str) -> Result<String, Box<SdkError>> {
328    // Handle the secret key parsing and map the error
329    let secret_key_from_pem = secret_key_from_pem(secret_key)?;
330
331    // Convert the secret key to public key and handle potential errors
332    let public_key = CasperTypesPublicKey::from(&secret_key_from_pem);
333
334    // Convert to desired public key format
335    let public_key_test: PublicKey = public_key.into();
336
337    // Return the public key as a string
338    Ok(public_key_test.to_string())
339}
340
341/// Converts a hexadecimal string to a vector of unsigned 8-bit integers (Uint8Array).
342///
343/// # Arguments
344///
345/// * `hex_string` - The hexadecimal string to convert.
346///
347/// # Returns
348///
349/// A vector of unsigned 8-bit integers (Uint8Array) containing the converted value.
350pub fn hex_to_uint8_vec(hex_string: &str) -> Vec<u8> {
351    let mut bytes = Vec::with_capacity(hex_string.len() / 2);
352    let mut hex_chars = hex_string.chars();
353    while let (Some(a), Some(b)) = (hex_chars.next(), hex_chars.next()) {
354        if let Ok(byte) = u8::from_str_radix(&format!("{a}{b}"), 16) {
355            bytes.push(byte);
356        } else {
357            // If an invalid hex pair is encountered, return an empty vector.
358            return Vec::new();
359        }
360    }
361    bytes
362}
363
364/// Converts a hexadecimal string to a regular string.
365///
366/// # Arguments
367///
368/// * `hex_string` - The hexadecimal string to convert.
369///
370/// # Returns
371///
372/// A regular string containing the converted value.
373pub fn hex_to_string(hex_string: &str) -> String {
374    match hex::decode(hex_string) {
375        Ok(bytes) => String::from_utf8_lossy(&bytes).to_string(),
376        Err(_) => hex_string.to_string(),
377    }
378}
379
380/// Converts motes to CSPR (Casper tokens).
381///
382/// # Arguments
383///
384/// * `motes` - The motes value to convert.
385///
386/// # Returns
387///
388/// A string representing the CSPR amount.
389pub fn motes_to_cspr(motes: &str) -> Result<String, Box<SdkError>> {
390    match BigDecimal::from_str(motes) {
391        Ok(motes_decimal) => {
392            let divisor = BigDecimal::from(1_000_000_000);
393            let cspr_decimal = &motes_decimal / divisor;
394            let formatted_cspr = format!("{cspr_decimal:.2}");
395
396            if formatted_cspr.ends_with(".00") {
397                Ok(formatted_cspr.replace(".00", ""))
398            } else {
399                Ok(formatted_cspr)
400            }
401        }
402        Err(err) => Err(Box::new(SdkError::CustomError {
403            context: "Failed to parse input as BigDecimal",
404            error: format!("{err:?}"),
405        })),
406    }
407}
408
409/// Pretty prints a serializable value as a JSON string.
410///
411/// # Arguments
412///
413/// * `value` - The serializable value to pretty print.
414/// * `verbosity` - An optional verbosity level for pretty printing.
415///
416/// # Returns
417///
418/// A JSON string representing the pretty printed value.
419pub fn json_pretty_print<T>(value: T, verbosity: Option<Verbosity>) -> Result<String, Box<SdkError>>
420where
421    T: Serialize,
422{
423    let deserialized = serde_json::to_value(&value).map_err(|e| Box::new(SdkError::from(e)))?;
424
425    match verbosity {
426        Some(Verbosity::Low) | None => Ok(deserialized.to_string()),
427        Some(Verbosity::Medium) => casper_types::json_pretty_print(&deserialized).map_err(|err| {
428            Box::new(SdkError::CustomError {
429                context: "Error in json_pretty_print",
430                error: format!("{err}"),
431            })
432        }),
433        Some(Verbosity::High) => {
434            serde_json::to_string_pretty(&deserialized).map_err(|e| Box::new(SdkError::from(e)))
435        }
436    }
437}
438
439/// Inserts a JavaScript value argument into a RuntimeArgs map.
440///
441/// # Arguments
442///
443/// * `args` - The RuntimeArgs map to insert the argument into.
444/// * `js_value_arg` - The JavaScript value argument to insert.
445///
446/// # Returns
447///
448/// The modified `RuntimeArgs` map.
449#[cfg(all(feature = "js", target_arch = "wasm32"))]
450pub fn insert_js_value_arg(
451    args: &mut RuntimeArgs,
452    js_value_arg: JsValue,
453) -> Result<&RuntimeArgs, SdkError> {
454    if js_value_arg.is_instance_of::<js_sys::Object>() {
455        let json_arg: JsonArg = js_value_arg
456            .into_serde()
457            .map_err(|err| SdkError::CustomError {
458                context: "Error converting to JsonArg",
459                error: format!("{err:?}"),
460            })?;
461
462        let named_arg = NamedArg::try_from(json_arg).map_err(|err| SdkError::CustomError {
463            context: "Error converting to NamedArg",
464            error: format!("{err:?}"),
465        })?;
466
467        args.insert_cl_value(named_arg.name(), named_arg.cl_value().clone());
468    } else if let Some(string_arg) = js_value_arg.as_string() {
469        let simple_arg = string_arg;
470        casper_client::cli::insert_arg(&simple_arg, args).map_err(|err| SdkError::CustomError {
471            context: "Error inserting simple arg",
472            error: format!("{err:?}"),
473        })?;
474    } else {
475        return Err(SdkError::CustomError {
476            context: "Error converting to JsonArg or Simple Arg",
477            error: String::from("Conversion failed"),
478        });
479    }
480
481    Ok(args)
482}
483
484/// Inserts an argument into a RuntimeArgs map.
485///
486/// # Arguments
487///
488/// * `args` - The RuntimeArgs map to insert the argument into.
489/// * `new_arg` - The argument as a string.
490///
491/// # Returns
492///
493/// The modified `RuntimeArgs` map.
494pub(crate) fn insert_arg(args: &mut RuntimeArgs, new_arg: String) -> &RuntimeArgs {
495    match serde_json::from_str::<JsonArg>(&new_arg) {
496        Ok(json_arg) => {
497            if let Ok(named_arg) = NamedArg::try_from(json_arg.clone()) {
498                // JSON args
499                args.insert_cl_value(named_arg.name(), named_arg.cl_value().clone());
500            }
501        }
502        Err(_) => {
503            // Simple args
504            let _ = casper_client::cli::insert_arg(&new_arg, args);
505        }
506    }
507    args
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513    use casper_types::U256;
514
515    #[test]
516    fn test_contract_hash_key_for_global_state() {
517        let hex = "5be5b0ef09a7016e11292848d77f539e55791cb07a7012fbc336b1f92a4fe743";
518        assert_eq!(
519            contract_hash_key_for_global_state(&format!("entity-contract-{hex}")),
520            format!("hash-{hex}")
521        );
522        assert_eq!(
523            contract_hash_key_for_global_state(&format!("hash-{hex}")),
524            format!("hash-{hex}")
525        );
526        assert_eq!(
527            contract_hash_key_for_global_state(hex),
528            format!("hash-{hex}")
529        );
530        assert_eq!(
531            contract_hash_key_for_global_state(&format!("uref-{hex}-007")),
532            format!("uref-{hex}-007")
533        );
534        assert_eq!(
535            strip_contract_key_prefix(&format!("entity-contract-{hex}")),
536            hex
537        );
538        assert_eq!(strip_contract_key_prefix(&format!("hash-{hex}")), hex);
539    }
540
541    #[test]
542    fn test_cl_value_to_json() {
543        let cl_value = CLValue::from_t((1, 2, 3)).unwrap();
544        let json_value = cl_value_to_json(&cl_value).unwrap();
545        assert_eq!(
546            json_value,
547            Value::Array(vec![
548                Value::Number(1.into()),
549                Value::Number(2.into()),
550                Value::Number(3.into())
551            ])
552        );
553    }
554
555    #[test]
556    fn test_get_current_timestamp() {
557        let timestamp = Some("1234567890".to_string());
558        let current_timestamp = get_current_timestamp(timestamp);
559        assert_eq!(&current_timestamp, "1970-01-15T06:56:07Z");
560    }
561
562    #[test]
563    fn test_get_blake2b_hash() {
564        let metadata = "some metadata";
565        let hash = get_blake2b_hash(metadata);
566        assert_eq!(
567            &hash,
568            "767de9efccc76bc0eef85ea81fcaa56dc7047e660c74b3dc39f84ab8c4931c0d"
569        );
570    }
571
572    #[test]
573    fn test_get_ttl_or_default() {
574        let ttl = Some("1h".to_string());
575        let ttl_value = get_ttl_or_default(ttl.as_deref());
576        assert_eq!(ttl_value, "1h".to_string());
577
578        let default_ttl = get_ttl_or_default(None);
579        assert_eq!(default_ttl, DEFAULT_TTL.to_string());
580    }
581
582    #[test]
583    fn test_parse_timestamp() {
584        let valid_timestamp = "2023-11-06T12:00:00Z";
585        let parsed_timestamp = parse_timestamp(valid_timestamp);
586        assert!(parsed_timestamp.is_ok());
587
588        let invalid_timestamp = "invalid_timestamp";
589        let parsed_timestamp = parse_timestamp(invalid_timestamp);
590        assert!(parsed_timestamp.is_err());
591    }
592
593    #[test]
594    fn test_parse_ttl() {
595        let valid_ttl = "1h";
596        let parsed_ttl = parse_ttl(valid_ttl);
597        assert!(parsed_ttl.is_ok());
598
599        let invalid_ttl = "invalid_ttl";
600        let parsed_ttl = parse_ttl(invalid_ttl);
601        assert!(parsed_ttl.is_err());
602    }
603
604    #[test]
605    fn test_get_gas_price_or_default() {
606        let gas_price = Some(100);
607        let price = get_gas_price_or_default(gas_price);
608        assert_eq!(price, 100);
609
610        let default_price = get_gas_price_or_default(None);
611        assert_eq!(default_price, DEFAULT_GAS_PRICE);
612    }
613
614    #[test]
615    fn test_get_str_or_default() {
616        let input_str = Some("test_string".to_string());
617        let result = get_str_or_default(input_str.as_ref());
618        assert_eq!(result, "test_string");
619
620        let default_str: Option<String> = None;
621        let result = get_str_or_default(default_str.as_ref());
622        assert_eq!(result, "");
623    }
624
625    #[test]
626    fn test_secret_key_generate() {
627        // Act
628        let result = secret_key_generate();
629
630        // Assert
631        assert!(result.is_ok());
632        let secret_key = result.unwrap();
633        assert_eq!(&secret_key.to_string(), "SecretKey::Ed25519");
634    }
635
636    #[test]
637    fn test_secret_key_secp256k1_generate() {
638        // Act
639        let result = secret_key_secp256k1_generate();
640
641        // Assert
642        assert!(result.is_ok());
643        let secret_key = result.unwrap();
644        assert_eq!(&secret_key.to_string(), "SecretKey::Secp256k1");
645    }
646
647    #[test]
648    fn test_secret_key_from_pem() {
649        let pem_key = "-----BEGIN PRIVATE KEY-----\nTEST\n-----END PRIVATE KEY-----";
650        let result = secret_key_from_pem(pem_key);
651        assert!(result.is_err());
652        let pem_key =
653        "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEII8ULlk1CJ12ZQ+bScjBt/IxMAZNggClWqK56D1/7CbI\n-----END PRIVATE KEY-----";
654        let result = secret_key_from_pem(pem_key);
655        assert!(result.is_ok());
656        assert_eq!(&result.unwrap().to_string(), "SecretKey::Ed25519");
657    }
658
659    #[test]
660    fn test_public_key_from_secret_key() {
661        let pem_key = "-----BEGIN PRIVATE KEY-----\nTEST\n-----END PRIVATE KEY-----";
662        let result = public_key_from_secret_key(pem_key);
663        assert!(result.is_err());
664        let pem_key =
665        "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEII8ULlk1CJ12ZQ+bScjBt/IxMAZNggClWqK56D1/7CbI-----END PRIVATE KEY-----";
666        let result = public_key_from_secret_key(pem_key);
667        assert!(result.is_ok());
668        assert_eq!(
669            result.unwrap(),
670            "01aff5c18a954604dd27d139d8e0cfc533ac3d53784d76c7a7ac5ff4039510fdf6"
671        );
672    }
673
674    #[test]
675    fn test_hex_to_uint8_vec() {
676        let hex_string = "0161e40005434ba3cd9a791a2827f5fa3ee514d1475fe72b2823cbaac9c3c71483";
677        let result = hex_to_uint8_vec(hex_string);
678        assert_eq!(
679            result,
680            vec![
681                1, 97, 228, 0, 5, 67, 75, 163, 205, 154, 121, 26, 40, 39, 245, 250, 62, 229, 20,
682                209, 71, 95, 231, 43, 40, 35, 203, 170, 201, 195, 199, 20, 131
683            ]
684        );
685    }
686
687    #[test]
688    fn test_hex_to_string() {
689        let hex_string = "48656c6c6f20436173706572";
690        let result = hex_to_string(hex_string);
691        assert_eq!(result, "Hello Casper");
692    }
693
694    #[test]
695    fn test_motes_to_cspr() {
696        let motes = "1000000000";
697        let result = motes_to_cspr(motes).unwrap();
698        assert_eq!(result, "1");
699    }
700
701    #[test]
702    fn test_json_pretty_print() {
703        #[derive(Serialize, Clone)]
704        struct TestData {
705            age: i32,
706            name: String,
707        }
708
709        let data = TestData {
710            age: 42,
711            name: "Joe".to_string(),
712        };
713
714        let result = json_pretty_print(data.clone(), None).unwrap();
715        assert_eq!(result, "{\"age\":42,\"name\":\"Joe\"}");
716
717        let result = json_pretty_print(data.clone(), Some(Verbosity::Low)).unwrap();
718        assert_eq!(result, "{\"age\":42,\"name\":\"Joe\"}");
719
720        let result = json_pretty_print(data.clone(), Some(Verbosity::Medium)).unwrap();
721        assert_eq!(result, "{\n  \"age\": 42,\n  \"name\": \"Joe\"\n}");
722
723        let result = json_pretty_print(data, Some(Verbosity::High)).unwrap();
724        assert_eq!(result, "{\n  \"age\": 42,\n  \"name\": \"Joe\"\n}");
725    }
726
727    #[test]
728    fn test_insert_arg_simple() {
729        let mut args = RuntimeArgs::new();
730        let new_arg = "message:String='Hello Casper";
731        let result_args = insert_arg(&mut args, new_arg.to_string());
732        assert_eq!(result_args.len(), 1);
733        let cl_value = result_args.get("message").unwrap();
734        let json = cl_value_to_json(cl_value).unwrap();
735        let expexted_json = Value::String("Hello Casper".to_string());
736        assert_eq!(json, expexted_json);
737    }
738
739    #[test]
740    fn test_insert_arg_json() {
741        let mut args = RuntimeArgs::new();
742        let arg_json = r#"{"name": "bar", "type": "U256", "value": 1}"#; // No brackets only one arg
743        let result_args = insert_arg(&mut args, arg_json.to_string());
744        assert_eq!(result_args.len(), 1);
745        let cl_value = result_args.get("bar").unwrap();
746        let json = cl_value_to_json(cl_value).unwrap();
747        let expexted_json = Value::String("1".to_string());
748        assert_eq!(json, expexted_json);
749    }
750
751    #[test]
752    pub fn test_make_dictionary_item_key() {
753        let key = Key::from_formatted_str(
754            "account-hash-e11bfffe63bf899ea07117af8a2bb43ef0078c0e38ebee6b6cb0b0e39c233538",
755        )
756        .unwrap();
757        let value = U256::from(1);
758        let dictionary_item_key = make_dictionary_item_key(&key, &value);
759        assert_eq!(
760            dictionary_item_key,
761            "145f6211a24c0a8af16b47e7aa58431ea25172eb402903b3c25ac92b9784c7a9".to_string()
762        );
763        let key = Key::from_formatted_str(
764            "account-hash-813428ce1a9805f1087db07e6017c6c4f5af0ee78a05591bb6577763e89b4f1f",
765        )
766        .unwrap();
767        let value = Key::from_formatted_str(
768            "account-hash-e11bfffe63bf899ea07117af8a2bb43ef0078c0e38ebee6b6cb0b0e39c233538",
769        )
770        .unwrap();
771        let dictionary_item_key = make_dictionary_item_key(&key, &value);
772        assert_eq!(
773            dictionary_item_key,
774            "1e26dc82db208943c3785c0e11b9d78b9c408fee748c78dda5a5d016840dedca".to_string()
775        );
776    }
777
778    #[test]
779    fn test_get_base64_key_from_account_hash() {
780        // Test with a known input and expected output
781        let input_hash =
782            "account-hash-b485c074cef7ccaccd0302949d2043ab7133abdb14cfa87e8392945c0bd80a5f";
783        let expected_output = "ALSFwHTO98yszQMClJ0gQ6txM6vbFM+ofoOSlFwL2Apf";
784
785        // Call the function under test
786        let result = get_base64_key_from_account_hash(input_hash).unwrap();
787
788        // Check the result against the expected output
789        assert_eq!(result, expected_output.to_string());
790    }
791
792    #[test]
793    fn test_get_base64_key_from_key_hash() {
794        // Test with a known input and expected output
795        let input_hash = "hash-b485c074cef7ccaccd0302949d2043ab7133abdb14cfa87e8392945c0bd80a5f";
796        let expected_output = "AbSFwHTO98yszQMClJ0gQ6txM6vbFM+ofoOSlFwL2Apf";
797
798        // Call the function under test
799        let result = get_base64_key_from_key_hash(input_hash).unwrap();
800
801        // Check the result against the expected output
802        assert_eq!(result, expected_output.to_string());
803    }
804}