sim-cli 0.22.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
411
412
413
414
415
416
417
use std::sync::{
    Arc,
    atomic::{AtomicU64, AtomicUsize, Ordering},
};

use dashmap::{DashMap, DashSet};
use simulator_client::{AccountDiffNotification, balances::balance_changes};
use solana_address::Address;
use solana_signature::Signature;
use solana_transaction_status::{EncodedConfirmedTransactionWithStatusMeta, EncodedTransaction};
use tokio::sync::mpsc::UnboundedSender;

use crate::output::{
    AccountDiff, AccountDiffRow, OutputEvent, SolChange, TokenChange, Transaction,
};

/// How many slots of tx records to retain in [`RecordsStore`] for account-diff
/// enrichment. Entries older than `max_seen_slot - RECORDS_RETENTION_SLOTS`
/// are dropped on the next slot advance. Set wide enough to absorb the skew
/// between the `transactionSubscribe` and `accountDiffSubscribe` streams in
/// account-diff mode; a late diff that misses the window degrades to empty
/// enrichment (the existing `None` arm in `on_account_diff_notification`).
const RECORDS_RETENTION_SLOTS: u64 = 64;

/// Per-tx records keyed by signature, backing two consumers:
///
/// - Summary totals at end-of-run, served by [`Self::total`] /
///   [`Self::successes`] counters that don't depend on map retention so they
///   stay accurate across the whole run.
/// - Account-diff enrichment, served by lookup against `transactions`. Only
///   used in `--subscription account-diff` mode to match each diff back to its
///   tx's balance/token data.
///
/// The store is bounded to the last `RECORDS_RETENTION_SLOTS` slots so a long
/// run can't accumulate every tx ever seen.
#[derive(Clone)]
pub(crate) struct RecordsStore {
    transactions: Arc<DashMap<Signature, BalanceChanges>>,
    /// Emitted account-diff identities, used to drop diffs a reconnect replay
    /// re-delivers for the resumed boundary slot. Bounded to the same slot
    /// window as `transactions`.
    account_diffs: Arc<DashSet<DiffKey>>,
    /// Independent retention high-water marks for `transactions` and
    /// `account_diffs`: the tx and diff streams arrive on separate channels, so
    /// a shared mark would let whichever advances first starve the other of
    /// pruning.
    tx_max_slot: Arc<AtomicU64>,
    diff_max_slot: Arc<AtomicU64>,
    total: Arc<AtomicUsize>,
    successes: Arc<AtomicUsize>,
    /// Counted before dedup or validation.
    received: Arc<AtomicU64>,
    dedup_swallowed: Arc<AtomicU64>,
    malformed_dropped: Arc<AtomicU64>,
}

/// Identity of an emitted account-diff: `(slot, transaction signature, account)`.
type DiffKey = (u64, Signature, Address);

/// Slim per-tx record: just what diff enrichment and retention need. Storing
/// the full [`Transaction`] would clone every log line on the hot path for
/// data nothing ever reads back.
struct BalanceChanges {
    slot: u64,
    sol_changes: Vec<SolChange>,
    token_changes: Vec<TokenChange>,
}

impl RecordsStore {
    pub(crate) fn new() -> Self {
        Self {
            transactions: Arc::new(DashMap::new()),
            account_diffs: Arc::new(DashSet::new()),
            tx_max_slot: Arc::new(AtomicU64::new(0)),
            diff_max_slot: Arc::new(AtomicU64::new(0)),
            total: Arc::new(AtomicUsize::new(0)),
            successes: Arc::new(AtomicUsize::new(0)),
            received: Arc::new(AtomicU64::new(0)),
            dedup_swallowed: Arc::new(AtomicU64::new(0)),
            malformed_dropped: Arc::new(AtomicU64::new(0)),
        }
    }

    pub(crate) fn total(&self) -> usize {
        self.total.load(Ordering::Relaxed)
    }

    pub(crate) fn successes(&self) -> usize {
        self.successes.load(Ordering::Relaxed)
    }

