diff --git a/src/helpers/mod.rs b/src/helpers/mod.rs index 058ad7a6..b63934af 100644 --- a/src/helpers/mod.rs +++ b/src/helpers/mod.rs @@ -203,6 +203,29 @@ pub fn get_base64_key_from_package_hash(formatted_hash: &str) -> Result Result> { + let key = Key::from_formatted_str(formatted_hash)?; + let key = key.to_bytes().unwrap(); + Ok(general_purpose::STANDARD.encode(key)) // base64.encode +} + /// Gets the time to live (TTL) value or returns the default value if not provided. /// /// # Arguments @@ -816,4 +839,17 @@ mod tests { // Check the result against the expected output assert_eq!(result, expected_output.to_string()); } + + #[test] + fn test_get_base64_key_from_key_hash() { + // Test with a known input and expected output + let input_hash = "hash-b485c074cef7ccaccd0302949d2043ab7133abdb14cfa87e8392945c0bd80a5f"; + let expected_output = "AbSFwHTO98yszQMClJ0gQ6txM6vbFM+ofoOSlFwL2Apf"; + + // Call the function under test + let result = get_base64_key_from_key_hash(input_hash).unwrap(); + + // Check the result against the expected output + assert_eq!(result, expected_output.to_string()); + } } diff --git a/src/js/interns.rs b/src/js/interns.rs index 00527adb..cddbba8b 100644 --- a/src/js/interns.rs +++ b/src/js/interns.rs @@ -281,6 +281,35 @@ pub fn get_base64_key_from_package_hash_js_alias( }) } +/// Converts a formatted key hash to a base64-encoded string (CEP-18 key encoding) for use in JavaScript. +/// +/// This function acts as a wrapper around `get_base64_key_from_key_hash` and maps errors to JavaScript-compatible errors. +/// +/// # Arguments +/// +/// * `formatted_key_hash` - A hex-formatted string representing the key hash. +/// Example: "hash-b485c074cef7ccaccd0302949d2043ab7133abdb14cfa87e8392945c0bd80a5f" +/// +/// # Returns +/// +/// Returns a `Result` containing the base64-encoded string on success. +/// Example: "AbSFwHTO98yszQMClJ0gQ6txM6vbFM+ofoOSlFwL2Apf" +/// +/// # Errors +/// +/// This function returns a `JsError` if: +/// - The input string is not a valid formatted key hash. +/// - The conversion to bytes or base64 encoding fails. +/// +/// The error message is formatted as a JavaScript-compatible string. +#[wasm_bindgen(js_name = "keyHashToBase64Key")] +pub fn get_base64_key_from_key_hash_js_alias(formatted_key_hash: &str) -> Result { + get_base64_key_from_key_hash(formatted_key_hash).map_err(|err| { + let error_text = format!("Error serializing package hash: {:?}", err); + JsError::new(&error_text) + }) +} + /// Gets the current timestamp. /// /// # Returns