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::{BTreeMap, 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_value(
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.to_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 (
576 StorageValueName::new("map_entry.map_key_template").unwrap(),
577 "0x123".to_string(),
578 ),
579 (
580 StorageValueName::new("token_metadata.max_supply").unwrap(),
581 20_000u64.to_string(),
582 ),
583 (StorageValueName::new("token_metadata.decimals").unwrap(), "2800".into()),
584 (StorageValueName::new("default_recallable_height").unwrap(), "0".into()),
585 ],
586 BTreeMap::new(),
587 );
588
589 let component = AccountComponent::from_template(&template, &storage_placeholders);
590 assert_matches::assert_matches!(
591 component,
592 Err(AccountError::AccountComponentTemplateInstantiationError(
593 AccountComponentTemplateError::StorageValueParsingError(
594 TemplateTypeError::ParseError { .. }
595 )
596 ))
597 );
598
599 let storage_placeholders = InitStorageData::new(
601 [
602 (
603 StorageValueName::new("map_entry.map_key_template").unwrap(),
604 "0x123".to_string(),
605 ),
606 (
607 StorageValueName::new("token_metadata.max_supply").unwrap(),
608 20_000u64.to_string(),
609 ),
610 (StorageValueName::new("token_metadata.decimals").unwrap(), "128".into()),
611 (StorageValueName::new("default_recallable_height").unwrap(), "0x0".into()),
612 ],
613 BTreeMap::new(),
614 );
615
616 let component = AccountComponent::from_template(&template, &storage_placeholders).unwrap();
617 assert_eq!(
618 component.supported_types(),
619 &[AccountType::FungibleFaucet, AccountType::RegularAccountImmutableCode]
620 .into_iter()
621 .collect()
622 );
623
624 let storage_map = component.storage_slots.first().unwrap();
625 match storage_map {
626 StorageSlot::Map(storage_map) => assert_eq!(storage_map.entries().count(), 3),
627 _ => panic!("should be map"),
628 }
629
630 let value_entry = component.storage_slots().get(2).unwrap();
631 match value_entry {
632 StorageSlot::Value(v) => {
633 assert_eq!(v, &EMPTY_WORD)
634 },
635 _ => panic!("should be value"),
636 }
637
638 let failed_instantiation =
639 AccountComponent::from_template(&template, &InitStorageData::default());
640
641 assert_matches::assert_matches!(
642 failed_instantiation,
643 Err(AccountError::AccountComponentTemplateInstantiationError(
644 AccountComponentTemplateError::PlaceholderValueNotProvided(_)
645 ))
646 );
647 }
648
649 #[test]
650 fn test_no_duplicate_slot_names() {
651 let toml_text = r#"
652 name = "Test Component"
653 description = "This is a test component"
654 version = "1.0.1"
655 supported-types = ["FungibleFaucet", "RegularAccountImmutableCode"]
656
657 [[storage]]
658 name = "test_duplicate"
659 slot = 0
660 type = "felt" # Felt is not a valid type for word slots
661 "#;
662
663 let err = AccountComponentMetadata::from_toml(toml_text).unwrap_err();
664 assert_matches::assert_matches!(err, AccountComponentTemplateError::InvalidType(_, _))
665 }
666
667 #[test]
668 fn map_template_can_build_from_entries() {
669 let map_name = StorageValueName::new("procedure_thresholds").unwrap();
670 let map_entry = StorageEntry::new_map(0, MapRepresentation::new_template(map_name.clone()));
671
672 let init_data = InitStorageData::from_toml(
673 r#"
674 procedure_thresholds = [
675 { key = "0x0000000000000000000000000000000000000000000000000000000000000001", value = "0x0000000000000000000000000000000000000000000000000000000000000010" },
676 { key = "0x0000000000000000000000000000000000000000000000000000000000000002", value = "0x0000000000000000000000000000000000000000000000000000000000000020" }
677 ]
678 "#,
679 )
680 .unwrap();
681
682 let entries = init_data.map_entries(&map_name).expect("map entries missing");
683 assert_eq!(entries.len(), 2);
684 assert_eq!(
685 entries[0],
686 (
687 Word::parse("0x0000000000000000000000000000000000000000000000000000000000000001",)
688 .unwrap(),
689 Word::parse("0x0000000000000000000000000000000000000000000000000000000000000010",)
690 .unwrap(),
691 )
692 );
693
694 let slots = map_entry.try_build_storage_slots(&init_data).unwrap();
695 assert_eq!(slots.len(), 1);
696
697 match &slots[0] {
698 StorageSlot::Map(storage_map) => {
699 assert_eq!(storage_map.num_entries(), 2);
700 let main_key = Word::parse(
701 "0x0000000000000000000000000000000000000000000000000000000000000001",
702 )
703 .unwrap();
704 let main_value_expected = Word::parse(
705 "0x0000000000000000000000000000000000000000000000000000000000000010",
706 )
707 .unwrap();
708 assert_eq!(storage_map.get(&main_key), main_value_expected);
709 },
710 _ => panic!("expected map storage slot"),
711 }
712 }
713
714 #[test]
715 fn map_template_requires_entries() {
716 let map_name = StorageValueName::new("procedure_thresholds").unwrap();
717 let map_entry = StorageEntry::new_map(0, MapRepresentation::new_template(map_name.clone()));
718
719 let result = map_entry.try_build_storage_slots(&InitStorageData::default());
720
721 assert_matches::assert_matches!(
722 result,
723 Err(AccountComponentTemplateError::PlaceholderValueNotProvided(name))
724 if name.as_str() == "procedure_thresholds"
725 );
726
727 let init_data = InitStorageData::from_toml(
730 r#"
731 procedure_thresholds = []
732 "#,
733 )
734 .unwrap();
735
736 let result = map_entry.try_build_storage_slots(&init_data).unwrap();
737
738 assert_eq!(result.len(), 1);
739 match &result[0] {
740 StorageSlot::Map(storage_map) => assert_eq!(storage_map.num_entries(), 0),
741 _ => panic!("expected map storage slot"),
742 }
743 }
744
745 #[test]
746 fn map_placeholder_requirement_is_reported() {
747 let targets = [AccountType::RegularAccountImmutableCode].into_iter().collect();
748 let map =
749 MapRepresentation::new_template(StorageValueName::new("procedure_thresholds").unwrap())
750 .with_description("Configures procedure thresholds");
751
752 let metadata = AccountComponentMetadata::new(
753 "test".into(),
754 "desc".into(),
755 Version::new(1, 0, 0),
756 targets,
757 vec![StorageEntry::new_map(0, map)],
758 )
759 .unwrap();
760
761 let requirements = metadata.get_placeholder_requirements();
762 let requirement = requirements
763 .get(&StorageValueName::new("procedure_thresholds").unwrap())
764 .expect("map placeholder should be reported");
765
766 assert_eq!(requirement.r#type.as_str(), "map");
767 assert_eq!(requirement.description.as_deref(), Some("Configures procedure thresholds"),);
768 }
769
770 #[test]
771 fn toml_template_map_roundtrip() {
772 let toml_text = r#"
773 name = "Test Component"
774 description = "Component with templated map"
775 version = "1.0.0"
776 supported-types = ["RegularAccountImmutableCode"]
777
778 [[storage]]
779 name = "my_map"
780 description = "Some description"
781 slot = 0
782 type = "map"
783 "#;
784
785 let metadata = AccountComponentMetadata::from_toml(toml_text).unwrap();
786 assert_eq!(metadata.storage_entries().len(), 1);
787 match metadata.storage_entries().first().unwrap() {
788 StorageEntry::Map { map, .. } => match map {
789 MapRepresentation::Template { identifier } => {
790 assert_eq!(identifier.name.as_str(), "my_map");
791 assert_eq!(identifier.description.as_deref(), Some("Some description"));
792 },
793 MapRepresentation::Value { .. } => panic!("expected template map"),
794 },
795 _ => panic!("expected map storage entry"),
796 }
797
798 let toml_roundtrip = metadata.to_toml().unwrap();
799 assert!(toml_roundtrip.contains("type = \"map\""));
800 }
801
802 #[test]
803 fn map_placeholder_populated_via_toml_array() {
804 let storage_entry = StorageEntry::new_map(
805 0,
806 MapRepresentation::new_template(StorageValueName::new("my_map").unwrap()),
807 );
808
809 let init_data = InitStorageData::from_toml(
810 r#"
811 my_map = [
812 { key = "0x0000000000000000000000000000000000000000000000000000000000000001", value = "0x0000000000000000000000000000000000000000000000000000000000000090" },
813 { key = "0x0000000000000000000000000000000000000000000000000000000000000002", value = ["1", "2", "3", "4"] }
814 ]
815 other_placeholder = "0xAB"
816 "#,
817 )
818 .unwrap();
819
820 assert_eq!(
821 init_data.get(&StorageValueName::new("other_placeholder").unwrap()).unwrap(),
822 "0xAB"
823 );
824
825 let slots = storage_entry.try_build_storage_slots(&init_data).unwrap();
826 assert_eq!(slots.len(), 1);
827 match &slots[0] {
828 StorageSlot::Map(storage_map) => {
829 assert_eq!(storage_map.num_entries(), 2);
830 let second_value = Word::from([
831 Felt::new(1u64),
832 Felt::new(2u64),
833 Felt::new(3u64),
834 Felt::new(4u64),
835 ]);
836 let second_key = Word::try_from(
837 "0x0000000000000000000000000000000000000000000000000000000000000002",
838 )
839 .unwrap();
840 assert_eq!(storage_map.get(&second_key), second_value);
841 },
842 _ => panic!("expected map storage slot"),
843 }
844 }
845
846 #[test]
847 fn toml_map_type_with_values_is_invalid() {
848 let toml_text = r#"
849 name = "Invalid"
850 description = "Invalid map"
851 version = "1.0.0"
852 supported-types = ["RegularAccountImmutableCode"]
853
854 [[storage]]
855 name = "bad_map"
856 slot = 0
857 type = "map"
858 values = [ { key = "0x1", value = "0x2" } ]
859 "#;
860
861 let metadata = AccountComponentMetadata::from_toml(toml_text).unwrap();
862 match metadata.storage_entries().first().unwrap() {
863 StorageEntry::Map { map, .. } => match map {
864 MapRepresentation::Value { entries, .. } => {
865 assert_eq!(entries.len(), 1);
866 },
867 _ => panic!("expected static map"),
868 },
869 _ => panic!("expected map storage entry"),
870 }
871 }
872
873 #[test]
874 fn toml_map_values_with_non_map_type_is_invalid() {
875 let toml_text = r#"
876 name = "Invalid"
877 description = "Invalid map"
878 version = "1.0.0"
879 supported-types = ["RegularAccountImmutableCode"]
880
881 [[storage]]
882 name = "bad_map"
883 slot = 0
884 type = "word"
885 values = [ { key = "0x1", value = "0x2" } ]
886 "#;
887
888 let result = AccountComponentMetadata::from_toml(toml_text);
889 assert_matches::assert_matches!(
890 result,
891 Err(AccountComponentTemplateError::TomlDeserializationError(_))
892 );
893 }
894
895 #[test]
896 fn toml_fail_multislot_arity_mismatch() {
897 let toml_text = r#"
898 name = "Test Component"
899 description = "Test multislot arity mismatch"
900 version = "1.0.1"
901 supported-types = ["FungibleFaucet"]
902
903 [[storage]]
904 name = "multislot_test"
905 slots = [0, 1]
906 values = [
907 [ "0x1", "0x2", "0x3", "0x4" ]
908 ]
909 "#;
910
911 let err = AccountComponentMetadata::from_toml(toml_text).unwrap_err();
912 assert_matches::assert_matches!(err, AccountComponentTemplateError::MultiSlotArityMismatch);
913 }
914
915 #[test]
916 fn toml_fail_multislot_duplicate_slot() {
917 let toml_text = r#"
918 name = "Test Component"
919 description = "Test multislot duplicate slot"
920 version = "1.0.1"
921 supported-types = ["FungibleFaucet"]
922
923 [[storage]]
924 name = "multislot_duplicate"
925 slots = [0, 1]
926 values = [
927 [ "0x1", "0x2", "0x3", "0x4" ],
928 [ "0x5", "0x6", "0x7", "0x8" ]
929 ]
930
931 [[storage]]
932 name = "multislot_duplicate"
933 slots = [1, 2]
934 values = [
935 [ "0x1", "0x2", "0x3", "0x4" ],
936 [ "0x5", "0x6", "0x7", "0x8" ]
937 ]
938 "#;
939
940 let err = AccountComponentMetadata::from_toml(toml_text).unwrap_err();
941 assert_matches::assert_matches!(err, AccountComponentTemplateError::DuplicateSlot(1));
942 }
943
944 #[test]
945 fn toml_fail_multislot_non_contiguous_slots() {
946 let toml_text = r#"
947 name = "Test Component"
948 description = "Test multislot non contiguous"
949 version = "1.0.1"
950 supported-types = ["FungibleFaucet"]
951
952 [[storage]]
953 name = "multislot_non_contiguous"
954 slots = [0, 2]
955 values = [
956 [ "0x1", "0x2", "0x3", "0x4" ],
957 [ "0x5", "0x6", "0x7", "0x8" ]
958 ]
959 "#;
960
961 let err = AccountComponentMetadata::from_toml(toml_text).unwrap_err();
962 assert!(err.source().unwrap().to_string().contains("are not contiguous"));
964 }
965
966 #[test]
967 fn toml_fail_duplicate_storage_entry_names() {
968 let toml_text = r#"
969 name = "Test Component"
970 description = "Component with duplicate storage entry names"
971 version = "1.0.1"
972 supported-types = ["FungibleFaucet"]
973
974 [[storage]]
975 # placeholder
976 name = "duplicate"
977 slot = 0
978 type = "word"
979
980 [[storage]]
981 name = "duplicate"
982 slot = 1
983 value = [ "0x1", "0x1", "0x1", "0x1" ]
984 "#;
985
986 let result = AccountComponentMetadata::from_toml(toml_text);
987 assert_matches::assert_matches!(
988 result.unwrap_err(),
989 AccountComponentTemplateError::DuplicateEntryNames(_)
990 );
991 }
992
993 #[test]
994 fn toml_fail_multislot_spans_one_slot() {
995 let toml_text = r#"
996 name = "Test Component"
997 description = "Test multislot spans one slot"
998 version = "1.0.1"
999 supported-types = ["RegularAccountImmutableCode"]
1000
1001 [[storage]]
1002 name = "multislot_one_slot"
1003 slots = [0]
1004 values = [
1005 [ "0x1", "0x2", "0x3", "0x4" ],
1006 ]
1007 "#;
1008
1009 let result = AccountComponentMetadata::from_toml(toml_text);
1010 assert_matches::assert_matches!(
1011 result.unwrap_err(),
1012 AccountComponentTemplateError::MultiSlotSpansOneSlot
1013 );
1014 }
1015
1016 #[test]
1017 fn test_toml_multislot_success() {
1018 let toml_text = r#"
1019 name = "Test Component"
1020 description = "A multi-slot success scenario"
1021 version = "1.0.1"
1022 supported-types = ["FungibleFaucet"]
1023
1024 [[storage]]
1025 name = "multi_slot_example"
1026 slots = [0, 1, 2]
1027 values = [
1028 ["0x1", "0x2", "0x3", "0x4"],
1029 ["0x5", "0x6", "0x7", "0x8"],
1030 ["0x9", "0xa", "0xb", "0xc"]
1031 ]
1032 "#;
1033
1034 let metadata = AccountComponentMetadata::from_toml(toml_text).unwrap();
1035 match &metadata.storage_entries()[0] {
1036 StorageEntry::MultiSlot { slots, word_entries } => match word_entries {
1037 crate::account::component::template::MultiWordRepresentation::Value {
1038 identifier,
1039 values,
1040 } => {
1041 assert_eq!(identifier.name.as_str(), "multi_slot_example");
1042 assert_eq!(slots, &(0..3));
1043 assert_eq!(values.len(), 3);
1044 },
1045 },
1046 _ => panic!("expected multislot"),
1047 }
1048 }
1049}