typhoon_errors/
error_code.rs

1use pinocchio::program_error::{ProgramError, ToStr};
2
3#[derive(Debug, PartialEq, Eq)]
4pub enum ErrorCode {
5    UnknownInstruction = 100,
6    AccountNotSigner,
7    AccountDiscriminatorMismatch,
8    HasOneConstraint,
9    AssertConstraint,
10    AddressConstraint,
11    TryingToInitPayerAsProgramAccount,
12    TokenConstraintViolated,
13    BufferFull,
14    InvalidReturnData,
15    InvalidDataLength,
16    InvalidDataAlignment,
17}
18
19impl TryFrom<u32> for ErrorCode {
20    type Error = ProgramError;
21
22    fn try_from(value: u32) -> Result<Self, Self::Error> {
23        match value {
24            100 => Ok(ErrorCode::UnknownInstruction),
25            101 => Ok(ErrorCode::AccountNotSigner),
26            102 => Ok(ErrorCode::AccountDiscriminatorMismatch),
27            103 => Ok(ErrorCode::HasOneConstraint),
28            104 => Ok(ErrorCode::AssertConstraint),
29            105 => Ok(ErrorCode::AddressConstraint),
30            106 => Ok(ErrorCode::TryingToInitPayerAsProgramAccount),
31            107 => Ok(ErrorCode::TokenConstraintViolated),
32            108 => Ok(ErrorCode::BufferFull),
33            109 => Ok(ErrorCode::InvalidReturnData),
34            110 => Ok(ErrorCode::InvalidDataLength),
35            111 => Ok(ErrorCode::InvalidDataAlignment),
36            _ => Err(ProgramError::InvalidArgument),
37        }
38    }
39}
40
41impl From<ErrorCode> for ProgramError {
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::UnknownInstruction => "Error: Unknown instruction",
54            ErrorCode::AccountNotSigner => "Error: Account is not a signer",
55            ErrorCode::AccountDiscriminatorMismatch => {
56                "Error: Discriminator did not match what was expected"
57            }
58            ErrorCode::HasOneConstraint => "Error: has_one constraint violated",
59            ErrorCode::AssertConstraint => "Error: assert constraint violated",
60            ErrorCode::AddressConstraint => "Error: address constraint violated",
61            ErrorCode::TryingToInitPayerAsProgramAccount => {
62                "Error: Cannot initialize a program account with the payer account"
63            }
64            ErrorCode::TokenConstraintViolated => "Error: Token constraint was violated",
65            ErrorCode::BufferFull => "Error: Buffer is full",
66            ErrorCode::InvalidReturnData => "Error: The return data is invalid",
67            ErrorCode::InvalidDataLength => "Error: Invalid data length",
68            ErrorCode::InvalidDataAlignment => "Error: Invalid data alignment",
69        }
70    }
71}