    pub(crate) fn received(&self) -> u64 {
        self.received.load(Ordering::Relaxed)
    }

    pub(crate) fn dedup_swallowed(&self) -> u64 {
        self.dedup_swallowed.load(Ordering::Relaxed)
    }

    pub(crate) fn malformed_dropped(&self) -> u64 {
        self.malformed_dropped.load(Ordering::Relaxed)
    }

    fn get(
        &self,
        sig: &Signature,
    ) -> Option<dashmap::mapref::one::Ref<'_, Signature, BalanceChanges>> {
        self.transactions.get(sig)
    }

    /// Record a tx, returning `true` only if this signature was not already
    /// present. Counters and retention advance solely for genuinely new
    /// records, so a reconnect that re-delivers an already-seen slot via the
    /// `replayFromSlot` resume cursor is idempotent — neither double-counted nor
    /// re-emitted.
    fn note_transaction(&self, sig: Signature, tx: &Transaction) -> bool {
        let stored = BalanceChanges {
            slot: tx.slot,
            sol_changes: tx.sol_changes.clone(),
            token_changes: tx.token_changes.clone(),
        };
        if self.transactions.insert(sig, stored).is_some() {
            self.dedup_swallowed.fetch_add(1, Ordering::Relaxed);
            return false;
        }
        self.total.fetch_add(1, Ordering::Relaxed);
        if tx.success {
            self.successes.fetch_add(1, Ordering::Relaxed);
        }
        advance_window(&self.tx_max_slot, tx.slot, |cutoff| {
            self.transactions.retain(|_, v| v.slot >= cutoff)
        });
        true
    }

    /// Record that an account-diff identity has been emitted, returning `true`
    /// the first time. Keeps the diff output duplicate-free when a resume replay
    /// re-delivers a boundary slot, bounded to the retention window so it can't
    /// grow unbounded.
    fn note_diff(&self, slot: u64, sig: Signature, account: Address) -> bool {
        let is_new = self.account_diffs.insert((slot, sig, account));
        if !is_new {
            self.dedup_swallowed.fetch_add(1, Ordering::Relaxed);
        }
        advance_window(&self.diff_max_slot, slot, |cutoff| {
            self.account_diffs.retain(|(s, _, _)| *s >= cutoff)
        });
        is_new
    }
}

/// Advance a retention high-water mark to `slot`; when it crosses into a new
/// max, invoke `prune` with the `slot - RECORDS_RETENTION_SLOTS` cutoff so the
/// caller evicts entries older than the window.
fn advance_window(max_slot: &AtomicU64, slot: u64, prune: impl FnOnce(u64)) {
    let prev_max = max_slot.fetch_max(slot, Ordering::Relaxed);
    if slot > prev_max
        && let Some(cutoff) = slot.checked_sub(RECORDS_RETENTION_SLOTS)
    {
        prune(cutoff);
    }
}

/// Handle a single account-diff notification from the subscription manager.
///
/// Emits a `diff` event on the NDJSON stream. Enrichment (`pre_lamports`,
/// `post_lamports`, `pre_tokens`, `post_tokens`) is read from the shared
/// records store, populated by the `transactionSubscribe` stream running
/// alongside this subscription in account-diff mode. If the matching tx
/// record hasn't arrived yet (small race window between two WS channels) or
/// has already aged out of the slot-window, the row's enrichment fields are
/// emitted as `None`.
pub(crate) fn on_account_diff_notification(
    records: &RecordsStore,
    output_tx: &UnboundedSender<OutputEvent>,
    notification: AccountDiffNotification,
) {
    records.received.fetch_add(1, Ordering::Relaxed);
    let Some(sig) = notification
        .signature
        .and_then(|s| s.parse::<Signature>().ok())
    else {
        return;
    };
    let Some(account) = notification.account.and_then(|a| a.parse::<Address>().ok()) else {
        return;
    };
    // Use the notification's slot, not the RecordsStore entry's, so slot,
    // tx_index, and block_time stay internally consistent — entry.slot can
    // lag across the two WS channels.
    let slot = notification.context.slot;
    // Skip a diff a reconnect already delivered (the NDJSON stream isn't deduped).
    if !records.note_diff(slot, sig, account) {
        return;
    }
    let tx_index = notification.tx_index;
    let block_time = notification.block_time;
    let diff = AccountDiff {
        account,
        pre_state: notification.pre,
        post_state: notification.post,
    };

    let row = match records.get(&sig) {
        Some(entry) => AccountDiffRow::from_diff(
            slot,
            sig,
            tx_index,
            block_time,
            &diff,
            &entry.sol_changes,
            &entry.token_changes,
        ),
        None => AccountDiffRow::from_diff(slot, sig, tx_index, block_time, &diff, &[], &[]),
    };

    let _ = output_tx.send(OutputEvent::Diff(row));
}

