waves_rust/model/asset/
asset_id.rs

1use crate::error::{Error, Result};
2use crate::model::ByteString;
3use crate::util::Base58;
4use serde_json::Value;
5use std::fmt;
6
7#[derive(Clone, Eq, PartialEq, Hash)]
8pub struct AssetId {
9    bytes: Vec<u8>,
10}
11
12impl fmt::Debug for AssetId {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        write!(f, "AssetId {{ {} }}", self.encoded())
15    }
16}
17
18impl AssetId {
19    pub fn from_string(asset_id: &str) -> Result<AssetId> {
20        Ok(Self::from_bytes(Base58::decode(asset_id)?))
21    }
22
23    pub fn from_bytes(bytes: Vec<u8>) -> AssetId {
24        AssetId { bytes }
25    }
26}
27
28impl ByteString for AssetId {
29    fn bytes(&self) -> Vec<u8> {
30        self.bytes.clone()
31    }
32
33    fn encoded(&self) -> String {
34        Base58::encode(&self.bytes, false)
35    }
36
37    fn encoded_with_prefix(&self) -> String {
38        Base58::encode(&self.bytes, true)
39    }
40}
41
42impl TryFrom<&str> for AssetId {
43    type Error = Error;
44
45    fn try_from(value: &str) -> Result<Self> {
46        AssetId::from_string(value)
47    }
48}
49
50impl From<AssetId> for Value {
51    fn from(value: AssetId) -> Self {
52        Value::String(value.encoded())
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use crate::error::Result;
59    use crate::model::{AssetId, ByteString};
60    use serde_json::Value;
61
62    #[test]
63    fn test_byte_string_for_asset_id() -> Result<()> {
64        let asset_id: AssetId = "8bt2MZjuUCJPmfucPfaZPTXqrxmoCHCC8gVnbjZ7bhH6".try_into()?;
65        let expected_bytes = vec![
66            112, 241, 63, 143, 135, 230, 99, 221, 151, 63, 90, 167, 36, 212, 184, 216, 209, 139,
67            159, 7, 132, 61, 191, 30, 148, 44, 33, 177, 250, 231, 193, 117,
68        ];
69        assert_eq!(expected_bytes, asset_id.bytes());
70        assert_eq!(
71            "8bt2MZjuUCJPmfucPfaZPTXqrxmoCHCC8gVnbjZ7bhH6",
72            asset_id.encoded()
73        );
74        assert_eq!(
75            "base58:8bt2MZjuUCJPmfucPfaZPTXqrxmoCHCC8gVnbjZ7bhH6",
76            asset_id.encoded_with_prefix()
77        );
78        Ok(())
79    }
80
81    #[test]
82    fn test_asset_id_to_json() -> Result<()> {
83        let asset_id: AssetId = "8bt2MZjuUCJPmfucPfaZPTXqrxmoCHCC8gVnbjZ7bhH6".try_into()?;
84        let json_value: Value = asset_id.into();
85        assert_eq!(
86            "8bt2MZjuUCJPmfucPfaZPTXqrxmoCHCC8gVnbjZ7bhH6",
87            json_value.as_str().unwrap_or("")
88        );
89        Ok(())
90    }
91}