Skip to main content

ic_query/icrc/model/
subaccount.rs

1//! Module: icrc::model::subaccount
2//!
3//! Responsibility: validate and normalize ICRC subaccount hex values.
4//! Does not own: command parsing, account construction, or report fields.
5//! Boundary: produces exactly 32 validated bytes or a typed ICRC error.
6
7use super::IcrcError;
8use crate::hex::hex_bytes;
9
10/// Validates and normalizes a 32-byte ICRC subaccount hex string.
11pub fn normalize_subaccount_hex(value: &str) -> Result<String, IcrcError> {
12    let bytes = subaccount_bytes_from_hex(value)?;
13    Ok(hex_bytes(&bytes))
14}
15
16pub(in crate::icrc) fn subaccount_bytes_from_hex(value: &str) -> Result<Vec<u8>, IcrcError> {
17    let value = value.trim();
18    if !value.len().is_multiple_of(2) {
19        return Err(IcrcError::InvalidSubaccountHex {
20            reason: "hex string must contain an even number of characters".to_string(),
21        });
22    }
23    let bytes = (0..value.len())
24        .step_by(2)
25        .map(|index| {
26            u8::from_str_radix(&value[index..index + 2], 16).map_err(|err| {
27                IcrcError::InvalidSubaccountHex {
28                    reason: err.to_string(),
29                }
30            })
31        })
32        .collect::<Result<Vec<_>, _>>()?;
33    if bytes.len() != 32 {
34        return Err(IcrcError::InvalidSubaccountLength { bytes: bytes.len() });
35    }
36    Ok(bytes)
37}