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