simulator-api 0.29.0

Wire-protocol types for the Solana simulator backtest WebSocket API
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
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Notifications from `replacementSubscribe`: one reroute result per original swap. Nothing stands
//! in for the original; the `original` kind is the original itself.
//!
//! Each notification is a [`ReplacementNotification`], tagged by `kind`:
//! - `requote`: the transaction re-quoted through the router
//!   ([`RequoteNotification`]).
//! - `directFill`: one hop rerouted directly to a venue through your template, a venue probe
//!   ([`VenueNotification`]).
//! - `original`: the original swap replayed as the baseline ([`OriginalNotification`]).
//!
//! Every kind flattens [`ReplacementCore`] and [`L1Score`] into its top level; the kinds that
//! simulate a whole transaction also flatten [`SimCost`].
//!
//! Wire keys are the camelCase of the field names (`batch_index` is `batchIndex`), except
//! [`ReplacementCore::error`], which is `err`. Units:
//! - Token amounts are raw base units of their mint, with no decimals applied.
//! - `fee` is in lamports.
//! - Changes are in basis points (bps): 1 bps = 0.01%.
//! - `swapMode` is `ExactIn` or `ExactOut`.
//! - `blockTime` is a Unix timestamp in seconds.

use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use solana_address::Address;
pub use solana_signature::Signature;

use crate::{EncodedBinary, SwapMode, route_plan::RoutePlan};

/// Basis points per whole unit.
pub const BPS_SCALE: i128 = 10_000;

/// The bound on one swap's recorded change: ±100,000 bps (±1,000%). Losses stop at −10,000 bps
/// (−100%) on their own, so only gains reach it.
pub const CHANGE_CLAMP_BPS: i128 = 10 * BPS_SCALE;

/// A recorded change, and whether [`CHANGE_CLAMP_BPS`] is what bounded it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChangeBps {
    /// The change in basis points, clamped to ±[`CHANGE_CLAMP_BPS`].
    pub bps: i64,
    /// Whether the clamp bounded it.
    pub clamped: bool,
}

/// Change from `base` to `new` in bps, `(new - base) * 10_000 / base`, clamped to
/// ±[`CHANGE_CLAMP_BPS`].
///
/// # Panics
///
/// Panics when `base` is 0.
pub fn clamped_change_bps(new: u64, base: u64) -> ChangeBps {
    let raw = (i128::from(new) - i128::from(base)) * BPS_SCALE / i128::from(base);
    ChangeBps {
        bps: raw.clamp(-CHANGE_CLAMP_BPS, CHANGE_CLAMP_BPS) as i64,
        clamped: raw.abs() >= CHANGE_CLAMP_BPS,
    }
}

/// The slot the payload was produced at, in the shape every other subscription's context takes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplacementContext {
    /// The slot the stand-in was simulated in.
    pub slot: u64,
}

/// The identity and outcome every notification carries, whatever its kind. Flattened into the
/// notification's top level.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReplacementCore {
    #[allow(missing_docs)]
    pub context: ReplacementContext,
    /// The slot the stand-in was simulated in.
    pub slot: u64,
    /// Batch within its slot that the original swap executed in. A reroute through the router is
    /// simulated just before this batch; a probe and the replayed original are simulated earlier,
    /// at the pricing point (see [`VenueNotification::quote_lag_blocks`]).
    pub batch_index: u32,
    /// The original swap's transaction signature, base58.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub original_signature: Signature,
    /// The original swap failed onchain, so it filled nothing. Defaults to `false`.
    #[serde(default)]
    pub original_failed: bool,
    /// `filled`, `reverted`, `unattributed`, `unsimulatable` or `unresolved`, for every kind. A
    /// string rather than an enum, so a value the server adds later still decodes.
    pub outcome: String,
    /// The failure bucket; absent unless it failed. Group failures by it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    /// The error message behind [`Self::category`]. `err` on the wire.
    #[serde(rename = "err", default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// What the original swap filled, and how the stand-in scored against it. Flattened into the
