lib.rs 9.9 KB

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