lib.rs 19 KB

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