simulator-api 0.30.0

Wire-protocol types for the Solana simulator backtest WebSocket API
Documentation
//! The SPL token-account layout shared by Token and Token-2022: build one, read its balance and
//! mint, or re-balance an existing one.

use solana_address::Address;
use solana_program_pack::Pack;
use spl_token_2022_interface::{
    extension::{StateWithExtensions, StateWithExtensionsMut},
    state::{Account, AccountState},
};
use thiserror::Error;

use crate::{AccountData, BinaryEncoding, EncodedBinary, mints};

/// Base SPL token-account length; Token-2022 extensions follow it.
pub const TOKEN_ACCOUNT_LEN: usize = Account::LEN;
/// Rent-exempt minimum for a base-length token account.
pub const TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS: u64 = 2_039_280;
/// The Token-2022 program.
pub const TOKEN_2022_PROGRAM_ID: Address = spl_token_2022_interface::ID;

/// The program that owns a token account, and so defines its layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenProgram {
    /// The original SPL Token program.
    Token,
    /// Token-2022, whose accounts may carry extensions after the base layout.
    Token2022,
}

impl TokenProgram {
    /// Both programs.
    pub const ALL: [Self; 2] = [Self::Token, Self::Token2022];

    /// The program's address.
    pub const fn id(self) -> Address {
        match self {
            Self::Token => spl_token_interface::ID,
            Self::Token2022 => TOKEN_2022_PROGRAM_ID,
        }
    }

    /// The program owning an account; `None` for any owner other than Token or Token-2022.
    pub fn of(owner: &Address) -> Option<Self> {
        Self::ALL.into_iter().find(|program| program.id() == *owner)
    }
}

/// Why [`with_token_amount`] could not re-balance an account.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum TokenAccountError {
    /// The account's owner, which is neither Token nor Token-2022.
    #[error("{0} is not a token program")]
    NotATokenProgram(Address),
    /// The data is too short, uninitialized, a mint, or carries an invalid `is_native` tag.
    #[error("not an initialized token account ({len} bytes)")]
    NotATokenAccount {
        /// Length of the rejected data, in bytes.
        len: usize,
    },
}

/// `amount` of an initialized token account; `None` for a mint, a closed account or short data.
pub fn token_amount(data: &[u8]) -> Option<u64> {
    unpack(data).map(|account| account.amount)
}

/// `mint` of an initialized token account; `None` for a mint, a closed account or short data.
pub fn token_mint(data: &[u8]) -> Option<Address> {
    unpack(data).map(|account| account.mint)
}

/// An initialized 165-byte account holding `amount` of `mint`. Wrapped SOL under Token gets
/// `is_native = Some(rent)` and `rent + amount` lamports, otherwise SyncNative/transfers revert.
/// Token-2022 mints whose transfers need account extensions (fee, hook, pausable) need the
/// real account re-balanced with [`with_token_amount`] instead.
pub fn token_account(
    program: TokenProgram,
    mint: Address,
    owner: Address,
    amount: u64,
) -> AccountData {
    let native = program == TokenProgram::Token && mint == mints::SOL;
    let mut data = [0; TOKEN_ACCOUNT_LEN];
    Account {
        mint,
        owner,
        amount,
        state: AccountState::Initialized,
        is_native: native.then_some(TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS).into(),
        ..Account::default()
    }
    .pack_into_slice(&mut data);
    let lamports = if native {
        TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS.saturating_add(amount)
    } else {
        TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS
    };

    AccountData {
        data: EncodedBinary::from_bytes(&data, BinaryEncoding::Base64),
        executable: false,
        lamports,
        owner: program.id(),
        space: TOKEN_ACCOUNT_LEN as u64,
    }
}

