sim-cli 0.13.0

CLI tool for running and comparing Solana simulator backtests
Documentation
use std::collections::{BTreeSet, HashMap};

use solana_address::Address;
use solana_signature::Signature;
use solana_transaction_status::{
    EncodedConfirmedTransactionWithStatusMeta, EncodedTransaction, UiMessage,
    UiTransactionTokenBalance, option_serializer::OptionSerializer,
};

use crate::output::{SolChange, TokenChange, Transaction};

/// One token balance, indexed by account index in [`token_index_map`].
struct TokenBalance {
    amount: u64,
    mint: Address,
    /// Absent when the RPC omitted it.
    owner: Option<Address>,
    decimals: u8,
}

/// Index token balances by account index. `None` if any address the RPC sent
/// back isn't parseable — the caller counts that as a malformed payload and
/// drops the whole transaction.
fn token_index_map(balances: &[UiTransactionTokenBalance]) -> Option<HashMap<u8, TokenBalance>> {
    balances
        .iter()
        .map(|t| {
            let amount = t.ui_token_amount.amount.parse::<u64>().unwrap_or(0);
            let owner = match &t.owner {
                OptionSerializer::Some(o) => Some(o.parse().ok()?),
                _ => None,
            };
            Some((
                t.account_index,
                TokenBalance {
                    amount,
                    mint: t.mint.parse().ok()?,
                    owner,
                    decimals: t.ui_token_amount.decimals,
                },
            ))
        })
        .collect()
}

