sim-cli 0.19.0

CLI tool for running and comparing Solana simulator backtests
Documentation
use std::io::BufRead;

use eyre::Context;
use serde::{Deserialize, Serialize};
use solana_address::Address;
use solana_signature::Signature;

/// Solana types are carried as base58 strings (`DisplayFromStr`) rather than
/// their byte-array serde representation, so the NDJSON stays human-readable
/// and unchanged from when these fields were `String`.
#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationMetadata {
    pub start_slot: u64,
    pub end_slot: u64,
    #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub program_ids: Vec<Address>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub program_so: Vec<String>,
    pub ran_at_unix_secs: u64,
    /// Empty when carried by the leading NDJSON `metadata` envelope (IDs
    /// aren't known until sessions have been created). The loader populates
    /// this from `session_started` events (emitted as each session begins) or
    /// the trailing `summary` envelope, whichever comes first.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub session_ids: Vec<String>,
}

/// One line in the NDJSON output stream. Envelope-tagged so a single file can
/// carry mixed event types. Order along the stream is: one `metadata`, zero
/// or more `tx`/`diff` events as they arrive (no inter-session sort
/// guarantee), then a trailing `summary` with totals + the realized session
/// IDs.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum OutputEvent {
    Metadata(SimulationMetadata),
    SessionStarted(SessionStartedRecord),
    Tx(Transaction),
    Diff(AccountDiffRow),
    Summary(SimulationSummary),
}

#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Transaction {
    pub slot: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<u64>,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub signature: Signature,
    pub success: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    pub logs: Vec<String>,
    pub sol_changes: Vec<SolChange>,
    pub token_changes: Vec<TokenChange>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub account_diffs: Vec<AccountDiff>,
}

#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountDiff {
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub account: Address,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_state: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_state: Option<serde_json::Value>,
}

#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SolChange {
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub pubkey: Address,
    pub pre_lamports: u64,
    pub post_lamports: u64,
}

impl SolChange {
    pub fn delta(&self) -> i64 {
        self.post_lamports as i64 - self.pre_lamports as i64
    }
}

#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenChange {
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub pubkey: Address,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub mint: Address,
    /// Absent when the RPC omitted it. `NoneAsEmptyString` keeps the `""` the
    /// field carried when it was a `String`, so old streams still read.
    #[serde_as(as = "serde_with::NoneAsEmptyString")]
    pub owner: Option<Address>,
    pub pre_amount: u64,
    pub post_amount: u64,
    pub decimals: u8,
}

impl TokenChange {
    pub fn delta(&self) -> i64 {
        self.post_amount as i64 - self.pre_amount as i64
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct SimulationSummary {
    pub total_transactions: usize,
    pub successes: usize,
    pub failures: usize,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub session_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub diagnostics: Option<RunDiagnostics>,
}

/// Delivery diagnostics carried on the trailing `summary` row, for triaging
/// transactions missing from the output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunDiagnostics {
    /// Transaction and account-diff notifications, counted before dedup.
    pub received: u64,
    pub dedup_swallowed: u64,
    pub malformed_dropped: u64,
    pub reconnects: u64,
}

#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenInfo {
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub mint: Address,
    #[serde_as(as = "serde_with::NoneAsEmptyString")]
    pub owner: Option<Address>,
    pub amount: u64,
    pub decimals: u8,
}

/// A single account diff row for NDJSON streaming, mapping 1:1 to a DB row.
#[serde_with::serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountDiffRow {
    pub slot: u64,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub tx_hash: Signature,
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub account: Address,
    /// Position of the transaction within its slot, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tx_index: Option<u32>,
    /// Unix-seconds block time of the slot, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub block_time: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_lamports: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_lamports: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_state: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_state: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pre_tokens: Option<TokenInfo>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub post_tokens: Option<TokenInfo>,
}

/// Emitted into the NDJSON stream when a backtest session starts so downstream
/// consumers (e.g. Prefect flows) can link to the session's CloudWatch logs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionStartedRecord {
    pub session_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_id: Option<String>,
    pub start_slot: u64,
    pub end_slot: u64,
}

