1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
use serde_json::Error as SerdeJsonError;
use std::error::Error as StdError;
use std::fmt;
use std::fmt::Debug;
use std::sync::Arc;

type ParentError = Arc<dyn StdError + Send + Sync + 'static>;

/// Switchboard Functions error suite
#[derive(Clone, Debug)]
pub enum SbError {
    // Generics
    Generic,
    Message(&'static str),
    CustomMessage(String),
    CustomError {
        message: String,
        source: ParentError,
    },
    Unexpected,
    // Environment Errors
    EnvVariableMissing(String),
    InvalidKeypairFile,
    KeyParseError,
    CheckSizeError,

    IoError(ParentError),

    // SGX Errors
    SgxError,
    SgxWriteError,

    // Network Errors
    NetworkError,

    // Quote Errors
    QuoteParseError,
    InvalidQuoteError,

    // QvnErrors
    QvnError(Arc<String>),

    // Docker/Container Errors
    DockerError,
    DockerFetchError,
    FunctionImageTooBigError,
    ContainerErrorMessage(String),
    ContainerError(ParentError),
    ContainerStartError(ParentError),
    ContainerCreateError(ParentError),
    ContainerNeedsUpdate,
    // ContainerCreateError,
    ContainerResultParseError,
    AttachError,
    ContainerTimeout,
    ContainerActive,
    ContainerBackoff(u64),
    FunctionErrorCountExceeded(u32),

    // Function Errors
    FunctionResultParseError,
    IllegalFunctionOutput,
    FunctionVerifyFailure,
    FunctionResultIllegalAccount,
    FunctionResultAccountsMismatch,
    FunctionResultInvalidData,
    FunctionResultInvalidPid,
    FunctionResultEmptyInstructions,

    // Transaction Errors
    TxFailure,
    TxCompileErr,
    TxDeserializationError,
    QvnTxSendFailure,
    InvalidInstructionError,

    // Chain specific Errors
    InvalidChain,
    AnchorParse,
    AnchorParseError,
    EvmError,

    // Misc
    IpfsParseError,
    IpfsNetworkError,
    HeartbeatRoutineFailure,
    EventListenerRoutineFailure,
    DecryptError,
    ParseError,
    MrEnclaveMismatch,
    FunctionResultIxIncorrectTargetChain,
    InvalidSignature,

    // Solana
    SolanaBlockhashError,
    SolanaSignError(ParentError, String),
    FunctionResultIxMissingDiscriminator,
    FunctionResultError(&'static str),
    FunctionResultIxError(&'static str),
    // An error which should fail to send the user generated transaction and should emit an error code
    FunctionResultFailoverError(u8, ParentError),
    // An error which should not be retried and should be dropped by the QVN.
    FunctionResultNonRetryableError(ParentError),

    AccountNotFound,
}

impl fmt::Display for SbError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SbError::EnvVariableMissing(message) => {
                write!(f, "Env variable missing: {}", message.as_str())
            }
            SbError::Message(message) => write!(f, "error: {}", message),
            SbError::CustomMessage(message) => write!(f, "error: {}", message.as_str()),
            SbError::CustomError {
                message, source, ..
            } => write!(f, "error: {} - {:?}", message.as_str(), source),
            SbError::FunctionResultError(message) => {
                write!(f, "error: FunctionResultError - {}", message)
            }
            SbError::FunctionResultIxError(message) => {
                write!(f, "error: FunctionResultIxError - {}", message)
            }
            SbError::FunctionResultFailoverError(code, source) => {
                write!(
                    f,
                    "error: FunctionResultFailoverError ({}) - {:?}",
                    code, source
                )
            }
            SbError::FunctionResultNonRetryableError(source) => {
                write!(f, "error: FunctionResultNonRetryableError - {:?}", source)
            }
            // Handle other error variants as needed
            _ => write!(f, "{:#?}", self),
        }
    }
}

impl From<&str> for SbError {
    fn from(error: &str) -> Self {
        SbError::CustomMessage(error.to_string())
    }
}
impl From<String> for SbError {
    fn from(error: String) -> Self {
        SbError::CustomMessage(error)
    }
}

impl From<hex::FromHexError> for SbError {
    fn from(error: hex::FromHexError) -> Self {
        SbError::CustomError {
            message: "hex error".to_string(),
            source: Arc::new(error),
        }
    }
}

impl StdError for SbError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            SbError::CustomError { source, .. } => Some(source.as_ref()), // Handle other error variants as needed
            SbError::ContainerError(source) => Some(source.as_ref()),
            SbError::ContainerStartError(source) => Some(source.as_ref()),
            SbError::SolanaSignError(source, ..) => Some(source.as_ref()),
            SbError::FunctionResultFailoverError(_code, source, ..) => Some(source.as_ref()),
            SbError::FunctionResultNonRetryableError(source, ..) => Some(source.as_ref()),
            _ => None,
        }
    }
}

impl From<SerdeJsonError> for SbError {
    fn from(error: SerdeJsonError) -> Self {
        SbError::CustomError {
            message: "serde_json error".to_string(),
            source: Arc::new(error),
        }
    }
}

impl From<std::io::Error> for SbError {
    fn from(val: std::io::Error) -> Self {
        SbError::IoError(std::sync::Arc::new(val))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn display_generic() {
        let error = SbError::Generic;
        assert_eq!(format!("{}", error), "Generic");
    }

    #[test]
    fn display_custom_message() {
        let error = SbError::CustomMessage("my custom message".to_string());
        assert_eq!(format!("{}", error), "error: my custom message");
    }

    #[test]
    fn display_env_variable_missing() {
        let error = SbError::EnvVariableMissing("MY_ENV_VAR".to_string());
        assert_eq!(format!("{}", error), "Env variable missing: MY_ENV_VAR");
    }

    #[test]
    fn from_str() {
        let error: SbError = "my custom message".into();
        assert_eq!(format!("{}", error), "error: my custom message");
    }

    #[test]
    fn from_hex_error() {
        let hex_error = hex::FromHexError::OddLength;
        let error: SbError = hex_error.into();
        assert_eq!(format!("{}", error), "error: hex error - OddLength");
    }

    #[test]
    fn from_serde_json_error() {
        let json = "\"";
        let serde_json_error = serde_json::from_str::<serde_json::Value>(json).unwrap_err();
        let error: SbError = serde_json_error.into();
        assert!(format!("{}", error).starts_with("error: serde_json error - "));
    }
}