Skip to content

Commit

Permalink
feat: add RevertReason enum (#450)
Browse files Browse the repository at this point in the history
* add RevertReason enum

* implement fmt

* make GenericContractError public

* fix ci

* enhance RevertReason impl

* some fixes
  • Loading branch information
tcoratger authored Dec 14, 2023
1 parent f1176b3 commit c2f6ad2
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 29 deletions.
4 changes: 2 additions & 2 deletions crates/sol-types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,8 @@ mod impl_core;
mod types;
pub use types::{
data_type as sol_data, decode_revert_reason, ContractError, EventTopic, GenericContractError,
Panic, PanicKind, Revert, Selectors, SolCall, SolEnum, SolError, SolEvent, SolEventInterface,
SolInterface, SolStruct, SolType, SolValue, TopicList,
GenericRevertReason, Panic, PanicKind, Revert, Selectors, SolCall, SolEnum, SolError, SolEvent,
SolEventInterface, SolInterface, SolStruct, SolType, SolValue, TopicList,
};

pub mod utils;
Expand Down
40 changes: 16 additions & 24 deletions crates/sol-types/src/types/error.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use crate::{
abi::token::{PackedSeqToken, Token, TokenSeq, WordToken},
GenericContractError, Result, SolInterface, SolType, Word,
};
use alloc::{
string::{String, ToString},
vec::Vec,
types::interface::{GenericRevertReason, RevertReason},
Result, SolType, Word,
};
use alloc::{string::String, vec::Vec};
use alloy_primitives::U256;
use core::{borrow::Borrow, fmt};

Expand Down Expand Up @@ -405,28 +403,22 @@ impl PanicKind {
}
}

/// Returns the revert reason from the given output data. Returns `None` if the
/// content is not a valid ABI-encoded [`GenericContractError`] or a [UTF-8
/// string](String) (for Vyper reverts).
pub fn decode_revert_reason(out: &[u8]) -> Option<String> {
// Try to decode as a generic contract error.
if let Ok(error) = GenericContractError::abi_decode(out, true) {
return Some(error.to_string());
}

// If that fails, try to decode as a regular string.
if let Ok(decoded_string) = core::str::from_utf8(out) {
return Some(decoded_string.to_string());
}

// If both attempts fail, return None.
None
/// Decodes and retrieves the reason for a revert from the provided output data.
///
/// This function attempts to decode the provided output data as a generic contract error
/// or a UTF-8 string (for Vyper reverts) using the `RevertReason::decode` method.
///
/// If successful, it returns the decoded revert reason wrapped in an `Option`.
///
/// If both attempts fail, it returns `None`.
pub fn decode_revert_reason(out: &[u8]) -> Option<GenericRevertReason> {
RevertReason::decode(out)
}

#[cfg(test)]
mod tests {
use super::*;
use crate::sol;
use crate::{sol, types::interface::SolInterface};
use alloy_primitives::{address, hex, keccak256};

#[test]
Expand Down Expand Up @@ -470,14 +462,14 @@ mod tests {
let revert = Revert::from("test_revert_reason");
let encoded = revert.abi_encode();
let decoded = decode_revert_reason(&encoded).unwrap();
assert_eq!(decoded, String::from("revert: test_revert_reason"));
assert_eq!(decoded, revert.into());
}

#[test]
fn decode_random_revert_reason() {
let revert_reason = String::from("test_revert_reason");
let decoded = decode_revert_reason(revert_reason.as_bytes()).unwrap();
assert_eq!(decoded, String::from("test_revert_reason"));
assert_eq!(decoded, String::from("test_revert_reason").into());
}

#[test]
Expand Down
82 changes: 80 additions & 2 deletions crates/sol-types/src/types/interface/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{Error, Panic, Result, Revert, SolError};
use alloc::vec::Vec;
use crate::{alloc::string::ToString, Error, Panic, Result, Revert, SolError};
use alloc::{string::String, vec::Vec};
use core::{convert::Infallible, fmt, iter::FusedIterator, marker::PhantomData};

#[cfg(feature = "std")]
Expand Down Expand Up @@ -369,6 +369,84 @@ impl<T> ContractError<T> {
}
}

/// Represents the reason for a revert in a generic contract error.
pub type GenericRevertReason = RevertReason<Infallible>;

/// Represents the reason for a revert in a smart contract.
///
/// This enum captures two possible scenarios for a revert:
///
/// - [`ContractError`](RevertReason::ContractError): Contains detailed error information, such as a
/// specific [`Revert`] or [`Panic`] error.
///
/// - [`RawString`](RevertReason::RawString): Represents a raw string message as the reason for the
/// revert.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RevertReason<T> {
/// A detailed contract error, including a specific revert or panic error.
ContractError(ContractError<T>),
/// Represents a raw string message as the reason for the revert.
RawString(String),
}

impl<T: fmt::Display> fmt::Display for RevertReason<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RevertReason::ContractError(error) => error.fmt(f),
RevertReason::RawString(raw_string) => write!(f, "{}", raw_string),
}
}
}

/// Converts a `ContractError<T>` into a `RevertReason<T>`.
impl<T> From<ContractError<T>> for RevertReason<T> {
fn from(error: ContractError<T>) -> Self {
RevertReason::ContractError(error)
}
}

/// Converts a `Revert` into a `RevertReason<T>`.
impl<T> From<Revert> for RevertReason<T> {
fn from(revert: Revert) -> Self {
RevertReason::ContractError(ContractError::Revert(revert))
}
}

/// Converts a `String` into a `RevertReason<T>`.
impl<T> From<String> for RevertReason<T> {
fn from(raw_string: String) -> Self {
RevertReason::RawString(raw_string)
}
}

impl<T: SolInterface> RevertReason<T>
where
RevertReason<T>: From<ContractError<Infallible>>,
{
/// Decodes and retrieves the reason for a revert from the provided output data.
///
/// This method attempts to decode the provided output data as a generic contract error
/// or a UTF-8 string (for Vyper reverts).
///
/// If successful, it returns the decoded revert reason wrapped in an `Option`.
///
/// If both attempts fail, it returns `None`.
pub fn decode(out: &[u8]) -> Option<Self> {
// Try to decode as a generic contract error.
if let Ok(error) = ContractError::<T>::abi_decode(out, true) {
return Some(error.into());
}

// If that fails, try to decode as a regular string.
if let Ok(decoded_string) = core::str::from_utf8(out) {
return Some(decoded_string.to_string().into());
}

// If both attempts fail, return None.
None
}
}

/// Iterator over the function or error selectors of a [`SolInterface`] type.
///
/// This `struct` is created by the [`selectors`] method on [`SolInterface`].
Expand Down
3 changes: 2 additions & 1 deletion crates/sol-types/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ pub use function::SolCall;

mod interface;
pub use interface::{
ContractError, GenericContractError, Selectors, SolEventInterface, SolInterface,
ContractError, GenericContractError, GenericRevertReason, Selectors, SolEventInterface,
SolInterface,
};

mod r#struct;
Expand Down

0 comments on commit c2f6ad2

Please sign in to comment.