Skip to main content

miden_protocol/asset/vault/
asset_class.rs

1use core::fmt::Display;
2
3use crate::Felt;
4use crate::utils::serde::{
5    ByteReader,
6    ByteWriter,
7    Deserializable,
8    DeserializationError,
9    Serializable,
10};
11
12/// The [`AssetClass`] in an [`AssetId`](crate::asset::AssetId) distinguishes different
13/// assets issued by the same faucet.
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
15pub struct AssetClass {
16    suffix: Felt,
17    prefix: Felt,
18}
19
20impl AssetClass {
21    /// The serialized size of an [`AssetClass`] in bytes.
22    pub const SERIALIZED_SIZE: usize = 2 * core::mem::size_of::<u64>();
23
24    /// Constructs an asset class from its parts.
25    pub fn new(suffix: Felt, prefix: Felt) -> Self {
26        Self { suffix, prefix }
27    }
28
29    /// Returns the suffix of the asset class.
30    pub fn suffix(&self) -> Felt {
31        self.suffix
32    }
33
34    /// Returns the prefix of the asset class.
35    pub fn prefix(&self) -> Felt {
36        self.prefix
37    }
38
39    /// Returns `true` if both prefix and suffix are zero, `false` otherwise.
40    pub fn is_empty(&self) -> bool {
41        self.prefix == Felt::ZERO && self.suffix == Felt::ZERO
42    }
43}
44
45impl Display for AssetClass {
46    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
47        f.write_fmt(format_args!(
48            "0x{:016x}{:016x}",
49            self.prefix().as_canonical_u64(),
50            self.suffix().as_canonical_u64()
51        ))
52    }
53}
54
55// SERIALIZATION
56// ================================================================================================
57
58impl Serializable for AssetClass {
59    fn write_into<W: ByteWriter>(&self, target: &mut W) {
60        target.write(self.suffix);
61        target.write(self.prefix);
62    }
63
64    fn get_size_hint(&self) -> usize {
65        Self::SERIALIZED_SIZE
66    }
67}
68
69impl Deserializable for AssetClass {
70    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
71        let suffix: Felt = source.read()?;
72        let prefix: Felt = source.read()?;
73
74        Ok(AssetClass::new(suffix, prefix))
75    }
76}