unchecked_account.rs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //! Explicit wrapper for AccountInfo types to emphasize
  2. //! that no checks are performed
  3. use crate::error::ErrorCode;
  4. use crate::{Accounts, AccountsExit, Key, Result, ToAccountInfos, ToAccountMetas};
  5. use solana_program::account_info::AccountInfo;
  6. use solana_program::instruction::AccountMeta;
  7. use solana_program::pubkey::Pubkey;
  8. use std::collections::BTreeSet;
  9. use std::ops::Deref;
  10. /// Explicit wrapper for AccountInfo types to emphasize
  11. /// that no checks are performed
  12. #[derive(Debug, Clone)]
  13. pub struct UncheckedAccount<'info>(&'info AccountInfo<'info>);
  14. impl<'info> UncheckedAccount<'info> {
  15. pub fn try_from(acc_info: &'info AccountInfo<'info>) -> Self {
  16. Self(acc_info)
  17. }
  18. }
  19. impl<'info, B> Accounts<'info, B> for UncheckedAccount<'info> {
  20. fn try_accounts(
  21. _program_id: &Pubkey,
  22. accounts: &mut &'info [AccountInfo<'info>],
  23. _ix_data: &[u8],
  24. _bumps: &mut B,
  25. _reallocs: &mut BTreeSet<Pubkey>,
  26. ) -> Result<Self> {
  27. if accounts.is_empty() {
  28. return Err(ErrorCode::AccountNotEnoughKeys.into());
  29. }
  30. let account = &accounts[0];
  31. *accounts = &accounts[1..];
  32. Ok(UncheckedAccount(account))
  33. }
  34. }
  35. impl<'info> ToAccountMetas for UncheckedAccount<'info> {
  36. fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
  37. let is_signer = is_signer.unwrap_or(self.is_signer);
  38. let meta = match self.is_writable {
  39. false => AccountMeta::new_readonly(*self.key, is_signer),
  40. true => AccountMeta::new(*self.key, is_signer),
  41. };
  42. vec![meta]
  43. }
  44. }
  45. impl<'info> ToAccountInfos<'info> for UncheckedAccount<'info> {
  46. fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
  47. vec![self.0.clone()]
  48. }
  49. }
  50. impl<'info> AccountsExit<'info> for UncheckedAccount<'info> {}
  51. impl<'info> AsRef<AccountInfo<'info>> for UncheckedAccount<'info> {
  52. fn as_ref(&self) -> &AccountInfo<'info> {
  53. self.0
  54. }
  55. }
  56. impl<'info> Deref for UncheckedAccount<'info> {
  57. type Target = AccountInfo<'info>;
  58. fn deref(&self) -> &Self::Target {
  59. self.0
  60. }
  61. }
  62. impl<'info> Key for UncheckedAccount<'info> {
  63. fn key(&self) -> Pubkey {
  64. *self.0.key
  65. }
  66. }