typhoon_errors/
lib.rs

1use {
2    num_traits::{FromPrimitive, ToPrimitive},
3    pinocchio::{msg, program_error::ProgramError},
4    thiserror::Error,
5};
6
7/// Maybe rework with thiserror 2.0
8#[derive(Debug, Error)]
9pub enum Error {
10    #[error("Program is not executable")]
11    InvalidProgramExecutable,
12
13    #[error("Account is initialized yet")]
14    AccountNotInitialized,
15
16    #[error("The given account is not mutable")]
17    AccountNotMutable,
18
19    #[error("Account is not a signer")]
20    AccountNotSigner,
21
22    #[error("The current owner of this account is not the expected one")]
23    AccountOwnedByWrongProgram,
24
25    #[error("Failed to serialize or deserialize account data")]
26    BorshIoError,
27
28    #[error("Discriminator did not match what was expected")]
29    AccountDiscriminatorMismatch,
30
31    #[error("has_one constraint violated")]
32    HasOneConstraint,
33
34    #[error("Cannot initialize a program account with the payer account")]
35    TryingToInitPayerAsProgramAccount,
36
37    #[error("Token constraint was violated")]
38    TokenConstraintViolated,
39}
40
41impl FromPrimitive for Error {
42    fn from_i64(n: i64) -> Option<Self> {
43        match n {
44            3000 => Some(Error::InvalidProgramExecutable),
45            3001 => Some(Error::AccountNotInitialized),
46            3002 => Some(Error::AccountNotMutable),
47            3003 => Some(Error::AccountNotSigner),
48            3004 => Some(Error::AccountOwnedByWrongProgram),
49            3005 => Some(Error::BorshIoError),
50            3006 => Some(Error::AccountDiscriminatorMismatch),
51            3007 => Some(Error::HasOneConstraint),
52            3008 => Some(Error::TryingToInitPayerAsProgramAccount),
53            3009 => Some(Error::TokenConstraintViolated),
54            _ => None,
55        }
56    }
57
58    fn from_u64(n: u64) -> Option<Self> {
59        Self::from_i64(n as i64)
60    }
61}
62
63impl ToPrimitive for Error {
64    fn to_i64(&self) -> Option<i64> {
65        match self {
66            Error::InvalidProgramExecutable => Some(3000),
67            Error::AccountNotInitialized => Some(3001),
68            Error::AccountNotMutable => Some(3002),
69            Error::AccountNotSigner => Some(3003),
70            Error::AccountOwnedByWrongProgram => Some(3004),
71            Error::BorshIoError => Some(3005),
72            Error::AccountDiscriminatorMismatch => Some(3006),
73            Error::HasOneConstraint => Some(3007),
74            Error::TryingToInitPayerAsProgramAccount => Some(3008),
75            Error::TokenConstraintViolated => Some(3009),
76        }
77    }
78
79    fn to_u64(&self) -> Option<u64> {
80        self.to_i64().map(|n| n as u64)
81    }
82}
83
84impl From<Error> for ProgramError {
85    fn from(value: Error) -> Self {
86        msg!(&format!("[ERROR] {value}"));
87        ProgramError::Custom(value.to_u32().unwrap())
88    }
89}