lib.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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::entrypoint::ProgramResult;
  27. use solana_program::instruction::AccountMeta;
  28. use solana_program::program_error::ProgramError;
  29. use solana_program::pubkey::Pubkey;
  30. use std::io::Write;
  31. mod account;
  32. mod account_info;
  33. mod account_meta;
  34. mod boxed;
  35. mod common;
  36. mod context;
  37. mod cpi_account;
  38. mod cpi_state;
  39. mod ctor;
  40. mod error;
  41. #[doc(hidden)]
  42. pub mod idl;
  43. mod loader;
  44. mod program;
  45. mod program_account;
  46. mod signer;
  47. pub mod state;
  48. mod system_program;
  49. mod sysvar;
  50. mod unchecked_account;
  51. mod vec;
  52. pub use crate::account::Account;
  53. #[doc(hidden)]
  54. #[allow(deprecated)]
  55. pub use crate::context::CpiStateContext;
  56. pub use crate::context::{Context, CpiContext};
  57. #[doc(hidden)]
  58. #[allow(deprecated)]
  59. pub use crate::cpi_account::CpiAccount;
  60. #[doc(hidden)]
  61. #[allow(deprecated)]
  62. pub use crate::cpi_state::CpiState;
  63. pub use crate::loader::Loader;
  64. pub use crate::program::Program;
  65. #[doc(hidden)]
  66. #[allow(deprecated)]
  67. pub use crate::program_account::ProgramAccount;
  68. pub use crate::signer::Signer;
  69. #[doc(hidden)]
  70. #[allow(deprecated)]
  71. pub use crate::state::ProgramState;
  72. pub use crate::system_program::System;
  73. pub use crate::sysvar::Sysvar;
  74. pub use crate::unchecked_account::UncheckedAccount;
  75. pub use anchor_attribute_access_control::access_control;
  76. pub use anchor_attribute_account::{account, declare_id, zero_copy};
  77. pub use anchor_attribute_error::error;
  78. pub use anchor_attribute_event::{emit, event};
  79. pub use anchor_attribute_interface::interface;
  80. pub use anchor_attribute_program::program;
  81. pub use anchor_attribute_state::state;
  82. pub use anchor_derive_accounts::Accounts;
  83. /// Borsh is the default serialization format for instructions and accounts.
  84. pub use borsh::{BorshDeserialize as AnchorDeserialize, BorshSerialize as AnchorSerialize};
  85. pub use solana_program;
  86. /// A data structure of validated accounts that can be deserialized from the
  87. /// input to a Solana program. Implementations of this trait should perform any
  88. /// and all requisite constraint checks on accounts to ensure the accounts
  89. /// maintain any invariants required for the program to run securely. In most
  90. /// cases, it's recommended to use the [`Accounts`](./derive.Accounts.html)
  91. /// derive macro to implement this trait.
  92. pub trait Accounts<'info>: ToAccountMetas + ToAccountInfos<'info> + Sized {
  93. /// Returns the validated accounts struct. What constitutes "valid" is
  94. /// program dependent. However, users of these types should never have to
  95. /// worry about account substitution attacks. For example, if a program
  96. /// expects a `Mint` account from the SPL token program in a particular
  97. /// field, then it should be impossible for this method to return `Ok` if
  98. /// any other account type is given--from the SPL token program or elsewhere.
  99. ///
  100. /// `program_id` is the currently executing program. `accounts` is the
  101. /// set of accounts to construct the type from. For every account used,
  102. /// the implementation should mutate the slice, consuming the used entry
  103. /// so that it cannot be used again.
  104. fn try_accounts(
  105. program_id: &Pubkey,
  106. accounts: &mut &[AccountInfo<'info>],
  107. ix_data: &[u8],
  108. ) -> Result<Self, ProgramError>;
  109. }
  110. /// The exit procedure for an account. Any cleanup or persistence to storage
  111. /// should be done here.
  112. pub trait AccountsExit<'info>: ToAccountMetas + ToAccountInfos<'info> {
  113. /// `program_id` is the currently executing program.
  114. fn exit(&self, program_id: &Pubkey) -> ProgramResult;
  115. }
  116. /// The close procedure to initiate garabage collection of an account, allowing
  117. /// one to retrieve the rent exemption.
  118. pub trait AccountsClose<'info>: ToAccountInfos<'info> {
  119. fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult;
  120. }
  121. /// Transformation to
  122. /// [`AccountMeta`](../solana_program/instruction/struct.AccountMeta.html)
  123. /// structs.
  124. pub trait ToAccountMetas {
  125. /// `is_signer` is given as an optional override for the signer meta field.
  126. /// This covers the edge case when a program-derived-address needs to relay
  127. /// a transaction from a client to another program but sign the transaction
  128. /// before the relay. The client cannot mark the field as a signer, and so
  129. /// we have to override the is_signer meta field given by the client.
  130. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta>;
  131. }
  132. /// Transformation to
  133. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html)
  134. /// structs.
  135. pub trait ToAccountInfos<'info> {
  136. fn to_account_infos(&self) -> Vec<AccountInfo<'info>>;
  137. }
  138. /// Transformation to an `AccountInfo` struct.
  139. pub trait ToAccountInfo<'info> {
  140. fn to_account_info(&self) -> AccountInfo<'info>;
  141. }
  142. /// A data structure that can be serialized 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. ///
  147. /// Implementors of this trait should ensure that any subsequent usage of the
  148. /// `AccountDeserialize` trait succeeds if and only if the account is of the
  149. /// correct type.
  150. ///
  151. /// In most cases, one can use the default implementation provided by the
  152. /// [`#[account]`](./attr.account.html) attribute.
  153. pub trait AccountSerialize {
  154. /// Serializes the account data into `writer`.
  155. fn try_serialize<W: Write>(&self, writer: &mut W) -> Result<(), ProgramError>;
  156. }
  157. /// A data structure that can be deserialized and stored into account storage,
  158. /// i.e. an
  159. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  160. /// mutable data slice.
  161. pub trait AccountDeserialize: Sized {
  162. /// Deserializes previously initialized account data. Should fail for all
  163. /// uninitialized accounts, where the bytes are zeroed. Implementations
  164. /// should be unique to a particular account type so that one can never
  165. /// successfully deserialize the data of one account type into another.
  166. /// For example, if the SPL token program where to implement this trait,
  167. /// it should impossible to deserialize a `Mint` account into a token
  168. /// `Account`.
  169. fn try_deserialize(buf: &mut &[u8]) -> Result<Self, ProgramError>;
  170. /// Deserializes account data without checking the account discriminator.
  171. /// This should only be used on account initialization, when the bytes of
  172. /// the account are zeroed.
  173. fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result<Self, ProgramError>;
  174. }
  175. /// An account data structure capable of zero copy deserialization.
  176. pub trait ZeroCopy: Discriminator + Copy + Clone + Zeroable + Pod {}
  177. /// Calculates the data for an instruction invocation, where the data is
  178. /// `Sha256(<namespace>::<method_name>)[..8] || BorshSerialize(args)`.
  179. /// `args` is a borsh serialized struct of named fields for each argument given
  180. /// to an instruction.
  181. pub trait InstructionData: AnchorSerialize {
  182. fn data(&self) -> Vec<u8>;
  183. }
  184. /// An event that can be emitted via a Solana log.
  185. pub trait Event: AnchorSerialize + AnchorDeserialize + Discriminator {
  186. fn data(&self) -> Vec<u8>;
  187. }
  188. // The serialized event data to be emitted via a Solana log.
  189. // TODO: remove this on the next major version upgrade.
  190. #[doc(hidden)]
  191. #[deprecated(since = "0.4.2", note = "Please use Event instead")]
  192. pub trait EventData: AnchorSerialize + Discriminator {
  193. fn data(&self) -> Vec<u8>;
  194. }
  195. /// 8 byte unique identifier for a type.
  196. pub trait Discriminator {
  197. fn discriminator() -> [u8; 8];
  198. }
  199. /// Bump seed for program derived addresses.
  200. pub trait Bump {
  201. fn seed(&self) -> u8;
  202. }
  203. /// Defines an address expected to own an account.
  204. pub trait Owner {
  205. fn owner() -> Pubkey;
  206. }
  207. /// Defines the id of a program.
  208. pub trait Id {
  209. fn id() -> Pubkey;
  210. }
  211. /// Defines the Pubkey of an account.
  212. pub trait Key {
  213. fn key(&self) -> Pubkey;
  214. }
  215. impl Key for Pubkey {
  216. fn key(&self) -> Pubkey {
  217. *self
  218. }
  219. }
  220. /// The prelude contains all commonly used components of the crate.
  221. /// All programs should include it via `anchor_lang::prelude::*;`.
  222. pub mod prelude {
  223. pub use super::{
  224. access_control, account, declare_id, emit, error, event, interface, program, require,
  225. state, zero_copy, Account, AccountDeserialize, AccountSerialize, Accounts, AccountsExit,
  226. AnchorDeserialize, AnchorSerialize, Context, CpiContext, Id, Key, Loader, Owner, Program,
  227. ProgramAccount, Signer, System, Sysvar, ToAccountInfo, ToAccountInfos, ToAccountMetas,
  228. UncheckedAccount,
  229. };
  230. #[allow(deprecated)]
  231. pub use super::{CpiAccount, CpiState, CpiStateContext, ProgramState};
  232. pub use borsh;
  233. pub use solana_program::account_info::{next_account_info, AccountInfo};
  234. pub use solana_program::entrypoint::ProgramResult;
  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::fees::Fees;
  242. pub use solana_program::sysvar::instructions::Instructions;
  243. pub use solana_program::sysvar::recent_blockhashes::RecentBlockhashes;
  244. pub use solana_program::sysvar::rent::Rent;
  245. pub use solana_program::sysvar::rewards::Rewards;
  246. pub use solana_program::sysvar::slot_hashes::SlotHashes;
  247. pub use solana_program::sysvar::slot_history::SlotHistory;
  248. pub use solana_program::sysvar::stake_history::StakeHistory;
  249. pub use solana_program::sysvar::Sysvar as SolanaSysvar;
  250. pub use thiserror;
  251. }
  252. // Internal module used by macros and unstable apis.
  253. #[doc(hidden)]
  254. pub mod __private {
  255. use solana_program::program_error::ProgramError;
  256. use solana_program::pubkey::Pubkey;
  257. pub use crate::ctor::Ctor;
  258. pub use crate::error::{Error, ErrorCode};
  259. pub use anchor_attribute_account::ZeroCopyAccessor;
  260. pub use anchor_attribute_event::EventIndex;
  261. pub use base64;
  262. pub use bytemuck;
  263. pub mod state {
  264. pub use crate::state::*;
  265. }
  266. // The starting point for user defined error codes.
  267. pub const ERROR_CODE_OFFSET: u32 = 300;
  268. // Calculates the size of an account, which may be larger than the deserialized
  269. // data in it. This trait is currently only used for `#[state]` accounts.
  270. #[doc(hidden)]
  271. pub trait AccountSize {
  272. fn size(&self) -> Result<u64, ProgramError>;
  273. }
  274. // Very experimental trait.
  275. pub trait ZeroCopyAccessor<Ty> {
  276. fn get(&self) -> Ty;
  277. fn set(input: &Ty) -> Self;
  278. }
  279. impl ZeroCopyAccessor<Pubkey> for [u8; 32] {
  280. fn get(&self) -> Pubkey {
  281. Pubkey::new(self)
  282. }
  283. fn set(input: &Pubkey) -> [u8; 32] {
  284. input.to_bytes()
  285. }
  286. }
  287. pub use crate::state::PROGRAM_STATE_SEED;
  288. pub const CLOSED_ACCOUNT_DISCRIMINATOR: [u8; 8] = [255, 255, 255, 255, 255, 255, 255, 255];
  289. }
  290. /// Ensures a condition is true, otherwise returns the given error.
  291. /// Use this with a custom error type.
  292. ///
  293. /// # Example
  294. ///
  295. /// After defining an `ErrorCode`
  296. ///
  297. /// ```ignore
  298. /// #[error]
  299. /// pub struct ErrorCode {
  300. /// InvalidArgument,
  301. /// }
  302. /// ```
  303. ///
  304. /// One can write a `require` assertion as
  305. ///
  306. /// ```ignore
  307. /// require!(condition, InvalidArgument);
  308. /// ```
  309. ///
  310. /// which would exit the program with the `InvalidArgument` error code if
  311. /// `condition` is false.
  312. #[macro_export]
  313. macro_rules! require {
  314. ($invariant:expr, $error:tt $(,)?) => {
  315. if !($invariant) {
  316. return Err(crate::ErrorCode::$error.into());
  317. }
  318. };
  319. ($invariant:expr, $error:expr $(,)?) => {
  320. if !($invariant) {
  321. return Err($error.into());
  322. }
  323. };
  324. }