system_account.rs 2.5 KB

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