/// notification's top level. `l1` in a name means the original (onchain) swap.
///
/// The scope differs by kind: a venue probe scores one HOP's onchain output, a replayed original
/// the net route flow across the whole SWAP's pair, a reroute what the original realized across
/// the transaction. Compare within a kind; never sum or average across kinds.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct L1Score {
    /// What the original swap filled, in raw base units (wire `l1Fill`). `None` when it filled
    /// zero, which is no baseline.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub l1_fill: Option<u64>,
    /// The stand-in against [`Self::l1_fill`] in bps, clamped to ±[`CHANGE_CLAMP_BPS`]
    /// (wire `changeVsL1Bps`). Positive means it beat the original swap. Absent when either side
    /// is missing or zero.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub change_vs_l1_bps: Option<i64>,
}

impl L1Score {
    /// Score `measured` against what the original swap moved on the same side. ExactIn measures
    /// output, so more is better; ExactOut measures the input charged, so the sign is flipped and
    /// positive always means the stand-in beat what traded. A historical fill of zero is no
    /// baseline: dividing by it would clamp to a number rather than say nothing.
    ///
    /// A measured zero is left unscored for the same reason. Some venues decline by returning
    /// zero rather than by reverting, which is a refusal to quote and not a quote of nothing;
    /// scored, it lands at [`CHANGE_CLAMP_BPS`] and a handful of declines sink a venue's mean far
    /// below what it actually paid.
    pub fn new(measured: Option<u64>, l1_fill: u64, mode: SwapMode) -> Self {
        let l1_fill = (l1_fill > 0).then_some(l1_fill);
        Self {
            l1_fill,
            change_vs_l1_bps: measured.filter(|&measured| measured > 0).zip(l1_fill).map(
                |(measured, l1)| {
                    let change = clamped_change_bps(measured, l1).bps;
                    match mode {
                        SwapMode::ExactIn => change,
                        SwapMode::ExactOut => -change,
                    }
                },
            ),
        }
    }
}

/// What simulating the stand-in cost. Flattened into the notification's top level.
///
/// Only the kinds that simulate a whole transaction carry it; a venue probe does not.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SimCost {
    #[allow(missing_docs)]
    pub compute_units_consumed: u64,
    /// The transaction fee, in lamports. `None` when it was not recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fee: Option<u64>,
}

/// One swap of a transaction rerouted through the router.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RerouteLegNotification {
    /// The mint the swap sells, base58.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub input_mint: Address,
    /// The mint the swap buys, base58.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub output_mint: Address,
    /// The swap's fixed amount, in raw base units: of `input_mint` for `ExactIn`, of
    /// `output_mint` for `ExactOut`.
    pub amount: u64,
    /// `ExactIn` or `ExactOut`, as [`SwapMode`] spells them.
    pub swap_mode: String,
    /// The output the original swap's instruction quoted, in raw base units of `output_mint`.
    pub original_quoted_out: u64,
    /// The output the router quoted for the reroute, in raw base units of `output_mint`.
    pub metis_quoted_out: u64,
    /// The router's route as text: `Raydium → Orca` for a path, `60% Raydium | 40% Orca` for a split,
    /// `(no route)` when it named no venue.
    pub route_summary: String,
    /// The route the router quoted, when it returned one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub route_plan: Option<RoutePlan>,
    /// The route the original swap took, which the reroute displaced.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub original_route_plan: Option<RoutePlan>,
    /// What each hop actually moved. `route_plan` is the quote; this is the fill, and the side
    /// to compare `original_route_plan` against.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realized_route_plan: Option<RoutePlan>,
}

/// A transaction rerouted through the router (`kind: "requote"`): the original swap's transaction
/// re-quoted and simulated. The original still executed onchain; this
/// result is never committed.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequoteNotification {
    /// The fields every kind carries, flattened into this object on the wire.
    #[serde(flatten)]
    pub core: ReplacementCore,
    /// Scored at whole-transaction scope: what the original realized against what the routed
    /// stand-in did, output against output in both swap modes. Absent for a multi-swap
    /// transaction, where no single pair names the fill; read [`Self::legs`] instead.
    #[serde(flatten)]
    pub comparison: L1Score,
    /// What simulating the routed transaction cost, flattened into this object on the wire.
    #[serde(flatten)]
    pub cost: SimCost,
    /// One per detected swap in the original, in order.
    #[serde(default)]
    pub legs: Vec<RerouteLegNotification>,
    /// The routed transaction that was simulated. Decode with
    /// `simulator_client::decode_transaction` (base64 wincode of `VersionedTransaction`) to inspect
    /// its instructions.
    pub routed_transaction: EncodedBinary,
    /// Program logs from simulating the routed transaction.
    #[serde(default)]
    pub logs: Vec<String>,
    /// What the routed swap produced, in raw output-mint base units. `None` for a multi-swap
    /// transaction, a missing output balance record, or a reverted simulation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub realized_output_amount: Option<u64>,
    /// What the original swap produced onchain, from its recorded balance changes, in raw
    /// output-mint base units. `None` under the same conditions, but set whatever the
    /// simulation's outcome, so it is present even when the core carries an error.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub original_realized_output_amount: Option<u64>,
}

