lib.rs 19 KB

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