alloy_rpc_types_trace/
common.rsuse alloy_primitives::TxHash;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TraceResult<Ok, Err> {
Success {
result: Ok,
#[serde(skip_serializing_if = "Option::is_none", rename = "txHash")]
#[doc(alias = "transaction_hash")]
tx_hash: Option<TxHash>,
},
Error {
error: Err,
#[serde(skip_serializing_if = "Option::is_none", rename = "txHash")]
#[doc(alias = "transaction_hash")]
tx_hash: Option<TxHash>,
},
}
impl<Ok, Err> TraceResult<Ok, Err> {
#[doc(alias = "transaction_hash")]
pub const fn tx_hash(&self) -> Option<TxHash> {
*match self {
Self::Success { tx_hash, .. } | Self::Error { tx_hash, .. } => tx_hash,
}
}
pub const fn success(&self) -> Option<&Ok> {
match self {
Self::Success { result, .. } => Some(result),
Self::Error { .. } => None,
}
}
pub const fn error(&self) -> Option<&Err> {
match self {
Self::Error { error, .. } => Some(error),
Self::Success { .. } => None,
}
}
pub const fn is_success(&self) -> bool {
matches!(self, Self::Success { .. })
}
pub const fn is_error(&self) -> bool {
matches!(self, Self::Error { .. })
}
pub const fn new_success(result: Ok, tx_hash: Option<TxHash>) -> Self {
Self::Success { result, tx_hash }
}
pub const fn new_error(error: Err, tx_hash: Option<TxHash>) -> Self {
Self::Error { error, tx_hash }
}
}
#[cfg(test)]
mod tests {
use super::*;
use similar_asserts::assert_eq;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct OkResult {
message: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct ErrResult {
code: i32,
}
#[test]
fn test_trace_result_getters() {
let tx_hash = Some(TxHash::ZERO);
let success_result: TraceResult<OkResult, ErrResult> =
TraceResult::new_success(OkResult { message: "Success".to_string() }, tx_hash);
assert!(success_result.is_success());
assert!(!success_result.is_error());
assert_eq!(success_result.tx_hash(), tx_hash);
assert_eq!(success_result.success(), Some(&OkResult { message: "Success".to_string() }));
assert_eq!(success_result.error(), None);
let error_result: TraceResult<OkResult, ErrResult> =
TraceResult::new_error(ErrResult { code: 404 }, tx_hash);
assert!(!error_result.is_success());
assert!(error_result.is_error());
assert_eq!(error_result.tx_hash(), tx_hash);
assert_eq!(error_result.success(), None);
assert_eq!(error_result.error(), Some(&ErrResult { code: 404 }));
}
}