miden_objects/account/component/template/storage/
placeholder.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use alloc::string::{String, ToString};

use thiserror::Error;
use vm_core::{
    utils::{ByteReader, ByteWriter, Deserializable, Serializable},
    Felt, Word,
};
use vm_processor::DeserializationError;

use crate::account::{component::template::AccountComponentTemplateError, StorageMap};

// STORAGE PLACEHOLDER
// ================================================================================================

/// A simple wrapper type around a string key that enables templating.
///
/// A storage placeholder is a string that identifies dynamic values within a component's metadata
/// storage entries. Storage placeholders are serialized as "{{key}}" and can be used as
/// placeholders in map keys, map values, or individual [Felt]s within a [Word].
///
/// At component instantiation, a map of keys to [StorageValue] must be provided to dynamically
/// replace these placeholders with the instance’s actual values.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct StoragePlaceholder {
    key: String,
}

/// An identifier for the expected type for a storage placeholder.
/// These indicate which variant of [StorageValue] should be provided when instantiating a
/// component.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum PlaceholderType {
    Felt,
    Map,
    Word,
}

impl core::fmt::Display for PlaceholderType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            PlaceholderType::Felt => f.write_str("Felt"),
            PlaceholderType::Map => f.write_str("Map"),
            PlaceholderType::Word => f.write_str("Word"),
        }
    }
}

impl StoragePlaceholder {
    /// Creates a new [StoragePlaceholder] from the provided string.
    ///
    /// A [StoragePlaceholder] serves as an identifier for storage values that are determined at
    /// instantiation time of an [AccountComponentTemplate](super::super::AccountComponentTemplate).
    ///
    /// The key can consist of one or more segments separated by dots (`.`).  
    /// Each segment must be non-empty and may contain only alphanumeric characters, underscores
    /// (`_`), or hyphens (`-`).
    ///
    /// # Errors
    ///
    /// This method returns an error if:
    /// - Any segment (or the whole key) is empty.
    /// - Any segment contains invalid characters.
    pub fn new(key: impl Into<String>) -> Result<Self, StoragePlaceholderError> {
        let key: String = key.into();
        Self::validate(&key)?;
        Ok(Self { key })
    }

    /// Returns the key name
    pub fn inner(&self) -> &str {
        &self.key
    }

    /// Checks if the given string is a valid key.
    /// A storage placeholder is valid if it's made of one or more segments that are non-empty
    /// alphanumeric strings.
    fn validate(key: &str) -> Result<(), StoragePlaceholderError> {
        if key.is_empty() {
            return Err(StoragePlaceholderError::EmptyKey);
        }

        for segment in key.split('.') {
            if segment.is_empty() {
                return Err(StoragePlaceholderError::EmptyKey);
            }

            for c in segment.chars() {
                if !(c.is_ascii_alphanumeric() || c == '_' || c == '-') {
                    return Err(StoragePlaceholderError::InvalidChar(key.into(), c));
                }
            }
        }

        Ok(())
    }
}

impl TryFrom<&str> for StoragePlaceholder {
    type Error = StoragePlaceholderError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if value.starts_with("{{") && value.ends_with("}}") {
            let inner = &value[2..value.len() - 2];
            Self::validate(inner)?;

            Ok(StoragePlaceholder { key: inner.to_string() })
        } else {
            Err(StoragePlaceholderError::FormatError(value.into()))
        }
    }
}

impl TryFrom<&String> for StoragePlaceholder {
    type Error = StoragePlaceholderError;

    fn try_from(value: &String) -> Result<Self, Self::Error> {
        Self::try_from(value.as_str())
    }
}

impl core::fmt::Display for StoragePlaceholder {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{{{{{}}}}}", self.key)
    }
}

#[derive(Debug, Error)]
pub enum StoragePlaceholderError {
    #[error("entire key and key segments cannot be empty")]
    EmptyKey,
    #[error("key `{0}` is invalid (expected string in {{...}} format)")]
    FormatError(String),
    #[error(
        "key `{0}` contains invalid character ({1}) (must be alphanumeric, underscore, or hyphen)"
    )]
    InvalidChar(String, char),
}

// SERIALIZATION
// ================================================================================================

impl Serializable for StoragePlaceholder {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        target.write(&self.key);
    }
}

impl Deserializable for StoragePlaceholder {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        let key: String = source.read()?;
        StoragePlaceholder::new(key)
            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
    }
}

// STORAGE VALUE
// ================================================================================================

/// Represents a value used within a templating context.
///
/// A [StorageValue] can be one of:
/// - `Felt(Felt)`: a single [Felt] value
/// - `Word(Word)`: a single [Word] value
/// - `Map(StorageMap)`: a storage map
///
/// These values are used to resolve dynamic placeholders at component instantiation.
#[derive(Clone, Debug)]
pub enum StorageValue {
    Felt(Felt),
    Word(Word),
    Map(StorageMap),
}

impl StorageValue {
    /// Returns `Some(&Felt)` if the variant is `Felt`, otherwise errors.
    pub fn as_felt(&self) -> Result<&Felt, AccountComponentTemplateError> {
        if let StorageValue::Felt(felt) = self {
            Ok(felt)
        } else {
            Err(AccountComponentTemplateError::IncorrectStorageValue("Felt".into()))
        }
    }

    /// Returns `Ok(&Word)` if the variant is `Word`, otherwise errors.
    pub fn as_word(&self) -> Result<&Word, AccountComponentTemplateError> {
        if let StorageValue::Word(word) = self {
            Ok(word)
        } else {
            Err(AccountComponentTemplateError::IncorrectStorageValue("Word".into()))
        }
    }

    /// Returns `Ok(&StorageMap>` if the variant is `Map`, otherwise errors.
    pub fn as_map(&self) -> Result<&StorageMap, AccountComponentTemplateError> {
        if let StorageValue::Map(map) = self {
            Ok(map)
        } else {
            Err(AccountComponentTemplateError::IncorrectStorageValue("Map".into()))
        }
    }
}