/// The hop a venue probe re-priced, as the original swap ran it onchain and as the replay ran it.
#[serde_as]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProbedHop {
    /// The block the hop executed in. The probe itself ran at [`ReplacementCore::slot`], which is
    /// earlier by [`VenueNotification::quote_lag_blocks`].
    pub slot: u64,
    /// That block's Unix timestamp, in seconds.
    pub block_time: i64,
    /// The transaction's position in that block.
    pub tx_index: u32,
    /// Which swap of the transaction this hop belongs to.
    pub ix_index: u32,
    /// Which hop of that swap this is.
    pub leg_index: u32,
    /// The venue program that priced the original hop. `None` when the route events attribute it to
    /// none.
    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
    #[serde(default)]
    pub program: Option<Address>,
    /// What the original hop took in, in raw base units.
    pub input_amount: u64,
    /// What the original hop paid out, in raw base units.
    pub output_amount: u64,
    /// The same hop as the replayed original took it. `None` when the replay did not recover the
    /// hop - it reverted, its route decoded without that hop, or it split the hop differently. Its
    /// input can differ from `input_amount` when an earlier hop filled differently, so compare
    /// output per unit of input.
    #[serde(default)]
    pub replay_input_amount: Option<u64>,
    /// What the replayed hop paid out, in raw base units. `None` under the same conditions as
    /// `replay_input_amount`.
    #[serde(default)]
    pub replay_output_amount: Option<u64>,
}

/// A venue probe (`kind: "directFill"`): one hop rerouted directly to a venue through your
/// template, simulated against the state it would have traded on.
///
/// A probe prices ONE hop, so the mints and amount here are the hop's, never the enclosing
/// swap's.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VenueNotification {
    /// The fields every kind carries, flattened into this object on the wire.
    #[serde(flatten)]
    pub core: ReplacementCore,
    /// Scored at hop scope, against the probed hop's own onchain output.
    #[serde(flatten)]
    pub comparison: L1Score,
    /// The template the hop was rebuilt through.
    pub template: String,
    /// The program that template's instruction calls: for one built from an aggregator's route,
    /// the aggregator's, which several venues share.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub program: Address,
    /// The hop this priced, as the original swap and the replay ran it.
    pub hop: ProbedHop,
    /// The transaction of block [`ReplacementCore::slot`] the pass that priced this probe ran
    /// just before; 0 at the block's start, its transaction count at its end.
    pub quote_tx_index: u32,
    /// Blocks between the block the hop executes in and the one it was priced at.
    pub quote_lag_blocks: u32,
    /// The mint the hop sells, base58.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub input_mint: Address,
    /// The mint the hop buys, base58.
    #[serde_as(as = "serde_with::DisplayFromStr")]
    pub output_mint: Address,
    /// The hop's fixed amount, in raw base units: its input for `ExactIn`, its output for
    /// `ExactOut`.
    pub amount: u64,
    /// `ExactIn` or `ExactOut`, as [`SwapMode`] spells them.
    pub swap_mode: String,
    /// What the template filled, in raw base units of the measured mint. `None` unless the probe
    /// filled attributably.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub template_fill: Option<u64>,
    /// What the probed template spent of its input; `None` unless the probe filled attributably.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spent_amount: Option<u64>,
}

/// The original swap replayed as the baseline (`kind: "original"`): the historical transaction
/// re-run against the state it was quoted at, so the other kinds can be scored against a number
/// produced the same way rather than against the chain's.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OriginalNotification {
    /// The fields every kind carries, flattened into this object on the wire.
    #[serde(flatten)]
    pub core: ReplacementCore,
    /// Scored at swap scope: the original swap's net route flow across the whole swap's pair.
    #[serde(flatten)]
    pub comparison: L1Score,
    /// What replaying the original cost, flattened into this object on the wire.
    #[serde(flatten)]
    pub cost: SimCost,
    /// The hops this replay produced.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub route_plan: Option<RoutePlan>,
    /// The hops the original swap took, decoded the same way, so the two are read against each
    /// other rather than against differently-derived numbers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub l1_route_plan: Option<RoutePlan>,
    /// What the replay produced, in raw output-mint base units, when a single swap's output could
    /// be read off it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub simulated_output_amount: Option<u64>,
}

