lib.rs 10 KB

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