lib.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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::program_error::ProgramError;
  28. use solana_program::pubkey::Pubkey;
  29. use std::io::Write;
  30. mod account_info;
  31. mod boxed;
  32. mod context;
  33. mod cpi_account;
  34. mod cpi_state;
  35. mod ctor;
  36. mod error;
  37. #[doc(hidden)]
  38. pub mod idl;
  39. mod loader;
  40. mod program_account;
  41. mod state;
  42. mod sysvar;
  43. mod vec;
  44. pub use crate::context::{Context, CpiContext, CpiStateContext};
  45. pub use crate::cpi_account::CpiAccount;
  46. pub use crate::cpi_state::CpiState;
  47. pub use crate::loader::Loader;
  48. pub use crate::program_account::ProgramAccount;
  49. pub use crate::state::ProgramState;
  50. pub use crate::sysvar::Sysvar;
  51. pub use anchor_attribute_access_control::access_control;
  52. pub use anchor_attribute_account::{account, associated, zero_copy};
  53. pub use anchor_attribute_error::error;
  54. pub use anchor_attribute_event::{emit, event};
  55. pub use anchor_attribute_interface::interface;
  56. pub use anchor_attribute_program::program;
  57. pub use anchor_attribute_state::state;
  58. pub use anchor_derive_accounts::Accounts;
  59. /// Borsh is the default serialization format for instructions and accounts.
  60. pub use borsh::{BorshDeserialize as AnchorDeserialize, BorshSerialize as AnchorSerialize};
  61. pub use solana_program;
  62. /// A data structure of validated accounts that can be deserialized from the
  63. /// input to a Solana program. Implementations of this trait should perform any
  64. /// and all requisite constraint checks on accounts to ensure the accounts
  65. /// maintain any invariants required for the program to run securely. In most
  66. /// cases, it's recommended to use the [`Accounts`](./derive.Accounts.html)
  67. /// derive macro to implement this trait.
  68. pub trait Accounts<'info>: ToAccountMetas + ToAccountInfos<'info> + Sized {
  69. /// Returns the validated accounts struct. What constitutes "valid" is
  70. /// program dependent. However, users of these types should never have to
  71. /// worry about account substitution attacks. For example, if a program
  72. /// expects a `Mint` account from the SPL token program in a particular
  73. /// field, then it should be impossible for this method to return `Ok` if
  74. /// any other account type is given--from the SPL token program or elsewhere.
  75. ///
  76. /// `program_id` is the currently executing program. `accounts` is the
  77. /// set of accounts to construct the type from. For every account used,
  78. /// the implementation should mutate the slice, consuming the used entry
  79. /// so that it cannot be used again.
  80. fn try_accounts(
  81. program_id: &Pubkey,
  82. accounts: &mut &[AccountInfo<'info>],
  83. ) -> Result<Self, ProgramError>;
  84. }
  85. /// The exit procedure for an account. Any cleanup or persistance to storage
  86. /// should be done here.
  87. pub trait AccountsExit<'info>: ToAccountMetas + ToAccountInfos<'info> {
  88. /// `program_id` is the currently executing program.
  89. fn exit(&self, program_id: &Pubkey) -> solana_program::entrypoint::ProgramResult;
  90. }
  91. /// A data structure of accounts providing a one time deserialization upon
  92. /// account initialization, i.e., when the data array for a given account is
  93. /// zeroed. Any subsequent call to `try_accounts_init` should fail. For all
  94. /// subsequent deserializations, it's expected that [`Accounts`] is used.
  95. pub trait AccountsInit<'info>: ToAccountMetas + ToAccountInfos<'info> + Sized {
  96. fn try_accounts_init(
  97. program_id: &Pubkey,
  98. accounts: &mut &[AccountInfo<'info>],
  99. ) -> Result<Self, ProgramError>;
  100. }
  101. /// Transformation to
  102. /// [`AccountMeta`](../solana_program/instruction/struct.AccountMeta.html)
  103. /// structs.
  104. pub trait ToAccountMetas {
  105. /// `is_signer` is given as an optional override for the signer meta field.
  106. /// This covers the edge case when a program-derived-address needs to relay
  107. /// a transaction from a client to another program but sign the transaction
  108. /// before the relay. The client cannot mark the field as a signer, and so
  109. /// we have to override the is_signer meta field given by the client.
  110. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta>;
  111. }
  112. /// Transformation to
  113. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html)
  114. /// structs.
  115. pub trait ToAccountInfos<'info> {
  116. fn to_account_infos(&self) -> Vec<AccountInfo<'info>>;
  117. }
  118. /// Transformation to an `AccountInfo` struct.
  119. pub trait ToAccountInfo<'info> {
  120. fn to_account_info(&self) -> AccountInfo<'info>;
  121. }
  122. /// A data structure that can be serialized and stored into account storage,
  123. /// i.e. an
  124. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  125. /// mutable data slice.
  126. ///
  127. /// Implementors of this trait should ensure that any subsequent usage of the
  128. /// `AccountDeserialize` trait succeeds if and only if the account is of the
  129. /// correct type.
  130. ///
  131. /// In most cases, one can use the default implementation provided by the
  132. /// [`#[account]`](./attr.account.html) attribute.
  133. pub trait AccountSerialize {
  134. /// Serializes the account data into `writer`.
  135. fn try_serialize<W: Write>(&self, writer: &mut W) -> Result<(), ProgramError>;
  136. }
  137. /// A data structure that can be deserialized and stored into account storage,
  138. /// i.e. an
  139. /// [`AccountInfo`](../solana_program/account_info/struct.AccountInfo.html#structfield.data)'s
  140. /// mutable data slice.
  141. pub trait AccountDeserialize: Sized {
  142. /// Deserializes previously initialized account data. Should fail for all
  143. /// uninitialized accounts, where the bytes are zeroed. Implementations
  144. /// should be unique to a particular account type so that one can never
  145. /// successfully deserialize the data of one account type into another.
  146. /// For example, if the SPL token program where to implement this trait,
  147. /// it should impossible to deserialize a `Mint` account into a token
  148. /// `Account`.
  149. fn try_deserialize(buf: &mut &[u8]) -> Result<Self, ProgramError>;
  150. /// Deserializes account data without checking the account discriminator.
  151. /// This should only be used on account initialization, when the bytes of
  152. /// the account are zeroed.
  153. fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result<Self, ProgramError>;
  154. }
  155. /// An account data structure capable of zero copy deserialization.
  156. pub trait ZeroCopy: Discriminator + Copy + Clone + Zeroable + Pod {}
  157. /// Calculates the data for an instruction invocation, where the data is
  158. /// `Sha256(<namespace>::<method_name>)[..8] || BorshSerialize(args)`.
  159. /// `args` is a borsh serialized struct of named fields for each argument given
  160. /// to an instruction.
  161. pub trait InstructionData: AnchorSerialize {
  162. fn data(&self) -> Vec<u8>;
  163. }
  164. /// An event that can be emitted via a Solana log.
  165. pub trait Event: AnchorSerialize + AnchorDeserialize + Discriminator {
  166. fn data(&self) -> Vec<u8>;
  167. }
  168. // The serialized event data to be emitted via a Solana log.
  169. // TODO: remove this on the next major version upgrade.
  170. #[doc(hidden)]
  171. #[deprecated(since = "0.4.2", note = "Please use Event instead")]
  172. pub trait EventData: AnchorSerialize + Discriminator {
  173. fn data(&self) -> Vec<u8>;
  174. }
  175. /// 8 byte unique identifier for a type.
  176. pub trait Discriminator {
  177. fn discriminator() -> [u8; 8];
  178. }
  179. /// Bump seed for program derived addresses.
  180. pub trait Bump {
  181. fn seed(&self) -> u8;
  182. }
  183. /// The prelude contains all commonly used components of the crate.
  184. /// All programs should include it via `anchor_lang::prelude::*;`.
  185. pub mod prelude {
  186. pub use super::{
  187. access_control, account, associated, emit, error, event, interface, program, state,
  188. zero_copy, AccountDeserialize, AccountSerialize, Accounts, AccountsExit, AccountsInit,
  189. AnchorDeserialize, AnchorSerialize, Context, CpiAccount, CpiContext, CpiState,
  190. CpiStateContext, Loader, ProgramAccount, ProgramState, Sysvar, ToAccountInfo,
  191. ToAccountInfos, ToAccountMetas,
  192. };
  193. pub use borsh;
  194. pub use solana_program::account_info::{next_account_info, AccountInfo};
  195. pub use solana_program::entrypoint::ProgramResult;
  196. pub use solana_program::instruction::AccountMeta;
  197. pub use solana_program::msg;
  198. pub use solana_program::program_error::ProgramError;
  199. pub use solana_program::pubkey::Pubkey;
  200. pub use solana_program::sysvar::clock::Clock;
  201. pub use solana_program::sysvar::epoch_schedule::EpochSchedule;
  202. pub use solana_program::sysvar::fees::Fees;
  203. pub use solana_program::sysvar::instructions::Instructions;
  204. pub use solana_program::sysvar::recent_blockhashes::RecentBlockhashes;
  205. pub use solana_program::sysvar::rent::Rent;
  206. pub use solana_program::sysvar::rewards::Rewards;
  207. pub use solana_program::sysvar::slot_hashes::SlotHashes;
  208. pub use solana_program::sysvar::slot_history::SlotHistory;
  209. pub use solana_program::sysvar::stake_history::StakeHistory;
  210. pub use solana_program::sysvar::Sysvar as SolanaSysvar;
  211. pub use thiserror;
  212. }
  213. // Internal module used by macros.
  214. #[doc(hidden)]
  215. pub mod __private {
  216. use solana_program::program_error::ProgramError;
  217. use solana_program::pubkey::Pubkey;
  218. pub use crate::ctor::Ctor;
  219. pub use crate::error::Error;
  220. pub use anchor_attribute_account::ZeroCopyAccessor;
  221. pub use anchor_attribute_event::EventIndex;
  222. pub use base64;
  223. pub use bytemuck;
  224. // Calculates the size of an account, which may be larger than the deserialized
  225. // data in it. This trait is currently only used for `#[state]` accounts.
  226. #[doc(hidden)]
  227. pub trait AccountSize {
  228. fn size(&self) -> Result<u64, ProgramError>;
  229. }
  230. // Very experimental trait.
  231. pub trait ZeroCopyAccessor<Ty> {
  232. fn get(&self) -> Ty;
  233. fn set(input: &Ty) -> Self;
  234. }
  235. impl ZeroCopyAccessor<Pubkey> for [u8; 32] {
  236. fn get(&self) -> Pubkey {
  237. Pubkey::new(self)
  238. }
  239. fn set(input: &Pubkey) -> [u8; 32] {
  240. input.to_bytes()
  241. }
  242. }
  243. pub use crate::state::PROGRAM_STATE_SEED;
  244. }