error.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. use anchor_lang::error_code;
  2. use borsh::maybestd::io::Error as BorshIoError;
  3. use solana_program::{program_error::ProgramError, pubkey::Pubkey};
  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. /// - >= 4100 misc error codes
  14. /// - = 5000 deprecated error code
  15. ///
  16. /// The starting point for user-defined errors is defined
  17. /// by the [ERROR_CODE_OFFSET](crate::error::ERROR_CODE_OFFSET).
  18. #[error_code(offset = 0)]
  19. pub enum ErrorCode {
  20. // Instructions
  21. /// 100 - 8 byte instruction identifier not provided
  22. #[msg("8 byte instruction identifier not provided")]
  23. InstructionMissing = 100,
  24. /// 101 - Fallback functions are not supported
  25. #[msg("Fallback functions are not supported")]
  26. InstructionFallbackNotFound,
  27. /// 102 - The program could not deserialize the given instruction
  28. #[msg("The program could not deserialize the given instruction")]
  29. InstructionDidNotDeserialize,
  30. /// 103 - The program could not serialize the given instruction
  31. #[msg("The program could not serialize the given instruction")]
  32. InstructionDidNotSerialize,
  33. // IDL instructions
  34. /// 1000 - The program was compiled without idl instructions
  35. #[msg("The program was compiled without idl instructions")]
  36. IdlInstructionStub = 1000,
  37. /// 1001 - Invalid program given to the IDL instruction
  38. #[msg("Invalid program given to the IDL instruction")]
  39. IdlInstructionInvalidProgram,
  40. /// 1002 - IDL Account must be empty in order to resize
  41. #[msg("IDL account must be empty in order to resize, try closing first")]
  42. IdlAccountNotEmpty,
  43. // Event instructions
  44. /// 1500 - The program was compiled without `event-cpi` feature
  45. #[msg("The program was compiled without `event-cpi` feature")]
  46. EventInstructionStub = 1500,
  47. // Constraints
  48. /// 2000 - A mut constraint was violated
  49. #[msg("A mut constraint was violated")]
  50. ConstraintMut = 2000,
  51. /// 2001 - A has one constraint was violated
  52. #[msg("A has one constraint was violated")]
  53. ConstraintHasOne,
  54. /// 2002 - A signer constraint was violated
  55. #[msg("A signer constraint was violated")]
  56. ConstraintSigner,
  57. /// 2003 - A raw constraint was violated
  58. #[msg("A raw constraint was violated")]
  59. ConstraintRaw,
  60. /// 2004 - An owner constraint was violated
  61. #[msg("An owner constraint was violated")]
  62. ConstraintOwner,
  63. /// 2005 - A rent exemption constraint was violated
  64. #[msg("A rent exemption constraint was violated")]
  65. ConstraintRentExempt,
  66. /// 2006 - A seeds constraint was violated
  67. #[msg("A seeds constraint was violated")]
  68. ConstraintSeeds,
  69. /// 2007 - An executable constraint was violated
  70. #[msg("An executable constraint was violated")]
  71. ConstraintExecutable,
  72. /// 2008 - Deprecated Error, feel free to replace with something else
  73. #[msg("Deprecated Error, feel free to replace with something else")]
  74. ConstraintState,
  75. /// 2009 - An associated constraint was violated
  76. #[msg("An associated constraint was violated")]
  77. ConstraintAssociated,
  78. /// 2010 - An associated init constraint was violated
  79. #[msg("An associated init constraint was violated")]
  80. ConstraintAssociatedInit,
  81. /// 2011 - A close constraint was violated
  82. #[msg("A close constraint was violated")]
  83. ConstraintClose,
  84. /// 2012 - An address constraint was violated
  85. #[msg("An address constraint was violated")]
  86. ConstraintAddress,
  87. /// 2013 - Expected zero account discriminant
  88. #[msg("Expected zero account discriminant")]
  89. ConstraintZero,
  90. /// 2014 - A token mint constraint was violated
  91. #[msg("A token mint constraint was violated")]
  92. ConstraintTokenMint,
  93. /// 2015 - A token owner constraint was violated
  94. #[msg("A token owner constraint was violated")]
  95. ConstraintTokenOwner,
  96. /// The mint mint is intentional -> a mint authority for the mint.
  97. ///
  98. /// 2016 - A mint mint authority constraint was violated
  99. #[msg("A mint mint authority constraint was violated")]
  100. ConstraintMintMintAuthority,
  101. /// 2017 - A mint freeze authority constraint was violated
  102. #[msg("A mint freeze authority constraint was violated")]
  103. ConstraintMintFreezeAuthority,
  104. /// 2018 - A mint decimals constraint was violated
  105. #[msg("A mint decimals constraint was violated")]
  106. ConstraintMintDecimals,
  107. /// 2019 - A space constraint was violated
  108. #[msg("A space constraint was violated")]
  109. ConstraintSpace,
  110. /// 2020 - A required account for the constraint is None
  111. #[msg("A required account for the constraint is None")]
  112. ConstraintAccountIsNone,
  113. /// The token token is intentional -> a token program for the token account.
  114. ///
  115. /// 2021 - A token account token program constraint was violated
  116. #[msg("A token account token program constraint was violated")]
  117. ConstraintTokenTokenProgram,
  118. /// 2022 - A mint token program constraint was violated
  119. #[msg("A mint token program constraint was violated")]
  120. ConstraintMintTokenProgram,
  121. /// 2023 - A mint token program constraint was violated
  122. #[msg("An associated token account token program constraint was violated")]
  123. ConstraintAssociatedTokenTokenProgram,
  124. // Require
  125. /// 2500 - A require expression was violated
  126. #[msg("A require expression was violated")]
  127. RequireViolated = 2500,
  128. /// 2501 - A require_eq expression was violated
  129. #[msg("A require_eq expression was violated")]
  130. RequireEqViolated,
  131. /// 2502 - A require_keys_eq expression was violated
  132. #[msg("A require_keys_eq expression was violated")]
  133. RequireKeysEqViolated,
  134. /// 2503 - A require_neq expression was violated
  135. #[msg("A require_neq expression was violated")]
  136. RequireNeqViolated,
  137. /// 2504 - A require_keys_neq expression was violated
  138. #[msg("A require_keys_neq expression was violated")]
  139. RequireKeysNeqViolated,
  140. /// 2505 - A require_gt expression was violated
  141. #[msg("A require_gt expression was violated")]
  142. RequireGtViolated,
  143. /// 2506 - A require_gte expression was violated
  144. #[msg("A require_gte expression was violated")]
  145. RequireGteViolated,
  146. // Accounts.
  147. /// 3000 - The account discriminator was already set on this account
  148. #[msg("The account discriminator was already set on this account")]
  149. AccountDiscriminatorAlreadySet = 3000,
  150. /// 3001 - No 8 byte discriminator was found on the account
  151. #[msg("No 8 byte discriminator was found on the account")]
  152. AccountDiscriminatorNotFound,
  153. /// 3002 - 8 byte discriminator did not match what was expected
  154. #[msg("8 byte discriminator did not match what was expected")]
  155. AccountDiscriminatorMismatch,
  156. /// 3003 - Failed to deserialize the account
  157. #[msg("Failed to deserialize the account")]
  158. AccountDidNotDeserialize,
  159. /// 3004 - Failed to serialize the account
  160. #[msg("Failed to serialize the account")]
  161. AccountDidNotSerialize,
  162. /// 3005 - Not enough account keys given to the instruction
  163. #[msg("Not enough account keys given to the instruction")]
  164. AccountNotEnoughKeys,
  165. /// 3006 - The given account is not mutable
  166. #[msg("The given account is not mutable")]
  167. AccountNotMutable,
  168. /// 3007 - The given account is owned by a different program than expected
  169. #[msg("The given account is owned by a different program than expected")]
  170. AccountOwnedByWrongProgram,
  171. /// 3008 - Program ID was not as expected
  172. #[msg("Program ID was not as expected")]
  173. InvalidProgramId,
  174. /// 3009 - Program account is not executable
  175. #[msg("Program account is not executable")]
  176. InvalidProgramExecutable,
  177. /// 3010 - The given account did not sign
  178. #[msg("The given account did not sign")]
  179. AccountNotSigner,
  180. /// 3011 - The given account is not owned by the system program
  181. #[msg("The given account is not owned by the system program")]
  182. AccountNotSystemOwned,
  183. /// 3012 - The program expected this account to be already initialized
  184. #[msg("The program expected this account to be already initialized")]
  185. AccountNotInitialized,
  186. /// 3013 - The given account is not a program data account
  187. #[msg("The given account is not a program data account")]
  188. AccountNotProgramData,
  189. /// 3014 - The given account is not the associated token account
  190. #[msg("The given account is not the associated token account")]
  191. AccountNotAssociatedTokenAccount,
  192. /// 3015 - The given public key does not match the required sysvar
  193. #[msg("The given public key does not match the required sysvar")]
  194. AccountSysvarMismatch,
  195. /// 3016 - The account reallocation exceeds the MAX_PERMITTED_DATA_INCREASE limit
  196. #[msg("The account reallocation exceeds the MAX_PERMITTED_DATA_INCREASE limit")]
  197. AccountReallocExceedsLimit,
  198. /// 3017 - The account was duplicated for more than one reallocation
  199. #[msg("The account was duplicated for more than one reallocation")]
  200. AccountDuplicateReallocs,
  201. // Miscellaneous
  202. /// 4100 - The declared program id does not match actual program id
  203. #[msg("The declared program id does not match the actual program id")]
  204. DeclaredProgramIdMismatch = 4100,
  205. /// 4101 - You cannot/should not initialize the payer account as a program account
  206. #[msg("You cannot/should not initialize the payer account as a program account")]
  207. TryingToInitPayerAsProgramAccount = 4101,
  208. // Deprecated
  209. /// 5000 - The API being used is deprecated and should no longer be used
  210. #[msg("The API being used is deprecated and should no longer be used")]
  211. Deprecated = 5000,
  212. }
  213. #[derive(Debug, PartialEq, Eq)]
  214. pub enum Error {
  215. AnchorError(Box<AnchorError>),
  216. ProgramError(Box<ProgramErrorWithOrigin>),
  217. }
  218. impl std::error::Error for Error {}
  219. impl Display for Error {
  220. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  221. match self {
  222. Error::AnchorError(ae) => Display::fmt(&ae, f),
  223. Error::ProgramError(pe) => Display::fmt(&pe, f),
  224. }
  225. }
  226. }
  227. impl From<AnchorError> for Error {
  228. fn from(ae: AnchorError) -> Self {
  229. Self::AnchorError(Box::new(ae))
  230. }
  231. }
  232. impl From<ProgramError> for Error {
  233. fn from(program_error: ProgramError) -> Self {
  234. Self::ProgramError(Box::new(program_error.into()))
  235. }
  236. }
  237. impl From<BorshIoError> for Error {
  238. fn from(error: BorshIoError) -> Self {
  239. Error::ProgramError(Box::new(ProgramError::from(error).into()))
  240. }
  241. }
  242. impl From<ProgramErrorWithOrigin> for Error {
  243. fn from(pe: ProgramErrorWithOrigin) -> Self {
  244. Self::ProgramError(Box::new(pe))
  245. }
  246. }
  247. impl Error {
  248. pub fn log(&self) {
  249. match self {
  250. Error::ProgramError(program_error) => program_error.log(),
  251. Error::AnchorError(anchor_error) => anchor_error.log(),
  252. }
  253. }
  254. pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
  255. match &mut self {
  256. Error::AnchorError(ae) => {
  257. ae.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
  258. }
  259. Error::ProgramError(pe) => {
  260. pe.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
  261. }
  262. };
  263. self
  264. }
  265. pub fn with_source(mut self, source: Source) -> Self {
  266. match &mut self {
  267. Error::AnchorError(ae) => {
  268. ae.error_origin = Some(ErrorOrigin::Source(source));
  269. }
  270. Error::ProgramError(pe) => {
  271. pe.error_origin = Some(ErrorOrigin::Source(source));
  272. }
  273. };
  274. self
  275. }
  276. pub fn with_pubkeys(mut self, pubkeys: (Pubkey, Pubkey)) -> Self {
  277. let pubkeys = Some(ComparedValues::Pubkeys((pubkeys.0, pubkeys.1)));
  278. match &mut self {
  279. Error::AnchorError(ae) => ae.compared_values = pubkeys,
  280. Error::ProgramError(pe) => pe.compared_values = pubkeys,
  281. };
  282. self
  283. }
  284. pub fn with_values(mut self, values: (impl ToString, impl ToString)) -> Self {
  285. match &mut self {
  286. Error::AnchorError(ae) => {
  287. ae.compared_values = Some(ComparedValues::Values((
  288. values.0.to_string(),
  289. values.1.to_string(),
  290. )))
  291. }
  292. Error::ProgramError(pe) => {
  293. pe.compared_values = Some(ComparedValues::Values((
  294. values.0.to_string(),
  295. values.1.to_string(),
  296. )))
  297. }
  298. };
  299. self
  300. }
  301. }
  302. #[derive(Debug)]
  303. pub struct ProgramErrorWithOrigin {
  304. pub program_error: ProgramError,
  305. pub error_origin: Option<ErrorOrigin>,
  306. pub compared_values: Option<ComparedValues>,
  307. }
  308. // Two ProgramErrors are equal when they have the same error code
  309. impl PartialEq for ProgramErrorWithOrigin {
  310. fn eq(&self, other: &Self) -> bool {
  311. self.program_error == other.program_error
  312. }
  313. }
  314. impl Eq for ProgramErrorWithOrigin {}
  315. impl Display for ProgramErrorWithOrigin {
  316. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  317. Display::fmt(&self.program_error, f)
  318. }
  319. }
  320. impl ProgramErrorWithOrigin {
  321. pub fn log(&self) {
  322. match &self.error_origin {
  323. None => {
  324. anchor_lang::solana_program::msg!(
  325. "ProgramError occurred. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  326. self.program_error,
  327. u64::from(self.program_error.clone()),
  328. self.program_error
  329. );
  330. }
  331. Some(ErrorOrigin::Source(source)) => {
  332. anchor_lang::solana_program::msg!(
  333. "ProgramError thrown in {}:{}. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  334. source.filename,
  335. source.line,
  336. self.program_error,
  337. u64::from(self.program_error.clone()),
  338. self.program_error
  339. );
  340. }
  341. Some(ErrorOrigin::AccountName(account_name)) => {
  342. // using sol_log because msg! wrongly interprets 5 inputs as u64
  343. anchor_lang::solana_program::log::sol_log(&format!(
  344. "ProgramError caused by account: {}. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  345. account_name,
  346. self.program_error,
  347. u64::from(self.program_error.clone()),
  348. self.program_error
  349. ));
  350. }
  351. }
  352. match &self.compared_values {
  353. Some(ComparedValues::Pubkeys((left, right))) => {
  354. anchor_lang::solana_program::msg!("Left:");
  355. left.log();
  356. anchor_lang::solana_program::msg!("Right:");
  357. right.log();
  358. }
  359. Some(ComparedValues::Values((left, right))) => {
  360. anchor_lang::solana_program::msg!("Left: {}", left);
  361. anchor_lang::solana_program::msg!("Right: {}", right);
  362. }
  363. None => (),
  364. }
  365. }
  366. pub fn with_source(mut self, source: Source) -> Self {
  367. self.error_origin = Some(ErrorOrigin::Source(source));
  368. self
  369. }
  370. pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
  371. self.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
  372. self
  373. }
  374. }
  375. impl From<ProgramError> for ProgramErrorWithOrigin {
  376. fn from(program_error: ProgramError) -> Self {
  377. Self {
  378. program_error,
  379. error_origin: None,
  380. compared_values: None,
  381. }
  382. }
  383. }
  384. #[derive(Debug)]
  385. pub enum ComparedValues {
  386. Values((String, String)),
  387. Pubkeys((Pubkey, Pubkey)),
  388. }
  389. #[derive(Debug)]
  390. pub enum ErrorOrigin {
  391. Source(Source),
  392. AccountName(String),
  393. }
  394. #[derive(Debug)]
  395. pub struct AnchorError {
  396. pub error_name: String,
  397. pub error_code_number: u32,
  398. pub error_msg: String,
  399. pub error_origin: Option<ErrorOrigin>,
  400. pub compared_values: Option<ComparedValues>,
  401. }
  402. impl AnchorError {
  403. pub fn log(&self) {
  404. match &self.error_origin {
  405. None => {
  406. anchor_lang::solana_program::log::sol_log(&format!(
  407. "AnchorError occurred. Error Code: {}. Error Number: {}. Error Message: {}.",
  408. self.error_name, self.error_code_number, self.error_msg
  409. ));
  410. }
  411. Some(ErrorOrigin::Source(source)) => {
  412. anchor_lang::solana_program::msg!(
  413. "AnchorError thrown in {}:{}. Error Code: {}. Error Number: {}. Error Message: {}.",
  414. source.filename,
  415. source.line,
  416. self.error_name,
  417. self.error_code_number,
  418. self.error_msg
  419. );
  420. }
  421. Some(ErrorOrigin::AccountName(account_name)) => {
  422. anchor_lang::solana_program::log::sol_log(&format!(
  423. "AnchorError caused by account: {}. Error Code: {}. Error Number: {}. Error Message: {}.",
  424. account_name,
  425. self.error_name,
  426. self.error_code_number,
  427. self.error_msg
  428. ));
  429. }
  430. }
  431. match &self.compared_values {
  432. Some(ComparedValues::Pubkeys((left, right))) => {
  433. anchor_lang::solana_program::msg!("Left:");
  434. left.log();
  435. anchor_lang::solana_program::msg!("Right:");
  436. right.log();
  437. }
  438. Some(ComparedValues::Values((left, right))) => {
  439. anchor_lang::solana_program::msg!("Left: {}", left);
  440. anchor_lang::solana_program::msg!("Right: {}", right);
  441. }
  442. None => (),
  443. }
  444. }
  445. pub fn with_source(mut self, source: Source) -> Self {
  446. self.error_origin = Some(ErrorOrigin::Source(source));
  447. self
  448. }
  449. pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
  450. self.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
  451. self
  452. }
  453. }
  454. impl Display for AnchorError {
  455. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  456. Debug::fmt(&self, f)
  457. }
  458. }
  459. /// Two `AnchorError`s are equal when they have the same error code
  460. impl PartialEq for AnchorError {
  461. fn eq(&self, other: &Self) -> bool {
  462. self.error_code_number == other.error_code_number
  463. }
  464. }
  465. impl Eq for AnchorError {}
  466. impl std::convert::From<Error> for anchor_lang::solana_program::program_error::ProgramError {
  467. fn from(e: Error) -> anchor_lang::solana_program::program_error::ProgramError {
  468. match e {
  469. Error::AnchorError(error) => {
  470. anchor_lang::solana_program::program_error::ProgramError::Custom(
  471. error.error_code_number,
  472. )
  473. }
  474. Error::ProgramError(program_error) => program_error.program_error,
  475. }
  476. }
  477. }
  478. #[derive(Debug)]
  479. pub struct Source {
  480. pub filename: &'static str,
  481. pub line: u32,
  482. }