sim-cli 0.21.0

CLI tool for running and comparing Solana simulator backtests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
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 = "Option::is_none")]
    pub session_name: Option<String>,
    #[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 session_name: Option<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(),
            session_name: Some("my-run".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"]["session_name"], "my-run");
        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_name: Some("my-run".to_string()),
            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();
        assert_eq!(json["data"]["session_name"], "my-run");
        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());
        assert!(summary.session_name.is_none());
    }

    #[test]
    fn output_event_session_started_omits_null_task_id_and_name() {
        let value = OutputEvent::SessionStarted(SessionStartedRecord {
            session_id: "backtest_abc".to_string(),
            session_name: None,
            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());
        assert!(json["data"].get("session_name").is_none());
    }
}