use anchor_lang::error_code;
use borsh::maybestd::io::Error as BorshIoError;
use solana_program::{program_error::ProgramError, pubkey::Pubkey};
use std::fmt::{Debug, Display};
pub const ERROR_CODE_OFFSET: u32 = 6000;
#[error_code(offset = 0)]
pub enum ErrorCode {
#[msg("8 byte instruction identifier not provided")]
InstructionMissing = 100,
#[msg("Fallback functions are not supported")]
InstructionFallbackNotFound,
#[msg("The program could not deserialize the given instruction")]
InstructionDidNotDeserialize,
#[msg("The program could not serialize the given instruction")]
InstructionDidNotSerialize,
#[msg("The program was compiled without idl instructions")]
IdlInstructionStub = 1000,
#[msg("Invalid program given to the IDL instruction")]
IdlInstructionInvalidProgram,
#[msg("IDL account must be empty in order to resize, try closing first")]
IdlAccountNotEmpty,
#[msg("The program was compiled without `event-cpi` feature")]
EventInstructionStub = 1500,
#[msg("A mut constraint was violated")]
ConstraintMut = 2000,
#[msg("A has one constraint was violated")]
ConstraintHasOne,
#[msg("A signer constraint was violated")]
ConstraintSigner,
#[msg("A raw constraint was violated")]
ConstraintRaw,
#[msg("An owner constraint was violated")]
ConstraintOwner,
#[msg("A rent exemption constraint was violated")]
ConstraintRentExempt,
#[msg("A seeds constraint was violated")]
ConstraintSeeds,
#[msg("An executable constraint was violated")]
ConstraintExecutable,
#[msg("Deprecated Error, feel free to replace with something else")]
ConstraintState,
#[msg("An associated constraint was violated")]
ConstraintAssociated,
#[msg("An associated init constraint was violated")]
ConstraintAssociatedInit,
#[msg("A close constraint was violated")]
ConstraintClose,
#[msg("An address constraint was violated")]
ConstraintAddress,
#[msg("Expected zero account discriminant")]
ConstraintZero,
#[msg("A token mint constraint was violated")]
ConstraintTokenMint,
#[msg("A token owner constraint was violated")]
ConstraintTokenOwner,
#[msg("A mint mint authority constraint was violated")]
ConstraintMintMintAuthority,
#[msg("A mint freeze authority constraint was violated")]
ConstraintMintFreezeAuthority,
#[msg("A mint decimals constraint was violated")]
ConstraintMintDecimals,
#[msg("A space constraint was violated")]
ConstraintSpace,
#[msg("A required account for the constraint is None")]
ConstraintAccountIsNone,
#[msg("A token account token program constraint was violated")]
ConstraintTokenTokenProgram,
#[msg("A mint token program constraint was violated")]
ConstraintMintTokenProgram,
#[msg("An associated token account token program constraint was violated")]
ConstraintAssociatedTokenTokenProgram,
#[msg("A require expression was violated")]
RequireViolated = 2500,
#[msg("A require_eq expression was violated")]
RequireEqViolated,
#[msg("A require_keys_eq expression was violated")]
RequireKeysEqViolated,
#[msg("A require_neq expression was violated")]
RequireNeqViolated,
#[msg("A require_keys_neq expression was violated")]
RequireKeysNeqViolated,
#[msg("A require_gt expression was violated")]
RequireGtViolated,
#[msg("A require_gte expression was violated")]
RequireGteViolated,
#[msg("The account discriminator was already set on this account")]
AccountDiscriminatorAlreadySet = 3000,
#[msg("No 8 byte discriminator was found on the account")]
AccountDiscriminatorNotFound,
#[msg("8 byte discriminator did not match what was expected")]
AccountDiscriminatorMismatch,
#[msg("Failed to deserialize the account")]
AccountDidNotDeserialize,
#[msg("Failed to serialize the account")]
AccountDidNotSerialize,
#[msg("Not enough account keys given to the instruction")]
AccountNotEnoughKeys,
#[msg("The given account is not mutable")]
AccountNotMutable,
#[msg("The given account is owned by a different program than expected")]
AccountOwnedByWrongProgram,
#[msg("Program ID was not as expected")]
InvalidProgramId,
#[msg("Program account is not executable")]
InvalidProgramExecutable,
#[msg("The given account did not sign")]
AccountNotSigner,
#[msg("The given account is not owned by the system program")]
AccountNotSystemOwned,
#[msg("The program expected this account to be already initialized")]
AccountNotInitialized,
#[msg("The given account is not a program data account")]
AccountNotProgramData,
#[msg("The given account is not the associated token account")]
AccountNotAssociatedTokenAccount,
#[msg("The given public key does not match the required sysvar")]
AccountSysvarMismatch,
#[msg("The account reallocation exceeds the MAX_PERMITTED_DATA_INCREASE limit")]
AccountReallocExceedsLimit,
#[msg("The account was duplicated for more than one reallocation")]
AccountDuplicateReallocs,
#[msg("The declared program id does not match the actual program id")]
DeclaredProgramIdMismatch = 4100,
#[msg("You cannot/should not initialize the payer account as a program account")]
TryingToInitPayerAsProgramAccount = 4101,
#[msg("The API being used is deprecated and should no longer be used")]
Deprecated = 5000,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
AnchorError(Box<AnchorError>),
ProgramError(Box<ProgramErrorWithOrigin>),
}
impl std::error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::AnchorError(ae) => Display::fmt(&ae, f),
Error::ProgramError(pe) => Display::fmt(&pe, f),
}
}
}
impl From<AnchorError> for Error {
fn from(ae: AnchorError) -> Self {
Self::AnchorError(Box::new(ae))
}
}
impl From<ProgramError> for Error {
fn from(program_error: ProgramError) -> Self {
Self::ProgramError(Box::new(program_error.into()))
}
}
impl From<BorshIoError> for Error {
fn from(error: BorshIoError) -> Self {
Error::ProgramError(Box::new(ProgramError::from(error).into()))
}
}
impl From<ProgramErrorWithOrigin> for Error {
fn from(pe: ProgramErrorWithOrigin) -> Self {
Self::ProgramError(Box::new(pe))
}
}
impl Error {
pub fn log(&self) {
match self {
Error::ProgramError(program_error) => program_error.log(),
Error::AnchorError(anchor_error) => anchor_error.log(),
}
}
pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
match &mut self {
Error::AnchorError(ae) => {
ae.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
}
Error::ProgramError(pe) => {
pe.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
}
};
self
}
pub fn with_source(mut self, source: Source) -> Self {
match &mut self {
Error::AnchorError(ae) => {
ae.error_origin = Some(ErrorOrigin::Source(source));
}
Error::ProgramError(pe) => {
pe.error_origin = Some(ErrorOrigin::Source(source));
}
};
self
}
pub fn with_pubkeys(mut self, pubkeys: (Pubkey, Pubkey)) -> Self {
let pubkeys = Some(ComparedValues::Pubkeys((pubkeys.0, pubkeys.1)));
match &mut self {
Error::AnchorError(ae) => ae.compared_values = pubkeys,
Error::ProgramError(pe) => pe.compared_values = pubkeys,
};
self
}
pub fn with_values(mut self, values: (impl ToString, impl ToString)) -> Self {
match &mut self {
Error::AnchorError(ae) => {
ae.compared_values = Some(ComparedValues::Values((
values.0.to_string(),
values.1.to_string(),
)))
}
Error::ProgramError(pe) => {
pe.compared_values = Some(ComparedValues::Values((
values.0.to_string(),
values.1.to_string(),
)))
}
};
self
}
}
#[derive(Debug)]
pub struct ProgramErrorWithOrigin {
pub program_error: ProgramError,
pub error_origin: Option<ErrorOrigin>,
pub compared_values: Option<ComparedValues>,
}
impl PartialEq for ProgramErrorWithOrigin {
fn eq(&self, other: &Self) -> bool {
self.program_error == other.program_error
}
}
impl Eq for ProgramErrorWithOrigin {}
impl Display for ProgramErrorWithOrigin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.program_error, f)
}
}
impl ProgramErrorWithOrigin {
pub fn log(&self) {
match &self.error_origin {
None => {
anchor_lang::solana_program::msg!(
"ProgramError occurred. Error Code: {:?}. Error Number: {}. Error Message: {}.",
self.program_error,
u64::from(self.program_error.clone()),
self.program_error
);
}
Some(ErrorOrigin::Source(source)) => {
anchor_lang::solana_program::msg!(
"ProgramError thrown in {}:{}. Error Code: {:?}. Error Number: {}. Error Message: {}.",
source.filename,
source.line,
self.program_error,
u64::from(self.program_error.clone()),
self.program_error
);
}
Some(ErrorOrigin::AccountName(account_name)) => {
anchor_lang::solana_program::log::sol_log(&format!(
"ProgramError caused by account: {}. Error Code: {:?}. Error Number: {}. Error Message: {}.",
account_name,
self.program_error,
u64::from(self.program_error.clone()),
self.program_error
));
}
}
match &self.compared_values {
Some(ComparedValues::Pubkeys((left, right))) => {
anchor_lang::solana_program::msg!("Left:");
left.log();
anchor_lang::solana_program::msg!("Right:");
right.log();
}
Some(ComparedValues::Values((left, right))) => {
anchor_lang::solana_program::msg!("Left: {}", left);
anchor_lang::solana_program::msg!("Right: {}", right);
}
None => (),
}
}
pub fn with_source(mut self, source: Source) -> Self {
self.error_origin = Some(ErrorOrigin::Source(source));
self
}
pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
self.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
self
}
}
impl From<ProgramError> for ProgramErrorWithOrigin {
fn from(program_error: ProgramError) -> Self {
Self {
program_error,
error_origin: None,
compared_values: None,
}
}
}
#[derive(Debug)]
pub enum ComparedValues {
Values((String, String)),
Pubkeys((Pubkey, Pubkey)),
}
#[derive(Debug)]
pub enum ErrorOrigin {
Source(Source),
AccountName(String),
}
#[derive(Debug)]
pub struct AnchorError {
pub error_name: String,
pub error_code_number: u32,
pub error_msg: String,
pub error_origin: Option<ErrorOrigin>,
pub compared_values: Option<ComparedValues>,
}
impl AnchorError {
pub fn log(&self) {
match &self.error_origin {
None => {
anchor_lang::solana_program::log::sol_log(&format!(
"AnchorError occurred. Error Code: {}. Error Number: {}. Error Message: {}.",
self.error_name, self.error_code_number, self.error_msg
));
}
Some(ErrorOrigin::Source(source)) => {
anchor_lang::solana_program::msg!(
"AnchorError thrown in {}:{}. Error Code: {}. Error Number: {}. Error Message: {}.",
source.filename,
source.line,
self.error_name,
self.error_code_number,
self.error_msg
);
}
Some(ErrorOrigin::AccountName(account_name)) => {
anchor_lang::solana_program::log::sol_log(&format!(
"AnchorError caused by account: {}. Error Code: {}. Error Number: {}. Error Message: {}.",
account_name,
self.error_name,
self.error_code_number,
self.error_msg
));
}
}
match &self.compared_values {
Some(ComparedValues::Pubkeys((left, right))) => {
anchor_lang::solana_program::msg!("Left:");
left.log();
anchor_lang::solana_program::msg!("Right:");
right.log();
}
Some(ComparedValues::Values((left, right))) => {
anchor_lang::solana_program::msg!("Left: {}", left);
anchor_lang::solana_program::msg!("Right: {}", right);
}
None => (),
}
}
pub fn with_source(mut self, source: Source) -> Self {
self.error_origin = Some(ErrorOrigin::Source(source));
self
}
pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
self.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
self
}
}
impl Display for AnchorError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self, f)
}
}
impl PartialEq for AnchorError {
fn eq(&self, other: &Self) -> bool {
self.error_code_number == other.error_code_number
}
}
impl Eq for AnchorError {}
impl std::convert::From<Error> for anchor_lang::solana_program::program_error::ProgramError {
fn from(e: Error) -> anchor_lang::solana_program::program_error::ProgramError {
match e {
Error::AnchorError(error) => {
anchor_lang::solana_program::program_error::ProgramError::Custom(
error.error_code_number,
)
}
Error::ProgramError(program_error) => program_error.program_error,
}
}
}
#[derive(Debug)]
pub struct Source {
pub filename: &'static str,
pub line: u32,
}