loader_account.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. use crate::error::ErrorCode;
  2. use crate::{
  3. Accounts, AccountsClose, AccountsExit, Key, Owner, ToAccountInfo, ToAccountInfos,
  4. ToAccountMetas, ZeroCopy,
  5. };
  6. use arrayref::array_ref;
  7. use solana_program::account_info::AccountInfo;
  8. use solana_program::entrypoint::ProgramResult;
  9. use solana_program::instruction::AccountMeta;
  10. use solana_program::program_error::ProgramError;
  11. use solana_program::pubkey::Pubkey;
  12. use std::cell::{Ref, RefMut};
  13. use std::fmt;
  14. use std::io::Write;
  15. use std::marker::PhantomData;
  16. use std::ops::DerefMut;
  17. /// Account AccountLoader facilitating on demand zero copy deserialization.
  18. /// Note that using accounts in this way is distinctly different from using,
  19. /// for example, the [`Account`](./struct.Account.html). Namely,
  20. /// one must call `load`, `load_mut`, or `load_init`, before reading or writing
  21. /// to the account. For more details on zero-copy-deserialization, see the
  22. /// [`account`](./attr.account.html) attribute.
  23. ///
  24. /// When using it's important to be mindful of any calls to `load` so as not to
  25. /// induce a `RefCell` panic, especially when sharing accounts across CPI
  26. /// boundaries. When in doubt, one should make sure all refs resulting from a
  27. /// call to `load` are dropped before CPI.
  28. #[derive(Clone)]
  29. pub struct AccountLoader<'info, T: ZeroCopy + Owner> {
  30. acc_info: AccountInfo<'info>,
  31. phantom: PhantomData<&'info T>,
  32. }
  33. impl<'info, T: ZeroCopy + Owner + fmt::Debug> fmt::Debug for AccountLoader<'info, T> {
  34. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  35. f.debug_struct("AccountLoader")
  36. .field("acc_info", &self.acc_info)
  37. .field("phantom", &self.phantom)
  38. .finish()
  39. }
  40. }
  41. impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> {
  42. fn new(acc_info: AccountInfo<'info>) -> AccountLoader<'info, T> {
  43. Self {
  44. acc_info,
  45. phantom: PhantomData,
  46. }
  47. }
  48. /// Constructs a new `Loader` from a previously initialized account.
  49. #[inline(never)]
  50. pub fn try_from(
  51. acc_info: &AccountInfo<'info>,
  52. ) -> Result<AccountLoader<'info, T>, ProgramError> {
  53. if acc_info.owner != &T::owner() {
  54. return Err(ErrorCode::AccountOwnedByWrongProgram.into());
  55. }
  56. let data: &[u8] = &acc_info.try_borrow_data()?;
  57. // Discriminator must match.
  58. let disc_bytes = array_ref![data, 0, 8];
  59. if disc_bytes != &T::discriminator() {
  60. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  61. }
  62. Ok(AccountLoader::new(acc_info.clone()))
  63. }
  64. /// Constructs a new `Loader` from an uninitialized account.
  65. #[inline(never)]
  66. pub fn try_from_unchecked(
  67. _program_id: &Pubkey,
  68. acc_info: &AccountInfo<'info>,
  69. ) -> Result<AccountLoader<'info, T>, ProgramError> {
  70. if acc_info.owner != &T::owner() {
  71. return Err(ErrorCode::AccountOwnedByWrongProgram.into());
  72. }
  73. Ok(AccountLoader::new(acc_info.clone()))
  74. }
  75. /// Returns a Ref to the account data structure for reading.
  76. pub fn load(&self) -> Result<Ref<T>, ProgramError> {
  77. let data = self.acc_info.try_borrow_data()?;
  78. let disc_bytes = array_ref![data, 0, 8];
  79. if disc_bytes != &T::discriminator() {
  80. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  81. }
  82. Ok(Ref::map(data, |data| bytemuck::from_bytes(&data[8..])))
  83. }
  84. /// Returns a `RefMut` to the account data structure for reading or writing.
  85. pub fn load_mut(&self) -> Result<RefMut<T>, ProgramError> {
  86. // AccountInfo api allows you to borrow mut even if the account isn't
  87. // writable, so add this check for a better dev experience.
  88. if !self.acc_info.is_writable {
  89. return Err(ErrorCode::AccountNotMutable.into());
  90. }
  91. let data = self.acc_info.try_borrow_mut_data()?;
  92. let disc_bytes = array_ref![data, 0, 8];
  93. if disc_bytes != &T::discriminator() {
  94. return Err(ErrorCode::AccountDiscriminatorMismatch.into());
  95. }
  96. Ok(RefMut::map(data, |data| {
  97. bytemuck::from_bytes_mut(&mut data.deref_mut()[8..])
  98. }))
  99. }
  100. /// Returns a `RefMut` to the account data structure for reading or writing.
  101. /// Should only be called once, when the account is being initialized.
  102. pub fn load_init(&self) -> Result<RefMut<T>, ProgramError> {
  103. // AccountInfo api allows you to borrow mut even if the account isn't
  104. // writable, so add this check for a better dev experience.
  105. if !self.acc_info.is_writable {
  106. return Err(ErrorCode::AccountNotMutable.into());
  107. }
  108. let data = self.acc_info.try_borrow_mut_data()?;
  109. // The discriminator should be zero, since we're initializing.
  110. let mut disc_bytes = [0u8; 8];
  111. disc_bytes.copy_from_slice(&data[..8]);
  112. let discriminator = u64::from_le_bytes(disc_bytes);
  113. if discriminator != 0 {
  114. return Err(ErrorCode::AccountDiscriminatorAlreadySet.into());
  115. }
  116. Ok(RefMut::map(data, |data| {
  117. bytemuck::from_bytes_mut(&mut data.deref_mut()[8..])
  118. }))
  119. }
  120. }
  121. impl<'info, T: ZeroCopy + Owner> Accounts<'info> for AccountLoader<'info, T> {
  122. #[inline(never)]
  123. fn try_accounts(
  124. _program_id: &Pubkey,
  125. accounts: &mut &[AccountInfo<'info>],
  126. _ix_data: &[u8],
  127. ) -> Result<Self, ProgramError> {
  128. if accounts.is_empty() {
  129. return Err(ErrorCode::AccountNotEnoughKeys.into());
  130. }
  131. let account = &accounts[0];
  132. *accounts = &accounts[1..];
  133. let l = AccountLoader::try_from(account)?;
  134. Ok(l)
  135. }
  136. }
  137. impl<'info, T: ZeroCopy + Owner> AccountsExit<'info> for AccountLoader<'info, T> {
  138. // The account *cannot* be loaded when this is called.
  139. fn exit(&self, _program_id: &Pubkey) -> ProgramResult {
  140. let mut data = self.acc_info.try_borrow_mut_data()?;
  141. let dst: &mut [u8] = &mut data;
  142. let mut cursor = std::io::Cursor::new(dst);
  143. cursor.write_all(&T::discriminator()).unwrap();
  144. Ok(())
  145. }
  146. }
  147. impl<'info, T: ZeroCopy + Owner> AccountsClose<'info> for AccountLoader<'info, T> {
  148. fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult {
  149. crate::common::close(self.to_account_info(), sol_destination)
  150. }
  151. }
  152. impl<'info, T: ZeroCopy + Owner> ToAccountMetas for AccountLoader<'info, T> {
  153. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  154. let is_signer = is_signer.unwrap_or(self.acc_info.is_signer);
  155. let meta = match self.acc_info.is_writable {
  156. false => AccountMeta::new_readonly(*self.acc_info.key, is_signer),
  157. true => AccountMeta::new(*self.acc_info.key, is_signer),
  158. };
  159. vec![meta]
  160. }
  161. }
  162. impl<'info, T: ZeroCopy + Owner> AsRef<AccountInfo<'info>> for AccountLoader<'info, T> {
  163. fn as_ref(&self) -> &AccountInfo<'info> {
  164. &self.acc_info
  165. }
  166. }
  167. impl<'info, T: ZeroCopy + Owner> ToAccountInfos<'info> for AccountLoader<'info, T> {
  168. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  169. vec![self.acc_info.clone()]
  170. }
  171. }
  172. impl<'info, T: ZeroCopy + Owner> ToAccountInfo<'info> for AccountLoader<'info, T> {
  173. fn to_account_info(&self) -> AccountInfo<'info> {
  174. self.acc_info.clone()
  175. }
  176. }
  177. impl<'info, T: ZeroCopy + Owner> Key for AccountLoader<'info, T> {
  178. fn key(&self) -> Pubkey {
  179. *self.acc_info.key
  180. }
  181. }