lib.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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 crate::solana_program::account_info::AccountInfo;
  26. use crate::solana_program::instruction::AccountMeta;
  27. use crate::solana_program::program_error::ProgramError;
  28. use crate::solana_program::pubkey::Pubkey;
  29. use bytemuck::{Pod, Zeroable};
  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 mod solana_program {
  60. pub use solana_feature_gate_interface as feature;
  61. pub use {
  62. solana_account_info as account_info, solana_clock as clock, solana_cpi as program,
  63. solana_msg::msg, solana_program_entrypoint as entrypoint,
  64. solana_program_entrypoint::entrypoint, solana_program_error as program_error,
  65. solana_program_memory as program_memory, solana_program_option as program_option,
  66. solana_program_pack as program_pack, solana_pubkey as pubkey,
  67. solana_sdk_ids::system_program, solana_system_interface::instruction as system_instruction,
  68. };
  69. pub mod instruction {
  70. pub use solana_instruction::*;
  71. /// Get the current stack height, transaction-level instructions are height
  72. /// TRANSACTION_LEVEL_STACK_HEIGHT, fist invoked inner instruction is height
  73. /// TRANSACTION_LEVEL_STACK_HEIGHT + 1, etc...
  74. pub fn get_stack_height() -> usize {
  75. #[cfg(target_os = "solana")]
  76. unsafe {
  77. solana_instruction::syscalls::sol_get_stack_height() as usize
  78. }
  79. #[cfg(not(target_os = "solana"))]
  80. {
  81. solana_sysvar::program_stubs::sol_get_stack_height() as usize
  82. }
  83. }
  84. }
  85. pub mod rent {
  86. pub use solana_sysvar::rent::*;
  87. }
  88. pub mod bpf_loader_upgradeable {
  89. #[allow(deprecated)]
  90. pub use solana_loader_v3_interface::{
  91. get_program_data_address,
  92. instruction::{
  93. close, close_any, create_buffer, deploy_with_max_program_len, extend_program,
  94. is_close_instruction, is_set_authority_checked_instruction,
  95. is_set_authority_instruction, is_upgrade_instruction, set_buffer_authority,
  96. set_buffer_authority_checked, set_upgrade_authority, set_upgrade_authority_checked,
  97. upgrade, write,
  98. },
  99. state::UpgradeableLoaderState,
  100. };
  101. pub use solana_sdk_ids::bpf_loader_upgradeable::{check_id, id, ID};
  102. }
  103. pub mod log {
  104. pub use solana_msg::{msg, sol_log};
  105. /// Print some slices as base64.
  106. pub fn sol_log_data(data: &[&[u8]]) {
  107. #[cfg(target_os = "solana")]
  108. unsafe {
  109. solana_define_syscall::definitions::sol_log_data(
  110. data as *const _ as *const u8,
  111. data.len() as u64,
  112. )
  113. };
  114. #[cfg(not(target_os = "solana"))]
  115. core::hint::black_box(data);
  116. }
  117. }
  118. pub mod sysvar {
  119. pub use solana_sysvar_id::{declare_deprecated_sysvar_id, declare_sysvar_id, SysvarId};
  120. #[deprecated(since = "2.2.0", note = "Use `solana-sysvar` crate instead")]
  121. #[allow(deprecated)]
  122. pub use {
  123. solana_sdk_ids::sysvar::{check_id, id, ID},
  124. solana_sysvar::{
  125. clock, epoch_rewards, epoch_schedule, fees, is_sysvar_id, last_restart_slot,
  126. recent_blockhashes, rent, rewards, slot_hashes, slot_history, stake_history,
  127. Sysvar, ALL_IDS,
  128. },
  129. };
  130. pub mod instructions {
  131. pub use solana_instruction::{BorrowedAccountMeta, BorrowedInstruction};
  132. #[cfg(not(target_os = "solana"))]
  133. pub use solana_instructions_sysvar::construct_instructions_data;
  134. #[deprecated(
  135. since = "2.2.0",
  136. note = "Use solana-instructions-sysvar crate instead"
  137. )]
  138. pub use solana_instructions_sysvar::{
  139. get_instruction_relative, load_current_index_checked, load_instruction_at_checked,
  140. store_current_index_checked, Instructions,
  141. };
  142. #[deprecated(since = "2.2.0", note = "Use solana-sdk-ids crate instead")]
  143. pub use solana_sdk_ids::sysvar::instructions::{check_id, id, ID};
  144. }
  145. }
  146. }
  147. #[cfg(feature = "event-cpi")]
  148. pub use anchor_attribute_event::{emit_cpi, event_cpi};
  149. #[cfg(feature = "idl-build")]
  150. pub use idl::IdlBuild;
  151. #[cfg(feature = "interface-instructions")]
  152. pub use anchor_attribute_program::interface;
  153. pub type Result<T> = std::result::Result<T, error::Error>;
  154. /// A data structure of validated accounts that can be deserialized from the
  155. /// input to a Solana program. Implementations of this trait should perform any
  156. /// and all requisite constraint checks on accounts to ensure the accounts
  157. /// maintain any invariants required for the program to run securely. In most
  158. /// cases, it's recommended to use the [`Accounts`](./derive.Accounts.html)
  159. /// derive macro to implement this trait.
  160. ///
  161. /// Generics:
  162. /// - `B`: the type of the PDA bumps cache struct generated by the `Accounts` struct.
  163. /// For example,
  164. /// ```rust,ignore
  165. /// pub struct Example<'info> {
  166. /// #[account(
  167. /// init,
  168. /// seeds = [...],
  169. /// bump,
  170. /// )]
  171. /// pub pda_1: UncheckedAccount<'info>,
  172. /// pub not_pda: UncheckedAccount<'info>,
  173. /// }
  174. /// ```
  175. ///
  176. /// generates:
  177. ///
  178. /// ```rust,ignore
  179. /// pub struct ExampleBumps {
  180. /// pub pda_1: u8,
  181. /// }
  182. /// ```
  183. pub trait Accounts<'info, B>: ToAccountMetas + ToAccountInfos<'info> + Sized {
  184. /// Returns the validated accounts struct. What constitutes "valid" is
  185. /// program dependent. However, users of these types should never have to
  186. /// worry about account substitution attacks. For example, if a program
  187. /// expects a `Mint` account from the SPL token program in a particular
  188. /// field, then it should be impossible for this method to return `Ok` if
  189. /// any other account type is given--from the SPL token program or elsewhere.
  190. ///
  191. /// `program_id` is the currently executing program. `accounts` is the
  192. /// set of accounts to construct the type from. For every account used,
  193. /// the implementation should mutate the slice, consuming the used entry
  194. /// so that it cannot be used again.
  195. fn try_accounts(
  196. program_id: &Pubkey,
  197. accounts: &mut &'info [AccountInfo<'info>],
  198. ix_data: &[u8],
  199. bumps: &mut B,
  200. reallocs: &mut BTreeSet<Pubkey>,
  201. ) -> Result<Self>;
  202. }
  203. /// Associated bump seeds for `Accounts`.
  204. pub trait Bumps {
  205. /// Struct to hold account bump seeds.
  206. type Bumps: Sized + Debug;
  207. }
  208. /// The exit procedure for an account. Any cleanup or persistence to storage
  209. /// should be done here.
  210. pub trait AccountsExit<'info>: ToAccountMetas + ToAccountInfos<'info> {
  211. /// `program_id` is the currently executing program.
  212. fn exit(&self, _program_id: &Pubkey) -> Result<()> {
  213. // no-op
  214. Ok(())
  215. }
  216. }
  217. /// The close procedure to initiate garabage collection of an account, allowing
  218. /// one to retrieve the rent exemption.
  219. pub trait AccountsClose<'info>: ToAccountInfos<'info> {
  220. fn close(&self, sol_destination: AccountInfo<'info>) -> Result<()>;
  221. }
  222. /// Transformation to
  223. /// [`AccountMeta`](../solana_program/instruction/struct.AccountMeta.html)
  224. /// structs.
  225. pub trait ToAccountMetas {
  226. /// `is_signer` is given as an optional override for the signer meta field.
  227. /// This covers the edge case when a program-derived-address needs to relay
  228. /// a transaction from a client to another program but sign the transaction
  229. /// before the relay. The client cannot mark the field as a signer, and so
  230. /// we have to override the is_signer meta field given by the client.
  231. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta>;
  232. }
  233. /// Transformation to
  234. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html)
  235. /// structs.
  236. pub trait ToAccountInfos<'info> {
  237. fn to_account_infos(&self) -> Vec<AccountInfo<'info>>;
  238. }
  239. /// Transformation to an `AccountInfo` struct.
  240. pub trait ToAccountInfo<'info> {
  241. fn to_account_info(&self) -> AccountInfo<'info>;
  242. }
  243. impl<'info, T> ToAccountInfo<'info> for T
  244. where
  245. T: AsRef<AccountInfo<'info>>,
  246. {
  247. fn to_account_info(&self) -> AccountInfo<'info> {
  248. self.as_ref().clone()
  249. }
  250. }
  251. /// Lamports related utility methods for accounts.
  252. pub trait Lamports<'info>: AsRef<AccountInfo<'info>> {
  253. /// Get the lamports of the account.
  254. fn get_lamports(&self) -> u64 {
  255. self.as_ref().lamports()
  256. }
  257. /// Add lamports to the account.
  258. ///
  259. /// This method is useful for transferring lamports from a PDA.
  260. ///
  261. /// # Requirements
  262. ///
  263. /// 1. The account must be marked `mut`.
  264. /// 2. The total lamports **before** the transaction must equal to total lamports **after**
  265. /// the transaction.
  266. /// 3. `lamports` field of the account info should not currently be borrowed.
  267. ///
  268. /// See [`Lamports::sub_lamports`] for subtracting lamports.
  269. fn add_lamports(&self, amount: u64) -> Result<&Self> {
  270. **self.as_ref().try_borrow_mut_lamports()? = self
  271. .get_lamports()
  272. .checked_add(amount)
  273. .ok_or(ProgramError::ArithmeticOverflow)?;
  274. Ok(self)
  275. }
  276. /// Subtract lamports from the account.
  277. ///
  278. /// This method is useful for transferring lamports from a PDA.
  279. ///
  280. /// # Requirements
  281. ///
  282. /// 1. The account must be owned by the executing program.
  283. /// 2. The account must be marked `mut`.
  284. /// 3. The total lamports **before** the transaction must equal to total lamports **after**
  285. /// the transaction.
  286. /// 4. `lamports` field of the account info should not currently be borrowed.
  287. ///
  288. /// See [`Lamports::add_lamports`] for adding lamports.
  289. fn sub_lamports(&self, amount: u64) -> Result<&Self> {
  290. **self.as_ref().try_borrow_mut_lamports()? = self
  291. .get_lamports()
  292. .checked_sub(amount)
  293. .ok_or(ProgramError::ArithmeticOverflow)?;
  294. Ok(self)
  295. }
  296. }
  297. impl<'info, T: AsRef<AccountInfo<'info>>> Lamports<'info> for T {}
  298. /// A data structure that can be serialized and stored into account storage,
  299. /// i.e. an
  300. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  301. /// mutable data slice.
  302. ///
  303. /// Implementors of this trait should ensure that any subsequent usage of the
  304. /// `AccountDeserialize` trait succeeds if and only if the account is of the
  305. /// correct type.
  306. ///
  307. /// In most cases, one can use the default implementation provided by the
  308. /// [`#[account]`](./attr.account.html) attribute.
  309. pub trait AccountSerialize {
  310. /// Serializes the account data into `writer`.
  311. fn try_serialize<W: Write>(&self, _writer: &mut W) -> Result<()> {
  312. Ok(())
  313. }
  314. }
  315. /// A data structure that can be deserialized and stored into account storage,
  316. /// i.e. an
  317. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  318. /// mutable data slice.
  319. pub trait AccountDeserialize: Sized {
  320. /// Deserializes previously initialized account data. Should fail for all
  321. /// uninitialized accounts, where the bytes are zeroed. Implementations
  322. /// should be unique to a particular account type so that one can never
  323. /// successfully deserialize the data of one account type into another.
  324. /// For example, if the SPL token program were to implement this trait,
  325. /// it should be impossible to deserialize a `Mint` account into a token
  326. /// `Account`.
  327. fn try_deserialize(buf: &mut &[u8]) -> Result<Self> {
  328. Self::try_deserialize_unchecked(buf)
  329. }
  330. /// Deserializes account data without checking the account discriminator.
  331. /// This should only be used on account initialization, when the bytes of
  332. /// the account are zeroed.
  333. fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result<Self>;
  334. }
  335. /// An account data structure capable of zero copy deserialization.
  336. pub trait ZeroCopy: Discriminator + Copy + Clone + Zeroable + Pod {}
  337. /// Calculates the data for an instruction invocation, where the data is
  338. /// `Discriminator + BorshSerialize(args)`. `args` is a borsh serialized
  339. /// struct of named fields for each argument given to an instruction.
  340. pub trait InstructionData: Discriminator + AnchorSerialize {
  341. fn data(&self) -> Vec<u8> {
  342. let mut data = Vec::with_capacity(256);
  343. data.extend_from_slice(Self::DISCRIMINATOR);
  344. self.serialize(&mut data).unwrap();
  345. data
  346. }
  347. /// Clears `data` and writes instruction data to it.
  348. ///
  349. /// We use a `Vec<u8>`` here because of the additional flexibility of re-allocation (only if
  350. /// necessary), and because the data field in `Instruction` expects a `Vec<u8>`.
  351. fn write_to(&self, mut data: &mut Vec<u8>) {
  352. data.clear();
  353. data.extend_from_slice(Self::DISCRIMINATOR);
  354. self.serialize(&mut data).unwrap()
  355. }
  356. }
  357. /// An event that can be emitted via a Solana log. See [`emit!`](crate::prelude::emit) for an example.
  358. pub trait Event: AnchorSerialize + AnchorDeserialize + Discriminator {
  359. fn data(&self) -> Vec<u8>;
  360. }
  361. /// Unique identifier for a type.
  362. ///
  363. /// This is not a trait you should derive manually, as various Anchor macros already derive it
  364. /// internally.
  365. ///
  366. /// Prior to Anchor v0.31, discriminators were always 8 bytes in size. However, starting with Anchor
  367. /// v0.31, it is possible to override the default discriminators, and discriminator length is no
  368. /// longer fixed, which means this trait can also be implemented for non-Anchor programs.
  369. ///
  370. /// It's important that the discriminator is always unique for the type you're implementing it
  371. /// for. While the discriminator can be at any length (including zero), the IDL generation does not
  372. /// currently allow empty discriminators for safety and convenience reasons. However, the trait
  373. /// definition still allows empty discriminators because some non-Anchor programs, e.g. the SPL
  374. /// Token program, don't have account discriminators. In that case, safety checks should never
  375. /// depend on the discriminator.
  376. pub trait Discriminator {
  377. /// Discriminator slice.
  378. ///
  379. /// See [`Discriminator`] trait documentation for more information.
  380. const DISCRIMINATOR: &'static [u8];
  381. }
  382. /// Defines the space of an account for initialization.
  383. pub trait Space {
  384. const INIT_SPACE: usize;
  385. }
  386. /// Bump seed for program derived addresses.
  387. pub trait Bump {
  388. fn seed(&self) -> u8;
  389. }
  390. /// Defines an address expected to own an account.
  391. pub trait Owner {
  392. fn owner() -> Pubkey;
  393. }
  394. /// Defines a list of addresses expected to own an account.
  395. pub trait Owners {
  396. fn owners() -> &'static [Pubkey];
  397. }
  398. /// Defines a trait for checking the owner of a program.
  399. pub trait CheckOwner {
  400. fn check_owner(owner: &Pubkey) -> Result<()>;
  401. }
  402. impl<T: Owners> CheckOwner for T {
  403. fn check_owner(owner: &Pubkey) -> Result<()> {
  404. if !Self::owners().contains(owner) {
  405. Err(
  406. error::Error::from(error::ErrorCode::AccountOwnedByWrongProgram)
  407. .with_account_name(*owner),
  408. )
  409. } else {
  410. Ok(())
  411. }
  412. }
  413. }
  414. /// Defines the id of a program.
  415. pub trait Id {
  416. fn id() -> Pubkey;
  417. }
  418. /// Defines the possible ids of a program.
  419. pub trait Ids {
  420. fn ids() -> &'static [Pubkey];
  421. }
  422. /// Defines a trait for checking the id of a program.
  423. pub trait CheckId {
  424. fn check_id(id: &Pubkey) -> Result<()>;
  425. }
  426. impl<T: Ids> CheckId for T {
  427. fn check_id(id: &Pubkey) -> Result<()> {
  428. if !Self::ids().contains(id) {
  429. Err(error::Error::from(error::ErrorCode::InvalidProgramId).with_account_name(*id))
  430. } else {
  431. Ok(())
  432. }
  433. }
  434. }
  435. /// Defines the Pubkey of an account.
  436. pub trait Key {
  437. fn key(&self) -> Pubkey;
  438. }
  439. impl Key for Pubkey {
  440. fn key(&self) -> Pubkey {
  441. *self
  442. }
  443. }
  444. /// The prelude contains all commonly used components of the crate.
  445. /// All programs should include it via `anchor_lang::prelude::*;`.
  446. pub mod prelude {
  447. pub use super::{
  448. access_control, account, accounts::account::Account,
  449. accounts::account_loader::AccountLoader, accounts::interface::Interface,
  450. accounts::interface_account::InterfaceAccount, accounts::program::Program,
  451. accounts::signer::Signer, accounts::system_account::SystemAccount,
  452. accounts::sysvar::Sysvar, accounts::unchecked_account::UncheckedAccount, constant,
  453. context::Context, context::CpiContext, declare_id, declare_program, emit, err, error,
  454. event, instruction, program, pubkey, require, require_eq, require_gt, require_gte,
  455. require_keys_eq, require_keys_neq, require_neq,
  456. solana_program::bpf_loader_upgradeable::UpgradeableLoaderState, source,
  457. system_program::System, zero_copy, AccountDeserialize, AccountSerialize, Accounts,
  458. AccountsClose, AccountsExit, AnchorDeserialize, AnchorSerialize, Discriminator, Id,
  459. InitSpace, Key, Lamports, Owner, ProgramData, Result, Space, ToAccountInfo, ToAccountInfos,
  460. ToAccountMetas,
  461. };
  462. pub use crate::solana_program::account_info::{next_account_info, AccountInfo};
  463. pub use crate::solana_program::instruction::AccountMeta;
  464. pub use crate::solana_program::msg;
  465. pub use crate::solana_program::program_error::ProgramError;
  466. pub use crate::solana_program::pubkey::Pubkey;
  467. pub use crate::solana_program::sysvar::clock::Clock;
  468. pub use crate::solana_program::sysvar::epoch_schedule::EpochSchedule;
  469. pub use crate::solana_program::sysvar::instructions::Instructions;
  470. pub use crate::solana_program::sysvar::rent::Rent;
  471. pub use crate::solana_program::sysvar::rewards::Rewards;
  472. pub use crate::solana_program::sysvar::slot_hashes::SlotHashes;
  473. pub use crate::solana_program::sysvar::slot_history::SlotHistory;
  474. pub use crate::solana_program::sysvar::stake_history::StakeHistory;
  475. pub use crate::solana_program::sysvar::Sysvar as SolanaSysvar;
  476. pub use anchor_attribute_error::*;
  477. pub use borsh;
  478. pub use error::*;
  479. pub use thiserror;
  480. #[cfg(feature = "event-cpi")]
  481. pub use super::{emit_cpi, event_cpi};
  482. #[cfg(feature = "idl-build")]
  483. pub use super::idl::IdlBuild;
  484. #[cfg(feature = "interface-instructions")]
  485. pub use super::interface;
  486. #[cfg(feature = "lazy-account")]
  487. pub use super::accounts::lazy_account::LazyAccount;
  488. }
  489. /// Internal module used by macros and unstable apis.
  490. #[doc(hidden)]
  491. pub mod __private {
  492. pub use anchor_attribute_account::ZeroCopyAccessor;
  493. pub use base64;
  494. pub use bytemuck;
  495. pub use crate::{bpf_writer::BpfWriter, common::is_closed};
  496. use crate::solana_program::pubkey::Pubkey;
  497. // Used to calculate the maximum between two expressions.
  498. // It is necessary for the calculation of the enum space.
  499. #[doc(hidden)]
  500. pub const fn max(a: usize, b: usize) -> usize {
  501. [a, b][(a < b) as usize]
  502. }
  503. // Very experimental trait.
  504. #[doc(hidden)]
  505. pub trait ZeroCopyAccessor<Ty> {
  506. fn get(&self) -> Ty;
  507. fn set(input: &Ty) -> Self;
  508. }
  509. #[doc(hidden)]
  510. impl ZeroCopyAccessor<Pubkey> for [u8; 32] {
  511. fn get(&self) -> Pubkey {
  512. Pubkey::from(*self)
  513. }
  514. fn set(input: &Pubkey) -> [u8; 32] {
  515. input.to_bytes()
  516. }
  517. }
  518. #[cfg(feature = "lazy-account")]
  519. pub use crate::lazy::Lazy;
  520. #[cfg(feature = "lazy-account")]
  521. pub use anchor_derive_serde::Lazy;
  522. }
  523. /// Ensures a condition is true, otherwise returns with the given error.
  524. /// Use this with or without a custom error type.
  525. ///
  526. /// # Example
  527. /// ```ignore
  528. /// // Instruction function
  529. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  530. /// require!(ctx.accounts.data.mutation_allowed, MyError::MutationForbidden);
  531. /// ctx.accounts.data.data = data;
  532. /// Ok(())
  533. /// }
  534. ///
  535. /// // An enum for custom error codes
  536. /// #[error_code]
  537. /// pub enum MyError {
  538. /// MutationForbidden
  539. /// }
  540. ///
  541. /// // An account definition
  542. /// #[account]
  543. /// #[derive(Default)]
  544. /// pub struct MyData {
  545. /// mutation_allowed: bool,
  546. /// data: u64
  547. /// }
  548. ///
  549. /// // An account validation struct
  550. /// #[derive(Accounts)]
  551. /// pub struct SetData<'info> {
  552. /// #[account(mut)]
  553. /// pub data: Account<'info, MyData>
  554. /// }
  555. /// ```
  556. #[macro_export]
  557. macro_rules! require {
  558. ($invariant:expr, $error:tt $(,)?) => {
  559. if !($invariant) {
  560. return Err(anchor_lang::error!($crate::ErrorCode::$error));
  561. }
  562. };
  563. ($invariant:expr, $error:expr $(,)?) => {
  564. if !($invariant) {
  565. return Err(anchor_lang::error!($error));
  566. }
  567. };
  568. }
  569. /// Ensures two NON-PUBKEY values are equal.
  570. ///
  571. /// Use [require_keys_eq](crate::prelude::require_keys_eq)
  572. /// to compare two pubkeys.
  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_eq!(ctx.accounts.data.data, 0);
  580. /// ctx.accounts.data.data = data;
  581. /// Ok(())
  582. /// }
  583. /// ```
  584. #[macro_export]
  585. macro_rules! require_eq {
  586. ($value1: expr, $value2: expr, $error_code:expr $(,)?) => {
  587. if $value1 != $value2 {
  588. return Err(error!($error_code).with_values(($value1, $value2)));
  589. }
  590. };
  591. ($value1: expr, $value2: expr $(,)?) => {
  592. if $value1 != $value2 {
  593. return Err(error!(anchor_lang::error::ErrorCode::RequireEqViolated)
  594. .with_values(($value1, $value2)));
  595. }
  596. };
  597. }
  598. /// Ensures two NON-PUBKEY values are not equal.
  599. ///
  600. /// Use [require_keys_neq](crate::prelude::require_keys_neq)
  601. /// to compare two pubkeys.
  602. ///
  603. /// Can be used with or without a custom error code.
  604. ///
  605. /// # Example
  606. /// ```rust,ignore
  607. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  608. /// require_neq!(ctx.accounts.data.data, 0);
  609. /// ctx.accounts.data.data = data;
  610. /// Ok(());
  611. /// }
  612. /// ```
  613. #[macro_export]
  614. macro_rules! require_neq {
  615. ($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
  616. if $value1 == $value2 {
  617. return Err(error!($error_code).with_values(($value1, $value2)));
  618. }
  619. };
  620. ($value1: expr, $value2: expr $(,)?) => {
  621. if $value1 == $value2 {
  622. return Err(error!(anchor_lang::error::ErrorCode::RequireNeqViolated)
  623. .with_values(($value1, $value2)));
  624. }
  625. };
  626. }
  627. /// Ensures two pubkeys values are equal.
  628. ///
  629. /// Use [require_eq](crate::prelude::require_eq)
  630. /// to compare two non-pubkey values.
  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_keys_eq!(ctx.accounts.data.authority.key(), ctx.accounts.authority.key());
  638. /// ctx.accounts.data.data = data;
  639. /// Ok(())
  640. /// }
  641. /// ```
  642. #[macro_export]
  643. macro_rules! require_keys_eq {
  644. ($value1: expr, $value2: expr, $error_code:expr $(,)?) => {
  645. if $value1 != $value2 {
  646. return Err(error!($error_code).with_pubkeys(($value1, $value2)));
  647. }
  648. };
  649. ($value1: expr, $value2: expr $(,)?) => {
  650. if $value1 != $value2 {
  651. return Err(error!(anchor_lang::error::ErrorCode::RequireKeysEqViolated)
  652. .with_pubkeys(($value1, $value2)));
  653. }
  654. };
  655. }
  656. /// Ensures two pubkeys are not equal.
  657. ///
  658. /// Use [require_neq](crate::prelude::require_neq)
  659. /// to compare two non-pubkey values.
  660. ///
  661. /// Can be used with or without a custom error code.
  662. ///
  663. /// # Example
  664. /// ```rust,ignore
  665. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  666. /// require_keys_neq!(ctx.accounts.data.authority.key(), ctx.accounts.other.key());
  667. /// ctx.accounts.data.data = data;
  668. /// Ok(())
  669. /// }
  670. /// ```
  671. #[macro_export]
  672. macro_rules! require_keys_neq {
  673. ($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
  674. if $value1 == $value2 {
  675. return Err(error!($error_code).with_pubkeys(($value1, $value2)));
  676. }
  677. };
  678. ($value1: expr, $value2: expr $(,)?) => {
  679. if $value1 == $value2 {
  680. return Err(
  681. error!(anchor_lang::error::ErrorCode::RequireKeysNeqViolated)
  682. .with_pubkeys(($value1, $value2)),
  683. );
  684. }
  685. };
  686. }
  687. /// Ensures the first NON-PUBKEY value is greater than the second
  688. /// NON-PUBKEY value.
  689. ///
  690. /// To include an equality check, use [require_gte](crate::require_gte).
  691. ///
  692. /// Can be used with or without a custom error code.
  693. ///
  694. /// # Example
  695. /// ```rust,ignore
  696. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  697. /// require_gt!(ctx.accounts.data.data, 0);
  698. /// ctx.accounts.data.data = data;
  699. /// Ok(());
  700. /// }
  701. /// ```
  702. #[macro_export]
  703. macro_rules! require_gt {
  704. ($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
  705. if $value1 <= $value2 {
  706. return Err(error!($error_code).with_values(($value1, $value2)));
  707. }
  708. };
  709. ($value1: expr, $value2: expr $(,)?) => {
  710. if $value1 <= $value2 {
  711. return Err(error!(anchor_lang::error::ErrorCode::RequireGtViolated)
  712. .with_values(($value1, $value2)));
  713. }
  714. };
  715. }
  716. /// Ensures the first NON-PUBKEY value is greater than or equal
  717. /// to the second NON-PUBKEY value.
  718. ///
  719. /// Can be used with or without a custom error code.
  720. ///
  721. /// # Example
  722. /// ```rust,ignore
  723. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  724. /// require_gte!(ctx.accounts.data.data, 1);
  725. /// ctx.accounts.data.data = data;
  726. /// Ok(());
  727. /// }
  728. /// ```
  729. #[macro_export]
  730. macro_rules! require_gte {
  731. ($value1: expr, $value2: expr, $error_code: expr $(,)?) => {
  732. if $value1 < $value2 {
  733. return Err(error!($error_code).with_values(($value1, $value2)));
  734. }
  735. };
  736. ($value1: expr, $value2: expr $(,)?) => {
  737. if $value1 < $value2 {
  738. return Err(error!(anchor_lang::error::ErrorCode::RequireGteViolated)
  739. .with_values(($value1, $value2)));
  740. }
  741. };
  742. }
  743. /// Returns with the given error.
  744. /// Use this with a custom error type.
  745. ///
  746. /// # Example
  747. /// ```ignore
  748. /// // Instruction function
  749. /// pub fn example(ctx: Context<Example>) -> Result<()> {
  750. /// err!(MyError::SomeError)
  751. /// }
  752. ///
  753. /// // An enum for custom error codes
  754. /// #[error_code]
  755. /// pub enum MyError {
  756. /// SomeError
  757. /// }
  758. /// ```
  759. #[macro_export]
  760. macro_rules! err {
  761. ($error:tt $(,)?) => {
  762. Err(anchor_lang::error!($crate::ErrorCode::$error))
  763. };
  764. ($error:expr $(,)?) => {
  765. Err(anchor_lang::error!($error))
  766. };
  767. }
  768. /// Creates a [`Source`](crate::error::Source)
  769. #[macro_export]
  770. macro_rules! source {
  771. () => {
  772. anchor_lang::error::Source {
  773. filename: file!(),
  774. line: line!(),
  775. }
  776. };
  777. }