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
23pub fn cl_value_to_json(cl_value: &CLValue) -> Option<Value> {
33 cl_value_to_json_from_casper_types(cl_value)
34}
35
36pub 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
53pub fn get_blake2b_hash(meta_data: &str) -> String {
63 hex::encode(Blake2b256::digest(meta_data.as_bytes()))
64}
65
66pub 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
107pub 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)) }
124
125pub 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)) }
147
148pub const ENTITY_CONTRACT_PREFIX: &str = "entity-contract-";
150pub const HASH_PREFIX: &str = "hash-";
152
153pub 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 formatted.to_string()
172 } else {
173 format!("{HASH_PREFIX}{formatted}")
174 }
175}
176
177pub 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
185pub 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
202pub 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
220pub 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
238pub fn get_gas_price_or_default(gas_price: Option<u64>) -> u64 {
248 gas_price.unwrap_or(DEFAULT_GAS_PRICE)
249}
250
251pub(crate) fn get_str_or_default(opt_str: Option<&String>) -> &str {
261 opt_str.map(String::as_str).unwrap_or_default()
262}
263
264pub 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
282pub 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
300pub 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
318pub fn public_key_from_secret_key(secret_key: &str) -> Result<String, Box<SdkError>> {
328 let secret_key_from_pem = secret_key_from_pem(secret_key)?;
330
331 let public_key = CasperTypesPublicKey::from(&secret_key_from_pem);
333
334 let public_key_test: PublicKey = public_key.into();
336
337 Ok(public_key_test.to_string())
339}
340
341pub 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 return Vec::new();
359 }
360 }
361 bytes
362}
363
364pub 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
380pub 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
409pub 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#[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
484pub(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 args.insert_cl_value(named_arg.name(), named_arg.cl_value().clone());
500 }
501 }
502 Err(_) => {
503 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!(¤t_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 let result = secret_key_generate();
629
630 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 let result = secret_key_secp256k1_generate();
640
641 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}"#; 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 let input_hash =
782 "account-hash-b485c074cef7ccaccd0302949d2043ab7133abdb14cfa87e8392945c0bd80a5f";
783 let expected_output = "ALSFwHTO98yszQMClJ0gQ6txM6vbFM+ofoOSlFwL2Apf";
784
785 let result = get_base64_key_from_account_hash(input_hash).unwrap();
787
788 assert_eq!(result, expected_output.to_string());
790 }
791
792 #[test]
793 fn test_get_base64_key_from_key_hash() {
794 let input_hash = "hash-b485c074cef7ccaccd0302949d2043ab7133abdb14cfa87e8392945c0bd80a5f";
796 let expected_output = "AbSFwHTO98yszQMClJ0gQ6txM6vbFM+ofoOSlFwL2Apf";
797
798 let result = get_base64_key_from_key_hash(input_hash).unwrap();
800
801 assert_eq!(result, expected_output.to_string());
803 }
804}