impl AccountDiffRow {
    pub fn from_diff(
        slot: u64,
        tx_hash: Signature,
        tx_index: Option<u32>,
        block_time: Option<i64>,
        diff: &AccountDiff,
        sol_changes: &[SolChange],
        token_changes: &[TokenChange],
    ) -> Self {
        let sol = sol_changes.iter().find(|s| s.pubkey == diff.account);
        let token = token_changes.iter().find(|t| t.pubkey == diff.account);

        Self {
            slot,
            tx_hash,
            account: diff.account,
            tx_index,
            block_time,
            pre_lamports: sol.map(|s| s.pre_lamports),
            post_lamports: sol.map(|s| s.post_lamports),
            pre_state: diff.pre_state.clone(),
            post_state: diff.post_state.clone(),
            pre_tokens: token.map(|t| TokenInfo {
                mint: t.mint,
                owner: t.owner,
                amount: t.pre_amount,
                decimals: t.decimals,
            }),
            post_tokens: token.map(|t| TokenInfo {
                mint: t.mint,
                owner: t.owner,
                amount: t.post_amount,
                decimals: t.decimals,
            }),
        }
    }
}

/// Error for an NDJSON stream that lacks the leading `metadata` envelope.
pub fn missing_metadata_envelope(path: &std::path::Path) -> eyre::Report {
    eyre::eyre!(
        "NDJSON stream {} is missing the leading `metadata` envelope",
        path.display()
    )
}

pub fn not_an_ndjson_stream(path: &std::path::Path) -> eyre::Report {
    eyre::eyre!("{} is not an NDJSON event stream", path.display())
}

/// Outcome of [`scan_ndjson_events`].
pub enum NdjsonScan {
    Complete,
    /// First non-blank line is not an envelope; no further lines were consumed.
    NotAnEnvelopeStream,
}