pub fn transaction_from_encoded(
    confirmed: EncodedConfirmedTransactionWithStatusMeta,
    signature: Signature,
    slot: u64,
) -> Option<Transaction> {
    let block_time = confirmed.block_time.map(|t| t as u64);
    let inner = confirmed.transaction;
    let meta = inner.meta.as_ref()?;
    let error = meta.err.as_ref().map(|e| e.to_string());

    let EncodedTransaction::Json(ui_tx) = &inner.transaction else {
        return None;
    };
    let parsed_keys: Option<Vec<Address>> = match &ui_tx.message {
        UiMessage::Raw(raw) => raw.account_keys.iter().map(|k| k.parse().ok()).collect(),
        UiMessage::Parsed(parsed) => parsed
            .account_keys
            .iter()
            .map(|k| k.pubkey.parse().ok())
            .collect(),
    };
    let mut keys = parsed_keys?;
    if let OptionSerializer::Some(addresses) = &meta.loaded_addresses {
        for key in addresses.writable.iter().chain(&addresses.readonly) {
            keys.push(key.parse().ok()?);
        }
    }

    let sol_changes: Vec<SolChange> = keys
        .iter()
        .enumerate()
        .filter_map(|(i, pubkey)| {
            let pre = *meta.pre_balances.get(i)?;
            let post = *meta.post_balances.get(i)?;
            if pre == post {
                return None;
            }
            Some(SolChange {
                pubkey: *pubkey,
                pre_lamports: pre,
                post_lamports: post,
            })
        })
        .collect();

    let empty = Vec::new();
    let pre_tokens = match &meta.pre_token_balances {
        OptionSerializer::Some(v) => v,
        _ => &empty,
    };
    let post_tokens = match &meta.post_token_balances {
        OptionSerializer::Some(v) => v,
        _ => &empty,
    };

    let pre_map = token_index_map(pre_tokens)?;
    let post_map = token_index_map(post_tokens)?;

    let mut all_indices: BTreeSet<u8> = BTreeSet::new();
    all_indices.extend(pre_map.keys().copied());
    all_indices.extend(post_map.keys().copied());

    let token_changes: Vec<TokenChange> = all_indices
        .into_iter()
        .filter_map(|idx| {
            let pubkey = *keys.get(idx as usize)?;
            let (pre_amount, balance) = match pre_map.get(&idx) {
                Some(info) => (info.amount, info),
                None => (0, post_map.get(&idx)?),
            };
            let post_amount = post_map.get(&idx).map_or(0, |i| i.amount);
            if pre_amount == post_amount {
                return None;
            }
            Some(TokenChange {
                pubkey,
                mint: balance.mint,
                owner: balance.owner,
                pre_amount,
                post_amount,
                decimals: balance.decimals,
            })
        })
        .collect();

    Some(Transaction {
        slot,
        timestamp: block_time,
        signature,
        success: error.is_none(),
        error,
        sol_changes,
        token_changes,
        logs: Vec::new(),
        account_diffs: Vec::new(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    // The decoder parses every address/signature, so the fixtures carry real
    // base58 rather than the placeholder labels they used to.
    const PAYER: &str = "11111111111111111111111111111112";
    const STATIC_1: &str = "11111111111111111111111111111113";
    const LOADED_W: &str = "11111111111111111111111111111114";
    const LOADED_R: &str = "11111111111111111111111111111115";
    const TOKEN_ACCT: &str = "11111111111111111111111111111116";
    const MINT_A: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
    const OWNER_1: &str = "So11111111111111111111111111111111111111112";
    const SIG: &str = "1111111111111111111111111111111111111111111111111111111111111111";

    fn signature() -> Signature {
        SIG.parse().expect("valid signature")
    }

    fn address(s: &str) -> Address {
        s.parse().expect("valid address")
    }

    /// Build the `getTransaction`-shaped wire JSON the subscription pushes and
    /// run it through the decoder. Deserializing a literal is sturdier than
    /// hand-constructing the many `OptionSerializer` fields.
    fn decode(transaction: serde_json::Value, meta: serde_json::Value) -> Option<Transaction> {
        let confirmed: EncodedConfirmedTransactionWithStatusMeta =
            serde_json::from_value(serde_json::json!({
                "slot": 42,
                "blockTime": 1_700_000_000,
                "transaction": transaction,
                "meta": meta,
            }))
            .unwrap();
        transaction_from_encoded(confirmed, signature(), 42)
    }

    fn raw_transaction(account_keys: &[&str]) -> serde_json::Value {
        serde_json::json!({
            "signatures": [SIG],
            "message": {
                "header": {
                    "numRequiredSignatures": 1,
                    "numReadonlySignedAccounts": 0,
                    "numReadonlyUnsignedAccounts": 0,
                },
                "accountKeys": account_keys,
                "recentBlockhash": "hash",
                "instructions": [],
            },
        })
    }

    fn token_balance(account_index: u8, amount: &str) -> serde_json::Value {
        serde_json::json!({
            "accountIndex": account_index,
            "mint": MINT_A,
            "owner": OWNER_1,
            "uiTokenAmount": {
                "uiAmount": null,
                "decimals": 6,
                "amount": amount,
                "uiAmountString": amount,
            },
        })
    }

    #[test]
    fn missing_meta_is_none() {
        let result = decode(raw_transaction(&[PAYER]), serde_json::Value::Null);
        assert!(result.is_none());
    }

    #[test]
    fn binary_transaction_is_none() {
        let meta = serde_json::json!({
            "err": null, "status": {"Ok": null}, "fee": 0,
            "preBalances": [100], "postBalances": [100],
        });
        assert!(decode(serde_json::json!("3qd..."), meta).is_none());
    }

    #[test]
    fn loaded_addresses_extend_static_keys_and_equal_balances_are_skipped() {
        let meta = serde_json::json!({
            "err": null, "status": {"Ok": null}, "fee": 0,
            // Indices: 0 payer, 1 static-1, 2 loaded-w, 3 loaded-r.
            "preBalances": [100, 50, 10, 7],
            "postBalances": [90, 50, 25, 7],
            "loadedAddresses": {"writable": [LOADED_W], "readonly": [LOADED_R]},
        });
        let tx = decode(raw_transaction(&[PAYER, STATIC_1]), meta).unwrap();

        assert!(tx.success);
        assert_eq!(tx.timestamp, Some(1_700_000_000));
        // static-1 and loaded-r are unchanged (pre == post) and must be skipped;
        // the change at index 2 must resolve to the loaded (not static) key.
        assert_eq!(
            tx.sol_changes
                .iter()
                .map(|c| (c.pubkey, c.pre_lamports, c.post_lamports))
                .collect::<Vec<_>>(),
            [(address(PAYER), 100, 90), (address(LOADED_W), 10, 25)]
        );
    }

    #[test]
    fn post_only_token_balance_gets_zero_pre_amount() {
        let meta = serde_json::json!({
            "err": null, "status": {"Ok": null}, "fee": 0,
            "preBalances": [100, 10], "postBalances": [100, 10],
            "postTokenBalances": [token_balance(1, "500")],
        });
        let tx = decode(raw_transaction(&[PAYER, TOKEN_ACCT]), meta).unwrap();

        assert_eq!(tx.token_changes.len(), 1);
        let change = &tx.token_changes[0];
        assert_eq!(change.pubkey, address(TOKEN_ACCT));
        assert_eq!(change.mint, address(MINT_A));
        assert_eq!(change.owner, Some(address(OWNER_1)));
        assert_eq!((change.pre_amount, change.post_amount), (0, 500));
        assert_eq!(change.decimals, 6);
    }

    #[test]
    fn equal_token_amounts_are_skipped() {
        let meta = serde_json::json!({
            "err": null, "status": {"Ok": null}, "fee": 0,
            "preBalances": [100, 10], "postBalances": [100, 10],
            "preTokenBalances": [token_balance(1, "500")],
            "postTokenBalances": [token_balance(1, "500")],
        });
        let tx = decode(raw_transaction(&[PAYER, TOKEN_ACCT]), meta).unwrap();
        assert!(tx.token_changes.is_empty());
    }
}