Skip to main content

light_token/
utils.rs

1//! Utility functions and default account configurations.
2
3// Re-export TokenDefaultAccounts from compressed-token-sdk
4pub use light_compressed_token_sdk::utils::TokenDefaultAccounts;
5use light_token_interface::state::Token;
6use solana_account_info::AccountInfo;
7use solana_program_error::ProgramError;
8use solana_pubkey::Pubkey;
9
10use crate::{constants::LIGHT_TOKEN_PROGRAM_ID as PROGRAM_ID, error::TokenSdkError};
11
12/// Returns the associated token address for a given owner and mint.
13pub fn get_associated_token_address(owner: &Pubkey, mint: &Pubkey) -> Pubkey {
14    get_associated_token_address_and_bump(owner, mint).0
15}
16
17/// Returns the associated token address and bump for a given owner and mint.
18pub fn get_associated_token_address_and_bump(owner: &Pubkey, mint: &Pubkey) -> (Pubkey, u8) {
19    Pubkey::find_program_address(
20        &[&owner.to_bytes(), &PROGRAM_ID.to_bytes(), &mint.to_bytes()],
21        &PROGRAM_ID,
22    )
23}
24
25/// Get the token balance from a Light token account.
26pub fn get_token_account_balance(token_account_info: &AccountInfo) -> Result<u64, ProgramError> {
27    Token::amount_from_account_info(token_account_info).map_err(Into::into)
28}
29
30/// Check if an account owner is a Light token program.
31///
32/// Returns `Ok(true)` if owner is `LIGHT_TOKEN_PROGRAM_ID`.
33/// Returns `Ok(false)` if owner is SPL Token or Token-2022.
34/// Returns `Err` if owner is unrecognized.
35pub fn is_light_token_owner(owner: &Pubkey) -> Result<bool, TokenSdkError> {
36    let light_token_program_id = PROGRAM_ID;
37
38    if owner == &light_token_program_id {
39        return Ok(true);
40    }
41
42    let spl_token = Pubkey::from(light_token_types::SPL_TOKEN_PROGRAM_ID);
43    let spl_token_2022 = Pubkey::from(light_token_types::SPL_TOKEN_2022_PROGRAM_ID);
44
45    if owner == &spl_token_2022 || owner == &spl_token {
46        return Ok(false);
47    }
48
49    Err(TokenSdkError::CannotDetermineAccountType)
50}
51
52/// Check if an account is a Light token account (by checking its owner).
53///
54/// Returns `Ok(true)` if owner is `LIGHT_TOKEN_PROGRAM_ID`.
55/// Returns `Ok(false)` if owner is SPL Token or Token-2022.
56/// Returns `Err` if owner is unrecognized.
57pub fn is_token_account(account_info: &AccountInfo) -> Result<bool, TokenSdkError> {
58    is_light_token_owner(account_info.owner)
59}