state.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. use crate::error::ErrorCode;
  2. use crate::{
  3. AccountDeserialize, AccountSerialize, Accounts, AccountsExit, CpiAccount, ToAccountInfo,
  4. ToAccountInfos, ToAccountMetas,
  5. };
  6. use solana_program::account_info::AccountInfo;
  7. use solana_program::entrypoint::ProgramResult;
  8. use solana_program::instruction::AccountMeta;
  9. use solana_program::program_error::ProgramError;
  10. use solana_program::pubkey::Pubkey;
  11. use std::ops::{Deref, DerefMut};
  12. pub const PROGRAM_STATE_SEED: &str = "unversioned";
  13. /// Boxed container for the program state singleton.
  14. #[derive(Clone)]
  15. pub struct ProgramState<'info, T: AccountSerialize + AccountDeserialize + Clone> {
  16. inner: Box<Inner<'info, T>>,
  17. }
  18. #[derive(Clone)]
  19. struct Inner<'info, T: AccountSerialize + AccountDeserialize + Clone> {
  20. info: AccountInfo<'info>,
  21. account: T,
  22. }
  23. impl<'a, T: AccountSerialize + AccountDeserialize + Clone> ProgramState<'a, T> {
  24. pub fn new(info: AccountInfo<'a>, account: T) -> ProgramState<'a, T> {
  25. Self {
  26. inner: Box::new(Inner { info, account }),
  27. }
  28. }
  29. /// Deserializes the given `info` into a `ProgramState`.
  30. #[inline(never)]
  31. pub fn try_from(info: &AccountInfo<'a>) -> Result<ProgramState<'a, T>, ProgramError> {
  32. let mut data: &[u8] = &info.try_borrow_data()?;
  33. Ok(ProgramState::new(
  34. info.clone(),
  35. T::try_deserialize(&mut data)?,
  36. ))
  37. }
  38. pub fn seed() -> &'static str {
  39. PROGRAM_STATE_SEED
  40. }
  41. pub fn address(program_id: &Pubkey) -> Pubkey {
  42. address(program_id)
  43. }
  44. }
  45. impl<'info, T> Accounts<'info> for ProgramState<'info, T>
  46. where
  47. T: AccountSerialize + AccountDeserialize + Clone,
  48. {
  49. #[inline(never)]
  50. fn try_accounts(
  51. program_id: &Pubkey,
  52. accounts: &mut &[AccountInfo<'info>],
  53. _ix_data: &[u8],
  54. ) -> Result<Self, ProgramError> {
  55. if accounts.is_empty() {
  56. return Err(ErrorCode::AccountNotEnoughKeys.into());
  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(ErrorCode::StateInvalidAddress.into());
  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(ErrorCode::AccountNotProgramOwned.into());
  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. }
  129. pub fn address(program_id: &Pubkey) -> Pubkey {
  130. let (base, _nonce) = Pubkey::find_program_address(&[], program_id);
  131. let seed = PROGRAM_STATE_SEED;
  132. let owner = program_id;
  133. Pubkey::create_with_seed(&base, seed, owner).unwrap()
  134. }