lib.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. //! Anchor ⚓ is a framework for Solana's Sealevel runtime providing several
  2. //! convenient developer tools.
  3. //!
  4. //! - Rust eDSL for writing safe, secure, and high level Solana programs
  5. //! - [IDL](https://en.wikipedia.org/wiki/Interface_description_language) specification
  6. //! - TypeScript package for generating clients from IDL
  7. //! - CLI and workspace management for developing complete applications
  8. //!
  9. //! If you're familiar with developing in Ethereum's
  10. //! [Solidity](https://docs.soliditylang.org/en/v0.7.4/),
  11. //! [Truffle](https://www.trufflesuite.com/),
  12. //! [web3.js](https://github.com/ethereum/web3.js) or Parity's
  13. //! [Ink!](https://github.com/paritytech/ink), then the experience will be
  14. //! familiar. Although the syntax and semantics are targeted at Solana, the high
  15. //! level workflow of writing RPC request handlers, emitting an IDL, and
  16. //! generating clients from IDL is the same.
  17. //!
  18. //! For detailed tutorials and examples on how to use Anchor, see the guided
  19. //! [tutorials](https://anchor-lang.com) or examples in the GitHub
  20. //! [repository](https://github.com/coral-xyz/anchor).
  21. //!
  22. //! Presented here are the Rust primitives for building on Solana.
  23. extern crate self as anchor_lang;
  24. use bytemuck::{Pod, Zeroable};
  25. use solana_program::account_info::AccountInfo;
  26. use solana_program::instruction::AccountMeta;
  27. use solana_program::pubkey::Pubkey;
  28. use std::collections::{BTreeMap, BTreeSet};
  29. use std::io::Write;
  30. mod account_meta;
  31. pub mod accounts;
  32. mod bpf_upgradeable_state;
  33. mod bpf_writer;
  34. mod common;
  35. pub mod context;
  36. pub mod error;
  37. #[doc(hidden)]
  38. pub mod idl;
  39. pub mod system_program;
  40. mod vec;
  41. pub use crate::bpf_upgradeable_state::*;
  42. pub use anchor_attribute_access_control::access_control;
  43. pub use anchor_attribute_account::{account, declare_id, zero_copy};
  44. pub use anchor_attribute_constant::constant;
  45. pub use anchor_attribute_error::*;
  46. pub use anchor_attribute_event::{emit, event};
  47. pub use anchor_attribute_program::program;
  48. pub use anchor_derive_accounts::Accounts;
  49. pub use anchor_derive_space::InitSpace;
  50. /// Borsh is the default serialization format for instructions and accounts.
  51. pub use borsh::{BorshDeserialize as AnchorDeserialize, BorshSerialize as AnchorSerialize};
  52. pub use solana_program;
  53. pub type Result<T> = std::result::Result<T, error::Error>;
  54. /// A data structure of validated accounts that can be deserialized from the
  55. /// input to a Solana program. Implementations of this trait should perform any
  56. /// and all requisite constraint checks on accounts to ensure the accounts
  57. /// maintain any invariants required for the program to run securely. In most
  58. /// cases, it's recommended to use the [`Accounts`](./derive.Accounts.html)
  59. /// derive macro to implement this trait.
  60. pub trait Accounts<'info>: ToAccountMetas + ToAccountInfos<'info> + Sized {
  61. /// Returns the validated accounts struct. What constitutes "valid" is
  62. /// program dependent. However, users of these types should never have to
  63. /// worry about account substitution attacks. For example, if a program
  64. /// expects a `Mint` account from the SPL token program in a particular
  65. /// field, then it should be impossible for this method to return `Ok` if
  66. /// any other account type is given--from the SPL token program or elsewhere.
  67. ///
  68. /// `program_id` is the currently executing program. `accounts` is the
  69. /// set of accounts to construct the type from. For every account used,
  70. /// the implementation should mutate the slice, consuming the used entry
  71. /// so that it cannot be used again.
  72. fn try_accounts(
  73. program_id: &Pubkey,
  74. accounts: &mut &[AccountInfo<'info>],
  75. ix_data: &[u8],
  76. bumps: &mut BTreeMap<String, u8>,
  77. reallocs: &mut BTreeSet<Pubkey>,
  78. ) -> Result<Self>;
  79. }
  80. /// The exit procedure for an account. Any cleanup or persistence to storage
  81. /// should be done here.
  82. pub trait AccountsExit<'info>: ToAccountMetas + ToAccountInfos<'info> {
  83. /// `program_id` is the currently executing program.
  84. fn exit(&self, _program_id: &Pubkey) -> Result<()> {
  85. // no-op
  86. Ok(())
  87. }
  88. }
  89. /// The close procedure to initiate garabage collection of an account, allowing
  90. /// one to retrieve the rent exemption.
  91. pub trait AccountsClose<'info>: ToAccountInfos<'info> {
  92. fn close(&self, sol_destination: AccountInfo<'info>) -> Result<()>;
  93. }
  94. /// Transformation to
  95. /// [`AccountMeta`](../solana_program/instruction/struct.AccountMeta.html)
  96. /// structs.
  97. pub trait ToAccountMetas {
  98. /// `is_signer` is given as an optional override for the signer meta field.
  99. /// This covers the edge case when a program-derived-address needs to relay
  100. /// a transaction from a client to another program but sign the transaction
  101. /// before the relay. The client cannot mark the field as a signer, and so
  102. /// we have to override the is_signer meta field given by the client.
  103. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta>;
  104. }
  105. /// Transformation to
  106. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html)
  107. /// structs.
  108. pub trait ToAccountInfos<'info> {
  109. fn to_account_infos(&self) -> Vec<AccountInfo<'info>>;
  110. }
  111. /// Transformation to an `AccountInfo` struct.
  112. pub trait ToAccountInfo<'info> {
  113. fn to_account_info(&self) -> AccountInfo<'info>;
  114. }
  115. impl<'info, T> ToAccountInfo<'info> for T
  116. where
  117. T: AsRef<AccountInfo<'info>>,
  118. {
  119. fn to_account_info(&self) -> AccountInfo<'info> {
  120. self.as_ref().clone()
  121. }
  122. }
  123. /// A data structure that can be serialized and stored into account storage,
  124. /// i.e. an
  125. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  126. /// mutable data slice.
  127. ///
  128. /// Implementors of this trait should ensure that any subsequent usage of the
  129. /// `AccountDeserialize` trait succeeds if and only if the account is of the
  130. /// correct type.
  131. ///
  132. /// In most cases, one can use the default implementation provided by the
  133. /// [`#[account]`](./attr.account.html) attribute.
  134. pub trait AccountSerialize {
  135. /// Serializes the account data into `writer`.
  136. fn try_serialize<W: Write>(&self, _writer: &mut W) -> Result<()> {
  137. Ok(())
  138. }
  139. }
  140. /// A data structure that can be deserialized and stored into account storage,
  141. /// i.e. an
  142. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  143. /// mutable data slice.
  144. pub trait AccountDeserialize: Sized {
  145. /// Deserializes previously initialized account data. Should fail for all
  146. /// uninitialized accounts, where the bytes are zeroed. Implementations
  147. /// should be unique to a particular account type so that one can never
  148. /// successfully deserialize the data of one account type into another.
  149. /// For example, if the SPL token program were to implement this trait,
  150. /// it should be impossible to deserialize a `Mint` account into a token
  151. /// `Account`.
  152. fn try_deserialize(buf: &mut &[u8]) -> Result<Self> {
  153. Self::try_deserialize_unchecked(buf)
  154. }
  155. /// Deserializes account data without checking the account discriminator.
  156. /// This should only be used on account initialization, when the bytes of
  157. /// the account are zeroed.
  158. fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result<Self>;
  159. }
  160. /// An account data structure capable of zero copy deserialization.
  161. pub trait ZeroCopy: Discriminator + Copy + Clone + Zeroable + Pod {}
  162. /// Calculates the data for an instruction invocation, where the data is
  163. /// `Sha256(<namespace>:<method_name>)[..8] || BorshSerialize(args)`.
  164. /// `args` is a borsh serialized struct of named fields for each argument given
  165. /// to an instruction.
  166. pub trait InstructionData: Discriminator + AnchorSerialize {
  167. fn data(&self) -> Vec<u8> {
  168. let mut d = Self::discriminator().to_vec();
  169. d.append(&mut self.try_to_vec().expect("Should always serialize"));
  170. d
  171. }
  172. }
  173. /// An event that can be emitted via a Solana log. See [`emit!`](crate::prelude::emit) for an example.
  174. pub trait Event: AnchorSerialize + AnchorDeserialize + Discriminator {
  175. fn data(&self) -> Vec<u8>;
  176. }
  177. // The serialized event data to be emitted via a Solana log.
  178. // TODO: remove this on the next major version upgrade.
  179. #[doc(hidden)]
  180. #[deprecated(since = "0.4.2", note = "Please use Event instead")]
  181. pub trait EventData: AnchorSerialize + Discriminator {
  182. fn data(&self) -> Vec<u8>;
  183. }
  184. /// 8 byte unique identifier for a type.
  185. pub trait Discriminator {
  186. const DISCRIMINATOR: [u8; 8];
  187. fn discriminator() -> [u8; 8] {
  188. Self::DISCRIMINATOR
  189. }
  190. }
  191. /// Defines the space of an account for initialization.
  192. pub trait Space {
  193. const INIT_SPACE: usize;
  194. }
  195. /// Bump seed for program derived addresses.
  196. pub trait Bump {
  197. fn seed(&self) -> u8;
  198. }
  199. /// Defines an address expected to own an account.
  200. pub trait Owner {
  201. fn owner() -> Pubkey;
  202. }
  203. /// Defines a list of addresses expected to own an account.
  204. pub trait Owners {
  205. fn owners() -> &'static [Pubkey];
  206. }
  207. /// Defines a trait for checking the owner of a program.
  208. pub trait CheckOwner {
  209. fn check_owner(owner: &Pubkey) -> Result<()>;
  210. }
  211. impl<T: Owners> CheckOwner for T {
  212. fn check_owner(owner: &Pubkey) -> Result<()> {
  213. if !Self::owners().contains(owner) {
  214. Err(
  215. error::Error::from(error::ErrorCode::AccountOwnedByWrongProgram)
  216. .with_account_name(*owner),
  217. )
  218. } else {
  219. Ok(())
  220. }
  221. }
  222. }
  223. /// Defines the id of a program.
  224. pub trait Id {
  225. fn id() -> Pubkey;
  226. }
  227. /// Defines the possible ids of a program.
  228. pub trait Ids {
  229. fn ids() -> &'static [Pubkey];
  230. }
  231. /// Defines a trait for checking the id of a program.
  232. pub trait CheckId {
  233. fn check_id(id: &Pubkey) -> Result<()>;
  234. }
  235. impl<T: Ids> CheckId for T {
  236. fn check_id(id: &Pubkey) -> Result<()> {
  237. if !Self::ids().contains(id) {
  238. Err(error::Error::from(error::ErrorCode::InvalidProgramId).with_account_name(*id))
  239. } else {
  240. Ok(())
  241. }
  242. }
  243. }
  244. /// Defines the Pubkey of an account.
  245. pub trait Key {
  246. fn key(&self) -> Pubkey;
  247. }
  248. impl Key for Pubkey {
  249. fn key(&self) -> Pubkey {
  250. *self
  251. }
  252. }
  253. /// The prelude contains all commonly used components of the crate.
  254. /// All programs should include it via `anchor_lang::prelude::*;`.
  255. pub mod prelude {
  256. pub use super::{
  257. access_control, account, accounts::account::Account,
  258. accounts::account_loader::AccountLoader, accounts::interface::Interface,
  259. accounts::interface_account::InterfaceAccount, accounts::program::Program,
  260. accounts::signer::Signer, accounts::system_account::SystemAccount,
  261. accounts::sysvar::Sysvar, accounts::unchecked_account::UncheckedAccount, constant,
  262. context::Context, context::CpiContext, declare_id, emit, err, error, event, program,
  263. require, require_eq, require_gt, require_gte, require_keys_eq, require_keys_neq,
  264. require_neq, solana_program::bpf_loader_upgradeable::UpgradeableLoaderState, source,
  265. system_program::System, zero_copy, AccountDeserialize, AccountSerialize, Accounts,
  266. AccountsClose, AccountsExit, AnchorDeserialize, AnchorSerialize, Id, InitSpace, Key, Owner,
  267. ProgramData, Result, Space, ToAccountInfo, ToAccountInfos, ToAccountMetas,
  268. };
  269. pub use anchor_attribute_error::*;
  270. pub use borsh;
  271. pub use error::*;
  272. pub use solana_program::account_info::{next_account_info, AccountInfo};
  273. pub use solana_program::instruction::AccountMeta;
  274. pub use solana_program::msg;
  275. pub use solana_program::program_error::ProgramError;
  276. pub use solana_program::pubkey::Pubkey;
  277. pub use solana_program::sysvar::clock::Clock;
  278. pub use solana_program::sysvar::epoch_schedule::EpochSchedule;
  279. pub use solana_program::sysvar::instructions::Instructions;
  280. pub use solana_program::sysvar::rent::Rent;
  281. pub use solana_program::sysvar::rewards::Rewards;
  282. pub use solana_program::sysvar::slot_hashes::SlotHashes;
  283. pub use solana_program::sysvar::slot_history::SlotHistory;
  284. pub use solana_program::sysvar::stake_history::StakeHistory;
  285. pub use solana_program::sysvar::Sysvar as SolanaSysvar;
  286. pub use thiserror;
  287. }
  288. /// Internal module used by macros and unstable apis.
  289. #[doc(hidden)]
  290. pub mod __private {
  291. /// The discriminator anchor uses to mark an account as closed.
  292. pub const CLOSED_ACCOUNT_DISCRIMINATOR: [u8; 8] = [255, 255, 255, 255, 255, 255, 255, 255];
  293. pub use anchor_attribute_account::ZeroCopyAccessor;
  294. pub use anchor_attribute_event::EventIndex;
  295. pub use base64;
  296. pub use bytemuck;
  297. use solana_program::pubkey::Pubkey;
  298. // Used to calculate the maximum between two expressions.
  299. // It is necessary for the calculation of the enum space.
  300. #[doc(hidden)]
  301. pub const fn max(a: usize, b: usize) -> usize {
  302. [a, b][(a < b) as usize]
  303. }
  304. // Very experimental trait.
  305. #[doc(hidden)]
  306. pub trait ZeroCopyAccessor<Ty> {
  307. fn get(&self) -> Ty;
  308. fn set(input: &Ty) -> Self;
  309. }
  310. #[doc(hidden)]
  311. impl ZeroCopyAccessor<Pubkey> for [u8; 32] {
  312. fn get(&self) -> Pubkey {
  313. Pubkey::new(self)
  314. }
  315. fn set(input: &Pubkey) -> [u8; 32] {
  316. input.to_bytes()
  317. }
  318. }
  319. }
  320. /// Ensures a condition is true, otherwise returns with the given error.
  321. /// Use this with or without a custom error type.
  322. ///
  323. /// # Example
  324. /// ```ignore
  325. /// // Instruction function
  326. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  327. /// require!(ctx.accounts.data.mutation_allowed, MyError::MutationForbidden);
  328. /// ctx.accounts.data.data = data;
  329. /// Ok(())
  330. /// }
  331. ///
  332. /// // An enum for custom error codes
  333. /// #[error_code]
  334. /// pub enum MyError {
  335. /// MutationForbidden
  336. /// }
  337. ///
  338. /// // An account definition
  339. /// #[account]
  340. /// #[derive(Default)]
  341. /// pub struct MyData {
  342. /// mutation_allowed: bool,
  343. /// data: u64
  344. /// }
  345. ///
  346. /// // An account validation struct
  347. /// #[derive(Accounts)]
  348. /// pub struct SetData<'info> {
  349. /// #[account(mut)]
  350. /// pub data: Account<'info, MyData>
  351. /// }
  352. /// ```
  353. #[macro_export]
  354. macro_rules! require {
  355. ($invariant:expr, $error:tt $(,)?) => {
  356. if !($invariant) {
  357. return Err(anchor_lang::error!($crate::ErrorCode::$error));
  358. }
  359. };
  360. ($invariant:expr, $error:expr $(,)?) => {
  361. if !($invariant) {
  362. return Err(anchor_lang::error!($error));
  363. }
  364. };
  365. }
  366. /// Ensures two NON-PUBKEY values are equal.
  367. ///
  368. /// Use [require_keys_eq](crate::prelude::require_keys_eq)
  369. /// to compare two pubkeys.
  370. ///
  371. /// Can be used with or without a custom error code.
  372. ///
  373. /// # Example
  374. /// ```rust,ignore
  375. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  376. /// require_eq!(ctx.accounts.data.data, 0);
  377. /// ctx.accounts.data.data = data;
  378. /// Ok(())
  379. /// }
  380. /// ```
  381. #[macro_export]
  382. macro_rules! require_eq {
  383. ($value1: expr, $value2: expr, $error_code:expr $(,)?) => {
  384. if $value1 != $value2 {
  385. return Err(error!($error_code).with_values(($value1, $value2)));
  386. }
  387. };
  388. ($value1: expr, $value2: expr $(,)?) => {
  389. if $value1 != $value2 {
  390. return Err(error!(anchor_lang::error::ErrorCode::RequireEqViolated)
  391. .with_values(($value1, $value2)));
  392. }
  393. };
  394. }
  395. /// Ensures two NON-PUBKEY values are not equal.
  396. ///
  397. /// Use [require_keys_neq](crate::prelude::require_keys_neq)
  398. /// to compare two pubkeys.
  399. ///
  400. /// Can be used with or without a custom error code.
  401. ///
  402. /// # Example
  403. /// ```rust,ignore
  404. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  405. /// require_neq!(ctx.accounts.data.data, 0);
  406. /// ctx.accounts.data.data = data;
  407. /// Ok(());
  408. /// }
  409. /// ```
  410. #[macro_export]
  411. macro_rules! require_neq {
  412. ($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
  413. if $value1 == $value2 {
  414. return Err(error!($error_code).with_values(($value1, $value2)));
  415. }
  416. };
  417. ($value1: expr, $value2: expr $(,)?) => {
  418. if $value1 == $value2 {
  419. return Err(error!(anchor_lang::error::ErrorCode::RequireNeqViolated)
  420. .with_values(($value1, $value2)));
  421. }
  422. };
  423. }
  424. /// Ensures two pubkeys values are equal.
  425. ///
  426. /// Use [require_eq](crate::prelude::require_eq)
  427. /// to compare two non-pubkey values.
  428. ///
  429. /// Can be used with or without a custom error code.
  430. ///
  431. /// # Example
  432. /// ```rust,ignore
  433. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  434. /// require_keys_eq!(ctx.accounts.data.authority.key(), ctx.accounts.authority.key());
  435. /// ctx.accounts.data.data = data;
  436. /// Ok(())
  437. /// }
  438. /// ```
  439. #[macro_export]
  440. macro_rules! require_keys_eq {
  441. ($value1: expr, $value2: expr, $error_code:expr $(,)?) => {
  442. if $value1 != $value2 {
  443. return Err(error!($error_code).with_pubkeys(($value1, $value2)));
  444. }
  445. };
  446. ($value1: expr, $value2: expr $(,)?) => {
  447. if $value1 != $value2 {
  448. return Err(error!(anchor_lang::error::ErrorCode::RequireKeysEqViolated)
  449. .with_pubkeys(($value1, $value2)));
  450. }
  451. };
  452. }
  453. /// Ensures two pubkeys are not equal.
  454. ///
  455. /// Use [require_neq](crate::prelude::require_neq)
  456. /// to compare two non-pubkey values.
  457. ///
  458. /// Can be used with or without a custom error code.
  459. ///
  460. /// # Example
  461. /// ```rust,ignore
  462. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  463. /// require_keys_neq!(ctx.accounts.data.authority.key(), ctx.accounts.other.key());
  464. /// ctx.accounts.data.data = data;
  465. /// Ok(())
  466. /// }
  467. /// ```
  468. #[macro_export]
  469. macro_rules! require_keys_neq {
  470. ($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
  471. if $value1 == $value2 {
  472. return Err(error!($error_code).with_pubkeys(($value1, $value2)));
  473. }
  474. };
  475. ($value1: expr, $value2: expr $(,)?) => {
  476. if $value1 == $value2 {
  477. return Err(
  478. error!(anchor_lang::error::ErrorCode::RequireKeysNeqViolated)
  479. .with_pubkeys(($value1, $value2)),
  480. );
  481. }
  482. };
  483. }
  484. /// Ensures the first NON-PUBKEY value is greater than the second
  485. /// NON-PUBKEY value.
  486. ///
  487. /// To include an equality check, use [require_gte](crate::require_gte).
  488. ///
  489. /// Can be used with or without a custom error code.
  490. ///
  491. /// # Example
  492. /// ```rust,ignore
  493. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  494. /// require_gt!(ctx.accounts.data.data, 0);
  495. /// ctx.accounts.data.data = data;
  496. /// Ok(());
  497. /// }
  498. /// ```
  499. #[macro_export]
  500. macro_rules! require_gt {
  501. ($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
  502. if $value1 <= $value2 {
  503. return Err(error!($error_code).with_values(($value1, $value2)));
  504. }
  505. };
  506. ($value1: expr, $value2: expr $(,)?) => {
  507. if $value1 <= $value2 {
  508. return Err(error!(anchor_lang::error::ErrorCode::RequireGtViolated)
  509. .with_values(($value1, $value2)));
  510. }
  511. };
  512. }
  513. /// Ensures the first NON-PUBKEY value is greater than or equal
  514. /// to the second NON-PUBKEY value.
  515. ///
  516. /// Can be used with or without a custom error code.
  517. ///
  518. /// # Example
  519. /// ```rust,ignore
  520. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  521. /// require_gte!(ctx.accounts.data.data, 1);
  522. /// ctx.accounts.data.data = data;
  523. /// Ok(());
  524. /// }
  525. /// ```
  526. #[macro_export]
  527. macro_rules! require_gte {
  528. ($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
  529. if $value1 < $value2 {
  530. return Err(error!($error_code).with_values(($value1, $value2)));
  531. }
  532. };
  533. ($value1: expr, $value2: expr $(,)?) => {
  534. if $value1 < $value2 {
  535. return Err(error!(anchor_lang::error::ErrorCode::RequireGteViolated)
  536. .with_values(($value1, $value2)));
  537. }
  538. };
  539. }
  540. /// Returns with the given error.
  541. /// Use this with a custom error type.
  542. ///
  543. /// # Example
  544. /// ```ignore
  545. /// // Instruction function
  546. /// pub fn example(ctx: Context<Example>) -> Result<()> {
  547. /// err!(MyError::SomeError)
  548. /// }
  549. ///
  550. /// // An enum for custom error codes
  551. /// #[error_code]
  552. /// pub enum MyError {
  553. /// SomeError
  554. /// }
  555. /// ```
  556. #[macro_export]
  557. macro_rules! err {
  558. ($error:tt $(,)?) => {
  559. Err(anchor_lang::error!($crate::ErrorCode::$error))
  560. };
  561. ($error:expr $(,)?) => {
  562. Err(anchor_lang::error!($error))
  563. };
  564. }
  565. /// Creates a [`Source`](crate::error::Source)
  566. #[macro_export]
  567. macro_rules! source {
  568. () => {
  569. anchor_lang::error::Source {
  570. filename: file!(),
  571. line: line!(),
  572. }
  573. };
  574. }