/// Handle a single `transactionSubscribe` notification.
///
/// The server pushes a fully-assembled, `getTransaction`-shaped payload, so we
/// build the [`Transaction`] record directly from the notification and skip
/// any per-tx fetch. Logs come from the meta in the payload.
pub(crate) fn on_transaction_notification(
    records: &RecordsStore,
    output_tx: &UnboundedSender<OutputEvent>,
    notification: EncodedConfirmedTransactionWithStatusMeta,
) {
    records.received.fetch_add(1, Ordering::Relaxed);
    let slot = notification.slot;
    let Some(signature) = primary_signature(&notification.transaction.transaction) else {
        records.malformed_dropped.fetch_add(1, Ordering::Relaxed);
        tracing::warn!(
            slot,
            "transactionSubscribe notification missing primary signature; dropping"
        );
        return;
    };

    let logs = notification
        .transaction
        .meta
        .as_ref()
        .and_then(|meta| match &meta.log_messages {
            solana_transaction_status::option_serializer::OptionSerializer::Some(v) => {
                Some(v.clone())
            }
            _ => None,
        })
        .unwrap_or_default();

    let compute_units = notification.transaction.meta.as_ref().and_then(|meta| {
        match &meta.compute_units_consumed {
            solana_transaction_status::option_serializer::OptionSerializer::Some(units) => {
                Some(*units)
            }
            _ => None,
        }
    });

    let changes = match balance_changes(&notification.transaction) {
        Ok(changes) => changes,
        Err(error) => {
            records.malformed_dropped.fetch_add(1, Ordering::Relaxed);
            tracing::warn!(
                slot,
                %signature,
                %error,
                "transactionSubscribe payload could not be decoded into a Transaction; dropping"
            );
            return;
        }
    };
    let error = notification
        .transaction
        .meta
        .as_ref()
        .and_then(|meta| meta.err.as_ref())
        .map(ToString::to_string);
    let tx = Transaction {
        slot,
        timestamp: notification.block_time.map(|t| t as u64),
        signature,
        success: error.is_none(),
        error,
        compute_units,
        logs,
        sol_changes: changes.sol.into_iter().map(SolChange::from).collect(),
        token_changes: changes.token.into_iter().map(TokenChange::from).collect(),
        account_diffs: Vec::new(),
    };
    // Emit only on first sight; a reconnect can re-deliver a slot (output isn't deduped).
    if records.note_transaction(signature, &tx) {
        let _ = output_tx.send(OutputEvent::Tx(tx));
    }
}

