Skip to main content

rain_metadata/error/
mod.rs

1use std::{string::FromUtf8Error, str::Utf8Error};
2
3use rain_metaboard_subgraph::metaboard_client::MetaboardSubgraphClientError;
4
5use crate::meta::KnownMagic;
6
7/// Covers all errors variants of Rain Metadat lib functionalities
8#[derive(Debug)]
9pub enum Error {
10    CorruptMeta,
11    InvalidHash,
12    UnknownMeta,
13    UnknownMagic,
14    NoRecordFound,
15    UnsupportedMeta,
16    BiggerThan32Bytes,
17    NulByteInInput,
18    InflateError(String),
19    InvalidInput(String),
20    InvalidUrl(String),
21    CorruptRecord(String),
22    SubgraphError(String),
23    Utf8Error(Utf8Error),
24    FromUtf8Error(FromUtf8Error),
25    ReqwestError(reqwest::Error),
26    SerdeCborError(serde_cbor::Error),
27    SerdeJsonError(serde_json::Error),
28    AbiCoderError(alloy::sol_types::Error),
29    ValidationErrors(validator::ValidationErrors),
30    DecodeHexStringError(alloy::primitives::hex::FromHexError),
31    InvalidMetaMagic(KnownMagic, KnownMagic),
32    MetaboardSubgraphClientError(MetaboardSubgraphClientError),
33}
34
35impl std::fmt::Display for Error {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            Error::CorruptMeta => f.write_str("corrupt meta"),
39            Error::UnknownMeta => f.write_str("unknown meta"),
40            Error::UnknownMagic => f.write_str("unknown magic"),
41            Error::UnsupportedMeta => f.write_str("unsupported meta"),
42            Error::InvalidHash => f.write_str("invalid keccak256 hash"),
43            Error::NoRecordFound => f.write_str("found no matching record"),
44            Error::BiggerThan32Bytes => {
45                f.write_str("unexpected input size, must be 32 bytes or less")
46            }
47            Error::NulByteInInput => f.write_str("unexpected nul byte in input"),
48            Error::InvalidInput(v) => write!(f, "invalid input: {}", v),
49            Error::InvalidUrl(v) => write!(f, "invalid URL: {}", v),
50            Error::CorruptRecord(v) => write!(f, "corrupt record: {}", v),
51            Error::SubgraphError(v) => write!(f, "subgraph error: {}", v),
52            Error::ReqwestError(v) => write!(f, "{}", v),
53            Error::InflateError(v) => write!(f, "{}", v),
54            Error::Utf8Error(v) => write!(f, "{}", v),
55            Error::AbiCoderError(v) => write!(f, "{}", v),
56            Error::SerdeCborError(v) => write!(f, "{}", v),
57            Error::SerdeJsonError(v) => write!(f, "{}", v),
58            Error::FromUtf8Error(v) => write!(f, "{}", v),
59            Error::DecodeHexStringError(v) => write!(f, "{}", v),
60            Error::ValidationErrors(v) => write!(f, "{}", v),
61            Error::InvalidMetaMagic(expected, actual) => {
62                write!(
63                    f,
64                    "invalid meta magic: expected {:?}, got {:?}",
65                    expected, actual
66                )
67            }
68            Error::MetaboardSubgraphClientError(v) => write!(f, "{}", v),
69        }
70    }
71}
72
73impl std::error::Error for Error {}
74
75impl From<serde_json::Error> for Error {
76    fn from(value: serde_json::Error) -> Self {
77        Error::SerdeJsonError(value)
78    }
79}
80
81impl From<serde_cbor::Error> for Error {
82    fn from(value: serde_cbor::Error) -> Self {
83        Error::SerdeCborError(value)
84    }
85}
86
87impl From<FromUtf8Error> for Error {
88    fn from(value: FromUtf8Error) -> Self {
89        Error::FromUtf8Error(value)
90    }
91}
92
93impl From<Utf8Error> for Error {
94    fn from(value: Utf8Error) -> Self {
95        Error::Utf8Error(value)
96    }
97}
98
99impl From<validator::ValidationErrors> for Error {
100    fn from(value: validator::ValidationErrors) -> Self {
101        Error::ValidationErrors(value)
102    }
103}
104
105impl From<alloy::sol_types::Error> for Error {
106    fn from(value: alloy::sol_types::Error) -> Self {
107        Error::AbiCoderError(value)
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    /// Fixed-string Display arms are part of the CLI's user-facing surface:
116    /// pin them exactly.
117    #[test]
118    fn test_display_fixed_strings() {
119        assert_eq!(Error::CorruptMeta.to_string(), "corrupt meta");
120        assert_eq!(Error::UnknownMeta.to_string(), "unknown meta");
121        assert_eq!(Error::UnknownMagic.to_string(), "unknown magic");
122        assert_eq!(Error::UnsupportedMeta.to_string(), "unsupported meta");
123        assert_eq!(Error::InvalidHash.to_string(), "invalid keccak256 hash");
124        assert_eq!(Error::NoRecordFound.to_string(), "found no matching record");
125        assert_eq!(
126            Error::BiggerThan32Bytes.to_string(),
127            "unexpected input size, must be 32 bytes or less"
128        );
129        assert_eq!(
130            Error::NulByteInInput.to_string(),
131            "unexpected nul byte in input"
132        );
133    }
134
135    /// Formatted wrappers carry the wrapped value in the rendered message.
136    #[test]
137    fn test_display_formatted_wrappers() {
138        assert_eq!(
139            Error::InvalidInput("abc".to_string()).to_string(),
140            "invalid input: abc"
141        );
142        assert_eq!(
143            Error::InvalidUrl("not-a-url".to_string()).to_string(),
144            "invalid URL: not-a-url"
145        );
146        assert_eq!(Error::InflateError("boom".to_string()).to_string(), "boom");
147        assert_eq!(
148            Error::CorruptRecord("bytecode is missing".to_string()).to_string(),
149            "corrupt record: bytecode is missing"
150        );
151        assert_eq!(
152            Error::SubgraphError("boom".to_string()).to_string(),
153            "subgraph error: boom"
154        );
155    }
156
157    /// InvalidMetaMagic renders expected first, actual second.
158    #[test]
159    fn test_display_invalid_meta_magic_field_order() {
160        let err = Error::InvalidMetaMagic(KnownMagic::RainMetaDocumentV1, KnownMagic::OpMetaV1);
161        assert_eq!(
162            err.to_string(),
163            "invalid meta magic: expected RainMetaDocumentV1, got OpMetaV1"
164        );
165    }
166
167    /// From impls must route each source error to its own variant, preserving
168    /// the source (observable through the rendered message).
169    #[test]
170    fn test_from_serde_json_routes_to_serde_json_error() {
171        let src = serde_json::from_str::<serde_json::Value>("{oops").unwrap_err();
172        let msg = src.to_string();
173        let err: Error = src.into();
174        match err {
175            Error::SerdeJsonError(e) => assert_eq!(e.to_string(), msg),
176            other => panic!("wrong variant: {:?}", other),
177        }
178    }
179
180    #[test]
181    fn test_from_utf8_error_routes_to_utf8_error() {
182        // The invalid byte is deliberate: it manufactures the source error.
183        #[allow(invalid_from_utf8)]
184        let src = std::str::from_utf8(&[0xff]).unwrap_err();
185        let err: Error = src.into();
186        match err {
187            Error::Utf8Error(e) => assert_eq!(e, src),
188            other => panic!("wrong variant: {:?}", other),
189        }
190    }
191
192    #[test]
193    fn test_from_from_utf8_error_routes_to_from_utf8_error() {
194        let src = String::from_utf8(vec![0xff]).unwrap_err();
195        let msg = src.to_string();
196        let err: Error = src.into();
197        match err {
198            Error::FromUtf8Error(e) => assert_eq!(e.to_string(), msg),
199            other => panic!("wrong variant: {:?}", other),
200        }
201    }
202}