pub mod hex {
pub fn hex_string_to_bytes<const N: usize>(
hex_str: &str,
expected_len: usize,
) -> Result<[u8; N], &'static str> {
if N != expected_len {
return Err("Array size mismatch");
}
let clean_hex = hex_str
.trim_start_matches("0x")
.trim_start_matches("0X")
.trim_start_matches("\\x")
.trim_start_matches("\\X");
if clean_hex.len() != N * 2 {
return Err("Invalid hex string length");
}
if !clean_hex.chars().all(|c| c.is_ascii_hexdigit()) {
return Err("Invalid hex characters");
}
let mut bytes = [0u8; N];
for (i, chunk) in clean_hex.as_bytes().chunks(2).enumerate() {
if i >= N {
break;
}
let hex_byte = std::str::from_utf8(chunk).map_err(|_| "Invalid UTF-8 in hex string")?;
bytes[i] = u8::from_str_radix(hex_byte, 16).map_err(|_| "Invalid hex byte")?;
}
Ok(bytes)
}
pub fn hex_string_to_u64_bytes(hex_str: &str) -> Result<[u8; 8], &'static str> {
hex_string_to_bytes::<8>(hex_str, 8)
}
pub fn hex_string_to_hash_bytes(hex_str: &str) -> Result<[u8; 32], &'static str> {
hex_string_to_bytes::<32>(hex_str, 32)
}
pub fn bytes_to_hex_string(bytes: &[u8]) -> String {
format!("0x{}", hex::encode(bytes))
}
}
pub mod claim {
use super::*;
use crate::dmt::EpochClaimData;
pub fn epoch_claim_data_from_hex(
customer_reward_pool: &str,
merchant_reward_pool: &str,
total_customer_activity: &str,
total_merchant_activity: &str,
) -> Result<EpochClaimData, &'static str> {
let customer_reward_pool_bytes = hex::hex_string_to_u64_bytes(customer_reward_pool)?;
let merchant_reward_pool_bytes = hex::hex_string_to_u64_bytes(merchant_reward_pool)?;
let total_customer_activity_bytes = hex::hex_string_to_u64_bytes(total_customer_activity)?;
let total_merchant_activity_bytes = hex::hex_string_to_u64_bytes(total_merchant_activity)?;
Ok(EpochClaimData {
customer_reward_pool: customer_reward_pool_bytes,
merchant_reward_pool: merchant_reward_pool_bytes,
total_customer_activity: total_customer_activity_bytes,
total_merchant_activity: total_merchant_activity_bytes,
})
}
pub fn epoch_claim_data_from_u64(
customer_reward_pool: u64,
merchant_reward_pool: u64,
total_customer_activity: u64,
total_merchant_activity: u64,
) -> EpochClaimData {
EpochClaimData {
customer_reward_pool: customer_reward_pool.to_le_bytes(),
merchant_reward_pool: merchant_reward_pool.to_le_bytes(),
total_customer_activity: total_customer_activity.to_le_bytes(),
total_merchant_activity: total_merchant_activity.to_le_bytes(),
}
}
}