solana_program_fork_cleon_00/
program_error.rs

1//! The [`ProgramError`] type and related definitions.
2
3#![allow(clippy::arithmetic_side_effects)]
4use {
5    crate::{decode_error::DecodeError, instruction::InstructionError, msg, pubkey::PubkeyError},
6    borsh::io::Error as BorshIoError,
7    num_traits::{FromPrimitive, ToPrimitive},
8    std::convert::TryFrom,
9    thiserror::Error,
10};
11
12/// Reasons the program may fail
13#[derive(Clone, Debug, Deserialize, Eq, Error, PartialEq, Serialize)]
14pub enum ProgramError {
15    /// Allows on-chain programs to implement program-specific error types and see them returned
16    /// by the Solana runtime. A program-specific error may be any type that is represented as
17    /// or serialized to a u32 integer.
18    #[error("Custom program error: {0:#x}")]
19    Custom(u32),
20    #[error("The arguments provided to a program instruction were invalid")]
21    InvalidArgument,
22    #[error("An instruction's data contents was invalid")]
23    InvalidInstructionData,
24    #[error("An account's data contents was invalid")]
25    InvalidAccountData,
26    #[error("An account's data was too small")]
27    AccountDataTooSmall,
28    #[error("An account's balance was too small to complete the instruction")]
29    InsufficientFunds,
30    #[error("The account did not have the expected program id")]
31    IncorrectProgramId,
32    #[error("A signature was required but not found")]
33    MissingRequiredSignature,
34    #[error("An initialize instruction was sent to an account that has already been initialized")]
35    AccountAlreadyInitialized,
36    #[error("An attempt to operate on an account that hasn't been initialized")]
37    UninitializedAccount,
38    #[error("The instruction expected additional account keys")]
39    NotEnoughAccountKeys,
40    #[error("Failed to borrow a reference to account data, already borrowed")]
41    AccountBorrowFailed,
42    #[error("Length of the seed is too long for address generation")]
43    MaxSeedLengthExceeded,
44    #[error("Provided seeds do not result in a valid address")]
45    InvalidSeeds,
46    #[error("IO Error: {0}")]
47    BorshIoError(String),
48    #[error("An account does not have enough lamports to be rent-exempt")]
49    AccountNotRentExempt,
50    #[error("Unsupported sysvar")]
51    UnsupportedSysvar,
52    #[error("Provided owner is not allowed")]
53    IllegalOwner,
54    #[error("Accounts data allocations exceeded the maximum allowed per transaction")]
55    MaxAccountsDataAllocationsExceeded,
56    #[error("Account data reallocation was invalid")]
57    InvalidRealloc,
58    #[error("Instruction trace length exceeded the maximum allowed per transaction")]
59    MaxInstructionTraceLengthExceeded,
60    #[error("Builtin programs must consume compute units")]
61    BuiltinProgramsMustConsumeComputeUnits,
62    #[error("Invalid account owner")]
63    InvalidAccountOwner,
64    #[error("Program arithmetic overflowed")]
65    ArithmeticOverflow,
66}
67
68pub trait PrintProgramError {
69    fn print<E>(&self)
70    where
71        E: 'static + std::error::Error + DecodeError<E> + PrintProgramError + FromPrimitive;
72}
73
74impl PrintProgramError for ProgramError {
75    fn print<E>(&self)
76    where
77        E: 'static + std::error::Error + DecodeError<E> + PrintProgramError + FromPrimitive,
78    {
79        match self {
80            Self::Custom(error) => {
81                if let Some(custom_error) = E::decode_custom_error_to_enum(*error) {
82                    custom_error.print::<E>();
83                } else {
84                    msg!("Error: Unknown");
85                }
86            }
87            Self::InvalidArgument => msg!("Error: InvalidArgument"),
88            Self::InvalidInstructionData => msg!("Error: InvalidInstructionData"),
89            Self::InvalidAccountData => msg!("Error: InvalidAccountData"),
90            Self::AccountDataTooSmall => msg!("Error: AccountDataTooSmall"),
91            Self::InsufficientFunds => msg!("Error: InsufficientFunds"),
92            Self::IncorrectProgramId => msg!("Error: IncorrectProgramId"),
93            Self::MissingRequiredSignature => msg!("Error: MissingRequiredSignature"),
94            Self::AccountAlreadyInitialized => msg!("Error: AccountAlreadyInitialized"),
95            Self::UninitializedAccount => msg!("Error: UninitializedAccount"),
96            Self::NotEnoughAccountKeys => msg!("Error: NotEnoughAccountKeys"),
97            Self::AccountBorrowFailed => msg!("Error: AccountBorrowFailed"),
98            Self::MaxSeedLengthExceeded => msg!("Error: MaxSeedLengthExceeded"),
99            Self::InvalidSeeds => msg!("Error: InvalidSeeds"),
100            Self::BorshIoError(_) => msg!("Error: BorshIoError"),
101            Self::AccountNotRentExempt => msg!("Error: AccountNotRentExempt"),
102            Self::UnsupportedSysvar => msg!("Error: UnsupportedSysvar"),
103            Self::IllegalOwner => msg!("Error: IllegalOwner"),
104            Self::MaxAccountsDataAllocationsExceeded => {
105                msg!("Error: MaxAccountsDataAllocationsExceeded")
106            }
107            Self::InvalidRealloc => msg!("Error: InvalidRealloc"),
108            Self::MaxInstructionTraceLengthExceeded => {
109                msg!("Error: MaxInstructionTraceLengthExceeded")
110            }
111            Self::BuiltinProgramsMustConsumeComputeUnits => {
112                msg!("Error: BuiltinProgramsMustConsumeComputeUnits")
113            }
114            Self::InvalidAccountOwner => msg!("Error: InvalidAccountOwner"),
115            Self::ArithmeticOverflow => msg!("Error: ArithmeticOverflow"),
116        }
117    }
118}
119
120/// Builtin return values occupy the upper 32 bits
121const BUILTIN_BIT_SHIFT: usize = 32;
122macro_rules! to_builtin {
123    ($error:expr) => {
124        ($error as u64) << BUILTIN_BIT_SHIFT
125    };
126}
127
128pub const CUSTOM_ZERO: u64 = to_builtin!(1);
129pub const INVALID_ARGUMENT: u64 = to_builtin!(2);
130pub const INVALID_INSTRUCTION_DATA: u64 = to_builtin!(3);
131pub const INVALID_ACCOUNT_DATA: u64 = to_builtin!(4);
132pub const ACCOUNT_DATA_TOO_SMALL: u64 = to_builtin!(5);
133pub const INSUFFICIENT_FUNDS: u64 = to_builtin!(6);
134pub const INCORRECT_PROGRAM_ID: u64 = to_builtin!(7);
135pub const MISSING_REQUIRED_SIGNATURES: u64 = to_builtin!(8);
136pub const ACCOUNT_ALREADY_INITIALIZED: u64 = to_builtin!(9);
137pub const UNINITIALIZED_ACCOUNT: u64 = to_builtin!(10);
138pub const NOT_ENOUGH_ACCOUNT_KEYS: u64 = to_builtin!(11);
139pub const ACCOUNT_BORROW_FAILED: u64 = to_builtin!(12);
140pub const MAX_SEED_LENGTH_EXCEEDED: u64 = to_builtin!(13);
141pub const INVALID_SEEDS: u64 = to_builtin!(14);
142pub const BORSH_IO_ERROR: u64 = to_builtin!(15);
143pub const ACCOUNT_NOT_RENT_EXEMPT: u64 = to_builtin!(16);
144pub const UNSUPPORTED_SYSVAR: u64 = to_builtin!(17);
145pub const ILLEGAL_OWNER: u64 = to_builtin!(18);
146pub const MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED: u64 = to_builtin!(19);
147pub const INVALID_ACCOUNT_DATA_REALLOC: u64 = to_builtin!(20);
148pub const MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED: u64 = to_builtin!(21);
149pub const BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS: u64 = to_builtin!(22);
150pub const INVALID_ACCOUNT_OWNER: u64 = to_builtin!(23);
151pub const ARITHMETIC_OVERFLOW: u64 = to_builtin!(24);
152// Warning: Any new program errors added here must also be:
153// - Added to the below conversions
154// - Added as an equivalent to InstructionError
155// - Be featureized in the BPF loader to return `InstructionError::InvalidError`
156//   until the feature is activated
157
158impl From<ProgramError> for u64 {
159    fn from(error: ProgramError) -> Self {
160        match error {
161            ProgramError::InvalidArgument => INVALID_ARGUMENT,
162            ProgramError::InvalidInstructionData => INVALID_INSTRUCTION_DATA,
163            ProgramError::InvalidAccountData => INVALID_ACCOUNT_DATA,
164            ProgramError::AccountDataTooSmall => ACCOUNT_DATA_TOO_SMALL,
165            ProgramError::InsufficientFunds => INSUFFICIENT_FUNDS,
166            ProgramError::IncorrectProgramId => INCORRECT_PROGRAM_ID,
167            ProgramError::MissingRequiredSignature => MISSING_REQUIRED_SIGNATURES,
168            ProgramError::AccountAlreadyInitialized => ACCOUNT_ALREADY_INITIALIZED,
169            ProgramError::UninitializedAccount => UNINITIALIZED_ACCOUNT,
170            ProgramError::NotEnoughAccountKeys => NOT_ENOUGH_ACCOUNT_KEYS,
171            ProgramError::AccountBorrowFailed => ACCOUNT_BORROW_FAILED,
172            ProgramError::MaxSeedLengthExceeded => MAX_SEED_LENGTH_EXCEEDED,
173            ProgramError::InvalidSeeds => INVALID_SEEDS,
174            ProgramError::BorshIoError(_) => BORSH_IO_ERROR,
175            ProgramError::AccountNotRentExempt => ACCOUNT_NOT_RENT_EXEMPT,
176            ProgramError::UnsupportedSysvar => UNSUPPORTED_SYSVAR,
177            ProgramError::IllegalOwner => ILLEGAL_OWNER,
178            ProgramError::MaxAccountsDataAllocationsExceeded => {
179                MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED
180            }
181            ProgramError::InvalidRealloc => INVALID_ACCOUNT_DATA_REALLOC,
182            ProgramError::MaxInstructionTraceLengthExceeded => {
183                MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED
184            }
185            ProgramError::BuiltinProgramsMustConsumeComputeUnits => {
186                BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS
187            }
188            ProgramError::InvalidAccountOwner => INVALID_ACCOUNT_OWNER,
189            ProgramError::ArithmeticOverflow => ARITHMETIC_OVERFLOW,
190            ProgramError::Custom(error) => {
191                if error == 0 {
192                    CUSTOM_ZERO
193                } else {
194                    error as u64
195                }
196            }
197        }
198    }
199}
200
201impl From<u64> for ProgramError {
202    fn from(error: u64) -> Self {
203        match error {
204            CUSTOM_ZERO => Self::Custom(0),
205            INVALID_ARGUMENT => Self::InvalidArgument,
206            INVALID_INSTRUCTION_DATA => Self::InvalidInstructionData,
207            INVALID_ACCOUNT_DATA => Self::InvalidAccountData,
208            ACCOUNT_DATA_TOO_SMALL => Self::AccountDataTooSmall,
209            INSUFFICIENT_FUNDS => Self::InsufficientFunds,
210            INCORRECT_PROGRAM_ID => Self::IncorrectProgramId,
211            MISSING_REQUIRED_SIGNATURES => Self::MissingRequiredSignature,
212            ACCOUNT_ALREADY_INITIALIZED => Self::AccountAlreadyInitialized,
213            UNINITIALIZED_ACCOUNT => Self::UninitializedAccount,
214            NOT_ENOUGH_ACCOUNT_KEYS => Self::NotEnoughAccountKeys,
215            ACCOUNT_BORROW_FAILED => Self::AccountBorrowFailed,
216            MAX_SEED_LENGTH_EXCEEDED => Self::MaxSeedLengthExceeded,
217            INVALID_SEEDS => Self::InvalidSeeds,
218            BORSH_IO_ERROR => Self::BorshIoError("Unknown".to_string()),
219            ACCOUNT_NOT_RENT_EXEMPT => Self::AccountNotRentExempt,
220            UNSUPPORTED_SYSVAR => Self::UnsupportedSysvar,
221            ILLEGAL_OWNER => Self::IllegalOwner,
222            MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED => Self::MaxAccountsDataAllocationsExceeded,
223            INVALID_ACCOUNT_DATA_REALLOC => Self::InvalidRealloc,
224            MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED => Self::MaxInstructionTraceLengthExceeded,
225            BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS => {
226                Self::BuiltinProgramsMustConsumeComputeUnits
227            }
228            INVALID_ACCOUNT_OWNER => Self::InvalidAccountOwner,
229            ARITHMETIC_OVERFLOW => Self::ArithmeticOverflow,
230            _ => Self::Custom(error as u32),
231        }
232    }
233}
234
235impl TryFrom<InstructionError> for ProgramError {
236    type Error = InstructionError;
237
238    fn try_from(error: InstructionError) -> Result<Self, Self::Error> {
239        match error {
240            Self::Error::Custom(err) => Ok(Self::Custom(err)),
241            Self::Error::InvalidArgument => Ok(Self::InvalidArgument),
242            Self::Error::InvalidInstructionData => Ok(Self::InvalidInstructionData),
243            Self::Error::InvalidAccountData => Ok(Self::InvalidAccountData),
244            Self::Error::AccountDataTooSmall => Ok(Self::AccountDataTooSmall),
245            Self::Error::InsufficientFunds => Ok(Self::InsufficientFunds),
246            Self::Error::IncorrectProgramId => Ok(Self::IncorrectProgramId),
247            Self::Error::MissingRequiredSignature => Ok(Self::MissingRequiredSignature),
248            Self::Error::AccountAlreadyInitialized => Ok(Self::AccountAlreadyInitialized),
249            Self::Error::UninitializedAccount => Ok(Self::UninitializedAccount),
250            Self::Error::NotEnoughAccountKeys => Ok(Self::NotEnoughAccountKeys),
251            Self::Error::AccountBorrowFailed => Ok(Self::AccountBorrowFailed),
252            Self::Error::MaxSeedLengthExceeded => Ok(Self::MaxSeedLengthExceeded),
253            Self::Error::InvalidSeeds => Ok(Self::InvalidSeeds),
254            Self::Error::BorshIoError(err) => Ok(Self::BorshIoError(err)),
255            Self::Error::AccountNotRentExempt => Ok(Self::AccountNotRentExempt),
256            Self::Error::UnsupportedSysvar => Ok(Self::UnsupportedSysvar),
257            Self::Error::IllegalOwner => Ok(Self::IllegalOwner),
258            Self::Error::MaxAccountsDataAllocationsExceeded => {
259                Ok(Self::MaxAccountsDataAllocationsExceeded)
260            }
261            Self::Error::InvalidRealloc => Ok(Self::InvalidRealloc),
262            Self::Error::MaxInstructionTraceLengthExceeded => {
263                Ok(Self::MaxInstructionTraceLengthExceeded)
264            }
265            Self::Error::BuiltinProgramsMustConsumeComputeUnits => {
266                Ok(Self::BuiltinProgramsMustConsumeComputeUnits)
267            }
268            Self::Error::InvalidAccountOwner => Ok(Self::InvalidAccountOwner),
269            Self::Error::ArithmeticOverflow => Ok(Self::ArithmeticOverflow),
270            _ => Err(error),
271        }
272    }
273}
274
275impl<T> From<T> for InstructionError
276where
277    T: ToPrimitive,
278{
279    fn from(error: T) -> Self {
280        let error = error.to_u64().unwrap_or(0xbad_c0de);
281        match error {
282            CUSTOM_ZERO => Self::Custom(0),
283            INVALID_ARGUMENT => Self::InvalidArgument,
284            INVALID_INSTRUCTION_DATA => Self::InvalidInstructionData,
285            INVALID_ACCOUNT_DATA => Self::InvalidAccountData,
286            ACCOUNT_DATA_TOO_SMALL => Self::AccountDataTooSmall,
287            INSUFFICIENT_FUNDS => Self::InsufficientFunds,
288            INCORRECT_PROGRAM_ID => Self::IncorrectProgramId,
289            MISSING_REQUIRED_SIGNATURES => Self::MissingRequiredSignature,
290            ACCOUNT_ALREADY_INITIALIZED => Self::AccountAlreadyInitialized,
291            UNINITIALIZED_ACCOUNT => Self::UninitializedAccount,
292            NOT_ENOUGH_ACCOUNT_KEYS => Self::NotEnoughAccountKeys,
293            ACCOUNT_BORROW_FAILED => Self::AccountBorrowFailed,
294            MAX_SEED_LENGTH_EXCEEDED => Self::MaxSeedLengthExceeded,
295            INVALID_SEEDS => Self::InvalidSeeds,
296            BORSH_IO_ERROR => Self::BorshIoError("Unknown".to_string()),
297            ACCOUNT_NOT_RENT_EXEMPT => Self::AccountNotRentExempt,
298            UNSUPPORTED_SYSVAR => Self::UnsupportedSysvar,
299            ILLEGAL_OWNER => Self::IllegalOwner,
300            MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED => Self::MaxAccountsDataAllocationsExceeded,
301            INVALID_ACCOUNT_DATA_REALLOC => Self::InvalidRealloc,
302            MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED => Self::MaxInstructionTraceLengthExceeded,
303            BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS => {
304                Self::BuiltinProgramsMustConsumeComputeUnits
305            }
306            INVALID_ACCOUNT_OWNER => Self::InvalidAccountOwner,
307            ARITHMETIC_OVERFLOW => Self::ArithmeticOverflow,
308            _ => {
309                // A valid custom error has no bits set in the upper 32
310                if error >> BUILTIN_BIT_SHIFT == 0 {
311                    Self::Custom(error as u32)
312                } else {
313                    Self::InvalidError
314                }
315            }
316        }
317    }
318}
319
320impl From<PubkeyError> for ProgramError {
321    fn from(error: PubkeyError) -> Self {
322        match error {
323            PubkeyError::MaxSeedLengthExceeded => Self::MaxSeedLengthExceeded,
324            PubkeyError::InvalidSeeds => Self::InvalidSeeds,
325            PubkeyError::IllegalOwner => Self::IllegalOwner,
326        }
327    }
328}
329
330impl From<BorshIoError> for ProgramError {
331    fn from(error: BorshIoError) -> Self {
332        Self::BorshIoError(format!("{error}"))
333    }
334}