/// One reroute result for an original swap, streamed over `replacementSubscribe`: through
/// the router, directly to a venue, or the original swap replayed as the baseline. Nothing stands
/// in for the original. Tagged by `kind`, with the variant's fields at the top level beside it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ReplacementNotification {
    /// A reroute through the router: the whole transaction re-quoted
    /// (`"kind": "requote"`).
    Requote(RequoteNotification),
    /// A reroute directly to a venue: one hop re-priced through a venue template
    /// (`"kind": "directFill"`).
    #[serde(rename = "directFill")]
    Venue(VenueNotification),
    /// The original swap replayed as the baseline (`"kind": "original"`).
    Original(OriginalNotification),
}

impl ReplacementNotification {
    /// What every kind carries, whichever shape it arrived in.
    pub const fn core(&self) -> &ReplacementCore {
        match self {
            Self::Requote(requote) => &requote.core,
            Self::Venue(probe) => &probe.core,
            Self::Original(original) => &original.core,
        }
    }
}

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

    use super::*;

    #[rstest]
    #[case::total_loss(0, 1_000, -10_000, false)]
    #[case::unchanged(1_000, 1_000, 0, false)]
    #[case::a_real_improvement(1_100, 1_000, 1_000, false)]
    #[case::ten_x_is_the_last_unclamped(101_000, 10_000, 91_000, false)]
    #[case::eleven_x_is_the_bound_itself(110_000, 10_000, 100_000, true)]
    #[case::dust_base(1_000_000, 1, 100_000, true)]
    fn a_change_reports_whether_the_clamp_bound_it(
        #[case] new: u64,
        #[case] base: u64,
        #[case] bps: i64,
        #[case] clamped: bool,
    ) {
        assert_eq!(clamped_change_bps(new, base), ChangeBps { bps, clamped });
    }

    #[rstest]
    #[case::no_baseline(Some(1_000), 0, SwapMode::ExactIn, None, None)]
    #[case::no_measurement(None, 1_000, SwapMode::ExactIn, Some(1_000), None)]
    #[case::beat_it(Some(1_100), 1_000, SwapMode::ExactIn, Some(1_000), Some(1_000))]
    #[case::lost_to_it(Some(900), 1_000, SwapMode::ExactIn, Some(1_000), Some(-1_000))]
    #[case::tiny_baseline_clamps(
        Some(u64::MAX),
        1,
        SwapMode::ExactIn,
        Some(1),
        Some(CHANGE_CLAMP_BPS as i64)
    )]
    // ExactOut measures the input charged, so paying less is the win and the sign flips.
    #[case::exact_out_paid_less(Some(900), 1_000, SwapMode::ExactOut, Some(1_000), Some(1_000))]
    #[case::exact_out_paid_more(Some(1_100), 1_000, SwapMode::ExactOut, Some(1_000), Some(-1_000))]
    // A venue declining with a zero is a refusal to quote, not a quote of nothing.
    #[case::a_declined_quote_is_unscored(Some(0), 1_000, SwapMode::ExactIn, Some(1_000), None)]
    fn scoring_a_fill_against_l1(
        #[case] measured: Option<u64>,
        #[case] l1_fill: u64,
        #[case] mode: SwapMode,
        #[case] expected_l1: Option<u64>,
        #[case] expected_bps: Option<i64>,
    ) {
        let scored = L1Score::new(measured, l1_fill, mode);
        assert_eq!(scored.l1_fill, expected_l1);
        assert_eq!(scored.change_vs_l1_bps, expected_bps);
    }

    /// The absent halves have to vanish rather than serialize as nulls: a consumer distinguishes
    /// "no baseline" from "scored zero", and both sides skip on `None`.
    #[test]
    fn an_unscored_comparison_emits_no_keys() {
        let empty = serde_json::to_value(L1Score::new(None, 0, SwapMode::ExactIn))
            .expect("a score serializes");
        assert_eq!(empty, serde_json::json!({}));
    }
}