program_account.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. use crate::error::ErrorCode;
  2. #[allow(deprecated)]
  3. use crate::CpiAccount;
  4. use crate::{
  5. AccountDeserialize, AccountSerialize, Accounts, AccountsClose, AccountsExit, Key,
  6. ToAccountInfo, ToAccountInfos, ToAccountMetas,
  7. };
  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::ops::{Deref, DerefMut};
  14. /// Boxed container for a deserialized `account`. Use this to reference any
  15. /// account owned by the currently executing program.
  16. #[derive(Clone)]
  17. pub struct ProgramAccount<'info, T: AccountSerialize + AccountDeserialize + Clone> {
  18. inner: Box<Inner<'info, T>>,
  19. }
  20. #[derive(Clone)]
  21. struct Inner<'info, T: AccountSerialize + AccountDeserialize + Clone> {
  22. info: AccountInfo<'info>,
  23. account: T,
  24. }
  25. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> ProgramAccount<'a, T> {
  26. fn new(info: AccountInfo<'a>, account: T) -> ProgramAccount<'a, T> {
  27. Self {
  28. inner: Box::new(Inner { info, account }),
  29. }
  30. }
  31. /// Deserializes the given `info` into a `ProgramAccount`.
  32. #[inline(never)]
  33. pub fn try_from(
  34. program_id: &Pubkey,
  35. info: &AccountInfo<'a>,
  36. ) -> Result<ProgramAccount<'a, T>, ProgramError> {
  37. if info.owner != program_id {
  38. return Err(ErrorCode::AccountNotProgramOwned.into());
  39. }
  40. let mut data: &[u8] = &info.try_borrow_data()?;
  41. Ok(ProgramAccount::new(
  42. info.clone(),
  43. T::try_deserialize(&mut data)?,
  44. ))
  45. }
  46. /// Deserializes the given `info` into a `ProgramAccount` without checking
  47. /// the account discriminator. Be careful when using this and avoid it if
  48. /// possible.
  49. #[inline(never)]
  50. pub fn try_from_unchecked(
  51. program_id: &Pubkey,
  52. info: &AccountInfo<'a>,
  53. ) -> Result<ProgramAccount<'a, T>, ProgramError> {
  54. if info.owner != program_id {
  55. return Err(ErrorCode::AccountNotProgramOwned.into());
  56. }
  57. let mut data: &[u8] = &info.try_borrow_data()?;
  58. Ok(ProgramAccount::new(
  59. info.clone(),
  60. T::try_deserialize_unchecked(&mut data)?,
  61. ))
  62. }
  63. pub fn into_inner(self) -> T {
  64. self.inner.account
  65. }
  66. }
  67. impl<'info, T> Accounts<'info> for ProgramAccount<'info, T>
  68. where
  69. T: AccountSerialize + AccountDeserialize + Clone,
  70. {
  71. #[inline(never)]
  72. fn try_accounts(
  73. program_id: &Pubkey,
  74. accounts: &mut &[AccountInfo<'info>],
  75. _ix_data: &[u8],
  76. ) -> Result<Self, ProgramError> {
  77. if accounts.is_empty() {
  78. return Err(ErrorCode::AccountNotEnoughKeys.into());
  79. }
  80. let account = &accounts[0];
  81. *accounts = &accounts[1..];
  82. ProgramAccount::try_from(program_id, account)
  83. }
  84. }
  85. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AccountsExit<'info>
  86. for ProgramAccount<'info, T>
  87. {
  88. fn exit(&self, _program_id: &Pubkey) -> ProgramResult {
  89. let info = self.to_account_info();
  90. let mut data = info.try_borrow_mut_data()?;
  91. let dst: &mut [u8] = &mut data;
  92. let mut cursor = std::io::Cursor::new(dst);
  93. self.inner.account.try_serialize(&mut cursor)?;
  94. Ok(())
  95. }
  96. }
  97. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AccountsClose<'info>
  98. for ProgramAccount<'info, T>
  99. {
  100. fn close(&self, sol_destination: AccountInfo<'info>) -> ProgramResult {
  101. crate::common::close(self.to_account_info(), sol_destination)
  102. }
  103. }
  104. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountMetas
  105. for ProgramAccount<'info, T>
  106. {
  107. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  108. let is_signer = is_signer.unwrap_or(self.inner.info.is_signer);
  109. let meta = match self.inner.info.is_writable {
  110. false => AccountMeta::new_readonly(*self.inner.info.key, is_signer),
  111. true => AccountMeta::new(*self.inner.info.key, is_signer),
  112. };
  113. vec![meta]
  114. }
  115. }
  116. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfos<'info>
  117. for ProgramAccount<'info, T>
  118. {
  119. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  120. vec![self.inner.info.clone()]
  121. }
  122. }
  123. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfo<'info>
  124. for ProgramAccount<'info, T>
  125. {
  126. fn to_account_info(&self) -> AccountInfo<'info> {
  127. self.inner.info.clone()
  128. }
  129. }
  130. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AsRef<AccountInfo<'info>>
  131. for ProgramAccount<'info, T>
  132. {
  133. fn as_ref(&self) -> &AccountInfo<'info> {
  134. &self.inner.info
  135. }
  136. }
  137. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> Deref for ProgramAccount<'a, T> {
  138. type Target = T;
  139. fn deref(&self) -> &Self::Target {
  140. &(*self.inner).account
  141. }
  142. }
  143. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> DerefMut for ProgramAccount<'a, T> {
  144. fn deref_mut(&mut self) -> &mut Self::Target {
  145. #[cfg(feature = "anchor-debug")]
  146. if !self.inner.info.is_writable {
  147. solana_program::msg!("The given ProgramAccount is not mutable");
  148. panic!();
  149. }
  150. &mut DerefMut::deref_mut(&mut self.inner).account
  151. }
  152. }
  153. #[allow(deprecated)]
  154. impl<'info, T> From<CpiAccount<'info, T>> for ProgramAccount<'info, T>
  155. where
  156. T: AccountSerialize + AccountDeserialize + Clone,
  157. {
  158. fn from(a: CpiAccount<'info, T>) -> Self {
  159. Self::new(a.to_account_info(), Deref::deref(&a).clone())
  160. }
  161. }
  162. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> Key for ProgramAccount<'info, T> {
  163. fn key(&self) -> Pubkey {
  164. *self.inner.info.key
  165. }
  166. }