/// Stream envelope events line by line without buffering the file. `E` is the
/// envelope to deserialize per line — [`OutputEvent`] for full fidelity, or a
/// caller-local slim mirror that skips payloads it doesn't need.
/// A malformed line after the first envelope fails with a line-numbered error.
pub fn scan_ndjson_events<R: BufRead, E: serde::de::DeserializeOwned>(
    mut reader: R,
    path: &std::path::Path,
    on_event: &mut dyn FnMut(E) -> eyre::Result<()>,
) -> eyre::Result<NdjsonScan> {
    let mut line = String::new();
    let mut line_number = 0_usize;
    let mut ndjson = false;
    loop {
        line.clear();
        if reader
            .read_line(&mut line)
            .with_context(|| format!("failed to read {}", path.display()))?
            == 0
        {
            return Ok(NdjsonScan::Complete);
        }
        line_number += 1;
        if line.trim().is_empty() {
            continue;
        }
        match serde_json::from_str::<E>(&line) {
            Ok(event) => {
                ndjson = true;
                on_event(event)?;
            }
            Err(error) if ndjson => {
                return Err(error).with_context(|| {
                    format!(
                        "failed to parse NDJSON line {line_number} in {}",
                        path.display()
                    )
                });
            }
            Err(_) => return Ok(NdjsonScan::NotAnEnvelopeStream),
        }
    }
}

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

    /// One line of each envelope kind, as an older build wrote them — every
    /// address/signature is a plain base58 string and must stay one now that
    /// the fields are typed. `summarize`/`compare` read files from old runs.
    const STREAM: &str = concat!(
        r#"{"type":"metadata","data":{"start_slot":1,"end_slot":2,"program_ids":["JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4"],"ran_at_unix_secs":7}}"#,
        "\n",
        r#"{"type":"tx","data":{"slot":1,"signature":"1111111111111111111111111111111111111111111111111111111111111111","success":true,"logs":[],"sol_changes":[{"pubkey":"11111111111111111111111111111111","pre_lamports":10,"post_lamports":5}],"token_changes":[{"pubkey":"So11111111111111111111111111111111111111112","mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","owner":"","pre_amount":1,"post_amount":2,"decimals":6}]}}"#,
        "\n",
        r#"{"type":"diff","data":{"slot":1,"tx_hash":"1111111111111111111111111111111111111111111111111111111111111111","account":"11111111111111111111111111111111"}}"#,
        "\n",
        r#"{"type":"summary","data":{"total_transactions":1,"successes":1,"failures":0}}"#,
    );

    #[test]
    fn every_envelope_round_trips_byte_identically() {
        for line in STREAM.lines() {
            let event: OutputEvent = serde_json::from_str(line).expect("parse");
            let original: serde_json::Value = serde_json::from_str(line).expect("json");
            let produced: serde_json::Value =
                serde_json::from_str(&serde_json::to_string(&event).expect("serialize"))
                    .expect("json");
            assert_eq!(original, produced, "wire format changed for: {line}");
        }
    }

    #[test]
    fn an_absent_token_owner_stays_an_empty_string() {
        let line = STREAM.lines().nth(1).expect("tx line");
        let event: OutputEvent = serde_json::from_str(line).expect("parse");
        let OutputEvent::Tx(tx) = &event else {
            panic!("expected a tx envelope");
        };
        assert_eq!(tx.token_changes[0].owner, None);
        assert!(
            serde_json::to_string(&event)
                .expect("serialize")
                .contains(r#""owner":"""#)
        );
    }

    #[test]
    fn a_malformed_address_is_rejected_rather_than_carried_through() {
        let line = r#"{"type":"tx","data":{"slot":1,"signature":"1111111111111111111111111111111111111111111111111111111111111111","success":true,"logs":[],"sol_changes":[{"pubkey":"not-an-address","pre_lamports":10,"post_lamports":5}],"token_changes":[]}}"#;
        assert!(serde_json::from_str::<OutputEvent>(line).is_err());
    }

    #[test]
    fn output_event_session_started_wire_format() {
        let value = OutputEvent::SessionStarted(SessionStartedRecord {
            session_id: "backtest_abc".to_string(),
            task_id: Some("task_xyz".to_string()),
            start_slot: 1,
            end_slot: 2,
        });
        let json: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&value).unwrap()).unwrap();
        assert_eq!(json["type"], "session_started");
        assert_eq!(json["data"]["session_id"], "backtest_abc");
        assert_eq!(json["data"]["task_id"], "task_xyz");
        assert_eq!(json["data"]["start_slot"], 1);
        assert_eq!(json["data"]["end_slot"], 2);
    }

    #[test]
    fn summary_diagnostics_wire_format() {
        let value = OutputEvent::Summary(SimulationSummary {
            total_transactions: 3,
            successes: 2,
            failures: 1,
            session_ids: Vec::new(),
            diagnostics: Some(RunDiagnostics {
                received: 5,
                dedup_swallowed: 2,
                malformed_dropped: 0,
                reconnects: 1,
            }),
        });
        let json: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&value).unwrap()).unwrap();
        let diagnostics = &json["data"]["diagnostics"];
        assert_eq!(diagnostics["received"], 5);
        assert_eq!(diagnostics["dedup_swallowed"], 2);
        assert_eq!(diagnostics["malformed_dropped"], 0);
        assert_eq!(diagnostics["reconnects"], 1);
    }

    #[test]
    fn summary_without_diagnostics_still_parses() {
        let line =
            r#"{"type":"summary","data":{"total_transactions":1,"successes":1,"failures":0}}"#;
        let event: OutputEvent = serde_json::from_str(line).unwrap();
        let OutputEvent::Summary(summary) = event else {
            panic!("expected summary");
        };
        assert!(summary.diagnostics.is_none());
    }

    #[test]
    fn output_event_session_started_omits_null_task_id() {
        let value = OutputEvent::SessionStarted(SessionStartedRecord {
            session_id: "backtest_abc".to_string(),
            task_id: None,
            start_slot: 1,
            end_slot: 2,
        });
        let json: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&value).unwrap()).unwrap();
        assert_eq!(json["type"], "session_started");
        assert!(json["data"].get("task_id").is_none());
    }
}