mpl_utils/token/
assertions.rs

1use solana_program::{
2    account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError, pubkey,
3    pubkey::Pubkey,
4};
5use spl_token_2022::state::Account;
6
7use crate::assert_initialized;
8
9pub static SPL_TOKEN_PROGRAM_IDS: [Pubkey; 2] = [
10    pubkey!("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
11    pubkey!("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"),
12];
13
14pub trait ToTokenAccount {
15    fn to_token_account(self) -> Account;
16}
17
18impl ToTokenAccount for AccountInfo<'_> {
19    fn to_token_account(self) -> Account {
20        assert_initialized(&self, ProgramError::UninitializedAccount).unwrap()
21    }
22}
23
24impl ToTokenAccount for Account {
25    fn to_token_account(self) -> Account {
26        self
27    }
28}
29
30pub fn assert_token_program_matches_package(
31    token_program_info: &AccountInfo,
32    error: impl Into<ProgramError>,
33) -> ProgramResult {
34    if SPL_TOKEN_PROGRAM_IDS
35        .iter()
36        .any(|program_id| program_id == token_program_info.key)
37    {
38        Ok(())
39    } else {
40        Err(error.into())
41    }
42}
43
44/// Asserts that
45/// * the given token account is initialized
46/// * it's owner matches the provided owner
47/// * it's mint matches the provided mint
48/// * it holds more than than 0 tokens of the given mint.
49/// Accepts either an &AccountInfo or an Account for token_account parameter.
50pub fn assert_holder(
51    token_account: impl ToTokenAccount,
52    owner_info: &AccountInfo,
53    mint_info: &AccountInfo,
54    error: impl Into<ProgramError> + Clone,
55) -> ProgramResult {
56    let token_account: Account = token_account.to_token_account();
57
58    if token_account.owner != *owner_info.key {
59        return Err(error.into());
60    }
61
62    if token_account.mint != *mint_info.key {
63        return Err(error.into());
64    }
65
66    if token_account.amount == 0 {
67        return Err(error.into());
68    }
69
70    Ok(())
71}