lib.rs 24 KB

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