gmsol_store/states/common/
token.rs

1use anchor_lang::prelude::*;
2use anchor_spl::{token::TokenAccount, token_interface};
3
4use crate::utils::pubkey::optional_address;
5
6pub use gmsol_utils::token_config::TokensCollector;
7
8/// Token Account.
9#[zero_copy]
10#[cfg_attr(feature = "debug", derive(Debug))]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct TokenAndAccount {
13    /// Token.
14    token: Pubkey,
15    /// Account.
16    account: Pubkey,
17}
18
19impl TokenAndAccount {
20    /// Initialize with token account.
21    pub fn init(&mut self, account: &Account<TokenAccount>) {
22        self.token = account.mint;
23        self.account = account.key();
24    }
25
26    /// Initialize with token account interface.
27    pub fn init_with_interface(
28        &mut self,
29        account: &InterfaceAccount<token_interface::TokenAccount>,
30    ) {
31        self.token = account.mint;
32        self.account = account.key();
33    }
34
35    /// Get token.
36    pub fn token(&self) -> Option<Pubkey> {
37        optional_address(&self.token).copied()
38    }
39
40    /// Get account.
41    pub fn account(&self) -> Option<Pubkey> {
42        optional_address(&self.account).copied()
43    }
44
45    /// Get token and account.
46    pub fn token_and_account(&self) -> Option<(Pubkey, Pubkey)> {
47        let token = self.token()?;
48        let account = self.account()?;
49        Some((token, account))
50    }
51}