system_account.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //! Type validating that the account is owned by the system program
  2. use crate::error::ErrorCode;
  3. use crate::*;
  4. use solana_program::account_info::AccountInfo;
  5. use solana_program::instruction::AccountMeta;
  6. use solana_program::pubkey::Pubkey;
  7. use solana_program::system_program;
  8. use std::collections::BTreeSet;
  9. use std::ops::Deref;
  10. /// Type validating that the account is owned by the system program
  11. ///
  12. /// Checks:
  13. ///
  14. /// - `SystemAccount.info.owner == SystemProgram`
  15. #[derive(Debug, Clone)]
  16. pub struct SystemAccount<'info> {
  17. info: AccountInfo<'info>,
  18. }
  19. impl<'info> SystemAccount<'info> {
  20. fn new(info: AccountInfo<'info>) -> SystemAccount<'info> {
  21. Self { info }
  22. }
  23. #[inline(never)]
  24. pub fn try_from(info: &AccountInfo<'info>) -> Result<SystemAccount<'info>> {
  25. if *info.owner != system_program::ID {
  26. return Err(ErrorCode::AccountNotSystemOwned.into());
  27. }
  28. Ok(SystemAccount::new(info.clone()))
  29. }
  30. }
  31. impl<'info, B> Accounts<'info, B> for SystemAccount<'info> {
  32. #[inline(never)]
  33. fn try_accounts(
  34. _program_id: &Pubkey,
  35. accounts: &mut &[AccountInfo<'info>],
  36. _ix_data: &[u8],
  37. _bumps: &mut B,
  38. _reallocs: &mut BTreeSet<Pubkey>,
  39. ) -> Result<Self> {
  40. if accounts.is_empty() {
  41. return Err(ErrorCode::AccountNotEnoughKeys.into());
  42. }
  43. let account = &accounts[0];
  44. *accounts = &accounts[1..];
  45. SystemAccount::try_from(account)
  46. }
  47. }
  48. impl<'info> AccountsExit<'info> for SystemAccount<'info> {}
  49. impl<'info> ToAccountMetas for SystemAccount<'info> {
  50. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  51. let is_signer = is_signer.unwrap_or(self.info.is_signer);
  52. let meta = match self.info.is_writable {
  53. false => AccountMeta::new_readonly(*self.info.key, is_signer),
  54. true => AccountMeta::new(*self.info.key, is_signer),
  55. };
  56. vec![meta]
  57. }
  58. }
  59. impl<'info> ToAccountInfos<'info> for SystemAccount<'info> {
  60. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  61. vec![self.info.clone()]
  62. }
  63. }
  64. impl<'info> AsRef<AccountInfo<'info>> for SystemAccount<'info> {
  65. fn as_ref(&self) -> &AccountInfo<'info> {
  66. &self.info
  67. }
  68. }
  69. impl<'info> Deref for SystemAccount<'info> {
  70. type Target = AccountInfo<'info>;
  71. fn deref(&self) -> &Self::Target {
  72. &self.info
  73. }
  74. }
  75. impl<'info> Key for SystemAccount<'info> {
  76. fn key(&self) -> Pubkey {
  77. *self.info.key
  78. }
  79. }