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