1use alloc::boxed::Box;
2use alloc::string::String;
3use alloc::vec::Vec;
4use core::ops::Range;
5
6use miden_core::utils::{ByteReader, ByteWriter, Deserializable, Serializable};
7use miden_core::{Felt, FieldElement};
8use miden_processor::DeserializationError;
9
10mod entry_content;
11pub use entry_content::*;
12
13use super::AccountComponentTemplateError;
14use crate::Word;
15use crate::account::StorageSlot;
16
17mod placeholder;
18pub use placeholder::{
19    PlaceholderTypeRequirement,
20    StorageValueName,
21    StorageValueNameError,
22    TemplateType,
23    TemplateTypeError,
24};
25
26mod init_storage_data;
27pub use init_storage_data::InitStorageData;
28
29#[cfg(feature = "std")]
30pub mod toml;
31
32pub type TemplateRequirementsIter<'a> =
35    Box<dyn Iterator<Item = (StorageValueName, PlaceholderTypeRequirement)> + 'a>;
36
37#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct FieldIdentifier {
45    pub name: StorageValueName,
47    pub description: Option<String>,
49}
50
51impl FieldIdentifier {
52    pub fn with_name(name: StorageValueName) -> Self {
54        Self { name, description: None }
55    }
56
57    pub fn with_description(name: StorageValueName, description: impl Into<String>) -> Self {
59        Self {
60            name,
61            description: Some(description.into()),
62        }
63    }
64
65    pub fn name(&self) -> &StorageValueName {
67        &self.name
68    }
69
70    pub fn description(&self) -> Option<&String> {
72        self.description.as_ref()
73    }
74}
75
76impl From<StorageValueName> for FieldIdentifier {
77    fn from(value: StorageValueName) -> Self {
78        FieldIdentifier::with_name(value)
79    }
80}
81
82impl Serializable for FieldIdentifier {
83    fn write_into<W: ByteWriter>(&self, target: &mut W) {
84        target.write(&self.name);
85        target.write(&self.description);
86    }
87}
88
89impl Deserializable for FieldIdentifier {
90    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
91        let name = StorageValueName::read_from(source)?;
92        let description = Option::<String>::read_from(source)?;
93        Ok(FieldIdentifier { name, description })
94    }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
108#[allow(clippy::large_enum_variant)]
109pub enum StorageEntry {
110    Value {
112        slot: u8,
114        word_entry: WordRepresentation,
116    },
117
118    Map {
120        slot: u8,
122        map: MapRepresentation,
124    },
125
126    MultiSlot {
128        slots: Range<u8>,
130        word_entries: MultiWordRepresentation,
132    },
133}
134
135impl StorageEntry {
136    pub fn new_value(slot: u8, word_entry: impl Into<WordRepresentation>) -> Self {
137        StorageEntry::Value { slot, word_entry: word_entry.into() }
138    }
139
140    pub fn new_map(slot: u8, map: MapRepresentation) -> Self {
141        StorageEntry::Map { slot, map }
142    }
143
144    pub fn new_multislot(
145        identifier: FieldIdentifier,
146        slots: Range<u8>,
147        values: Vec<[FeltRepresentation; 4]>,
148    ) -> Self {
149        StorageEntry::MultiSlot {
150            slots,
151            word_entries: MultiWordRepresentation::Value { identifier, values },
152        }
153    }
154
155    pub fn name(&self) -> Option<&StorageValueName> {
156        match self {
157            StorageEntry::Value { word_entry, .. } => word_entry.name(),
158            StorageEntry::Map { map, .. } => Some(map.name()),
159            StorageEntry::MultiSlot { word_entries, .. } => match word_entries {
160                MultiWordRepresentation::Value { identifier, .. } => Some(&identifier.name),
161            },
162        }
163    }
164
165    pub fn slot_indices(&self) -> Range<u8> {
167        match self {
168            StorageEntry::MultiSlot { slots, .. } => slots.clone(),
169            StorageEntry::Value { slot, .. } | StorageEntry::Map { slot, .. } => *slot..*slot + 1,
170        }
171    }
172
173    pub fn template_requirements(&self) -> TemplateRequirementsIter<'_> {
176        match self {
177            StorageEntry::Value { word_entry, .. } => {
178                word_entry.template_requirements(StorageValueName::empty())
179            },
180            StorageEntry::Map { map, .. } => map.template_requirements(),
181            StorageEntry::MultiSlot { word_entries, .. } => match word_entries {
182                MultiWordRepresentation::Value { identifier, values } => {
183                    Box::new(values.iter().flat_map(move |word| {
184                        word.iter()
185                            .flat_map(move |f| f.template_requirements(identifier.name.clone()))
186                    }))
187                },
188            },
189        }
190    }
191
192    pub fn try_build_storage_slots(
202        &self,
203        init_storage_data: &InitStorageData,
204    ) -> Result<Vec<StorageSlot>, AccountComponentTemplateError> {
205        match self {
206            StorageEntry::Value { word_entry, .. } => {
207                let slot =
208                    word_entry.try_build_word(init_storage_data, StorageValueName::empty())?;
209                Ok(vec![StorageSlot::Value(slot)])
210            },
211            StorageEntry::Map { map, .. } => {
212                let storage_map = map.try_build_map(init_storage_data)?;
213                Ok(vec![StorageSlot::Map(storage_map)])
214            },
215            StorageEntry::MultiSlot { word_entries, .. } => {
216                match word_entries {
217                    MultiWordRepresentation::Value { identifier, values } => {
218                        Ok(values
219                            .iter()
220                            .map(|word_repr| {
221                                let mut result = [Felt::ZERO; 4];
222
223                                for (index, felt_repr) in word_repr.iter().enumerate() {
224                                    result[index] = felt_repr.try_build_felt(
225                                        init_storage_data,
226                                        identifier.name.clone(),
227                                    )?;
228                                }
229                                Ok(StorageSlot::Value(Word::from(result)))
231                            })
232                            .collect::<Result<Vec<StorageSlot>, _>>()?)
233                    },
234                }
235            },
236        }
237    }
238
239    pub(super) fn validate(&self) -> Result<(), AccountComponentTemplateError> {
241        match self {
242            StorageEntry::Map { map, .. } => map.validate(),
243            StorageEntry::MultiSlot { slots, word_entries, .. } => {
244                if slots.len() == 1 {
245                    return Err(AccountComponentTemplateError::MultiSlotSpansOneSlot);
246                }
247
248                if slots.len() != word_entries.num_words() {
249                    return Err(AccountComponentTemplateError::MultiSlotArityMismatch);
250                }
251
252                word_entries.validate()
253            },
254            StorageEntry::Value { word_entry, .. } => Ok(word_entry.validate()?),
255        }
256    }
257}
258
259impl Serializable for StorageEntry {
263    fn write_into<W: ByteWriter>(&self, target: &mut W) {
264        match self {
265            StorageEntry::Value { slot, word_entry } => {
266                target.write_u8(0u8);
267                target.write_u8(*slot);
268                target.write(word_entry);
269            },
270            StorageEntry::Map { slot, map } => {
271                target.write_u8(1u8);
272                target.write_u8(*slot);
273                target.write(map);
274            },
275            StorageEntry::MultiSlot { word_entries, slots } => {
276                target.write_u8(2u8);
277                target.write(word_entries);
278                target.write(slots.start);
279                target.write(slots.end);
280            },
281        }
282    }
283}
284
285impl Deserializable for StorageEntry {
286    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
287        let variant_tag = source.read_u8()?;
288        match variant_tag {
289            0 => {
290                let slot = source.read_u8()?;
291                let word_entry: WordRepresentation = source.read()?;
292                Ok(StorageEntry::Value { slot, word_entry })
293            },
294            1 => {
295                let slot = source.read_u8()?;
296                let map: MapRepresentation = source.read()?;
297                Ok(StorageEntry::Map { slot, map })
298            },
299            2 => {
300                let word_entries: MultiWordRepresentation = source.read()?;
301                let slots_start: u8 = source.read()?;
302                let slots_end: u8 = source.read()?;
303                Ok(StorageEntry::MultiSlot {
304                    slots: slots_start..slots_end,
305                    word_entries,
306                })
307            },
308            _ => Err(DeserializationError::InvalidValue(format!(
309                "unknown variant tag '{variant_tag}' for StorageEntry"
310            ))),
311        }
312    }
313}
314
315#[derive(Debug, Clone, PartialEq, Eq)]
320#[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))]
321pub struct MapEntry {
322    key: WordRepresentation,
323    value: WordRepresentation,
324}
325
326impl MapEntry {
327    pub fn new(key: impl Into<WordRepresentation>, value: impl Into<WordRepresentation>) -> Self {
328        Self { key: key.into(), value: value.into() }
329    }
330
331    pub fn key(&self) -> &WordRepresentation {
332        &self.key
333    }
334
335    pub fn value(&self) -> &WordRepresentation {
336        &self.value
337    }
338
339    pub fn into_parts(self) -> (WordRepresentation, WordRepresentation) {
340        let MapEntry { key, value } = self;
341        (key, value)
342    }
343
344    pub fn template_requirements(
345        &self,
346        placeholder_prefix: StorageValueName,
347    ) -> TemplateRequirementsIter<'_> {
348        let key_iter = self.key.template_requirements(placeholder_prefix.clone());
349        let value_iter = self.value.template_requirements(placeholder_prefix);
350
351        Box::new(key_iter.chain(value_iter))
352    }
353}
354
355impl Serializable for MapEntry {
356    fn write_into<W: ByteWriter>(&self, target: &mut W) {
357        self.key.write_into(target);
358        self.value.write_into(target);
359    }
360}
361
362impl Deserializable for MapEntry {
363    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
364        let key = WordRepresentation::read_from(source)?;
365        let value = WordRepresentation::read_from(source)?;
366        Ok(MapEntry { key, value })
367    }
368}
369
370#[cfg(test)]
374mod tests {
375    use alloc::collections::BTreeSet;
376    use alloc::string::ToString;
377    use core::error::Error;
378    use core::panic;
379
380    use miden_assembly::Assembler;
381    use miden_core::utils::{Deserializable, Serializable};
382    use miden_core::{EMPTY_WORD, Felt, Word};
383    use semver::Version;
384
385    use crate::account::component::FieldIdentifier;
386    use crate::account::component::template::storage::placeholder::TemplateType;
387    use crate::account::component::template::{
388        AccountComponentMetadata,
389        InitStorageData,
390        MapEntry,
391        MapRepresentation,
392        StorageValueName,
393    };
394    use crate::account::{
395        AccountComponent,
396        AccountComponentTemplate,
397        AccountType,
398        FeltRepresentation,
399        StorageEntry,
400        StorageSlot,
401        TemplateTypeError,
402        WordRepresentation,
403    };
404    use crate::errors::AccountComponentTemplateError;
405    use crate::testing::account_code::CODE;
406    use crate::{AccountError, word};
407
408    #[test]
409    fn test_storage_entry_serialization() {
410        let felt_array: [FeltRepresentation; 4] = [
411            FeltRepresentation::from(Felt::new(0xabc)),
412            FeltRepresentation::from(Felt::new(1218)),
413            FeltRepresentation::from(Felt::new(0xdba3)),
414            FeltRepresentation::new_template(
415                TemplateType::native_felt(),
416                StorageValueName::new("slot3").unwrap(),
417            )
418            .with_description("dummy description"),
419        ];
420
421        let test_word: Word = word!("0x000001");
422        let test_word = test_word.map(FeltRepresentation::from);
423
424        let map_representation = MapRepresentation::new(
425            vec![
426                MapEntry {
427                    key: WordRepresentation::new_template(
428                        TemplateType::native_word(),
429                        StorageValueName::new("foo").unwrap().into(),
430                    ),
431                    value: WordRepresentation::new_value(test_word.clone(), None),
432                },
433                MapEntry {
434                    key: WordRepresentation::new_value(test_word.clone(), None),
435                    value: WordRepresentation::new_template(
436                        TemplateType::native_word(),
437                        StorageValueName::new("bar").unwrap().into(),
438                    ),
439                },
440                MapEntry {
441                    key: WordRepresentation::new_template(
442                        TemplateType::native_word(),
443                        StorageValueName::new("baz").unwrap().into(),
444                    ),
445                    value: WordRepresentation::new_value(test_word, None),
446                },
447            ],
448            StorageValueName::new("map").unwrap(),
449        )
450        .with_description("a storage map description");
451
452        let storage = vec![
453            StorageEntry::new_value(0, felt_array.clone()),
454            StorageEntry::new_map(1, map_representation),
455            StorageEntry::new_multislot(
456                FieldIdentifier::with_description(
457                    StorageValueName::new("multi").unwrap(),
458                    "Multi slot entry",
459                ),
460                2..4,
461                vec![
462                    [
463                        FeltRepresentation::new_template(
464                            TemplateType::native_felt(),
465                            StorageValueName::new("test").unwrap(),
466                        ),
467                        FeltRepresentation::new_template(
468                            TemplateType::native_felt(),
469                            StorageValueName::new("test2").unwrap(),
470                        ),
471                        FeltRepresentation::new_template(
472                            TemplateType::native_felt(),
473                            StorageValueName::new("test3").unwrap(),
474                        ),
475                        FeltRepresentation::new_template(
476                            TemplateType::native_felt(),
477                            StorageValueName::new("test4").unwrap(),
478                        ),
479                    ],
480                    felt_array,
481                ],
482            ),
483            StorageEntry::new_value(
484                4,
485                WordRepresentation::new_template(
486                    TemplateType::native_word(),
487                    StorageValueName::new("single").unwrap().into(),
488                ),
489            ),
490        ];
491
492        let config = AccountComponentMetadata {
493            name: "Test Component".into(),
494            description: "This is a test component".into(),
495            version: Version::parse("1.0.0").unwrap(),
496            supported_types: BTreeSet::from([AccountType::FungibleFaucet]),
497            storage,
498        };
499        let toml = config.as_toml().unwrap();
500        let deserialized = AccountComponentMetadata::from_toml(&toml).unwrap();
501
502        assert_eq!(deserialized, config);
503    }
504
505    #[test]
506    pub fn toml_serde_roundtrip() {
507        let toml_text = r#"
508        name = "Test Component"
509        description = "This is a test component"
510        version = "1.0.1"
511        supported-types = ["FungibleFaucet", "RegularAccountImmutableCode"]
512
513        [[storage]]
514        name = "map_entry"
515        slot = 0
516        values = [
517            { key = "0x1", value = ["0x1","0x2","0x3","0"]},
518            { key = "0x3", value = "0x123" }, 
519            { key = { name = "map_key_template", description = "this tests that the default type is correctly set"}, value = "0x3" },
520        ]
521
522        [[storage]]
523        name = "token_metadata"
524        description = "Contains metadata about the token associated to the faucet account"
525        slot = 1
526        value = [
527            { type = "felt", name = "max_supply", description = "Maximum supply of the token in base units" }, # placeholder
528            { type = "token_symbol", value = "TST" }, # hardcoded non-felt type
529            { type = "u8", name = "decimals", description = "Number of decimal places" }, # placeholder
530            { value = "0" }, 
531        ]
532
533        [[storage]]
534        name = "default_recallable_height"
535        slot = 2
536        type = "word"
537        "#;
538
539        let component_metadata = AccountComponentMetadata::from_toml(toml_text).unwrap();
540        let requirements = component_metadata.get_placeholder_requirements();
541
542        assert_eq!(requirements.len(), 4);
543
544        let supply = requirements
545            .get(&StorageValueName::new("token_metadata.max_supply").unwrap())
546            .unwrap();
547        assert_eq!(supply.r#type.as_str(), "felt");
548
549        let decimals = requirements
550            .get(&StorageValueName::new("token_metadata.decimals").unwrap())
551            .unwrap();
552        assert_eq!(decimals.r#type.as_str(), "u8");
553
554        let default_recallable_height = requirements
555            .get(&StorageValueName::new("default_recallable_height").unwrap())
556            .unwrap();
557        assert_eq!(default_recallable_height.r#type.as_str(), "word");
558
559        let map_key_template = requirements
560            .get(&StorageValueName::new("map_entry.map_key_template").unwrap())
561            .unwrap();
562        assert_eq!(map_key_template.r#type.as_str(), "word");
563
564        let library = Assembler::default().assemble_library([CODE]).unwrap();
565        let template = AccountComponentTemplate::new(component_metadata, library);
566
567        let template_bytes = template.to_bytes();
568        let template_deserialized =
569            AccountComponentTemplate::read_from_bytes(&template_bytes).unwrap();
570        assert_eq!(template, template_deserialized);
571
572        let storage_placeholders = InitStorageData::new([
574            (
575                StorageValueName::new("map_entry.map_key_template").unwrap(),
576                "0x123".to_string(),
577            ),
578            (
579                StorageValueName::new("token_metadata.max_supply").unwrap(),
580                20_000u64.to_string(),
581            ),
582            (StorageValueName::new("token_metadata.decimals").unwrap(), "2800".into()),
583            (StorageValueName::new("default_recallable_height").unwrap(), "0".into()),
584        ]);
585
586        let component = AccountComponent::from_template(&template, &storage_placeholders);
587        assert_matches::assert_matches!(
588            component,
589            Err(AccountError::AccountComponentTemplateInstantiationError(
590                AccountComponentTemplateError::StorageValueParsingError(
591                    TemplateTypeError::ParseError { .. }
592                )
593            ))
594        );
595
596        let storage_placeholders = InitStorageData::new([
598            (
599                StorageValueName::new("map_entry.map_key_template").unwrap(),
600                "0x123".to_string(),
601            ),
602            (
603                StorageValueName::new("token_metadata.max_supply").unwrap(),
604                20_000u64.to_string(),
605            ),
606            (StorageValueName::new("token_metadata.decimals").unwrap(), "128".into()),
607            (StorageValueName::new("default_recallable_height").unwrap(), "0x0".into()),
608        ]);
609
610        let component = AccountComponent::from_template(&template, &storage_placeholders).unwrap();
611        assert_eq!(
612            component.supported_types(),
613            &[AccountType::FungibleFaucet, AccountType::RegularAccountImmutableCode]
614                .into_iter()
615                .collect()
616        );
617
618        let storage_map = component.storage_slots.first().unwrap();
619        match storage_map {
620            StorageSlot::Map(storage_map) => assert_eq!(storage_map.entries().count(), 3),
621            _ => panic!("should be map"),
622        }
623
624        let value_entry = component.storage_slots().get(2).unwrap();
625        match value_entry {
626            StorageSlot::Value(v) => {
627                assert_eq!(v, &EMPTY_WORD)
628            },
629            _ => panic!("should be value"),
630        }
631
632        let failed_instantiation =
633            AccountComponent::from_template(&template, &InitStorageData::default());
634
635        assert_matches::assert_matches!(
636            failed_instantiation,
637            Err(AccountError::AccountComponentTemplateInstantiationError(
638                AccountComponentTemplateError::PlaceholderValueNotProvided(_)
639            ))
640        );
641    }
642
643    #[test]
644    fn test_no_duplicate_slot_names() {
645        let toml_text = r#"
646        name = "Test Component"
647        description = "This is a test component"
648        version = "1.0.1"
649        supported-types = ["FungibleFaucet", "RegularAccountImmutableCode"]
650
651        [[storage]]
652        name = "test_duplicate"
653        slot = 0
654        type = "felt" # Felt is not a valid type for word slots
655        "#;
656
657        let err = AccountComponentMetadata::from_toml(toml_text).unwrap_err();
658        assert_matches::assert_matches!(err, AccountComponentTemplateError::InvalidType(_, _))
659    }
660
661    #[test]
662    fn toml_fail_multislot_arity_mismatch() {
663        let toml_text = r#"
664        name = "Test Component"
665        description = "Test multislot arity mismatch"
666        version = "1.0.1"
667        supported-types = ["FungibleFaucet"]
668
669        [[storage]]
670        name = "multislot_test"
671        slots = [0, 1]
672        values = [
673            [ "0x1", "0x2", "0x3", "0x4" ]
674        ]
675    "#;
676
677        let err = AccountComponentMetadata::from_toml(toml_text).unwrap_err();
678        assert_matches::assert_matches!(err, AccountComponentTemplateError::MultiSlotArityMismatch);
679    }
680
681    #[test]
682    fn toml_fail_multislot_duplicate_slot() {
683        let toml_text = r#"
684        name = "Test Component"
685        description = "Test multislot duplicate slot"
686        version = "1.0.1"
687        supported-types = ["FungibleFaucet"]
688
689        [[storage]]
690        name = "multislot_duplicate"
691        slots = [0, 1]
692        values = [
693            [ "0x1", "0x2", "0x3", "0x4" ],
694            [ "0x5", "0x6", "0x7", "0x8" ]
695        ]
696
697        [[storage]]
698        name = "multislot_duplicate"
699        slots = [1, 2]
700        values = [
701            [ "0x1", "0x2", "0x3", "0x4" ],
702            [ "0x5", "0x6", "0x7", "0x8" ]
703        ]
704    "#;
705
706        let err = AccountComponentMetadata::from_toml(toml_text).unwrap_err();
707        assert_matches::assert_matches!(err, AccountComponentTemplateError::DuplicateSlot(1));
708    }
709
710    #[test]
711    fn toml_fail_multislot_non_contiguous_slots() {
712        let toml_text = r#"
713        name = "Test Component"
714        description = "Test multislot non contiguous"
715        version = "1.0.1"
716        supported-types = ["FungibleFaucet"]
717
718        [[storage]]
719        name = "multislot_non_contiguous"
720        slots = [0, 2]
721        values = [
722            [ "0x1", "0x2", "0x3", "0x4" ],
723            [ "0x5", "0x6", "0x7", "0x8" ]
724        ]
725    "#;
726
727        let err = AccountComponentMetadata::from_toml(toml_text).unwrap_err();
728        assert!(err.source().unwrap().to_string().contains("are not contiguous"));
730    }
731
732    #[test]
733    fn toml_fail_duplicate_storage_entry_names() {
734        let toml_text = r#"
735        name = "Test Component"
736        description = "Component with duplicate storage entry names"
737        version = "1.0.1"
738        supported-types = ["FungibleFaucet"]
739
740        [[storage]]
741        # placeholder
742        name = "duplicate"
743        slot = 0
744        type = "word"
745
746        [[storage]]
747        name = "duplicate"
748        slot = 1
749        value = [ "0x1", "0x1", "0x1", "0x1" ]
750    "#;
751
752        let result = AccountComponentMetadata::from_toml(toml_text);
753        assert_matches::assert_matches!(
754            result.unwrap_err(),
755            AccountComponentTemplateError::DuplicateEntryNames(_)
756        );
757    }
758
759    #[test]
760    fn toml_fail_multislot_spans_one_slot() {
761        let toml_text = r#"
762        name = "Test Component"
763        description = "Test multislot spans one slot"
764        version = "1.0.1"
765        supported-types = ["RegularAccountImmutableCode"]
766
767        [[storage]]
768        name = "multislot_one_slot"
769        slots = [0]
770        values = [
771            [ "0x1", "0x2", "0x3", "0x4" ],
772        ]
773    "#;
774
775        let result = AccountComponentMetadata::from_toml(toml_text);
776        assert_matches::assert_matches!(
777            result.unwrap_err(),
778            AccountComponentTemplateError::MultiSlotSpansOneSlot
779        );
780    }
781
782    #[test]
783    fn test_toml_multislot_success() {
784        let toml_text = r#"
785        name = "Test Component"
786        description = "A multi-slot success scenario"
787        version = "1.0.1"
788        supported-types = ["FungibleFaucet"]
789
790        [[storage]]
791        name = "multi_slot_example"
792        slots = [0, 1, 2]
793        values = [
794            ["0x1", "0x2", "0x3", "0x4"],
795            ["0x5", "0x6", "0x7", "0x8"],
796            ["0x9", "0xa", "0xb", "0xc"]
797        ]
798    "#;
799
800        let metadata = AccountComponentMetadata::from_toml(toml_text).unwrap();
801        match &metadata.storage_entries()[0] {
802            StorageEntry::MultiSlot { slots, word_entries } => match word_entries {
803                crate::account::component::template::MultiWordRepresentation::Value {
804                    identifier,
805                    values,
806                } => {
807                    assert_eq!(identifier.name.as_str(), "multi_slot_example");
808                    assert_eq!(slots, &(0..3));
809                    assert_eq!(values.len(), 3);
810                },
811            },
812            _ => panic!("expected multislot"),
813        }
814    }
815}