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

feature: DynSolType::decode_params #166

Merged
merged 1 commit into from
Jul 2, 2023
Merged
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
37 changes: 35 additions & 2 deletions crates/dyn-abi/src/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,15 +271,48 @@ impl DynSolType {
}
}

/// Decode a single value. Fails if the value does not match this type.
/// Decode a [`DynSolValue`] from a byte slice. Fails if the value does not
/// match this type.
///
/// This method is used for decoding function arguments. It tries to
/// determine whether the user intended to decode a sequence or an
/// individual value. If the `self` type is a tuple, the `data` will be
/// decoded as a sequence, otherwise it will be decoded as a single value.
///
/// ## Example
///
/// ```ignore
/// // This function takes a single simple param. The user should use
/// // DynSolType::Uint(256).decode_params(data) to decode the param.
/// function myFunc(uint256 a) public;
///
/// // This function takes 2 params. The user should use
/// // DynSolType::Tuple(
/// // vec![DynSolType::Uint(256), DynSolType::Bool])
/// // .decode_params(data)
/// function myFunc(uint256 b, bool c) public;
/// ```
pub fn decode_params(&self, data: &[u8]) -> Result<DynSolValue> {
match self {
DynSolType::Tuple(_) => self.decode_sequence(data),
_ => self.decode_single(data),
}
}

/// Decode a [`DynSolValue`] from a byte slice. Fails if the value does not
/// match this type.
///
/// This method is used for decoding single values. It assumes the `data`
/// argument is an encoded single-element sequence wrapping the `self` type.
pub fn decode_single(&self, data: &[u8]) -> Result<DynSolValue> {
let mut decoder = crate::Decoder::new(data, false);
let mut token = self.empty_dyn_token();
token.decode_single_populate(&mut decoder)?;
self.detokenize(token)
}

/// Decode a sequence of values. Fails if the values do not match this type.
/// Decode a [`DynSolValue`] from a byte slice. Fails if the value does not
/// match this type.
pub fn decode_sequence(&self, data: &[u8]) -> Result<DynSolValue> {
let mut decoder = crate::Decoder::new(data, false);
let mut token = self.empty_dyn_token();
Expand Down