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 [`with_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` with its balance set to `amount` and every other byte kept. A native account's
109/// lamports become its stored reserve plus `amount`.
110///
111/// Errors when the owner is not a token program, or the data is not an initialized token account
112/// with a valid `is_native` tag.
113pub fn with_token_amount(
114    account: &solana_account::Account,
115    amount: u64,
116) -> Result<AccountData, TokenAccountError> {
117    if TokenProgram::of(&account.owner).is_none() {
118        return Err(TokenAccountError::NotATokenProgram(account.owner));
119    }
120    let mut patched = account.clone();
121    let mut state = StateWithExtensionsMut::<Account>::unpack(&mut patched.data).map_err(|_| {
122        TokenAccountError::NotATokenAccount {
123            len: account.data.len(),
124        }
125    })?;
126    state.base.amount = amount;
127    state.pack_base();
128    if let Some(reserve) = Option::<u64>::from(state.base.is_native) {
129        patched.lamports = reserve.saturating_add(amount);
130    }
131    Ok(AccountData::from(&patched))
132}
133
134fn unpack(data: &[u8]) -> Option<Account> {
135    StateWithExtensions::<Account>::unpack(data)
136        .ok()
137        .map(|state| state.base)
138}
139
140#[cfg(test)]
141mod tests {
142    use rstest::rstest;
143    use spl_token_2022_interface::{
144        extension::AccountType, generic_token_account::ACCOUNT_INITIALIZED_INDEX,
145    };
146
147    use super::*;
148
149    const AMOUNT_VALUE: u64 = 4_200;
150
151    fn mint() -> Address {
152        Address::from([7; 32])
153    }
154
155    fn holder() -> Address {
156        Address::from([8; 32])
157    }
158
159    fn account(owner: Address, data: Vec<u8>, lamports: u64) -> solana_account::Account {
160        solana_account::Account {
161            lamports,
162            data,
163            owner,
164            ..Default::default()
165        }
166    }
167
168    /// A Token-2022 account with its account-type byte and an opaque extension tail.
169    fn extended(base: &AccountData) -> Vec<u8> {
170        let mut data = base.data.decode().unwrap();
171        data.push(AccountType::Account.into());
172        data.extend([0xAB; 12]);
173        data
174    }
175
176    #[rstest]
177    #[case::token(TokenProgram::Token, mint(), None)]
178    #[case::token_wrapped_sol(
179        TokenProgram::Token,
180        mints::SOL,
181        Some(TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS)
182    )]
183    #[case::token_2022(TokenProgram::Token2022, mint(), None)]
184    #[case::token_2022_with_the_token_native_mint(TokenProgram::Token2022, mints::SOL, None)]
185    fn the_builder_round_trips_through_spl(
186        #[case] program: TokenProgram,
187        #[case] mint: Address,
188        #[case] is_native: Option<u64>,
189    ) {
190        let built = token_account(program, mint, holder(), AMOUNT_VALUE);
191        let unpacked = Account::unpack(&built.data.decode().unwrap()).unwrap();
192
193        assert_eq!(
194            (
195                unpacked.mint,
196                unpacked.owner,
197                unpacked.amount,
198                unpacked.state,
199                Option::<u64>::from(unpacked.is_native),
200            ),
201            (
202                mint,
203                holder(),
204                AMOUNT_VALUE,
205                AccountState::Initialized,
206                is_native
207            )
208        );
209        assert_eq!(
210            built.lamports,
211            TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS + is_native.map_or(0, |_| AMOUNT_VALUE)
212        );
213        assert_eq!(built.space, TOKEN_ACCOUNT_LEN as u64);
214        assert_eq!(built.owner, program.id());
215    }
216
217    #[test]
218    fn the_rent_exempt_minimum_matches_the_default_rent() {
219        assert_eq!(
220            TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS,
221            solana_rent::Rent::default().minimum_balance(TOKEN_ACCOUNT_LEN)
222        );
223    }
224
225    #[test]
226    fn a_system_owner_is_not_a_token_program() {
227        assert_eq!(TokenProgram::of(&solana_sdk_ids::system_program::ID), None);
228        assert_eq!(
229            with_token_amount(&account(solana_sdk_ids::system_program::ID, vec![], 1), 1).err(),
230            Some(TokenAccountError::NotATokenProgram(
231                solana_sdk_ids::system_program::ID
232            ))
233        );
234    }
235
236    #[test]
237    fn a_native_account_takes_its_stored_reserve_plus_the_amount() {
238        let reserve: u64 = 3_000_000;
239        let mut data = vec![0; TOKEN_ACCOUNT_LEN];
240        Account {
241            mint: mints::SOL,
242            owner: holder(),
243            amount: 1,
244            state: AccountState::Initialized,
245            is_native: Some(reserve).into(),
246            ..Account::default()
247        }
248        .pack_into_slice(&mut data);
249        let native = account(spl_token_interface::ID, data, 1);
250
251        let patched = with_token_amount(&native, AMOUNT_VALUE).unwrap();
252
253        assert_eq!(patched.lamports, reserve + AMOUNT_VALUE);
254        assert_eq!(
255            token_amount(&patched.data.decode().unwrap()),
256            Some(AMOUNT_VALUE)
257        );
258    }
259
260    #[test]
261    fn a_non_native_account_keeps_its_lamports() {
262        let data = token_account(TokenProgram::Token, mint(), holder(), 1)
263            .data
264            .decode()
265            .unwrap();
266
267        let patched =
268            with_token_amount(&account(spl_token_interface::ID, data, 99), AMOUNT_VALUE).unwrap();
269
270        assert_eq!(patched.lamports, 99);
271    }
272
273    #[test]
274    fn an_extended_token_2022_account_keeps_every_byte_but_its_amount() {
275        let data = extended(&token_account(TokenProgram::Token2022, mint(), holder(), 1));
276        let patched = with_token_amount(
277            &account(TOKEN_2022_PROGRAM_ID, data.clone(), 5),
278            AMOUNT_VALUE,
279        )
280        .unwrap()
281        .data
282        .decode()
283        .unwrap();
284
285        assert_eq!(patched.len(), data.len());
286        assert_eq!(patched[TOKEN_ACCOUNT_LEN..], data[TOKEN_ACCOUNT_LEN..]);
287        assert_eq!(
288            Account::unpack(&patched[..TOKEN_ACCOUNT_LEN]).unwrap(),
289            Account {
290                amount: AMOUNT_VALUE,
291                ..Account::unpack(&data[..TOKEN_ACCOUNT_LEN]).unwrap()
292            }
293        );
294        assert_eq!(token_amount(&patched), Some(AMOUNT_VALUE));
295        assert_eq!(token_mint(&patched), Some(mint()));
296    }
297
298    #[rstest]
299    #[case::short(vec![1; 64])]
300    #[case::uninitialized(vec![0; TOKEN_ACCOUNT_LEN])]
301    #[case::bad_native_tag({
302        let mut data = token_account(TokenProgram::Token, mint(), holder(), 1).data.decode().unwrap();
303        data[ACCOUNT_INITIALIZED_INDEX + 1] = 2;
304        data
305    })]
306    fn data_that_is_not_an_initialized_token_account_is_rejected(#[case] data: Vec<u8>) {
307        let len = data.len();
308        assert_eq!(
309            with_token_amount(&account(spl_token_interface::ID, data, 1), 1).err(),
310            Some(TokenAccountError::NotATokenAccount { len })
311        );
312    }
313
314    #[rstest]
315    #[case::mint(vec![1; 82])]
316    #[case::short(vec![1; 64])]
317    #[case::uninitialized(vec![0; TOKEN_ACCOUNT_LEN])]
318    #[case::extended_mint({
319        let mut data = vec![1; TOKEN_ACCOUNT_LEN + 8];
320        data[TOKEN_ACCOUNT_LEN] = AccountType::Mint.into();
321        data
322    })]
323    fn readers_see_nothing_in_data_that_is_not_a_token_account(#[case] data: Vec<u8>) {
324        assert_eq!((token_amount(&data), token_mint(&data)), (None, None));
325    }
326
327    #[rstest]
328    #[case::base(token_account(TokenProgram::Token, mint(), holder(), AMOUNT_VALUE).data.decode().unwrap())]
329    #[case::extended(extended(&token_account(TokenProgram::Token2022, mint(), holder(), AMOUNT_VALUE)))]
330    fn readers_see_a_token_account_balance_and_mint(#[case] data: Vec<u8>) {
331        assert_eq!(
332            (token_amount(&data), token_mint(&data)),
333            (Some(AMOUNT_VALUE), Some(mint()))
334        );
335    }
336
337    #[test]
338    fn a_native_balance_of_u64_max_saturates() {
339        let built = token_account(TokenProgram::Token, mints::SOL, holder(), u64::MAX);
340        assert_eq!(built.lamports, u64::MAX);
341
342        let native = account(spl_token_interface::ID, built.data.decode().unwrap(), 1);
343        assert_eq!(
344            with_token_amount(&native, u64::MAX).unwrap().lamports,
345            u64::MAX
346        );
347    }
348}