Skip to main content

simulator_api/
token.rs

1//! The SPL token-account layout shared by Token and Token-2022: build one, read its balance and
2//! mint, or re-balance an existing one.
3
4use solana_address::Address;
5use solana_program_pack::Pack;
6use spl_token_2022_interface::{
7    extension::{StateWithExtensions, StateWithExtensionsMut},
8    state::{Account, AccountState},
9};
10use thiserror::Error;
11
12use crate::{AccountData, BinaryEncoding, EncodedBinary, mints};
13
14/// Base SPL token-account length; Token-2022 extensions follow it.
15pub const TOKEN_ACCOUNT_LEN: usize = Account::LEN;
16/// Rent-exempt minimum for a base-length token account.
17pub const TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS: u64 = 2_039_280;
18/// The Token-2022 program.
19pub const TOKEN_2022_PROGRAM_ID: Address = spl_token_2022_interface::ID;
20
21/// The program that owns a token account, and so defines its layout.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum TokenProgram {
24    /// The original SPL Token program.
25    Token,
26    /// Token-2022, whose accounts may carry extensions after the base layout.
27    Token2022,
28}
29
30impl TokenProgram {
31    /// Both programs.
32    pub const ALL: [Self; 2] = [Self::Token, Self::Token2022];
33
34    /// The program's address.
35    pub const fn id(self) -> Address {
36        match self {
37            Self::Token => spl_token_interface::ID,
38            Self::Token2022 => TOKEN_2022_PROGRAM_ID,
39        }
40    }
41
42    /// The program owning an account; `None` for any owner other than Token or Token-2022.
43    pub fn of(owner: &Address) -> Option<Self> {
44        Self::ALL.into_iter().find(|program| program.id() == *owner)
45    }
46}
47
48/// Why [`set_token_amount`] could not re-balance an account.
49#[derive(Debug, Error, PartialEq, Eq)]
50pub enum TokenAccountError {
51    /// The account's owner, which is neither Token nor Token-2022.
52    #[error("{0} is not a token program")]
53    NotATokenProgram(Address),
54    /// The data is too short, uninitialized, a mint, or carries an invalid `is_native` tag.
55    #[error("not an initialized token account ({len} bytes)")]
56    NotATokenAccount {
57        /// Length of the rejected data, in bytes.
58        len: usize,
59    },
60}
61
62/// `amount` of an initialized token account; `None` for a mint, a closed account or short data.
63pub fn token_amount(data: &[u8]) -> Option<u64> {
64    unpack(data).map(|account| account.amount)
65}
66
67/// `mint` of an initialized token account; `None` for a mint, a closed account or short data.
68pub fn token_mint(data: &[u8]) -> Option<Address> {
69    unpack(data).map(|account| account.mint)
70}
71
72/// An initialized 165-byte account holding `amount` of `mint`. Wrapped SOL under Token gets
73/// `is_native = Some(rent)` and `rent + amount` lamports, otherwise SyncNative/transfers revert.
74/// Token-2022 mints whose transfers need account extensions (fee, hook, pausable) need the
75/// real account re-balanced with [`with_token_amount`] instead.
76pub fn token_account(
77    program: TokenProgram,
78    mint: Address,
79    owner: Address,
80    amount: u64,
81) -> AccountData {
82    let native = program == TokenProgram::Token && mint == mints::SOL;
83    let mut data = [0; TOKEN_ACCOUNT_LEN];
84    Account {
85        mint,
86        owner,
87        amount,
88        state: AccountState::Initialized,
89        is_native: native.then_some(TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS).into(),
90        ..Account::default()
91    }
92    .pack_into_slice(&mut data);
93    let lamports = if native {
94        TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS.saturating_add(amount)
95    } else {
96        TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS
97    };
98
99    AccountData {
100        data: EncodedBinary::from_bytes(&data, BinaryEncoding::Base64),
101        executable: false,
102        lamports,
103        owner: program.id(),
104        space: TOKEN_ACCOUNT_LEN as u64,
105    }
106}
107
108/// `account` re-balanced to `amount` as [`set_token_amount`] does, failing as it does.
109pub fn with_token_amount(
110    account: &solana_account::Account,
111    amount: u64,
112) -> Result<AccountData, TokenAccountError> {
113    let mut patched = account.clone();
114    set_token_amount(&mut patched, amount)?;
115    Ok(AccountData::from(&patched))
116}
117
118/// Sets `account`'s balance to `amount`, keeping every other byte; a native account's lamports
119/// become its stored reserve plus `amount`.
120/// Errors, leaving `account` unchanged, unless it is an initialized token account.
121pub fn set_token_amount(
122    account: &mut solana_account::Account,
123    amount: u64,
124) -> Result<(), TokenAccountError> {
125    if TokenProgram::of(&account.owner).is_none() {
126        return Err(TokenAccountError::NotATokenProgram(account.owner));
127    }
128    let len = account.data.len();
129    #[expect(
130        clippy::map_err_ignore,
131        reason = "ProgramError from unpack adds no detail beyond the account data length"
132    )]
133    let mut state = StateWithExtensionsMut::<Account>::unpack(&mut account.data)
134        .map_err(|_| TokenAccountError::NotATokenAccount { len })?;
135    state.base.amount = amount;
136    state.pack_base();
137    if let Some(reserve) = Option::<u64>::from(state.base.is_native) {
138        account.lamports = reserve.saturating_add(amount);
139    }
140    Ok(())
141}
142
143fn unpack(data: &[u8]) -> Option<Account> {
144    StateWithExtensions::<Account>::unpack(data)
145        .ok()
146        .map(|state| state.base)
147}
148
149#[cfg(test)]
150mod tests {
151    use rstest::rstest;
152    use spl_token_2022_interface::{
153        extension::AccountType, generic_token_account::ACCOUNT_INITIALIZED_INDEX,
154    };
155
156    use super::*;
157
158    const AMOUNT_VALUE: u64 = 4_200;
159
160    fn mint() -> Address {
161        Address::from([7; 32])
162    }
163
164    fn holder() -> Address {
165        Address::from([8; 32])
166    }
167
168    fn account(owner: Address, data: Vec<u8>, lamports: u64) -> solana_account::Account {
169        solana_account::Account {
170            lamports,
171            data,
172            owner,
173            ..Default::default()
174        }
175    }
176
177    /// A Token-2022 account with its account-type byte and an opaque extension tail.
178    fn extended(base: &AccountData) -> Vec<u8> {
179        let mut data = base.data.decode().unwrap();
180        data.push(AccountType::Account.into());
181        data.extend([0xAB; 12]);
182        data
183    }
184
185    #[rstest]
186    #[case::token(TokenProgram::Token, mint(), None)]
187    #[case::token_wrapped_sol(
188        TokenProgram::Token,
189        mints::SOL,
190        Some(TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS)
191    )]
192    #[case::token_2022(TokenProgram::Token2022, mint(), None)]
193    #[case::token_2022_with_the_token_native_mint(TokenProgram::Token2022, mints::SOL, None)]
194    fn the_builder_round_trips_through_spl(
195        #[case] program: TokenProgram,
196        #[case] mint: Address,
197        #[case] is_native: Option<u64>,
198    ) {
199        let built = token_account(program, mint, holder(), AMOUNT_VALUE);
200        let unpacked = Account::unpack(&built.data.decode().unwrap()).unwrap();
201
202        assert_eq!(
203            (
204                unpacked.mint,
205                unpacked.owner,
206                unpacked.amount,
207                unpacked.state,
208                Option::<u64>::from(unpacked.is_native),
209            ),
210            (
211                mint,
212                holder(),
213                AMOUNT_VALUE,
214                AccountState::Initialized,
215                is_native
216            )
217        );
218        assert_eq!(
219            built.lamports,
220            TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS + is_native.map_or(0, |_| AMOUNT_VALUE)
221        );
222        assert_eq!(built.space, TOKEN_ACCOUNT_LEN as u64);
223        assert_eq!(built.owner, program.id());
224    }
225
226    #[test]
227    fn the_rent_exempt_minimum_matches_the_default_rent() {
228        assert_eq!(
229            TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS,
230            solana_rent::Rent::default().minimum_balance(TOKEN_ACCOUNT_LEN)
231        );
232    }
233
234    #[test]
235    fn a_system_owner_is_not_a_token_program() {
236        assert_eq!(TokenProgram::of(&solana_sdk_ids::system_program::ID), None);
237        assert_eq!(
238            with_token_amount(&account(solana_sdk_ids::system_program::ID, vec![], 1), 1).err(),
239            Some(TokenAccountError::NotATokenProgram(
240                solana_sdk_ids::system_program::ID
241            ))
242        );
243    }
244
245    #[test]
246    fn a_native_account_takes_its_stored_reserve_plus_the_amount() {
247        let reserve: u64 = 3_000_000;
248        let mut data = vec![0; TOKEN_ACCOUNT_LEN];
249        Account {
250            mint: mints::SOL,
251            owner: holder(),
252            amount: 1,
253            state: AccountState::Initialized,
254            is_native: Some(reserve).into(),
255            ..Account::default()
256        }
257        .pack_into_slice(&mut data);
258        let native = account(spl_token_interface::ID, data, 1);
259
260        let patched = with_token_amount(&native, AMOUNT_VALUE).unwrap();
261
262        assert_eq!(patched.lamports, reserve + AMOUNT_VALUE);
263        assert_eq!(
264            token_amount(&patched.data.decode().unwrap()),
265            Some(AMOUNT_VALUE)
266        );
267    }
268
269    #[test]
270    fn a_non_native_account_keeps_its_lamports() {
271        let data = token_account(TokenProgram::Token, mint(), holder(), 1)
272            .data
273            .decode()
274            .unwrap();
275
276        let patched =
277            with_token_amount(&account(spl_token_interface::ID, data, 99), AMOUNT_VALUE).unwrap();
278
279        assert_eq!(patched.lamports, 99);
280    }
281
282    #[test]
283    fn an_extended_token_2022_account_keeps_every_byte_but_its_amount() {
284        let data = extended(&token_account(TokenProgram::Token2022, mint(), holder(), 1));
285        let patched = with_token_amount(
286            &account(TOKEN_2022_PROGRAM_ID, data.clone(), 5),
287            AMOUNT_VALUE,
288        )
289        .unwrap()
290        .data
291        .decode()
292        .unwrap();
293
294        assert_eq!(patched.len(), data.len());
295        assert_eq!(patched[TOKEN_ACCOUNT_LEN..], data[TOKEN_ACCOUNT_LEN..]);
296        assert_eq!(
297            Account::unpack(&patched[..TOKEN_ACCOUNT_LEN]).unwrap(),
298            Account {
299                amount: AMOUNT_VALUE,
300                ..Account::unpack(&data[..TOKEN_ACCOUNT_LEN]).unwrap()
301            }
302        );
303        assert_eq!(token_amount(&patched), Some(AMOUNT_VALUE));
304        assert_eq!(token_mint(&patched), Some(mint()));
305    }
306
307    #[rstest]
308    #[case::short(vec![1; 64])]
309    #[case::uninitialized(vec![0; TOKEN_ACCOUNT_LEN])]
310    #[case::bad_native_tag({
311        let mut data = token_account(TokenProgram::Token, mint(), holder(), 1).data.decode().unwrap();
312        data[ACCOUNT_INITIALIZED_INDEX + 1] = 2;
313        data
314    })]
315    fn data_that_is_not_an_initialized_token_account_is_rejected(#[case] data: Vec<u8>) {
316        let len = data.len();
317        assert_eq!(
318            with_token_amount(&account(spl_token_interface::ID, data, 1), 1).err(),
319            Some(TokenAccountError::NotATokenAccount { len })
320        );
321    }
322
323    #[rstest]
324    #[case::mint(vec![1; 82])]
325    #[case::short(vec![1; 64])]
326    #[case::uninitialized(vec![0; TOKEN_ACCOUNT_LEN])]
327    #[case::extended_mint({
328        let mut data = vec![1; TOKEN_ACCOUNT_LEN + 8];
329        data[TOKEN_ACCOUNT_LEN] = AccountType::Mint.into();
330        data
331    })]
332    fn readers_see_nothing_in_data_that_is_not_a_token_account(#[case] data: Vec<u8>) {
333        assert_eq!((token_amount(&data), token_mint(&data)), (None, None));
334    }
335
336    #[rstest]
337    #[case::base(token_account(TokenProgram::Token, mint(), holder(), AMOUNT_VALUE).data.decode().unwrap())]
338    #[case::extended(extended(&token_account(TokenProgram::Token2022, mint(), holder(), AMOUNT_VALUE)))]
339    fn readers_see_a_token_account_balance_and_mint(#[case] data: Vec<u8>) {
340        assert_eq!(
341            (token_amount(&data), token_mint(&data)),
342            (Some(AMOUNT_VALUE), Some(mint()))
343        );
344    }
345
346    #[test]
347    fn a_native_balance_of_u64_max_saturates() {
348        let built = token_account(TokenProgram::Token, mints::SOL, holder(), u64::MAX);
349        assert_eq!(built.lamports, u64::MAX);
350
351        let native = account(spl_token_interface::ID, built.data.decode().unwrap(), 1);
352        assert_eq!(
353            with_token_amount(&native, u64::MAX).unwrap().lamports,
354            u64::MAX
355        );
356    }
357}