error.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. /// - = 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. // Require
  105. /// 2500 - A require expression was violated
  106. #[msg("A require expression was violated")]
  107. RequireViolated = 2500,
  108. /// 2501 - A require_eq expression was violated
  109. #[msg("A require_eq expression was violated")]
  110. RequireEqViolated,
  111. /// 2502 - A require_keys_eq expression was violated
  112. #[msg("A require_keys_eq expression was violated")]
  113. RequireKeysEqViolated,
  114. /// 2503 - A require_neq expression was violated
  115. #[msg("A require_neq expression was violated")]
  116. RequireNeqViolated,
  117. /// 2504 - A require_keys_neq expression was violated
  118. #[msg("A require_keys_neq expression was violated")]
  119. RequireKeysNeqViolated,
  120. /// 2505 - A require_gt expression was violated
  121. #[msg("A require_gt expression was violated")]
  122. RequireGtViolated,
  123. /// 2506 - A require_gte expression was violated
  124. #[msg("A require_gte expression was violated")]
  125. RequireGteViolated,
  126. // Accounts.
  127. /// 3000 - The account discriminator was already set on this account
  128. #[msg("The account discriminator was already set on this account")]
  129. AccountDiscriminatorAlreadySet = 3000,
  130. /// 3001 - No 8 byte discriminator was found on the account
  131. #[msg("No 8 byte discriminator was found on the account")]
  132. AccountDiscriminatorNotFound,
  133. /// 3002 - 8 byte discriminator did not match what was expected
  134. #[msg("8 byte discriminator did not match what was expected")]
  135. AccountDiscriminatorMismatch,
  136. /// 3003 - Failed to deserialize the account
  137. #[msg("Failed to deserialize the account")]
  138. AccountDidNotDeserialize,
  139. /// 3004 - Failed to serialize the account
  140. #[msg("Failed to serialize the account")]
  141. AccountDidNotSerialize,
  142. /// 3005 - Not enough account keys given to the instruction
  143. #[msg("Not enough account keys given to the instruction")]
  144. AccountNotEnoughKeys,
  145. /// 3006 - The given account is not mutable
  146. #[msg("The given account is not mutable")]
  147. AccountNotMutable,
  148. /// 3007 - The given account is owned by a different program than expected
  149. #[msg("The given account is owned by a different program than expected")]
  150. AccountOwnedByWrongProgram,
  151. /// 3008 - Program ID was not as expected
  152. #[msg("Program ID was not as expected")]
  153. InvalidProgramId,
  154. /// 3009 - Program account is not executable
  155. #[msg("Program account is not executable")]
  156. InvalidProgramExecutable,
  157. /// 3010 - The given account did not sign
  158. #[msg("The given account did not sign")]
  159. AccountNotSigner,
  160. /// 3011 - The given account is not owned by the system program
  161. #[msg("The given account is not owned by the system program")]
  162. AccountNotSystemOwned,
  163. /// 3012 - The program expected this account to be already initialized
  164. #[msg("The program expected this account to be already initialized")]
  165. AccountNotInitialized,
  166. /// 3013 - The given account is not a program data account
  167. #[msg("The given account is not a program data account")]
  168. AccountNotProgramData,
  169. /// 3014 - The given account is not the associated token account
  170. #[msg("The given account is not the associated token account")]
  171. AccountNotAssociatedTokenAccount,
  172. /// 3015 - The given public key does not match the required sysvar
  173. #[msg("The given public key does not match the required sysvar")]
  174. AccountSysvarMismatch,
  175. // State.
  176. /// 4000 - The given state account does not have the correct address
  177. #[msg("The given state account does not have the correct address")]
  178. StateInvalidAddress = 4000,
  179. // Miscellaneous
  180. /// 4100 - The declared program id does not match actual program id
  181. #[msg("The declared program id does not match the actual program id")]
  182. DeclaredProgramIdMismatch = 4100,
  183. // Deprecated
  184. /// 5000 - The API being used is deprecated and should no longer be used
  185. #[msg("The API being used is deprecated and should no longer be used")]
  186. Deprecated = 5000,
  187. }
  188. #[derive(Debug, PartialEq, Eq)]
  189. pub enum Error {
  190. AnchorError(AnchorError),
  191. ProgramError(ProgramErrorWithOrigin),
  192. }
  193. impl std::error::Error for Error {}
  194. impl Display for Error {
  195. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  196. match self {
  197. Error::AnchorError(ae) => Display::fmt(&ae, f),
  198. Error::ProgramError(pe) => Display::fmt(&pe, f),
  199. }
  200. }
  201. }
  202. impl From<AnchorError> for Error {
  203. fn from(ae: AnchorError) -> Self {
  204. Self::AnchorError(ae)
  205. }
  206. }
  207. impl From<ProgramError> for Error {
  208. fn from(program_error: ProgramError) -> Self {
  209. Self::ProgramError(program_error.into())
  210. }
  211. }
  212. impl From<BorshIoError> for Error {
  213. fn from(error: BorshIoError) -> Self {
  214. Error::ProgramError(ProgramError::from(error).into())
  215. }
  216. }
  217. impl From<ProgramErrorWithOrigin> for Error {
  218. fn from(pe: ProgramErrorWithOrigin) -> Self {
  219. Self::ProgramError(pe)
  220. }
  221. }
  222. impl Error {
  223. pub fn log(&self) {
  224. match self {
  225. Error::ProgramError(program_error) => program_error.log(),
  226. Error::AnchorError(anchor_error) => anchor_error.log(),
  227. }
  228. }
  229. pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
  230. match &mut self {
  231. Error::AnchorError(ae) => {
  232. ae.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
  233. }
  234. Error::ProgramError(pe) => {
  235. pe.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
  236. }
  237. };
  238. self
  239. }
  240. pub fn with_source(mut self, source: Source) -> Self {
  241. match &mut self {
  242. Error::AnchorError(ae) => {
  243. ae.error_origin = Some(ErrorOrigin::Source(source));
  244. }
  245. Error::ProgramError(pe) => {
  246. pe.error_origin = Some(ErrorOrigin::Source(source));
  247. }
  248. };
  249. self
  250. }
  251. pub fn with_pubkeys(mut self, pubkeys: (Pubkey, Pubkey)) -> Self {
  252. let pubkeys = Some(ComparedValues::Pubkeys((pubkeys.0, pubkeys.1)));
  253. match &mut self {
  254. Error::AnchorError(ae) => ae.compared_values = pubkeys,
  255. Error::ProgramError(pe) => pe.compared_values = pubkeys,
  256. };
  257. self
  258. }
  259. pub fn with_values(mut self, values: (impl ToString, impl ToString)) -> Self {
  260. match &mut self {
  261. Error::AnchorError(ae) => {
  262. ae.compared_values = Some(ComparedValues::Values((
  263. values.0.to_string(),
  264. values.1.to_string(),
  265. )))
  266. }
  267. Error::ProgramError(pe) => {
  268. pe.compared_values = Some(ComparedValues::Values((
  269. values.0.to_string(),
  270. values.1.to_string(),
  271. )))
  272. }
  273. };
  274. self
  275. }
  276. }
  277. #[derive(Debug)]
  278. pub struct ProgramErrorWithOrigin {
  279. pub program_error: ProgramError,
  280. pub error_origin: Option<ErrorOrigin>,
  281. pub compared_values: Option<ComparedValues>,
  282. }
  283. // Two ProgramErrors are equal when they have the same error code
  284. impl PartialEq for ProgramErrorWithOrigin {
  285. fn eq(&self, other: &Self) -> bool {
  286. self.program_error == other.program_error
  287. }
  288. }
  289. impl Eq for ProgramErrorWithOrigin {}
  290. impl Display for ProgramErrorWithOrigin {
  291. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  292. Display::fmt(&self.program_error, f)
  293. }
  294. }
  295. impl ProgramErrorWithOrigin {
  296. pub fn log(&self) {
  297. match &self.error_origin {
  298. None => {
  299. anchor_lang::solana_program::msg!(
  300. "ProgramError occurred. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  301. self.program_error,
  302. u64::from(self.program_error.clone()),
  303. self.program_error
  304. );
  305. }
  306. Some(ErrorOrigin::Source(source)) => {
  307. anchor_lang::solana_program::msg!(
  308. "ProgramError thrown in {}:{}. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  309. source.filename,
  310. source.line,
  311. self.program_error,
  312. u64::from(self.program_error.clone()),
  313. self.program_error
  314. );
  315. }
  316. Some(ErrorOrigin::AccountName(account_name)) => {
  317. // using sol_log because msg! wrongly interprets 5 inputs as u64
  318. anchor_lang::solana_program::log::sol_log(&format!(
  319. "ProgramError caused by account: {}. Error Code: {:?}. Error Number: {}. Error Message: {}.",
  320. account_name,
  321. self.program_error,
  322. u64::from(self.program_error.clone()),
  323. self.program_error
  324. ));
  325. }
  326. }
  327. match &self.compared_values {
  328. Some(ComparedValues::Pubkeys((left, right))) => {
  329. anchor_lang::solana_program::msg!("Left:");
  330. left.log();
  331. anchor_lang::solana_program::msg!("Right:");
  332. right.log();
  333. }
  334. Some(ComparedValues::Values((left, right))) => {
  335. anchor_lang::solana_program::msg!("Left: {}", left);
  336. anchor_lang::solana_program::msg!("Right: {}", right);
  337. }
  338. None => (),
  339. }
  340. }
  341. pub fn with_source(mut self, source: Source) -> Self {
  342. self.error_origin = Some(ErrorOrigin::Source(source));
  343. self
  344. }
  345. pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
  346. self.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
  347. self
  348. }
  349. }
  350. impl From<ProgramError> for ProgramErrorWithOrigin {
  351. fn from(program_error: ProgramError) -> Self {
  352. Self {
  353. program_error,
  354. error_origin: None,
  355. compared_values: None,
  356. }
  357. }
  358. }
  359. #[derive(Debug)]
  360. pub enum ComparedValues {
  361. Values((String, String)),
  362. Pubkeys((Pubkey, Pubkey)),
  363. }
  364. #[derive(Debug)]
  365. pub enum ErrorOrigin {
  366. Source(Source),
  367. AccountName(String),
  368. }
  369. #[derive(Debug)]
  370. pub struct AnchorError {
  371. pub error_name: String,
  372. pub error_code_number: u32,
  373. pub error_msg: String,
  374. pub error_origin: Option<ErrorOrigin>,
  375. pub compared_values: Option<ComparedValues>,
  376. }
  377. impl AnchorError {
  378. pub fn log(&self) {
  379. match &self.error_origin {
  380. None => {
  381. anchor_lang::solana_program::log::sol_log(&format!(
  382. "AnchorError occurred. Error Code: {}. Error Number: {}. Error Message: {}.",
  383. self.error_name, self.error_code_number, self.error_msg
  384. ));
  385. }
  386. Some(ErrorOrigin::Source(source)) => {
  387. anchor_lang::solana_program::msg!(
  388. "AnchorError thrown in {}:{}. Error Code: {}. Error Number: {}. Error Message: {}.",
  389. source.filename,
  390. source.line,
  391. self.error_name,
  392. self.error_code_number,
  393. self.error_msg
  394. );
  395. }
  396. Some(ErrorOrigin::AccountName(account_name)) => {
  397. anchor_lang::solana_program::log::sol_log(&format!(
  398. "AnchorError caused by account: {}. Error Code: {}. Error Number: {}. Error Message: {}.",
  399. account_name,
  400. self.error_name,
  401. self.error_code_number,
  402. self.error_msg
  403. ));
  404. }
  405. }
  406. match &self.compared_values {
  407. Some(ComparedValues::Pubkeys((left, right))) => {
  408. anchor_lang::solana_program::msg!("Left:");
  409. left.log();
  410. anchor_lang::solana_program::msg!("Right:");
  411. right.log();
  412. }
  413. Some(ComparedValues::Values((left, right))) => {
  414. anchor_lang::solana_program::msg!("Left: {}", left);
  415. anchor_lang::solana_program::msg!("Right: {}", right);
  416. }
  417. None => (),
  418. }
  419. }
  420. pub fn with_source(mut self, source: Source) -> Self {
  421. self.error_origin = Some(ErrorOrigin::Source(source));
  422. self
  423. }
  424. pub fn with_account_name(mut self, account_name: impl ToString) -> Self {
  425. self.error_origin = Some(ErrorOrigin::AccountName(account_name.to_string()));
  426. self
  427. }
  428. }
  429. impl Display for AnchorError {
  430. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  431. Debug::fmt(&self, f)
  432. }
  433. }
  434. /// Two `AnchorError`s are equal when they have the same error code
  435. impl PartialEq for AnchorError {
  436. fn eq(&self, other: &Self) -> bool {
  437. self.error_code_number == other.error_code_number
  438. }
  439. }
  440. impl Eq for AnchorError {}
  441. impl std::convert::From<Error> for anchor_lang::solana_program::program_error::ProgramError {
  442. fn from(e: Error) -> anchor_lang::solana_program::program_error::ProgramError {
  443. match e {
  444. Error::AnchorError(AnchorError {
  445. error_code_number, ..
  446. }) => {
  447. anchor_lang::solana_program::program_error::ProgramError::Custom(error_code_number)
  448. }
  449. Error::ProgramError(program_error) => program_error.program_error,
  450. }
  451. }
  452. }
  453. #[derive(Debug)]
  454. pub struct Source {
  455. pub filename: &'static str,
  456. pub line: u32,
  457. }