Skip to content
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

feat(json-abi): improve JsonAbi::to_sol #408

Merged
merged 10 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
*.sol linguist-language=Solidity
**/tests/abi/* linguist-vendored
**/tests/contracts/* linguist-vendored
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ getrandom = "0.2"
hex = { package = "const-hex", version = "1.5", default-features = false, features = ["alloc"] }
itoa = "1"
once_cell = "1"
pretty_assertions = "1.4"
proptest = "1"
proptest-derive = "0.4"
rand = { version = "0.8", default-features = false }
Expand Down
3 changes: 2 additions & 1 deletion crates/json-abi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, optional = true }

[dev-dependencies]
serde_json.workspace = true
criterion.workspace = true
ethabi = "18"
pretty_assertions.workspace = true
serde_json.workspace = true

[features]
default = ["std"]
Expand Down
97 changes: 81 additions & 16 deletions crates/json-abi/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ macro_rules! entry_and_push {
}

type FlattenValues<'a, V> = Flatten<btree_map::Values<'a, String, Vec<V>>>;
type FlattenValuesMut<'a, V> = Flatten<btree_map::ValuesMut<'a, String, Vec<V>>>;
type FlattenIntoValues<V> = Flatten<btree_map::IntoValues<String, Vec<V>>>;

/// The JSON contract ABI, as specified in the [Solidity ABI spec][ref].
Expand Down Expand Up @@ -216,53 +217,117 @@ impl JsonAbi {
out.push('{');
if len > 0 {
out.push('\n');
crate::to_sol::ToSol::to_sol(self, out);
crate::to_sol::ToSol::to_sol(self, &mut crate::to_sol::SolPrinter::new(out));
}
out.push('}');
}

/// Returns this contract's constructor.
/// Deduplicates all functions, errors, and events which have the same name and inputs.
pub fn dedup(&mut self) {
macro_rules! same_bucket {
() => {
|a, b| {
// Already grouped by name
debug_assert_eq!(a.name, b.name);
a.inputs == b.inputs
}
};
}
for functions in self.functions.values_mut() {
functions.dedup_by(same_bucket!());
}
for errors in self.errors.values_mut() {
errors.dedup_by(same_bucket!());
}
for events in self.events.values_mut() {
events.dedup_by(same_bucket!());
}
}

/// Returns an immutable reference to the constructor.
#[inline]
pub const fn constructor(&self) -> Option<&Constructor> {
self.constructor.as_ref()
}

/// Gets all the functions with the given name.
/// Returns a mutable reference to the constructor.
#[inline]
pub fn constructor_mut(&mut self) -> Option<&mut Constructor> {
self.constructor.as_mut()
}

/// Returns an immutable reference to the list of all the functions with the given name.
#[inline]
pub fn function(&self, name: &str) -> Option<&Vec<Function>> {
self.functions.get(name)
}

/// Returns a mutable reference to the list of all the functions with the given name.
#[inline]
pub fn function_mut(&mut self, name: &str) -> Option<&mut Vec<Function>> {
self.functions.get_mut(name)
}

/// Returns an immutable reference to the list of all the events with the given name.
#[inline]
pub fn function(&self, name: &str) -> Option<&[Function]> {
self.functions.get(name).map(Vec::as_slice)
pub fn event(&self, name: &str) -> Option<&Vec<Event>> {
self.events.get(name)
}

/// Gets all the events with the given name.
/// Returns a mutable reference to the list of all the events with the given name.
#[inline]
pub fn event(&self, name: &str) -> Option<&[Event]> {
self.events.get(name).map(Vec::as_slice)
pub fn event_mut(&mut self, name: &str) -> Option<&mut Vec<Event>> {
self.events.get_mut(name)
}

/// Gets all the errors with the given name.
/// Returns an immutable reference to the list of all the errors with the given name.
#[inline]
pub fn error(&self, name: &str) -> Option<&[Error]> {
self.errors.get(name).map(Vec::as_slice)
pub fn error(&self, name: &str) -> Option<&Vec<Error>> {
self.errors.get(name)
}

/// Iterates over all the functions of the contract in arbitrary order.
/// Returns a mutable reference to the list of all the errors with the given name.
#[inline]
pub fn error_mut(&mut self, name: &str) -> Option<&mut Vec<Error>> {
self.errors.get_mut(name)
}

/// Returns an iterator over immutable references to the functions.
#[inline]
pub fn functions(&self) -> FlattenValues<'_, Function> {
self.functions.values().flatten()
}

/// Iterates over all the events of the contract in arbitrary order.
/// Returns an iterator over mutable references to the functions.
#[inline]
pub fn functions_mut(&mut self) -> FlattenValuesMut<'_, Function> {
self.functions.values_mut().flatten()
}

/// Returns an iterator over immutable references to the events.
#[inline]
pub fn events(&self) -> FlattenValues<'_, Event> {
self.events.values().flatten()
}

/// Iterates over all the errors of the contract in arbitrary order.
/// Returns an iterator over mutable references to the events.
#[inline]
pub fn events_mut(&mut self) -> FlattenValuesMut<'_, Event> {
self.events.values_mut().flatten()
}

/// Returns an iterator over immutable references to the errors.
#[inline]
pub fn errors(&self) -> FlattenValues<'_, Error> {
self.errors.values().flatten()
}

/// Returns an iterator over mutable references to the errors.
#[inline]
pub fn errors_mut(&mut self) -> FlattenValuesMut<'_, Error> {
self.errors.values_mut().flatten()
}

/// Inserts an item into the ABI.
fn insert_item(&mut self, item: AbiItem<'_>) -> Result<(), &'static str> {
match item {
Expand Down Expand Up @@ -346,7 +411,7 @@ macro_rules! iter_impl {
};
}

/// An iterator over all of the items in the ABI.
/// An iterator over immutable references of items in an ABI.
///
/// This `struct` is created by [`JsonAbi::items`]. See its documentation for
/// more.
Expand All @@ -369,7 +434,7 @@ impl<'a> Iterator for Items<'a> {

iter_impl!(traits Items<'_>);

/// An iterator over all of the items in the ABI.
/// An iterator over items in an ABI.
///
/// This `struct` is created by [`JsonAbi::into_items`]. See its documentation
/// for more.
Expand Down
20 changes: 8 additions & 12 deletions crates/json-abi/src/param.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,18 +294,14 @@ impl fmt::Display for EventParam {
impl<'de> Deserialize<'de> for EventParam {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
BorrowedParam::deserialize(deserializer).and_then(|inner| {
if let Some(indexed) = inner.indexed {
inner.validate_fields()?;
Ok(Self {
name: inner.name.to_owned(),
ty: inner.ty.to_owned(),
indexed,
internal_type: inner.internal_type.map(Into::into),
components: inner.components.into_owned(),
})
} else {
Err(serde::de::Error::custom("indexed is required in event params"))
}
inner.validate_fields()?;
Ok(Self {
name: inner.name.to_owned(),
ty: inner.ty.to_owned(),
indexed: inner.indexed.unwrap_or(false),
internal_type: inner.internal_type.map(Into::into),
components: inner.components.into_owned(),
})
})
}
}
Expand Down
Loading