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    BufferFull,
15    InvalidReturnData,
16}
17
18impl TryFrom<u32> for ErrorCode {
19    type Error = ProgramError;
20
21    #[inline(always)]
22    fn try_from(value: u32) -> Result<Self, Self::Error> {
23        match value {
24            100 => Ok(ErrorCode::InvalidProgramExecutable),
25            101 => Ok(ErrorCode::AccountNotInitialized),
26            102 => Ok(ErrorCode::AccountNotMutable),
27            103 => Ok(ErrorCode::AccountNotSigner),
28            104 => Ok(ErrorCode::AccountOwnedByWrongProgram),
29            105 => Ok(ErrorCode::AccountDiscriminatorMismatch),
30            106 => Ok(ErrorCode::HasOneConstraint),
31            107 => Ok(ErrorCode::TryingToInitPayerAsProgramAccount),
32            108 => Ok(ErrorCode::TokenConstraintViolated),
33            109 => Ok(ErrorCode::BufferFull),
34            110 => Ok(ErrorCode::InvalidReturnData),
35            _ => Err(ProgramError::InvalidArgument),
36        }
37    }
38}
39
40impl From<ErrorCode> for ProgramError {
41    #[inline(always)]
42    fn from(e: ErrorCode) -> Self {
43        ProgramError::Custom(e as u32)
44    }
45}
46
47impl ToStr for ErrorCode {
48    fn to_str<E>(&self) -> &'static str
49    where
50        E: 'static + ToStr + TryFrom<u32>,
51    {
52        match self {
53            ErrorCode::InvalidProgramExecutable => "Error: Program is not executable",
54            ErrorCode::AccountNotInitialized => "Error: Account is not initialized yet",
55            ErrorCode::AccountNotMutable => "Error: The given account is not mutable",
56            ErrorCode::AccountNotSigner => "Error: Account is not a signer",
57            ErrorCode::AccountOwnedByWrongProgram => {
58                "Error: The current owner of this account is not the expected one"
59            }
60            ErrorCode::AccountDiscriminatorMismatch => {
61                "Error: Discriminator did not match what was expected"
62            }
63            ErrorCode::HasOneConstraint => "Error: has_one constraint violated",
64            ErrorCode::TryingToInitPayerAsProgramAccount => {
65                "Error: Cannot initialize a program account with the payer account"
66            }
67            ErrorCode::TokenConstraintViolated => "Error: Token constraint was violated",
68            ErrorCode::BufferFull => "Error: Buffer is full",
69            ErrorCode::InvalidReturnData => "Error: The return data is invalid",
70        }
71    }
72}