use hayabusa_errors::Result;
use hayabusa_ser::{FromBytesUnchecked, RawZcDeserialize, Zc, Deserialize};
use hayabusa_utility::fail_with_ctx;
use pinocchio::{
account_info::{AccountInfo, Ref}, hint::unlikely, program_error::ProgramError, pubkey::Pubkey
};
#[repr(C)]
pub struct Mint {
mint_authority_flag: [u8; 4],
mint_authority: Pubkey,
supply: [u8; 8],
decimals: u8,
is_initialized: u8,
freeze_authority_flag: [u8; 4],
freeze_authority: Pubkey,
}
impl Zc for Mint {}
impl Deserialize for Mint {}
unsafe impl RawZcDeserialize for Mint {
fn try_deserialize_raw<'a>(account_info: &'a AccountInfo) -> Result<Ref<'a, Self>> {
if unlikely(account_info.data_len() != Self::LEN) {
fail_with_ctx!(
"HAYABUSA_SER_MINT_DATA_TOO_SHORT",
ProgramError::InvalidAccountData,
account_info.key(),
&u32::to_le_bytes(account_info.data_len() as u32),
);
}
if unlikely(!account_info.is_owned_by(&crate::ID)) {
fail_with_ctx!(
"HAYABUSA_SER_MINT_INVALID_ACCOUNT_OWNER",
ProgramError::InvalidAccountOwner,
account_info.key(),
account_info.owner(),
);
}
Ok(Ref::map(account_info.try_borrow_data()?, |d| unsafe {
Self::from_bytes_unchecked(d)
}))
}
}
impl FromBytesUnchecked for Mint {}
impl Mint {
pub const LEN: usize = core::mem::size_of::<Mint>();
#[inline(always)]
pub fn has_mint_authority(&self) -> bool {
self.mint_authority_flag[0] == 1
}
pub fn mint_authority(&self) -> Option<&Pubkey> {
if self.has_mint_authority() {
Some(self.mint_authority_unchecked())
} else {
None
}
}
#[inline(always)]
pub fn mint_authority_unchecked(&self) -> &Pubkey {
&self.mint_authority
}
pub fn supply(&self) -> u64 {
u64::from_le_bytes(self.supply)
}
pub fn decimals(&self) -> u8 {
self.decimals
}
pub fn is_initialized(&self) -> bool {
self.is_initialized == 1
}
#[inline(always)]
pub fn has_freeze_authority(&self) -> bool {
self.freeze_authority_flag[0] == 1
}
pub fn freeze_authority(&self) -> Option<&Pubkey> {
if self.has_freeze_authority() {
Some(self.freeze_authority_unchecked())
} else {
None
}
}
#[inline(always)]
pub fn freeze_authority_unchecked(&self) -> &Pubkey {
&self.freeze_authority
}
}