/// Pull the first signature off an [`EncodedTransaction`]. Returns `None` for
/// encodings we don't decode (binary forms), for a transaction with no
/// signatures (nothing to key the records map by), or for one whose signature
/// isn't parseable.
fn primary_signature(encoded: &EncodedTransaction) -> Option<Signature> {
    let raw = match encoded {
        EncodedTransaction::Json(ui_tx) => ui_tx.signatures.first(),
        EncodedTransaction::LegacyBinary(_) | EncodedTransaction::Binary(_, _) => None,
        EncodedTransaction::Accounts(parsed) => parsed.signatures.first(),
    };
    raw?.parse().ok()
}

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

    /// Deterministic label -> value mapping, so the fixtures keep readable
    /// names while the typed fields hold real base58.
    fn sig(label: &str) -> Signature {
        let mut bytes = [0_u8; 64];
        bytes[..label.len()].copy_from_slice(label.as_bytes());
        Signature::from(bytes)
    }

    fn addr(label: &str) -> Address {
        let mut bytes = [0_u8; 32];
        bytes[..label.len()].copy_from_slice(label.as_bytes());
        Address::from(bytes)
    }

    fn tx(slot: u64, signature: &str, success: bool) -> Transaction {
        Transaction {
            slot,
            timestamp: None,
            signature: sig(signature),
            success,
            error: None,
            compute_units: None,
            logs: Vec::new(),
            sol_changes: Vec::new(),
            token_changes: Vec::new(),
            account_diffs: Vec::new(),
        }
    }

    #[test]
    fn note_transaction_dedups_repeated_signatures() {
        let store = RecordsStore::new();
        assert!(store.note_transaction(sig("sig"), &tx(10, "sig", true)));
        assert!(!store.note_transaction(sig("sig"), &tx(10, "sig", true)));
        assert_eq!(store.total(), 1);
        assert_eq!(store.successes(), 1);
        assert_eq!(store.dedup_swallowed(), 1);
    }

    fn notification(pre: &[u64], post: &[u64]) -> EncodedConfirmedTransactionWithStatusMeta {
        serde_json::from_value(serde_json::json!({
            "slot": 7,
            "blockTime": 1_700_000_000,
            "transaction": {
                "signatures": [sig("sig").to_string()],
                "message": {
                    "header": {
                        "numRequiredSignatures": 1,
                        "numReadonlySignedAccounts": 0,
                        "numReadonlyUnsignedAccounts": 0,
                    },
                    "accountKeys": [addr("payer").to_string()],
                    "recentBlockhash": "hash",
                    "instructions": [],
                },
            },
            "meta": {
                "err": null, "status": {"Ok": null}, "fee": 0,
                "preBalances": pre, "postBalances": post,
                "logMessages": ["log"],
                "computeUnitsConsumed": 1_234,
            },
        }))
        .expect("valid notification")
    }

    #[test]
    fn transaction_notification_emits_record() {
        let store = RecordsStore::new();
        let (output_tx, mut output_rx) = tokio::sync::mpsc::unbounded_channel();
        on_transaction_notification(&store, &output_tx, notification(&[100], &[90]));

        let Ok(OutputEvent::Tx(tx)) = output_rx.try_recv() else {
            panic!("expected a transaction record");
        };
        assert_eq!((tx.slot, tx.timestamp), (7, Some(1_700_000_000)));
        assert!(tx.success);
        assert_eq!(tx.logs, ["log"]);
        assert_eq!(tx.compute_units, Some(1_234));
        assert_eq!(tx.sol_changes[0].delta(), -10);
    }

    #[test]
    fn malformed_transaction_notification_is_dropped() {
        let store = RecordsStore::new();
        let (output_tx, mut output_rx) = tokio::sync::mpsc::unbounded_channel();
        on_transaction_notification(&store, &output_tx, notification(&[100], &[]));

        assert!(output_rx.try_recv().is_err());
        assert_eq!(store.malformed_dropped(), 1);
    }

    #[test]
    fn note_diff_dedups_repeated_identities() {
        let store = RecordsStore::new();
        assert!(store.note_diff(5, sig("sig"), addr("acct")));
        assert!(!store.note_diff(5, sig("sig"), addr("acct")));
        assert!(store.note_diff(5, sig("sig"), addr("other")));
        assert!(store.note_diff(6, sig("sig"), addr("acct")));
        assert_eq!(store.dedup_swallowed(), 1);
    }
}