state.rs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. use crate::{
  2. AccountDeserialize, AccountSerialize, Accounts, AccountsExit, CpiAccount, ToAccountInfo,
  3. 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 the program state singleton.
  12. #[derive(Clone)]
  13. pub struct ProgramState<'info, T: AccountSerialize + AccountDeserialize + Clone> {
  14. inner: Box<Inner<'info, T>>,
  15. }
  16. #[derive(Clone)]
  17. struct Inner<'info, T: AccountSerialize + AccountDeserialize + Clone> {
  18. info: AccountInfo<'info>,
  19. account: T,
  20. }
  21. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> ProgramState<'a, T> {
  22. pub fn new(info: AccountInfo<'a>, account: T) -> ProgramState<'a, T> {
  23. Self {
  24. inner: Box::new(Inner { info, account }),
  25. }
  26. }
  27. /// Deserializes the given `info` into a `ProgramState`.
  28. #[inline(never)]
  29. pub fn try_from(info: &AccountInfo<'a>) -> Result<ProgramState<'a, T>, ProgramError> {
  30. let mut data: &[u8] = &info.try_borrow_data()?;
  31. Ok(ProgramState::new(
  32. info.clone(),
  33. T::try_deserialize(&mut data)?,
  34. ))
  35. }
  36. pub fn seed() -> &'static str {
  37. "unversioned"
  38. }
  39. pub fn address(program_id: &Pubkey) -> Pubkey {
  40. let (base, _nonce) = Pubkey::find_program_address(&[], program_id);
  41. let seed = Self::seed();
  42. let owner = program_id;
  43. Pubkey::create_with_seed(&base, seed, owner).unwrap()
  44. }
  45. }
  46. impl<'info, T> Accounts<'info> for ProgramState<'info, T>
  47. where
  48. T: AccountSerialize + AccountDeserialize + Clone,
  49. {
  50. #[inline(never)]
  51. fn try_accounts(
  52. program_id: &Pubkey,
  53. accounts: &mut &[AccountInfo<'info>],
  54. ) -> Result<Self, ProgramError> {
  55. if accounts.len() == 0 {
  56. return Err(ProgramError::NotEnoughAccountKeys);
  57. }
  58. let account = &accounts[0];
  59. *accounts = &accounts[1..];
  60. if account.key != &Self::address(program_id) {
  61. return Err(ProgramError::Custom(1)); // todo: proper error.
  62. }
  63. let pa = ProgramState::try_from(account)?;
  64. if pa.inner.info.owner != program_id {
  65. return Err(ProgramError::Custom(1)); // todo: proper error.
  66. }
  67. Ok(pa)
  68. }
  69. }
  70. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountMetas
  71. for ProgramState<'info, T>
  72. {
  73. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  74. let is_signer = is_signer.unwrap_or(self.inner.info.is_signer);
  75. let meta = match self.inner.info.is_writable {
  76. false => AccountMeta::new_readonly(*self.inner.info.key, is_signer),
  77. true => AccountMeta::new(*self.inner.info.key, is_signer),
  78. };
  79. vec![meta]
  80. }
  81. }
  82. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfos<'info>
  83. for ProgramState<'info, T>
  84. {
  85. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  86. vec![self.inner.info.clone()]
  87. }
  88. }
  89. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfo<'info>
  90. for ProgramState<'info, T>
  91. {
  92. fn to_account_info(&self) -> AccountInfo<'info> {
  93. self.inner.info.clone()
  94. }
  95. }
  96. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> Deref for ProgramState<'a, T> {
  97. type Target = T;
  98. fn deref(&self) -> &Self::Target {
  99. &(*self.inner).account
  100. }
  101. }
  102. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> DerefMut for ProgramState<'a, T> {
  103. fn deref_mut(&mut self) -> &mut Self::Target {
  104. &mut DerefMut::deref_mut(&mut self.inner).account
  105. }
  106. }
  107. impl<'info, T> From<CpiAccount<'info, T>> for ProgramState<'info, T>
  108. where
  109. T: AccountSerialize + AccountDeserialize + Clone,
  110. {
  111. fn from(a: CpiAccount<'info, T>) -> Self {
  112. Self::new(a.to_account_info(), Deref::deref(&a).clone())
  113. }
  114. }
  115. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AccountsExit<'info>
  116. for ProgramState<'info, T>
  117. {
  118. fn exit(&self, _program_id: &Pubkey) -> ProgramResult {
  119. let info = self.to_account_info();
  120. let mut data = info.try_borrow_mut_data()?;
  121. let dst: &mut [u8] = &mut data;
  122. let mut cursor = std::io::Cursor::new(dst);
  123. self.inner.account.try_serialize(&mut cursor)?;
  124. Ok(())
  125. }
  126. }