program_account.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. use crate::{
  2. AccountDeserialize, AccountSerialize, Accounts, AccountsExit, AccountsInit, CpiAccount,
  3. ToAccountInfo, ToAccountInfos, ToAccountMetas,
  4. };
  5. use solana_program::account_info::AccountInfo;
  6. use solana_program::entrypoint::ProgramResult;
  7. use solana_program::instruction::AccountMeta;
  8. use solana_program::program_error::ProgramError;
  9. use solana_program::pubkey::Pubkey;
  10. use std::ops::{Deref, DerefMut};
  11. /// Boxed container for a deserialized `account`. Use this to reference any
  12. /// account owned by the currently executing program.
  13. #[derive(Clone)]
  14. pub struct ProgramAccount<'info, T: AccountSerialize + AccountDeserialize + Clone> {
  15. inner: Box<Inner<'info, T>>,
  16. }
  17. #[derive(Clone)]
  18. struct Inner<'info, T: AccountSerialize + AccountDeserialize + Clone> {
  19. info: AccountInfo<'info>,
  20. account: T,
  21. }
  22. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> ProgramAccount<'a, T> {
  23. pub fn new(info: AccountInfo<'a>, account: T) -> ProgramAccount<'a, T> {
  24. Self {
  25. inner: Box::new(Inner { info, account }),
  26. }
  27. }
  28. /// Deserializes the given `info` into a `ProgramAccount`.
  29. #[inline(never)]
  30. pub fn try_from(info: &AccountInfo<'a>) -> Result<ProgramAccount<'a, T>, ProgramError> {
  31. let mut data: &[u8] = &info.try_borrow_data()?;
  32. Ok(ProgramAccount::new(
  33. info.clone(),
  34. T::try_deserialize(&mut data)?,
  35. ))
  36. }
  37. /// Deserializes the zero-initialized `info` into a `ProgramAccount` without
  38. /// checking the account type. This should only be used upon program account
  39. /// initialization (since the entire account data array is zeroed and thus
  40. /// no account type is set).
  41. #[inline(never)]
  42. pub fn try_from_init(info: &AccountInfo<'a>) -> Result<ProgramAccount<'a, T>, ProgramError> {
  43. let mut data: &[u8] = &info.try_borrow_data()?;
  44. // The discriminator should be zero, since we're initializing.
  45. let mut disc_bytes = [0u8; 8];
  46. disc_bytes.copy_from_slice(&data[..8]);
  47. let discriminator = u64::from_le_bytes(disc_bytes);
  48. if discriminator != 0 {
  49. return Err(ProgramError::InvalidAccountData);
  50. }
  51. Ok(ProgramAccount::new(
  52. info.clone(),
  53. T::try_deserialize_unchecked(&mut data)?,
  54. ))
  55. }
  56. }
  57. impl<'info, T> Accounts<'info> for ProgramAccount<'info, T>
  58. where
  59. T: AccountSerialize + AccountDeserialize + Clone,
  60. {
  61. #[inline(never)]
  62. fn try_accounts(
  63. program_id: &Pubkey,
  64. accounts: &mut &[AccountInfo<'info>],
  65. ) -> Result<Self, ProgramError> {
  66. if accounts.is_empty() {
  67. return Err(ProgramError::NotEnoughAccountKeys);
  68. }
  69. let account = &accounts[0];
  70. *accounts = &accounts[1..];
  71. let pa = ProgramAccount::try_from(account)?;
  72. if pa.inner.info.owner != program_id {
  73. return Err(ProgramError::Custom(1)); // todo: proper error
  74. }
  75. Ok(pa)
  76. }
  77. }
  78. impl<'info, T> AccountsInit<'info> for ProgramAccount<'info, T>
  79. where
  80. T: AccountSerialize + AccountDeserialize + Clone,
  81. {
  82. #[inline(never)]
  83. fn try_accounts_init(
  84. _program_id: &Pubkey,
  85. accounts: &mut &[AccountInfo<'info>],
  86. ) -> Result<Self, ProgramError> {
  87. if accounts.is_empty() {
  88. return Err(ProgramError::NotEnoughAccountKeys);
  89. }
  90. let account = &accounts[0];
  91. *accounts = &accounts[1..];
  92. ProgramAccount::try_from_init(account)
  93. }
  94. }
  95. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AccountsExit<'info>
  96. for ProgramAccount<'info, T>
  97. {
  98. fn exit(&self, _program_id: &Pubkey) -> ProgramResult {
  99. let info = self.to_account_info();
  100. let mut data = info.try_borrow_mut_data()?;
  101. let dst: &mut [u8] = &mut data;
  102. let mut cursor = std::io::Cursor::new(dst);
  103. self.inner.account.try_serialize(&mut cursor)?;
  104. Ok(())
  105. }
  106. }
  107. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountMetas
  108. for ProgramAccount<'info, T>
  109. {
  110. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  111. let is_signer = is_signer.unwrap_or(self.inner.info.is_signer);
  112. let meta = match self.inner.info.is_writable {
  113. false => AccountMeta::new_readonly(*self.inner.info.key, is_signer),
  114. true => AccountMeta::new(*self.inner.info.key, is_signer),
  115. };
  116. vec![meta]
  117. }
  118. }
  119. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfos<'info>
  120. for ProgramAccount<'info, T>
  121. {
  122. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  123. vec![self.inner.info.clone()]
  124. }
  125. }
  126. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfo<'info>
  127. for ProgramAccount<'info, T>
  128. {
  129. fn to_account_info(&self) -> AccountInfo<'info> {
  130. self.inner.info.clone()
  131. }
  132. }
  133. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> Deref for ProgramAccount<'a, T> {
  134. type Target = T;
  135. fn deref(&self) -> &Self::Target {
  136. &(*self.inner).account
  137. }
  138. }
  139. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> DerefMut for ProgramAccount<'a, T> {
  140. fn deref_mut(&mut self) -> &mut Self::Target {
  141. &mut DerefMut::deref_mut(&mut self.inner).account
  142. }
  143. }
  144. impl<'info, T> From<CpiAccount<'info, T>> for ProgramAccount<'info, T>
  145. where
  146. T: AccountSerialize + AccountDeserialize + Clone,
  147. {
  148. fn from(a: CpiAccount<'info, T>) -> Self {
  149. Self::new(a.to_account_info(), Deref::deref(&a).clone())
  150. }
  151. }