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_pubkey::Pubkey;
8
9use crate::{constants::LIGHT_TOKEN_PROGRAM_ID as PROGRAM_ID, error::TokenSdkError};
10
11/// Returns the associated token address for a given owner and mint.
12pub fn get_associated_token_address(owner: &Pubkey, mint: &Pubkey) -> Pubkey {
13    get_associated_token_address_and_bump(owner, mint).0
14}
15
16/// Returns the associated token address and bump for a given owner and mint.
17pub fn get_associated_token_address_and_bump(owner: &Pubkey, mint: &Pubkey) -> (Pubkey, u8) {
18    Pubkey::find_program_address(
19        &[&owner.to_bytes(), &PROGRAM_ID.to_bytes(), &mint.to_bytes()],
20        &PROGRAM_ID,
21    )
22}
23
24/// Get the token balance from a Light token account.
25pub fn get_token_account_balance(token_account_info: &AccountInfo) -> Result<u64, TokenSdkError> {
26    let data = token_account_info
27        .try_borrow_data()
28        .map_err(|_| TokenSdkError::AccountBorrowFailed)?;
29    Token::amount_from_slice(&data).map_err(|_| TokenSdkError::InvalidAccountData)
30}
31
32/// Check if an account owner is a Light token program.
33///
34/// Returns `Ok(true)` if owner is `LIGHT_TOKEN_PROGRAM_ID`.
35/// Returns `Ok(false)` if owner is SPL Token or Token-2022.
36/// Returns `Err` if owner is unrecognized.
37pub fn is_light_token_owner(owner: &Pubkey) -> Result<bool, TokenSdkError> {
38    let light_token_program_id = PROGRAM_ID;
39
40    if owner == &light_token_program_id {
41        return Ok(true);
42    }
43
44    let spl_token = Pubkey::from(light_token_types::SPL_TOKEN_PROGRAM_ID);
45    let spl_token_2022 = Pubkey::from(light_token_types::SPL_TOKEN_2022_PROGRAM_ID);
46
47    if owner == &spl_token_2022 || owner == &spl_token {
48        return Ok(false);
49    }
50
51    Err(TokenSdkError::CannotDetermineAccountType)
52}
53
54/// Check if an account is a Light token account (by checking its owner).
55///
56/// Returns `Ok(true)` if owner is `LIGHT_TOKEN_PROGRAM_ID`.
57/// Returns `Ok(false)` if owner is SPL Token or Token-2022.
58/// Returns `Err` if owner is unrecognized.
59pub fn is_token_account(account_info: &AccountInfo) -> Result<bool, TokenSdkError> {
60    is_light_token_owner(account_info.owner)
61}