account_loader.rs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. //! Type facilitating on demand zero copy deserialization.
  2. use crate::error::ErrorCode;
  3. use crate::{
  4. Accounts, AccountsClose, AccountsExit, Bump, Owner, ToAccountInfo, ToAccountInfos,
  5. ToAccountMetas, ZeroCopy,
  6. };
  7. use arrayref::array_ref;
  8. use solana_program::account_info::AccountInfo;
  9. use solana_program::entrypoint::ProgramResult;
  10. use solana_program::instruction::AccountMeta;
  11. use solana_program::program_error::ProgramError;
  12. use solana_program::pubkey::Pubkey;
  13. use std::cell::{Ref, RefMut};
  14. use std::fmt;
  15. use std::marker::PhantomData;
  16. use std::mem;
  17. use std::ops::DerefMut;
  18. /// Type facilitating on demand zero copy deserialization.
  19. ///
  20. /// Note that using accounts in this way is distinctly different from using,
  21. /// for example, the [`Account`](./struct.Account.html). Namely,
  22. /// one must call
  23. /// - `load` when the account is not mutable
  24. /// - `load_mut` when the account is mutable
  25. ///
  26. /// For more details on zero-copy-deserialization, see the
  27. /// [`account`](./attr.account.html) attribute.
  28. /// <p style=";padding:0.75em;border: 1px solid #ee6868">
  29. /// <strong>⚠️ </strong> When using this type it's important to be mindful
  30. /// of any calls to the <code>load</code> functions so as not to
  31. /// induce a <code>RefCell</code> panic, especially when sharing accounts across CPI
  32. /// boundaries. When in doubt, one should make sure all refs resulting from
  33. /// a call to a <code>load</code> function are dropped before CPI.
  34. /// This can be done explicitly by calling <code>drop(my_var)</code> or implicitly
  35. /// by wrapping the code using the <code>Ref</code> in braces <code>{..}</code> or
  36. /// moving it into its own function.
  37. /// </p>
  38. ///
  39. /// # Example
  40. /// ```ignore
  41. /// use anchor_lang::prelude::*;
  42. ///
  43. /// declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
  44. ///
  45. /// #[program]
  46. /// pub mod bar {
  47. /// use super::*;
  48. ///
  49. /// pub fn create_bar(ctx: Context<CreateBar>, data: u64) -> ProgramResult {
  50. /// let bar = &mut ctx.accounts.bar.load_init()?;
  51. /// bar.authority = ctx.accounts.authority.key();
  52. /// bar.data = data;
  53. /// Ok(())
  54. /// }
  55. ///
  56. /// pub fn update_bar(ctx: Context<UpdateBar>, data: u64) -> ProgramResult {
  57. /// (*ctx.accounts.bar.load_mut()?).data = data;
  58. /// Ok(())
  59. /// }
  60. /// }
  61. ///
  62. /// #[account(zero_copy)]
  63. /// #[derive(Default)]
  64. /// pub struct Bar {
  65. /// authority: Pubkey,
  66. /// data: u64
  67. /// }
  68. ///
  69. /// #[derive(Accounts)]
  70. /// pub struct CreateBar<'info> {
  71. /// #[account(
  72. /// init,
  73. /// payer = authority
  74. /// )]
  75. /// bar: AccountLoader<'info, Bar>,
  76. /// #[account(mut)]
  77. /// authority: Signer<'info>,
  78. /// system_program: AccountInfo<'info>,
  79. /// }
  80. ///
  81. /// #[derive(Accounts)]
  82. /// pub struct UpdateBar<'info> {
  83. /// #[account(
  84. /// mut,
  85. /// has_one = authority,
  86. /// )]
  87. /// pub bar: AccountLoader<'info, Bar>,
  88. /// pub authority: Signer<'info>,
  89. /// }
  90. /// ```
  91. #[derive(Clone)]
  92. pub struct AccountLoader<'info, T: ZeroCopy + Owner> {
  93. acc_info: AccountInfo<'info>,
  94. phantom: PhantomData<&'info T>,
  95. }
  96. impl<'info, T: ZeroCopy + Owner + fmt::Debug> fmt::Debug for AccountLoader<'info, T> {
  97. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  98. f.debug_struct("AccountLoader")
  99. .field("acc_info", &self.acc_info)
  100. .field("phantom", &self.phantom)
  101. .finish()
  102. }
  103. }
  104. impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> {
  105. fn new(acc_info: AccountInfo<'info>) -> AccountLoader<'info, T> {
  106. Self {
  107. acc_info,
  108. phantom: PhantomData,
  109. }
  110. }
  111. /// Constructs a new `Loader` from a previously initialized account.
  112. #[inline(never)]
  113. pub fn try_from(
  114. acc_info: &AccountInfo<'info>,
  115. ) -> Result<AccountLoader<'info, T>, ProgramError> {
  116. if acc_info.owner != &T::owner() {
  117. return Err(ErrorCode::AccountOwnedByWrongProgram.into());
  118. }
  119. let data: &[u8] = &acc_info.try_borrow_data()?;
  120. // Discriminator must match.
  121. #[cfg(feature = "deprecated-layout")]
  122. let disc_bytes = array_ref![data, 0, 8];
  123. #[cfg(not(feature = "deprecated-layout"))]
  124. let disc_bytes = array_ref![data, 2, 4];
  125. if disc_bytes != &T::discriminator() {
  126. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  127. }
  128. Ok(AccountLoader::new(acc_info.clone()))
  129. }
  130. /// Constructs a new `Loader` from an uninitialized account.
  131. #[inline(never)]
  132. pub fn try_from_unchecked(
  133. _program_id: &Pubkey,
  134. acc_info: &AccountInfo<'info>,
  135. ) -> Result<AccountLoader<'info, T>, ProgramError> {
  136. if acc_info.owner != &T::owner() {
  137. return Err(ErrorCode::AccountOwnedByWrongProgram.into());
  138. }
  139. Ok(AccountLoader::new(acc_info.clone()))
  140. }
  141. /// Returns a Ref to the account data structure for reading.
  142. pub fn load(&self) -> Result<Ref<T>, ProgramError> {
  143. let data = self.acc_info.try_borrow_data()?;
  144. #[cfg(feature = "deprecated-layout")]
  145. let disc_bytes = array_ref![data, 0, 8];
  146. #[cfg(not(feature = "deprecated-layout"))]
  147. let disc_bytes = array_ref![data, 2, 4];
  148. if disc_bytes != &T::discriminator() {
  149. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  150. }
  151. Ok(Ref::map(data, |data| {
  152. bytemuck::from_bytes(&data[8..mem::size_of::<T>() + 8])
  153. }))
  154. }
  155. /// Returns a `RefMut` to the account data structure for reading or writing.
  156. pub fn load_mut(&self) -> Result<RefMut<T>, ProgramError> {
  157. // AccountInfo api allows you to borrow mut even if the account isn't
  158. // writable, so add this check for a better dev experience.
  159. if !self.acc_info.is_writable {
  160. return Err(ErrorCode::AccountNotMutable.into());
  161. }
  162. let data = self.acc_info.try_borrow_mut_data()?;
  163. #[cfg(feature = "deprecated-layout")]
  164. let disc_bytes = array_ref![data, 0, 8];
  165. #[cfg(not(feature = "deprecated-layout"))]
  166. let disc_bytes = array_ref![data, 2, 4];
  167. if disc_bytes != &T::discriminator() {
  168. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  169. }
  170. Ok(RefMut::map(data, |data| {
  171. bytemuck::from_bytes_mut(&mut data.deref_mut()[8..mem::size_of::<T>() + 8])
  172. }))
  173. }
  174. }
  175. impl<'info, T: ZeroCopy + Owner> Accounts<'info> for AccountLoader<'info, T> {
  176. #[inline(never)]
  177. fn try_accounts(
  178. _program_id: &Pubkey,
  179. accounts: &mut &[AccountInfo<'info>],
  180. _ix_data: &[u8],
  181. ) -> Result<Self, ProgramError> {
  182. if accounts.is_empty() {
  183. return Err(ErrorCode::AccountNotEnoughKeys.into());
  184. }
  185. let account = &accounts[0];
  186. *accounts = &accounts[1..];
  187. let l = AccountLoader::try_from(account)?;
  188. Ok(l)
  189. }
  190. }
  191. impl<'info, T: ZeroCopy + Owner> AccountsExit<'info> for AccountLoader<'info, T> {
  192. // The account *cannot* be loaded when this is called.
  193. fn exit(&self, _program_id: &Pubkey) -> ProgramResult {
  194. // No-op.
  195. Ok(())
  196. }
  197. }
  198. impl<'info, T: ZeroCopy + Owner> AccountsClose<'info> for AccountLoader<'info, T> {
  199. fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult {
  200. crate::common::close(self.to_account_info(), sol_destination)
  201. }
  202. }
  203. impl<'info, T: ZeroCopy + Owner> ToAccountMetas for AccountLoader<'info, T> {
  204. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  205. let is_signer = is_signer.unwrap_or(self.acc_info.is_signer);
  206. let meta = match self.acc_info.is_writable {
  207. false => AccountMeta::new_readonly(*self.acc_info.key, is_signer),
  208. true => AccountMeta::new(*self.acc_info.key, is_signer),
  209. };
  210. vec![meta]
  211. }
  212. }
  213. impl<'info, T: ZeroCopy + Owner> AsRef<AccountInfo<'info>> for AccountLoader<'info, T> {
  214. fn as_ref(&self) -> &AccountInfo<'info> {
  215. &self.acc_info
  216. }
  217. }
  218. impl<'info, T: ZeroCopy + Owner> ToAccountInfos<'info> for AccountLoader<'info, T> {
  219. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  220. vec![self.acc_info.clone()]
  221. }
  222. }
  223. #[cfg(not(feature = "deprecated-layout"))]
  224. impl<'info, T> Bump for T
  225. where
  226. T: AsRef<AccountInfo<'info>>,
  227. {
  228. fn seed(&self) -> u8 {
  229. self.as_ref().data.borrow()[1]
  230. }
  231. }