-
Notifications
You must be signed in to change notification settings - Fork 106
feat: extend InitStorageData and allow passing native structs
#2230
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
98c040f
feat: Extend InitStorageData and allow passing native structs
igamigo 636f727
Merge branch 'next' into igamigo-init-refactor
igamigo c1c7f8f
chore: re-add refactored comments
igamigo a4250a7
review: refactor and simplify structs
igamigo 935e521
chore: lints
igamigo 012de90
chore: move serde code
igamigo 8de6882
chore: unit test for ExcessiveNesting
mmagician b6180d2
unit test for InvalidMapEntryKey
mmagician 5b1f9ed
chore: unit test for InvalidMapEntrySchema
mmagician e1a3fd3
chore: unit test for EmptyTable & InvalidStorageValueName
mmagician 3438219
Merge branch 'next' into igamigo-init-refactor
mmagician a4844ab
reviews: amend comment
igamigo 2a145c1
reviews: remove initstoragedata::new
igamigo ac6e3c0
Merge branch 'next' into igamigo-init-refactor
bobbinth fde5efd
reviews: comments, move code around, conflict on duplicates when parsing
igamigo 8d47859
chore: merge
igamigo 743fcb2
Merge branch 'next' into igamigo-init-refactor
bobbinth File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,18 +1,22 @@ | ||
| use alloc::collections::BTreeMap; | ||
| use alloc::string::String; | ||
| use alloc::string::{String, ToString}; | ||
| use alloc::vec::Vec; | ||
|
|
||
| use thiserror::Error; | ||
|
|
||
| use super::StorageValueName; | ||
| use crate::account::StorageSlotName; | ||
| use crate::{Felt, FieldElement, Word}; | ||
|
|
||
| /// A raw word value provided via [`InitStorageData`]. | ||
| /// A word value provided via [`InitStorageData`]. | ||
| /// | ||
| /// This is used for defining specific values in relation to a component's schema, where each values | ||
| /// is supplied as either an atomic string (e.g. `"0x1234"`, `"16"`, `"BTC"`) or an array of 4 field | ||
| /// elements. | ||
| /// This is used for defining specific values in relation to a component's schema, where each value | ||
| /// is supplied as either a fully-typed word, an atomic string (e.g. `"0x1234"`, `"16"`, `"BTC"`), | ||
| /// or an array of 4 field elements. | ||
| #[derive(Clone, Debug, PartialEq, Eq)] | ||
| #[cfg_attr(feature = "std", derive(serde::Deserialize, serde::Serialize))] | ||
| #[cfg_attr(feature = "std", serde(untagged))] | ||
| pub enum WordValue { | ||
| /// A fully-typed word value. | ||
| FullyTyped(Word), | ||
| /// Represents a single word value, given by a single string input. | ||
| Atomic(String), | ||
| /// Represents a word through four string-encoded field elements. | ||
|
|
@@ -31,47 +35,182 @@ impl From<&str> for WordValue { | |
| } | ||
| } | ||
|
|
||
| impl From<Word> for WordValue { | ||
| fn from(value: Word) -> Self { | ||
| WordValue::FullyTyped(value) | ||
| } | ||
| } | ||
|
|
||
| impl From<Felt> for WordValue { | ||
| /// Converts a [`Felt`] to a [`WordValue`] as a Word in the form `[0, 0, 0, felt]`. | ||
| fn from(value: Felt) -> Self { | ||
| WordValue::FullyTyped(Word::from([Felt::ZERO, Felt::ZERO, Felt::ZERO, value])) | ||
| } | ||
| } | ||
|
|
||
| impl From<[Felt; 4]> for WordValue { | ||
| fn from(value: [Felt; 4]) -> Self { | ||
| WordValue::FullyTyped(Word::from(value)) | ||
| } | ||
| } | ||
|
|
||
| // INIT STORAGE DATA | ||
| // ==================================================================================================== | ||
|
|
||
| /// Represents the data required to initialize storage entries when instantiating an | ||
| /// [AccountComponent](crate::account::AccountComponent) from component metadata (either provided | ||
| /// directly or extracted from a package). | ||
| /// | ||
| /// An [`InitStorageData`] can be created from a TOML string when the `std` feature flag is set. | ||
| #[derive(Clone, Debug, Default)] | ||
| pub struct InitStorageData { | ||
| /// A mapping of init value names to their raw values. | ||
| /// A mapping of storage value names to their init values. | ||
| value_entries: BTreeMap<StorageValueName, WordValue>, | ||
| /// A mapping of storage map slot names to their raw key/value entries. | ||
| map_entries: BTreeMap<StorageValueName, Vec<(WordValue, WordValue)>>, | ||
| /// A mapping of storage map slot names to their init key/value entries. | ||
| map_entries: BTreeMap<StorageSlotName, Vec<(WordValue, WordValue)>>, | ||
| } | ||
|
|
||
| impl InitStorageData { | ||
| /// Creates a new instance of [InitStorageData]. | ||
| /// | ||
| /// A [`BTreeMap`] is constructed from the passed iterator, so duplicate keys will cause | ||
| /// overridden values. | ||
| pub fn new( | ||
| entries: impl IntoIterator<Item = (StorageValueName, WordValue)>, | ||
| map_entries: impl IntoIterator<Item = (StorageValueName, Vec<(WordValue, WordValue)>)>, | ||
| ) -> Self { | ||
| InitStorageData { | ||
| value_entries: entries.into_iter().collect(), | ||
| map_entries: map_entries.into_iter().collect(), | ||
| } | ||
| } | ||
|
|
||
| /// Returns a reference to the underlying init values map. | ||
| pub fn values(&self) -> &BTreeMap<StorageValueName, WordValue> { | ||
| &self.value_entries | ||
| } | ||
|
|
||
| /// Returns a reference to the stored init value, or [`Option::None`] if the key is not | ||
| /// present. | ||
| pub fn get(&self, key: &StorageValueName) -> Option<&WordValue> { | ||
| self.value_entries.get(key) | ||
| /// Returns a reference to the underlying init map entries. | ||
| pub fn maps(&self) -> &BTreeMap<StorageSlotName, Vec<(WordValue, WordValue)>> { | ||
| &self.map_entries | ||
| } | ||
|
|
||
| /// Returns a reference to the stored init value for the given name. | ||
| pub fn value_entry(&self, name: &StorageValueName) -> Option<&WordValue> { | ||
| self.value_entries.get(name) | ||
| } | ||
|
|
||
| /// Returns a reference to the stored init value for a full slot name. | ||
| pub fn slot_value_entry(&self, slot_name: &StorageSlotName) -> Option<&WordValue> { | ||
| let name = StorageValueName::from_slot_name(slot_name); | ||
| self.value_entries.get(&name) | ||
| } | ||
|
|
||
| /// Returns the map entries associated with the given storage map slot name, if any. | ||
| pub fn map_entries(&self, key: &StorageValueName) -> Option<&Vec<(WordValue, WordValue)>> { | ||
| self.map_entries.get(key) | ||
| pub fn map_entries(&self, slot_name: &StorageSlotName) -> Option<&Vec<(WordValue, WordValue)>> { | ||
| self.map_entries.get(slot_name) | ||
| } | ||
|
|
||
| /// Returns true if any init value entry targets the given slot name. | ||
| pub fn has_value_entries_for_slot(&self, slot_name: &StorageSlotName) -> bool { | ||
| self.value_entries.keys().any(|name| name.slot_name() == slot_name) | ||
| } | ||
|
|
||
| /// Returns true if any init value entry targets a field of the given slot name. | ||
| pub fn has_field_entries_for_slot(&self, slot_name: &StorageSlotName) -> bool { | ||
| self.value_entries | ||
| .keys() | ||
| .any(|name| name.slot_name() == slot_name && name.field_name().is_some()) | ||
| } | ||
|
|
||
| // MUTATORS | ||
| // -------------------------------------------------------------------------------------------- | ||
|
|
||
| /// Inserts a value entry, returning an error on duplicate or conflicting keys. | ||
| /// | ||
| /// The value can be any type that implements `Into<WordValue>`, e.g.: | ||
| /// | ||
| /// - `Word`: a fully-typed word value | ||
| /// - `[Felt; 4]`: converted to a Word | ||
| /// - `Felt`: converted to `[0, 0, 0, felt]` | ||
| /// - `String` or `&str`: a parseable string value | ||
| /// - `WordValue`: a raw or fully-typed word value | ||
| pub fn insert_value( | ||
| &mut self, | ||
| name: StorageValueName, | ||
| value: impl Into<WordValue>, | ||
| ) -> Result<(), InitStorageDataError> { | ||
| if self.value_entries.contains_key(&name) { | ||
| return Err(InitStorageDataError::DuplicateKey(name.to_string())); | ||
| } | ||
| if self.map_entries.contains_key(name.slot_name()) { | ||
| return Err(InitStorageDataError::ConflictingEntries(name.slot_name().as_str().into())); | ||
| } | ||
| self.value_entries.insert(name, value.into()); | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Sets a value entry, overriding any existing entry for the name. | ||
| /// | ||
| /// Returns an error if the [`StorageValueName`] has been used for a map slot. | ||
| pub fn set_value( | ||
| &mut self, | ||
| name: StorageValueName, | ||
| value: impl Into<WordValue>, | ||
| ) -> Result<(), InitStorageDataError> { | ||
| if self.map_entries.contains_key(name.slot_name()) { | ||
| return Err(InitStorageDataError::ConflictingEntries(name.slot_name().as_str().into())); | ||
| } | ||
| self.value_entries.insert(name, value.into()); | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Inserts a single map entry, returning an error on duplicate or conflicting keys. | ||
| /// | ||
| /// See [`Self::insert_value`] for examples of supported types for `key` and `value`. | ||
| pub fn insert_map_entry( | ||
| &mut self, | ||
| slot_name: StorageSlotName, | ||
| key: impl Into<WordValue>, | ||
| value: impl Into<WordValue>, | ||
| ) -> Result<(), InitStorageDataError> { | ||
|
Comment on lines
+157
to
+162
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same comment re potentially making |
||
| if self.has_value_entries_for_slot(&slot_name) { | ||
| return Err(InitStorageDataError::ConflictingEntries(slot_name.as_str().into())); | ||
| } | ||
|
|
||
| let key = key.into(); | ||
| if let Some(entries) = self.map_entries.get(&slot_name) | ||
| && entries.iter().any(|(existing_key, _)| existing_key == &key) | ||
| { | ||
| return Err(InitStorageDataError::DuplicateKey(format!( | ||
| "{}[{key:?}]", | ||
| slot_name.as_str() | ||
| ))); | ||
| } | ||
|
|
||
| self.map_entries.entry(slot_name).or_default().push((key, value.into())); | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Sets map entries for the slot, replacing any existing entries. | ||
| /// | ||
| /// Returns an error if there are conflicting value entries. | ||
| pub fn set_map_values( | ||
| &mut self, | ||
| slot_name: StorageSlotName, | ||
| entries: Vec<(WordValue, WordValue)>, | ||
| ) -> Result<(), InitStorageDataError> { | ||
|
Comment on lines
+184
to
+188
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same comment re |
||
| if self.has_value_entries_for_slot(&slot_name) { | ||
| return Err(InitStorageDataError::ConflictingEntries(slot_name.as_str().into())); | ||
| } | ||
| self.map_entries.insert(slot_name, entries); | ||
| Ok(()) | ||
| } | ||
|
|
||
| /// Merges another [`InitStorageData`] into this one, overwriting value entries and appending | ||
| /// map entries. | ||
| pub fn merge_with(&mut self, other: InitStorageData) { | ||
| self.value_entries.extend(other.value_entries); | ||
| for (slot_name, entries) in other.map_entries { | ||
| self.map_entries.entry(slot_name).or_default().extend(entries); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // ERRORS | ||
| // ==================================================================================================== | ||
|
|
||
| /// Error returned when creating [`InitStorageData`] with invalid entries. | ||
| #[derive(Debug, Error, PartialEq, Eq)] | ||
| pub enum InitStorageDataError { | ||
| #[error("duplicate init key `{0}`")] | ||
| DuplicateKey(String), | ||
| #[error("conflicting init entries for `{0}`")] | ||
| ConflictingEntries(String), | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe not for this PR, but would it make sense to also define the type for the
nameparameter asimpl TryInto<StorageValueName>? This way, it may be possible to write something like:Also, maybe we should implement more conversions for
WordValue- e.g.,From<u32>,From<[u32; 4]>etc. Or if there is a way somehow to do a blanket implementation so that anything that can be converted into word can be converted intoWordValue, that would be even better - but not sure that's possible.