state.rs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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.is_empty() {
  56. return Err(ProgramError::NotEnoughAccountKeys);
  57. }
  58. let account = &accounts[0];
  59. *accounts = &accounts[1..];
  60. if account.key != &Self::address(program_id) {
  61. solana_program::msg!("Invalid state address");
  62. return Err(ProgramError::Custom(1)); // todo: proper error.
  63. }
  64. let pa = ProgramState::try_from(account)?;
  65. if pa.inner.info.owner != program_id {
  66. solana_program::msg!("Invalid state owner");
  67. return Err(ProgramError::Custom(1)); // todo: proper error.
  68. }
  69. Ok(pa)
  70. }
  71. }
  72. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountMetas
  73. for ProgramState<'info, T>
  74. {
  75. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  76. let is_signer = is_signer.unwrap_or(self.inner.info.is_signer);
  77. let meta = match self.inner.info.is_writable {
  78. false => AccountMeta::new_readonly(*self.inner.info.key, is_signer),
  79. true => AccountMeta::new(*self.inner.info.key, is_signer),
  80. };
  81. vec![meta]
  82. }
  83. }
  84. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfos<'info>
  85. for ProgramState<'info, T>
  86. {
  87. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  88. vec![self.inner.info.clone()]
  89. }
  90. }
  91. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfo<'info>
  92. for ProgramState<'info, T>
  93. {
  94. fn to_account_info(&self) -> AccountInfo<'info> {
  95. self.inner.info.clone()
  96. }
  97. }
  98. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> Deref for ProgramState<'a, T> {
  99. type Target = T;
  100. fn deref(&self) -> &Self::Target {
  101. &(*self.inner).account
  102. }
  103. }
  104. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> DerefMut for ProgramState<'a, T> {
  105. fn deref_mut(&mut self) -> &mut Self::Target {
  106. &mut DerefMut::deref_mut(&mut self.inner).account
  107. }
  108. }
  109. impl<'info, T> From<CpiAccount<'info, T>> for ProgramState<'info, T>
  110. where
  111. T: AccountSerialize + AccountDeserialize + Clone,
  112. {
  113. fn from(a: CpiAccount<'info, T>) -> Self {
  114. Self::new(a.to_account_info(), Deref::deref(&a).clone())
  115. }
  116. }
  117. impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AccountsExit<'info>
  118. for ProgramState<'info, T>
  119. {
  120. fn exit(&self, _program_id: &Pubkey) -> ProgramResult {
  121. let info = self.to_account_info();
  122. let mut data = info.try_borrow_mut_data()?;
  123. let dst: &mut [u8] = &mut data;
  124. let mut cursor = std::io::Cursor::new(dst);
  125. self.inner.account.try_serialize(&mut cursor)?;
  126. Ok(())
  127. }
  128. }