miden_protocol/account/account_id/v1/
prefix.rs1use alloc::string::{String, ToString};
2use core::fmt;
3use core::hash::Hash;
4
5use miden_core::Felt;
6
7use crate::account::account_id::v1::{self, validate_prefix};
8use crate::account::{AccountIdVersion, AccountType, AssetCallbackFlag};
9use crate::errors::AccountIdError;
10use crate::utils::serde::{
11 ByteReader,
12 ByteWriter,
13 Deserializable,
14 DeserializationError,
15 Serializable,
16};
17
18#[derive(Debug, Copy, Clone, Eq, PartialEq)]
25pub struct AccountIdPrefixV1 {
26 prefix: Felt,
27}
28
29impl Hash for AccountIdPrefixV1 {
30 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
31 self.prefix.as_canonical_u64().hash(state);
32 }
33}
34
35impl AccountIdPrefixV1 {
36 const SERIALIZED_SIZE: usize = 8;
41
42 pub fn new_unchecked(prefix: Felt) -> Self {
48 if cfg!(debug_assertions) {
50 validate_prefix(prefix)
51 .expect("AccountIdPrefix::new_unchecked called with invalid prefix");
52 }
53
54 AccountIdPrefixV1 { prefix }
55 }
56
57 pub fn new(prefix: Felt) -> Result<Self, AccountIdError> {
59 validate_prefix(prefix)?;
60
61 Ok(AccountIdPrefixV1 { prefix })
62 }
63
64 pub const fn as_felt(&self) -> Felt {
69 self.prefix
70 }
71
72 pub fn as_u64(&self) -> u64 {
74 self.prefix.as_canonical_u64()
75 }
76
77 pub fn account_type(&self) -> AccountType {
80 v1::extract_account_type(self.prefix.as_canonical_u64())
81 }
82
83 pub fn is_public(&self) -> bool {
85 self.account_type().is_public()
86 }
87
88 pub fn asset_callback_flag(&self) -> AssetCallbackFlag {
92 v1::extract_asset_callback_flag(self.prefix.as_canonical_u64())
93 }
94
95 pub fn version(&self) -> AccountIdVersion {
97 v1::extract_version(self.prefix.as_canonical_u64())
98 .expect("account ID prefix should have been constructed with a valid version")
99 }
100
101 pub fn to_hex(self) -> String {
103 format!("0x{:016x}", self.prefix.as_canonical_u64())
104 }
105}
106
107impl From<AccountIdPrefixV1> for Felt {
111 fn from(id: AccountIdPrefixV1) -> Self {
112 id.prefix
113 }
114}
115
116impl From<AccountIdPrefixV1> for [u8; 8] {
117 fn from(id: AccountIdPrefixV1) -> Self {
118 let mut result = [0_u8; 8];
119 result[..8].copy_from_slice(&id.prefix.as_canonical_u64().to_be_bytes());
120 result
121 }
122}
123
124impl From<AccountIdPrefixV1> for u64 {
125 fn from(id: AccountIdPrefixV1) -> Self {
126 id.prefix.as_canonical_u64()
127 }
128}
129
130impl TryFrom<[u8; 8]> for AccountIdPrefixV1 {
134 type Error = AccountIdError;
135
136 fn try_from(mut value: [u8; 8]) -> Result<Self, Self::Error> {
140 value.reverse();
142
143 let num = u64::from_le_bytes(value);
144 Felt::try_from(num)
145 .map_err(|err| {
146 AccountIdError::AccountIdInvalidPrefixFieldElement(
147 DeserializationError::InvalidValue(err.to_string()),
148 )
149 })
150 .and_then(Self::new)
151 }
152}
153
154impl TryFrom<u64> for AccountIdPrefixV1 {
155 type Error = AccountIdError;
156
157 fn try_from(value: u64) -> Result<Self, Self::Error> {
161 let element = Felt::try_from(value).map_err(|err| {
162 AccountIdError::AccountIdInvalidPrefixFieldElement(DeserializationError::InvalidValue(
163 err.to_string(),
164 ))
165 })?;
166 Self::new(element)
167 }
168}
169
170impl TryFrom<Felt> for AccountIdPrefixV1 {
171 type Error = AccountIdError;
172
173 fn try_from(element: Felt) -> Result<Self, Self::Error> {
177 Self::new(element)
178 }
179}
180
181impl PartialOrd for AccountIdPrefixV1 {
185 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
186 Some(self.cmp(other))
187 }
188}
189
190impl Ord for AccountIdPrefixV1 {
191 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
192 self.prefix.as_canonical_u64().cmp(&other.prefix.as_canonical_u64())
193 }
194}
195
196impl fmt::Display for AccountIdPrefixV1 {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198 write!(f, "{}", self.to_hex())
199 }
200}
201
202impl Serializable for AccountIdPrefixV1 {
206 fn write_into<W: ByteWriter>(&self, target: &mut W) {
207 let bytes: [u8; 8] = (*self).into();
208 bytes.write_into(target);
209 }
210
211 fn get_size_hint(&self) -> usize {
212 Self::SERIALIZED_SIZE
213 }
214}
215
216impl Deserializable for AccountIdPrefixV1 {
217 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
218 <[u8; 8]>::read_from(source)?
219 .try_into()
220 .map_err(|err: AccountIdError| DeserializationError::InvalidValue(err.to_string()))
221 }
222}
223
224#[cfg(test)]
228mod tests {
229 use super::*;
230 use crate::account::{AccountId, AccountIdPrefix};
231 use crate::testing::account_id::{
232 ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET,
233 ACCOUNT_ID_PRIVATE_SENDER,
234 ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
235 ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE,
236 ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
237 };
238
239 #[test]
240 fn test_account_id_prefix_conversion_roundtrip() {
241 for (idx, account_id) in [
242 ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
243 ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE,
244 ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
245 ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET,
246 ACCOUNT_ID_PRIVATE_SENDER,
247 ]
248 .into_iter()
249 .enumerate()
250 {
251 let full_id = AccountId::try_from(account_id).unwrap();
252 let prefix = full_id.prefix();
253 assert_eq!(
254 prefix,
255 AccountIdPrefix::read_from_bytes(&prefix.to_bytes()).unwrap(),
256 "failed in {idx}"
257 );
258 }
259 }
260}