use {
crate::{
bpf_writer::BpfWriter,
error::{Error, ErrorCode},
solana_program::{
account_info::AccountInfo, instruction::AccountMeta, pubkey::Pubkey, system_program,
},
AccountDeserialize, AccountSerialize, Accounts, AccountsClose, AccountsExit, Key, Owner,
Result, ToAccountInfos, ToAccountMetas,
},
std::{
collections::BTreeSet,
fmt,
ops::{Deref, DerefMut},
},
};
#[derive(Clone)]
pub struct Account<'info, T: AccountSerialize + AccountDeserialize + Clone> {
account: T,
info: &'info AccountInfo<'info>,
}
impl<T: AccountSerialize + AccountDeserialize + Clone + fmt::Debug> fmt::Debug for Account<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.fmt_with_name("Account", f)
}
}
impl<T: AccountSerialize + AccountDeserialize + Clone + fmt::Debug> Account<'_, T> {
pub(crate) fn fmt_with_name(&self, name: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(name)
.field("account", &self.account)
.field("info", &self.info)
.finish()
}
}
impl<'a, T: AccountSerialize + AccountDeserialize + Clone> Account<'a, T> {
pub(crate) fn new(info: &'a AccountInfo<'a>, account: T) -> Account<'a, T> {
Self { info, account }
}
pub(crate) fn exit_with_expected_owner(
&self,
expected_owner: &Pubkey,
program_id: &Pubkey,
) -> Result<()> {
if expected_owner == program_id && !crate::common::is_closed(self.info) {
let mut data = self.info.try_borrow_mut_data()?;
let dst: &mut [u8] = &mut data;
let mut writer = BpfWriter::new(dst);
self.account.try_serialize(&mut writer)?;
}
Ok(())
}
pub fn into_inner(self) -> T {
self.account
}
pub fn set_inner(&mut self, inner: T) {
self.account = inner;
}
}
impl<'a, T: AccountSerialize + AccountDeserialize + Owner + Clone> Account<'a, T> {
pub fn reload(&mut self) -> Result<()> {
if self.info.owner != &T::owner() {
return Err(Error::from(ErrorCode::AccountOwnedByWrongProgram)
.with_pubkeys((*self.info.owner, T::owner())));
}
let mut data: &[u8] = &self.info.try_borrow_data()?;
self.account = T::try_deserialize(&mut data)?;
Ok(())
}
#[inline(never)]
pub fn try_from(info: &'a AccountInfo<'a>) -> Result<Account<'a, T>> {
if info.owner == &system_program::ID && info.lamports() == 0 {
return Err(ErrorCode::AccountNotInitialized.into());
}
if info.owner != &T::owner() {
return Err(Error::from(ErrorCode::AccountOwnedByWrongProgram)
.with_pubkeys((*info.owner, T::owner())));
}
let mut data: &[u8] = &info.try_borrow_data()?;
Ok(Account::new(info, T::try_deserialize(&mut data)?))
}
#[inline(never)]
pub fn try_from_unchecked(info: &'a AccountInfo<'a>) -> Result<Account<'a, T>> {
if info.owner == &system_program::ID && info.lamports() == 0 {
return Err(ErrorCode::AccountNotInitialized.into());
}
if info.owner != &T::owner() {
return Err(Error::from(ErrorCode::AccountOwnedByWrongProgram)
.with_pubkeys((*info.owner, T::owner())));
}
let mut data: &[u8] = &info.try_borrow_data()?;
Ok(Account::new(info, T::try_deserialize_unchecked(&mut data)?))
}
}
impl<'info, B, T: AccountSerialize + AccountDeserialize + Owner + Clone> Accounts<'info, B>
for Account<'info, T>
where
T: AccountSerialize + AccountDeserialize + Owner + Clone,
{
#[inline(never)]
fn try_accounts(
_program_id: &Pubkey,
accounts: &mut &'info [AccountInfo<'info>],
_ix_data: &[u8],
_bumps: &mut B,
_reallocs: &mut BTreeSet<Pubkey>,
) -> Result<Self> {
if accounts.is_empty() {
return Err(ErrorCode::AccountNotEnoughKeys.into());
}
let account = &accounts[0];
*accounts = &accounts[1..];
Account::try_from(account)
}
}
impl<'info, T: AccountSerialize + AccountDeserialize + Owner + Clone> AccountsExit<'info>
for Account<'info, T>
{
fn exit(&self, program_id: &Pubkey) -> Result<()> {
self.exit_with_expected_owner(&T::owner(), program_id)
}
}
impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AccountsClose<'info>
for Account<'info, T>
{
fn close(&self, sol_destination: AccountInfo<'info>) -> Result<()> {
crate::common::close(self.as_ref(), sol_destination.as_ref())
}
}
impl<T: AccountSerialize + AccountDeserialize + Clone> ToAccountMetas for Account<'_, T> {
fn to_account_metas(&self, is_signer: Option<bool>) -> Vec<AccountMeta> {
let is_signer = is_signer.unwrap_or(self.info.is_signer);
let meta = match self.info.is_writable {
false => AccountMeta::new_readonly(*self.info.key, is_signer),
true => AccountMeta::new(*self.info.key, is_signer),
};
vec![meta]
}
}
impl<'info, T: AccountSerialize + AccountDeserialize + Clone> ToAccountInfos<'info>
for Account<'info, T>
{
fn to_account_infos(&self) -> Vec<AccountInfo<'info>> {
vec![self.info.clone()]
}
}
impl<'info, T: AccountSerialize + AccountDeserialize + Clone> AsRef<AccountInfo<'info>>
for Account<'info, T>
{
fn as_ref(&self) -> &AccountInfo<'info> {
self.info
}
}
impl<T: AccountSerialize + AccountDeserialize + Clone> AsRef<T> for Account<'_, T> {
fn as_ref(&self) -> &T {
&self.account
}
}
impl<T: AccountSerialize + AccountDeserialize + Clone> Deref for Account<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&(self).account
}
}
impl<T: AccountSerialize + AccountDeserialize + Clone> DerefMut for Account<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
#[cfg(feature = "anchor-debug")]
if !self.info.is_writable {
crate::solana_program::msg!("The given Account is not mutable");
panic!();
}
&mut self.account
}
}
impl<T: AccountSerialize + AccountDeserialize + Clone> Key for Account<'_, T> {
fn key(&self) -> Pubkey {
*self.info.key
}
}