typhoon_errors/
error_code.rs

1use pinocchio::program_error::{ProgramError, ToStr};
2
3#[derive(Debug, PartialEq, Eq)]
4pub enum ErrorCode {
5    InvalidProgramExecutable = 100,
6    AccountNotInitialized,
7    AccountNotMutable,
8    AccountNotSigner,
9    AccountOwnedByWrongProgram,
10    AccountDiscriminatorMismatch,
11    HasOneConstraint,
12    TryingToInitPayerAsProgramAccount,
13    TokenConstraintViolated,
14}
15
16impl TryFrom<u32> for ErrorCode {
17    type Error = ProgramError;
18
19    fn try_from(value: u32) -> Result<Self, Self::Error> {
20        match value {
21            100 => Ok(ErrorCode::InvalidProgramExecutable),
22            101 => Ok(ErrorCode::AccountNotInitialized),
23            102 => Ok(ErrorCode::AccountNotMutable),
24            103 => Ok(ErrorCode::AccountNotSigner),
25            104 => Ok(ErrorCode::AccountOwnedByWrongProgram),
26            105 => Ok(ErrorCode::AccountDiscriminatorMismatch),
27            106 => Ok(ErrorCode::HasOneConstraint),
28            107 => Ok(ErrorCode::TryingToInitPayerAsProgramAccount),
29            108 => Ok(ErrorCode::TokenConstraintViolated),
30            _ => Err(ProgramError::InvalidArgument),
31        }
32    }
33}
34
35impl From<ErrorCode> for ProgramError {
36    fn from(e: ErrorCode) -> Self {
37        ProgramError::Custom(e as u32)
38    }
39}
40
41impl ToStr for ErrorCode {
42    fn to_str<E>(&self) -> &'static str
43    where
44        E: 'static + ToStr + TryFrom<u32>,
45    {
46        match self {
47            ErrorCode::InvalidProgramExecutable => "Error: Program is not executable",
48            ErrorCode::AccountNotInitialized => "Error: Account is not initialized yet",
49            ErrorCode::AccountNotMutable => "Error: The given account is not mutable",
50            ErrorCode::AccountNotSigner => "Error: Account is not a signer",
51            ErrorCode::AccountOwnedByWrongProgram => {
52                "Error: The current owner of this account is not the expected one"
53            }
54            ErrorCode::AccountDiscriminatorMismatch => {
55                "Error: Discriminator did not match what was expected"
56            }
57            ErrorCode::HasOneConstraint => "Error: has_one constraint violated",
58            ErrorCode::TryingToInitPayerAsProgramAccount => {
59                "Error: Cannot initialize a program account with the payer account"
60            }
61            ErrorCode::TokenConstraintViolated => "Error: Token constraint was violated",
62        }
63    }
64}