error.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. use anchor_attribute_error::error_code;
  2. use borsh::maybestd::io::Error as BorshIoError;
  3. use solana_program::program_error::ProgramError;
  4. use std::fmt::{Debug, Display};
  5. /// The starting point for user defined error codes.
  6. pub const ERROR_CODE_OFFSET: u32 = 6000;
  7. /// Error codes that can be returned by internal framework code.
  8. ///
  9. /// - >= 100 Instruction error codes
  10. /// - >= 1000 IDL error codes
  11. /// - >= 2000 constraint error codes
  12. /// - >= 3000 account error codes
  13. /// - = 4000 state error code
  14. /// - >= 4100 misc error codes
  15. /// - = 5000 deprecated error code
  16. ///
  17. /// The starting point for user-defined errors is defined
  18. /// by the [ERROR_CODE_OFFSET](crate::error::ERROR_CODE_OFFSET).
  19. #[error_code(offset = 0)]
  20. pub enum ErrorCode {
  21. // Instructions
  22. /// 100 - 8 byte instruction identifier not provided
  23. #[msg("8 byte instruction identifier not provided")]
  24. InstructionMissing = 100,
  25. /// 101 - Fallback functions are not supported
  26. #[msg("Fallback functions are not supported")]
  27. InstructionFallbackNotFound,
  28. /// 102 - The program could not deserialize the given instruction
  29. #[msg("The program could not deserialize the given instruction")]
  30. InstructionDidNotDeserialize,
  31. /// 103 - The program could not serialize the given instruction
  32. #[msg("The program could not serialize the given instruction")]
  33. InstructionDidNotSerialize,
  34. // IDL instructions
  35. /// 1000 - The program was compiled without idl instructions
  36. #[msg("The program was compiled without idl instructions")]
  37. IdlInstructionStub = 1000,
  38. /// 1001 - Invalid program given to the IDL instruction
  39. #[msg("Invalid program given to the IDL instruction")]
  40. IdlInstructionInvalidProgram,
  41. // Constraints
  42. /// 2000 - A mut constraint was violated
  43. #[msg("A mut constraint was violated")]
  44. ConstraintMut = 2000,
  45. /// 2001 - A has one constraint was violated
  46. #[msg("A has one constraint was violated")]
  47. ConstraintHasOne,
  48. /// 2002 - A signer constraint was violated
  49. #[msg("A signer constraint was violated")]
  50. ConstraintSigner,
  51. /// 2003 - A raw constraint was violated
  52. #[msg("A raw constraint was violated")]
  53. ConstraintRaw,
  54. /// 2004 - An owner constraint was violated
  55. #[msg("An owner constraint was violated")]
  56. ConstraintOwner,
  57. /// 2005 - A rent exemption constraint was violated
  58. #[msg("A rent exemption constraint was violated")]
  59. ConstraintRentExempt,
  60. /// 2006 - A seeds constraint was violated
  61. #[msg("A seeds constraint was violated")]
  62. ConstraintSeeds,
  63. /// 2007 - An executable constraint was violated
  64. #[msg("An executable constraint was violated")]
  65. ConstraintExecutable,
  66. /// 2008 - A state constraint was violated
  67. #[msg("A state constraint was violated")]
  68. ConstraintState,
  69. /// 2009 - An associated constraint was violated
  70. #[msg("An associated constraint was violated")]
  71. ConstraintAssociated,
  72. /// 2010 - An associated init constraint was violated
  73. #[msg("An associated init constraint was violated")]
  74. ConstraintAssociatedInit,
  75. /// 2011 - A close constraint was violated
  76. #[msg("A close constraint was violated")]
  77. ConstraintClose,
  78. /// 2012 - An address constraint was violated
  79. #[msg("An address constraint was violated")]
  80. ConstraintAddress,
  81. /// 2013 - Expected zero account discriminant
  82. #[msg("Expected zero account discriminant")]
  83. ConstraintZero,
  84. /// 2014 - A token mint constraint was violated
  85. #[msg("A token mint constraint was violated")]
  86. ConstraintTokenMint,
  87. /// 2015 - A token owner constraint was violated
  88. #[msg("A token owner constraint was violated")]
  89. ConstraintTokenOwner,
  90. /// The mint mint is intentional -> a mint authority for the mint.
  91. ///
  92. /// 2016 - A mint mint authority constraint was violated
  93. #[msg("A mint mint authority constraint was violated")]
  94. ConstraintMintMintAuthority,
  95. /// 2017 - A mint freeze authority constraint was violated
  96. #[msg("A mint freeze authority constraint was violated")]
  97. ConstraintMintFreezeAuthority,
  98. /// 2018 - A mint decimals constraint was violated
  99. #[msg("A mint decimals constraint was violated")]
  100. ConstraintMintDecimals,
  101. /// 2019 - A space constraint was violated
  102. #[msg("A space constraint was violated")]
  103. ConstraintSpace,
  104. // Accounts.
  105. /// 3000 - The account discriminator was already set on this account
  106. #[msg("The account discriminator was already set on this account")]
  107. AccountDiscriminatorAlreadySet = 3000,
  108. /// 3001 - No 8 byte discriminator was found on the account
  109. #[msg("No 8 byte discriminator was found on the account")]
  110. AccountDiscriminatorNotFound,
  111. /// 3002 - 8 byte discriminator did not match what was expected
  112. #[msg("8 byte discriminator did not match what was expected")]
  113. AccountDiscriminatorMismatch,
  114. /// 3003 - Failed to deserialize the account
  115. #[msg("Failed to deserialize the account")]
  116. AccountDidNotDeserialize,
  117. /// 3004 - Failed to serialize the account
  118. #[msg("Failed to serialize the account")]
  119. AccountDidNotSerialize,
  120. /// 3005 - Not enough account keys given to the instruction
  121. #[msg("Not enough account keys given to the instruction")]
  122. AccountNotEnoughKeys,
  123. /// 3006 - The given account is not mutable
  124. #[msg("The given account is not mutable")]
  125. AccountNotMutable,
  126. /// 3007 - The given account is owned by a different program than expected
  127. #[msg("The given account is owned by a different program than expected")]
  128. AccountOwnedByWrongProgram,
  129. /// 3008 - Program ID was not as expected
  130. #[msg("Program ID was not as expected")]
  131. InvalidProgramId,
  132. /// 3009 - Program account is not executable
  133. #[msg("Program account is not executable")]
  134. InvalidProgramExecutable,
  135. /// 3010 - The given account did not sign
  136. #[msg("The given account did not sign")]
  137. AccountNotSigner,
  138. /// 3011 - The given account is not owned by the system program
  139. #[msg("The given account is not owned by the system program")]
  140. AccountNotSystemOwned,
  141. /// 3012 - The program expected this account to be already initialized
  142. #[msg("The program expected this account to be already initialized")]
  143. AccountNotInitialized,
  144. /// 3013 - The given account is not a program data account
  145. #[msg("The given account is not a program data account")]
  146. AccountNotProgramData,
  147. /// 3014 - The given account is not the associated token account
  148. #[msg("The given account is not the associated token account")]
  149. AccountNotAssociatedTokenAccount,
  150. /// 3015 - The given public key does not match the required sysvar
  151. #[msg("The given public key does not match the required sysvar")]
  152. AccountSysvarMismatch,
  153. // State.
  154. /// 4000 - The given state account does not have the correct address
  155. #[msg("The given state account does not have the correct address")]
  156. StateInvalidAddress = 4000,
  157. // Miscellaneous
  158. /// 4100 - The declared program id does not match actual program id
  159. #[msg("The declared program id does not match the actual program id")]
  160. DeclaredProgramIdMismatch = 4100,
  161. // Deprecated
  162. /// 5000 - The API being used is deprecated and should no longer be used
  163. #[msg("The API being used is deprecated and should no longer be used")]
  164. Deprecated = 5000,
  165. }
  166. #[derive(Debug)]
  167. pub enum Error {
  168. AnchorError(AnchorError),
  169. ProgramError(ProgramErrorWithOrigin),
  170. }
  171. impl std::error::Error for Error {}
  172. impl Display for Error {
  173. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  174. match self {
  175. Error::AnchorError(ae) => Display::fmt(&ae, f),
  176. Error::ProgramError(pe) => Display::fmt(&pe, f),
  177. }
  178. }
  179. }
  180. impl Display for AnchorError {
  181. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  182. Debug::fmt(&self, f)
  183. }
  184. }
  185. impl From<AnchorError> for Error {
  186. fn from(ae: AnchorError) -> Self {
  187. Self::AnchorError(ae)
  188. }
  189. }
  190. impl From<ProgramError> for Error {
  191. fn from(program_error: ProgramError) -> Self {
  192. Self::ProgramError(program_error.into())
  193. }
  194. }
  195. impl From<BorshIoError> for Error {
  196. fn from(error: BorshIoError) -> Self {
  197. Error::ProgramError(ProgramError::from(error).into())
  198. }
  199. }
  200. impl From<ProgramErrorWithOrigin> for Error {
  201. fn from(pe: ProgramErrorWithOrigin) -> Self {
  202. Self::ProgramError(pe)
  203. }
  204. }
  205. impl Error {
  206. pub fn log(&self) {
  207. match self {
  208. Error::ProgramError(program_error) => program_error.log(),
  209. Error::AnchorError(anchor_error) => anchor_error.log(),
  210. }
  211. }
  212. pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
  213. match &mut self {
  214. Error::AnchorError(ae) => ae.account_name = Some(account_name.to_string()),
  215. Error::ProgramError(pe) => pe.account_name = Some(account_name.to_string()),
  216. };
  217. self
  218. }
  219. pub fn with_source(mut self, source: Source) -> Self {
  220. match &mut self {
  221. Error::AnchorError(ae) => ae.source = Some(source),
  222. Error::ProgramError(pe) => pe.source = Some(source),
  223. };
  224. self
  225. }
  226. }
  227. #[derive(Debug)]
  228. pub struct ProgramErrorWithOrigin {
  229. pub program_error: ProgramError,
  230. pub source: Option<Source>,
  231. pub account_name: Option<String>,
  232. }
  233. impl Display for ProgramErrorWithOrigin {
  234. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  235. Display::fmt(&self.program_error, f)
  236. }
  237. }
  238. impl ProgramErrorWithOrigin {
  239. pub fn log(&self) {
  240. if let Some(source) = &self.source {
  241. anchor_lang::solana_program::msg!(
  242. "ProgramError thrown in {}:{}. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  243. source.filename,
  244. source.line,
  245. self.program_error,
  246. u64::from(self.program_error.clone()),
  247. self.program_error
  248. );
  249. } else if let Some(account_name) = &self.account_name {
  250. anchor_lang::solana_program::log::sol_log(&format!(
  251. "ProgramError caused by account: {}. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  252. account_name,
  253. self.program_error,
  254. u64::from(self.program_error.clone()),
  255. self.program_error
  256. ));
  257. } else {
  258. anchor_lang::solana_program::log::sol_log(&format!(
  259. "ProgramError occurred. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  260. self.program_error,
  261. u64::from(self.program_error.clone()),
  262. self.program_error
  263. ));
  264. }
  265. }
  266. }
  267. impl From<ProgramError> for ProgramErrorWithOrigin {
  268. fn from(program_error: ProgramError) -> Self {
  269. Self {
  270. program_error,
  271. source: None,
  272. account_name: None,
  273. }
  274. }
  275. }
  276. #[derive(Debug)]
  277. pub struct AnchorError {
  278. pub error_name: String,
  279. pub error_code_number: u32,
  280. pub error_msg: String,
  281. pub source: Option<Source>,
  282. pub account_name: Option<String>,
  283. }
  284. impl AnchorError {
  285. pub fn log(&self) {
  286. if let Some(source) = &self.source {
  287. anchor_lang::solana_program::msg!(
  288. "AnchorError thrown in {}:{}. Error Code: {}. Error Number: {}. Error Message: {}.",
  289. source.filename,
  290. source.line,
  291. self.error_name,
  292. self.error_code_number,
  293. self.error_msg
  294. );
  295. } else if let Some(account_name) = &self.account_name {
  296. anchor_lang::solana_program::log::sol_log(&format!(
  297. "AnchorError caused by account: {}. Error Code: {}. Error Number: {}. Error Message: {}.",
  298. account_name,
  299. self.error_name,
  300. self.error_code_number,
  301. self.error_msg
  302. ));
  303. } else {
  304. anchor_lang::solana_program::log::sol_log(&format!(
  305. "AnchorError occurred. Error Code: {}. Error Number: {}. Error Message: {}.",
  306. self.error_name, self.error_code_number, self.error_msg
  307. ));
  308. }
  309. }
  310. }
  311. impl std::convert::From<Error> for anchor_lang::solana_program::program_error::ProgramError {
  312. fn from(e: Error) -> anchor_lang::solana_program::program_error::ProgramError {
  313. match e {
  314. Error::AnchorError(AnchorError {
  315. error_name: _,
  316. error_code_number,
  317. error_msg: _,
  318. source: _,
  319. account_name: _,
  320. }) => {
  321. anchor_lang::solana_program::program_error::ProgramError::Custom(error_code_number)
  322. }
  323. Error::ProgramError(program_error) => program_error.program_error,
  324. }
  325. }
  326. }
  327. #[derive(Debug)]
  328. pub struct Source {
  329. pub filename: &'static str,
  330. pub line: u32,
  331. }