/// `account` with its balance set to `amount` and every other byte kept. A native account's
/// lamports become its stored reserve plus `amount`.
///
/// Errors when the owner is not a token program, or the data is not an initialized token account
/// with a valid `is_native` tag.
pub fn with_token_amount(
    account: &solana_account::Account,
    amount: u64,
) -> Result<AccountData, TokenAccountError> {
    if TokenProgram::of(&account.owner).is_none() {
        return Err(TokenAccountError::NotATokenProgram(account.owner));
    }
    let mut patched = account.clone();
    let mut state = StateWithExtensionsMut::<Account>::unpack(&mut patched.data).map_err(|_| {
        TokenAccountError::NotATokenAccount {
            len: account.data.len(),
        }
    })?;
    state.base.amount = amount;
    state.pack_base();
    if let Some(reserve) = Option::<u64>::from(state.base.is_native) {
        patched.lamports = reserve.saturating_add(amount);
    }
    Ok(AccountData::from(&patched))
}

fn unpack(data: &[u8]) -> Option<Account> {
    StateWithExtensions::<Account>::unpack(data)
        .ok()
        .map(|state| state.base)
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use spl_token_2022_interface::{
        extension::AccountType, generic_token_account::ACCOUNT_INITIALIZED_INDEX,
    };

    use super::*;

    const AMOUNT_VALUE: u64 = 4_200;

    fn mint() -> Address {
        Address::from([7; 32])
    }

    fn holder() -> Address {
        Address::from([8; 32])
    }

    fn account(owner: Address, data: Vec<u8>, lamports: u64) -> solana_account::Account {
        solana_account::Account {
            lamports,
            data,
            owner,
            ..Default::default()
        }
    }

    /// A Token-2022 account with its account-type byte and an opaque extension tail.
    fn extended(base: &AccountData) -> Vec<u8> {
        let mut data = base.data.decode().unwrap();
        data.push(AccountType::Account.into());
        data.extend([0xAB; 12]);
        data
    }

    #[rstest]
    #[case::token(TokenProgram::Token, mint(), None)]
    #[case::token_wrapped_sol(
        TokenProgram::Token,
        mints::SOL,
        Some(TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS)
    )]
    #[case::token_2022(TokenProgram::Token2022, mint(), None)]
    #[case::token_2022_with_the_token_native_mint(TokenProgram::Token2022, mints::SOL, None)]
    fn the_builder_round_trips_through_spl(
        #[case] program: TokenProgram,
        #[case] mint: Address,
        #[case] is_native: Option<u64>,
    ) {
        let built = token_account(program, mint, holder(), AMOUNT_VALUE);
        let unpacked = Account::unpack(&built.data.decode().unwrap()).unwrap();

        assert_eq!(
            (
                unpacked.mint,
                unpacked.owner,
                unpacked.amount,
                unpacked.state,
                Option::<u64>::from(unpacked.is_native),
            ),
            (
                mint,
                holder(),
                AMOUNT_VALUE,
                AccountState::Initialized,
                is_native
            )
        );
        assert_eq!(
            built.lamports,
            TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS + is_native.map_or(0, |_| AMOUNT_VALUE)
        );
        assert_eq!(built.space, TOKEN_ACCOUNT_LEN as u64);
        assert_eq!(built.owner, program.id());
    }

    #[test]
    fn the_rent_exempt_minimum_matches_the_default_rent() {
        assert_eq!(
            TOKEN_ACCOUNT_RENT_EXEMPT_LAMPORTS,
            solana_rent::Rent::default().minimum_balance(TOKEN_ACCOUNT_LEN)
        );
    }

    #[test]
    fn a_system_owner_is_not_a_token_program() {
        assert_eq!(TokenProgram::of(&solana_sdk_ids::system_program::ID), None);
        assert_eq!(
            with_token_amount(&account(solana_sdk_ids::system_program::ID, vec![], 1), 1).err(),
            Some(TokenAccountError::NotATokenProgram(
                solana_sdk_ids::system_program::ID
            ))
        );
    }

    #[test]
    fn a_native_account_takes_its_stored_reserve_plus_the_amount() {
        let reserve: u64 = 3_000_000;
        let mut data = vec![0; TOKEN_ACCOUNT_LEN];
        Account {
            mint: mints::SOL,
            owner: holder(),
            amount: 1,
            state: AccountState::Initialized,
            is_native: Some(reserve).into(),
            ..Account::default()
        }
        .pack_into_slice(&mut data);
        let native = account(spl_token_interface::ID, data, 1);

        let patched = with_token_amount(&native, AMOUNT_VALUE).unwrap();

        assert_eq!(patched.lamports, reserve + AMOUNT_VALUE);
        assert_eq!(
            token_amount(&patched.data.decode().unwrap()),
            Some(AMOUNT_VALUE)
        );
    }

    #[test]
    fn a_non_native_account_keeps_its_lamports() {
        let data = token_account(TokenProgram::Token, mint(), holder(), 1)
            .data
            .decode()
            .unwrap();

        let patched =
            with_token_amount(&account(spl_token_interface::ID, data, 99), AMOUNT_VALUE).unwrap();

        assert_eq!(patched.lamports, 99);
    }

    #[test]
    fn an_extended_token_2022_account_keeps_every_byte_but_its_amount() {
        let data = extended(&token_account(TokenProgram::Token2022, mint(), holder(), 1));
        let patched = with_token_amount(
            &account(TOKEN_2022_PROGRAM_ID, data.clone(), 5),
            AMOUNT_VALUE,
        )
        .unwrap()
        .data
        .decode()
        .unwrap();

        assert_eq!(patched.len(), data.len());
        assert_eq!(patched[TOKEN_ACCOUNT_LEN..], data[TOKEN_ACCOUNT_LEN..]);
        assert_eq!(
            Account::unpack(&patched[..TOKEN_ACCOUNT_LEN]).unwrap(),
            Account {
                amount: AMOUNT_VALUE,
                ..Account::unpack(&data[..TOKEN_ACCOUNT_LEN]).unwrap()
            }
        );
        assert_eq!(token_amount(&patched), Some(AMOUNT_VALUE));
        assert_eq!(token_mint(&patched), Some(mint()));
    }

    #[rstest]
    #[case::short(vec![1; 64])]
    #[case::uninitialized(vec![0; TOKEN_ACCOUNT_LEN])]
    #[case::bad_native_tag({
        let mut data = token_account(TokenProgram::Token, mint(), holder(), 1).data.decode().unwrap();
        data[ACCOUNT_INITIALIZED_INDEX + 1] = 2;
        data
    })]
    fn data_that_is_not_an_initialized_token_account_is_rejected(#[case] data: Vec<u8>) {
        let len = data.len();
        assert_eq!(
            with_token_amount(&account(spl_token_interface::ID, data, 1), 1).err(),
            Some(TokenAccountError::NotATokenAccount { len })
        );
    }

    #[rstest]
    #[case::mint(vec![1; 82])]
    #[case::short(vec![1; 64])]
    #[case::uninitialized(vec![0; TOKEN_ACCOUNT_LEN])]
    #[case::extended_mint({
        let mut data = vec![1; TOKEN_ACCOUNT_LEN + 8];
        data[TOKEN_ACCOUNT_LEN] = AccountType::Mint.into();
        data
    })]
    fn readers_see_nothing_in_data_that_is_not_a_token_account(#[case] data: Vec<u8>) {
        assert_eq!((token_amount(&data), token_mint(&data)), (None, None));
    }

    #[rstest]
    #[case::base(token_account(TokenProgram::Token, mint(), holder(), AMOUNT_VALUE).data.decode().unwrap())]
    #[case::extended(extended(&token_account(TokenProgram::Token2022, mint(), holder(), AMOUNT_VALUE)))]
    fn readers_see_a_token_account_balance_and_mint(#[case] data: Vec<u8>) {
        assert_eq!(
            (token_amount(&data), token_mint(&data)),
            (Some(AMOUNT_VALUE), Some(mint()))
        );
    }

    #[test]
    fn a_native_balance_of_u64_max_saturates() {
        let built = token_account(TokenProgram::Token, mints::SOL, holder(), u64::MAX);
        assert_eq!(built.lamports, u64::MAX);

        let native = account(spl_token_interface::ID, built.data.decode().unwrap(), 1);
        assert_eq!(
            with_token_amount(&native, u64::MAX).unwrap().lamports,
            u64::MAX
        );
    }
}