lib.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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://project-serum.github.io/anchor) or examples in the GitHub
  20. //! [repository](https://github.com/project-serum/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;
  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. mod ctor;
  37. pub mod error;
  38. #[doc(hidden)]
  39. pub mod idl;
  40. mod system_program;
  41. pub use crate::system_program::System;
  42. mod vec;
  43. pub use crate::bpf_upgradeable_state::*;
  44. pub use anchor_attribute_access_control::access_control;
  45. pub use anchor_attribute_account::{account, declare_id, zero_copy};
  46. pub use anchor_attribute_constant::constant;
  47. pub use anchor_attribute_error;
  48. pub use anchor_attribute_event::{emit, event};
  49. pub use anchor_attribute_interface::interface;
  50. pub use anchor_attribute_program::program;
  51. pub use anchor_attribute_state::state;
  52. pub use anchor_derive_accounts::Accounts;
  53. /// Borsh is the default serialization format for instructions and accounts.
  54. pub use borsh::{BorshDeserialize as AnchorDeserialize, BorshSerialize as AnchorSerialize};
  55. pub use solana_program;
  56. pub type Result<T> = std::result::Result<T, error::Error>;
  57. /// A data structure of validated accounts that can be deserialized from the
  58. /// input to a Solana program. Implementations of this trait should perform any
  59. /// and all requisite constraint checks on accounts to ensure the accounts
  60. /// maintain any invariants required for the program to run securely. In most
  61. /// cases, it's recommended to use the [`Accounts`](./derive.Accounts.html)
  62. /// derive macro to implement this trait.
  63. pub trait Accounts<'info>: ToAccountMetas + ToAccountInfos<'info> + Sized {
  64. /// Returns the validated accounts struct. What constitutes "valid" is
  65. /// program dependent. However, users of these types should never have to
  66. /// worry about account substitution attacks. For example, if a program
  67. /// expects a `Mint` account from the SPL token program in a particular
  68. /// field, then it should be impossible for this method to return `Ok` if
  69. /// any other account type is given--from the SPL token program or elsewhere.
  70. ///
  71. /// `program_id` is the currently executing program. `accounts` is the
  72. /// set of accounts to construct the type from. For every account used,
  73. /// the implementation should mutate the slice, consuming the used entry
  74. /// so that it cannot be used again.
  75. fn try_accounts(
  76. program_id: &Pubkey,
  77. accounts: &mut &[AccountInfo<'info>],
  78. ix_data: &[u8],
  79. bumps: &mut BTreeMap<String, u8>,
  80. ) -> Result<Self>;
  81. }
  82. /// The exit procedure for an account. Any cleanup or persistence to storage
  83. /// should be done here.
  84. pub trait AccountsExit<'info>: ToAccountMetas + ToAccountInfos<'info> {
  85. /// `program_id` is the currently executing program.
  86. fn exit(&self, _program_id: &Pubkey) -> Result<()> {
  87. // no-op
  88. Ok(())
  89. }
  90. }
  91. /// The close procedure to initiate garabage collection of an account, allowing
  92. /// one to retrieve the rent exemption.
  93. pub trait AccountsClose<'info>: ToAccountInfos<'info> {
  94. fn close(&self, sol_destination: AccountInfo<'info>) -> Result<()>;
  95. }
  96. /// Transformation to
  97. /// [`AccountMeta`](../solana_program/instruction/struct.AccountMeta.html)
  98. /// structs.
  99. pub trait ToAccountMetas {
  100. /// `is_signer` is given as an optional override for the signer meta field.
  101. /// This covers the edge case when a program-derived-address needs to relay
  102. /// a transaction from a client to another program but sign the transaction
  103. /// before the relay. The client cannot mark the field as a signer, and so
  104. /// we have to override the is_signer meta field given by the client.
  105. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta>;
  106. }
  107. /// Transformation to
  108. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html)
  109. /// structs.
  110. pub trait ToAccountInfos<'info> {
  111. fn to_account_infos(&self) -> Vec<AccountInfo<'info>>;
  112. }
  113. /// Transformation to an `AccountInfo` struct.
  114. pub trait ToAccountInfo<'info> {
  115. fn to_account_info(&self) -> AccountInfo<'info>;
  116. }
  117. impl<'info, T> ToAccountInfo<'info> for T
  118. where
  119. T: AsRef<AccountInfo<'info>>,
  120. {
  121. fn to_account_info(&self) -> AccountInfo<'info> {
  122. self.as_ref().clone()
  123. }
  124. }
  125. /// A data structure that can be serialized and stored into account storage,
  126. /// i.e. an
  127. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  128. /// mutable data slice.
  129. ///
  130. /// Implementors of this trait should ensure that any subsequent usage of the
  131. /// `AccountDeserialize` trait succeeds if and only if the account is of the
  132. /// correct type.
  133. ///
  134. /// In most cases, one can use the default implementation provided by the
  135. /// [`#[account]`](./attr.account.html) attribute.
  136. pub trait AccountSerialize {
  137. /// Serializes the account data into `writer`.
  138. fn try_serialize<W: Write>(&self, _writer: &mut W) -> Result<()> {
  139. Ok(())
  140. }
  141. }
  142. /// A data structure that can be deserialized and stored into account storage,
  143. /// i.e. an
  144. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  145. /// mutable data slice.
  146. pub trait AccountDeserialize: Sized {
  147. /// Deserializes previously initialized account data. Should fail for all
  148. /// uninitialized accounts, where the bytes are zeroed. Implementations
  149. /// should be unique to a particular account type so that one can never
  150. /// successfully deserialize the data of one account type into another.
  151. /// For example, if the SPL token program were to implement this trait,
  152. /// it should be impossible to deserialize a `Mint` account into a token
  153. /// `Account`.
  154. fn try_deserialize(buf: &mut &[u8]) -> Result<Self> {
  155. Self::try_deserialize_unchecked(buf)
  156. }
  157. /// Deserializes account data without checking the account discriminator.
  158. /// This should only be used on account initialization, when the bytes of
  159. /// the account are zeroed.
  160. fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result<Self>;
  161. }
  162. /// An account data structure capable of zero copy deserialization.
  163. pub trait ZeroCopy: Discriminator + Copy + Clone + Zeroable + Pod {}
  164. /// Calculates the data for an instruction invocation, where the data is
  165. /// `Sha256(<namespace>::<method_name>)[..8] || BorshSerialize(args)`.
  166. /// `args` is a borsh serialized struct of named fields for each argument given
  167. /// to an instruction.
  168. pub trait InstructionData: AnchorSerialize {
  169. fn data(&self) -> Vec<u8>;
  170. }
  171. /// An event that can be emitted via a Solana log.
  172. pub trait Event: AnchorSerialize + AnchorDeserialize + Discriminator {
  173. fn data(&self) -> Vec<u8>;
  174. }
  175. // The serialized event data to be emitted via a Solana log.
  176. // TODO: remove this on the next major version upgrade.
  177. #[doc(hidden)]
  178. #[deprecated(since = "0.4.2", note = "Please use Event instead")]
  179. pub trait EventData: AnchorSerialize + Discriminator {
  180. fn data(&self) -> Vec<u8>;
  181. }
  182. /// 8 byte unique identifier for a type.
  183. pub trait Discriminator {
  184. fn discriminator() -> [u8; 8];
  185. }
  186. /// Bump seed for program derived addresses.
  187. pub trait Bump {
  188. fn seed(&self) -> u8;
  189. }
  190. /// Defines an address expected to own an account.
  191. pub trait Owner {
  192. fn owner() -> Pubkey;
  193. }
  194. /// Defines the id of a program.
  195. pub trait Id {
  196. fn id() -> Pubkey;
  197. }
  198. /// Defines the Pubkey of an account.
  199. pub trait Key {
  200. fn key(&self) -> Pubkey;
  201. }
  202. impl Key for Pubkey {
  203. fn key(&self) -> Pubkey {
  204. *self
  205. }
  206. }
  207. /// The prelude contains all commonly used components of the crate.
  208. /// All programs should include it via `anchor_lang::prelude::*;`.
  209. pub mod prelude {
  210. pub use super::{
  211. access_control, account, accounts::account::Account,
  212. accounts::account_loader::AccountLoader, accounts::program::Program,
  213. accounts::signer::Signer, accounts::system_account::SystemAccount,
  214. accounts::sysvar::Sysvar, accounts::unchecked_account::UncheckedAccount, constant,
  215. context::Context, context::CpiContext, declare_id, emit, err, error, event, interface,
  216. program, require, require_eq, require_keys_eq,
  217. solana_program::bpf_loader_upgradeable::UpgradeableLoaderState, source, state, zero_copy,
  218. AccountDeserialize, AccountSerialize, Accounts, AccountsExit, AnchorDeserialize,
  219. AnchorSerialize, Id, Key, Owner, ProgramData, Result, System, ToAccountInfo,
  220. ToAccountInfos, ToAccountMetas,
  221. };
  222. pub use anchor_attribute_error::*;
  223. pub use borsh;
  224. pub use error::*;
  225. pub use solana_program::account_info::{next_account_info, AccountInfo};
  226. pub use solana_program::instruction::AccountMeta;
  227. pub use solana_program::msg;
  228. pub use solana_program::program_error::ProgramError;
  229. pub use solana_program::pubkey::Pubkey;
  230. pub use solana_program::sysvar::clock::Clock;
  231. pub use solana_program::sysvar::epoch_schedule::EpochSchedule;
  232. pub use solana_program::sysvar::fees::Fees;
  233. pub use solana_program::sysvar::instructions::Instructions;
  234. pub use solana_program::sysvar::recent_blockhashes::RecentBlockhashes;
  235. pub use solana_program::sysvar::rent::Rent;
  236. pub use solana_program::sysvar::rewards::Rewards;
  237. pub use solana_program::sysvar::slot_hashes::SlotHashes;
  238. pub use solana_program::sysvar::slot_history::SlotHistory;
  239. pub use solana_program::sysvar::stake_history::StakeHistory;
  240. pub use solana_program::sysvar::Sysvar as SolanaSysvar;
  241. pub use thiserror;
  242. }
  243. /// Internal module used by macros and unstable apis.
  244. #[doc(hidden)]
  245. pub mod __private {
  246. use super::Result;
  247. /// The discriminator anchor uses to mark an account as closed.
  248. pub const CLOSED_ACCOUNT_DISCRIMINATOR: [u8; 8] = [255, 255, 255, 255, 255, 255, 255, 255];
  249. pub use crate::ctor::Ctor;
  250. pub use anchor_attribute_account::ZeroCopyAccessor;
  251. pub use anchor_attribute_event::EventIndex;
  252. pub use base64;
  253. pub use bytemuck;
  254. use solana_program::pubkey::Pubkey;
  255. pub mod state {
  256. pub use crate::accounts::state::*;
  257. }
  258. // Calculates the size of an account, which may be larger than the deserialized
  259. // data in it. This trait is currently only used for `#[state]` accounts.
  260. #[doc(hidden)]
  261. pub trait AccountSize {
  262. fn size(&self) -> Result<u64>;
  263. }
  264. // Very experimental trait.
  265. #[doc(hidden)]
  266. pub trait ZeroCopyAccessor<Ty> {
  267. fn get(&self) -> Ty;
  268. fn set(input: &Ty) -> Self;
  269. }
  270. #[doc(hidden)]
  271. impl ZeroCopyAccessor<Pubkey> for [u8; 32] {
  272. fn get(&self) -> Pubkey {
  273. Pubkey::new(self)
  274. }
  275. fn set(input: &Pubkey) -> [u8; 32] {
  276. input.to_bytes()
  277. }
  278. }
  279. #[doc(hidden)]
  280. pub use crate::accounts::state::PROGRAM_STATE_SEED;
  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::anchor_attribute_error::error!(
  320. crate::ErrorCode::$error
  321. ));
  322. }
  323. };
  324. ($invariant:expr, $error:expr $(,)?) => {
  325. if !($invariant) {
  326. return Err(anchor_lang::anchor_attribute_error::error!($error));
  327. }
  328. };
  329. }
  330. /// Ensures two NON-PUBKEY values are equal.
  331. ///
  332. /// Use [require_keys_eq](crate::prelude::require_keys_eq)
  333. /// to compare two pubkeys.
  334. ///
  335. /// Can be used with or without a custom error code.
  336. ///
  337. /// # Example
  338. /// ```rust,ignore
  339. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  340. /// require_eq!(ctx.accounts.data.data, 0);
  341. /// ctx.accounts.data.data = data;
  342. /// Ok(())
  343. /// }
  344. /// ```
  345. #[macro_export]
  346. macro_rules! require_eq {
  347. ($value1: expr, $value2: expr, $error_code:expr $(,)?) => {
  348. if $value1 != $value2 {
  349. return Err(error!($error_code).with_values(($value1, $value2)));
  350. }
  351. };
  352. ($value1: expr, $value2: expr $(,)?) => {
  353. if $value1 != $value2 {
  354. return Err(error!(anchor_lang::error::ErrorCode::RequireEqViolated)
  355. .with_values(($value1, $value2)));
  356. }
  357. };
  358. }
  359. /// Ensures two pubkeys values are equal.
  360. ///
  361. /// Use [require_eq](crate::prelude::require_eq)
  362. /// to compare two non-pubkey values.
  363. ///
  364. /// Can be used with or without a custom error code.
  365. ///
  366. /// # Example
  367. /// ```rust,ignore
  368. /// pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
  369. /// require_keys_eq!(ctx.accounts.data.authority.key(), ctx.accounts.authority.key());
  370. /// ctx.accounts.data.data = data;
  371. /// Ok(())
  372. /// }
  373. /// ```
  374. #[macro_export]
  375. macro_rules! require_keys_eq {
  376. ($value1: expr, $value2: expr, $error_code:expr $(,)?) => {
  377. if $value1 != $value2 {
  378. return Err(error!($error_code).with_pubkeys(($value1, $value2)));
  379. }
  380. };
  381. ($value1: expr, $value2: expr $(,)?) => {
  382. if $value1 != $value2 {
  383. return Err(error!(anchor_lang::error::ErrorCode::RequireKeysEqViolated)
  384. .with_pubkeys(($value1, $value2)));
  385. }
  386. };
  387. }
  388. /// Returns with the given error.
  389. /// Use this with a custom error type.
  390. ///
  391. /// # Example
  392. /// ```ignore
  393. /// // Instruction function
  394. /// pub fn example(ctx: Context<Example>) -> Result<()> {
  395. /// err!(MyError::SomeError)
  396. /// }
  397. ///
  398. /// // An enum for custom error codes
  399. /// #[error_code]
  400. /// pub enum MyError {
  401. /// SomeError
  402. /// }
  403. /// ```
  404. #[macro_export]
  405. macro_rules! err {
  406. ($error:tt $(,)?) => {
  407. Err(anchor_lang::anchor_attribute_error::error!(
  408. crate::ErrorCode::$error
  409. ))
  410. };
  411. ($error:expr $(,)?) => {
  412. Err(anchor_lang::anchor_attribute_error::error!($error))
  413. };
  414. }
  415. /// Creates a [`Source`](crate::error::Source)
  416. #[macro_export]
  417. macro_rules! source {
  418. () => {
  419. anchor_lang::error::Source {
  420. filename: file!(),
  421. line: line!(),
  422. }
  423. };
  424. }