Skip to main content

simulator_api/
replacement.rs

1//! Notifications from `replacementSubscribe`: one reroute result per original swap. Nothing stands
2//! in for the original; the `original` kind is the original itself.
3//!
4//! Each notification is a [`ReplacementNotification`], tagged by `kind`:
5//! - `requote`: the transaction re-quoted through the router
6//!   ([`RequoteNotification`]).
7//! - `directFill`: one hop rerouted directly to a venue through your template, a venue probe
8//!   ([`VenueNotification`]).
9//! - `original`: the original swap replayed as the baseline ([`OriginalNotification`]).
10//!
11//! Every kind flattens [`ReplacementCore`] and [`L1Score`] into its top level; the kinds that
12//! simulate a whole transaction also flatten [`SimCost`].
13//!
14//! Wire keys are the camelCase of the field names (`batch_index` is `batchIndex`), except
15//! [`ReplacementCore::error`], which is `err`. Units:
16//! - Token amounts are raw base units of their mint, with no decimals applied.
17//! - `fee` is in lamports.
18//! - Changes are in basis points (bps): 1 bps = 0.01%.
19//! - `swapMode` is `ExactIn` or `ExactOut`.
20//! - `blockTime` is a Unix timestamp in seconds.
21
22use serde::{Deserialize, Serialize};
23use serde_with::serde_as;
24use solana_address::Address;
25pub use solana_signature::Signature;
26
27use crate::{EncodedBinary, SwapMode, route_plan::RoutePlan};
28
29/// Basis points per whole unit.
30pub const BPS_SCALE: i128 = 10_000;
31
32/// The bound on one swap's recorded change: ±100,000 bps (±1,000%). Losses stop at −10,000 bps
33/// (−100%) on their own, so only gains reach it.
34pub const CHANGE_CLAMP_BPS: i128 = 10 * BPS_SCALE;
35
36/// A recorded change, and whether [`CHANGE_CLAMP_BPS`] is what bounded it.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub struct ChangeBps {
39    /// The change in basis points, clamped to ±[`CHANGE_CLAMP_BPS`].
40    pub bps: i64,
41    /// Whether the clamp bounded it.
42    pub clamped: bool,
43}
44
45/// Change from `base` to `new` in bps, `(new - base) * 10_000 / base`, clamped to
46/// ±[`CHANGE_CLAMP_BPS`].
47///
48/// # Panics
49///
50/// Panics when `base` is 0.
51pub fn clamped_change_bps(new: u64, base: u64) -> ChangeBps {
52    let raw = (i128::from(new) - i128::from(base)) * BPS_SCALE / i128::from(base);
53    #[expect(
54        clippy::cast_possible_truncation,
55        reason = "clamped to ±CHANGE_CLAMP_BPS (±100_000), which fits in i64"
56    )]
57    let bps = raw.clamp(-CHANGE_CLAMP_BPS, CHANGE_CLAMP_BPS) as i64;
58    ChangeBps {
59        bps,
60        clamped: raw.abs() >= CHANGE_CLAMP_BPS,
61    }
62}
63
64/// The slot the payload was produced at, in the shape every other subscription's context takes.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct ReplacementContext {
67    /// The slot the stand-in was simulated in.
68    pub slot: u64,
69}
70
71/// The identity and outcome every notification carries, whatever its kind. Flattened into the
72/// notification's top level.
73#[serde_as]
74#[derive(Debug, Clone, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76pub struct ReplacementCore {
77    #[expect(missing_docs, reason = "self-explanatory")]
78    pub context: ReplacementContext,
79    /// The slot the stand-in was simulated in.
80    pub slot: u64,
81    /// Batch within its slot that the original swap executed in. A reroute through the router is
82    /// simulated just before this batch; a probe and the replayed original are simulated earlier,
83    /// at the pricing point (see [`VenueNotification::quote_lag_blocks`]).
84    pub batch_index: u32,
85    /// The original swap's transaction signature, base58.
86    #[serde_as(as = "serde_with::DisplayFromStr")]
87    pub original_signature: Signature,
88    /// The original swap failed onchain, so it filled nothing. Defaults to `false`.
89    #[serde(default)]
90    pub original_failed: bool,
91    /// `filled`, `reverted`, `unattributed`, `unsimulatable` or `unresolved`, for every kind. A
92    /// string rather than an enum, so a value the server adds later still decodes.
93    pub outcome: String,
94    /// The failure bucket; absent unless it failed. Group failures by it.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub category: Option<String>,
97    /// The error message behind [`Self::category`]. `err` on the wire.
98    #[serde(rename = "err", default, skip_serializing_if = "Option::is_none")]
99    pub error: Option<String>,
100}
101
102/// What the original swap filled, and how the stand-in scored against it. Flattened into the
103/// notification's top level. `l1` in a name means the original (onchain) swap.
104///
105/// The scope differs by kind: a venue probe scores one HOP's onchain output, a replayed original
106/// the net route flow across the whole SWAP's pair, a reroute what the original realized across
107/// the transaction. Compare within a kind; never sum or average across kinds.
108#[derive(Debug, Clone, Serialize, Deserialize)]
109#[serde(rename_all = "camelCase")]
110pub struct L1Score {
111    /// What the original swap filled, in raw base units (wire `l1Fill`). `None` when it filled
112    /// zero, which is no baseline.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub l1_fill: Option<u64>,
115    /// The stand-in against [`Self::l1_fill`] in bps, clamped to ±[`CHANGE_CLAMP_BPS`]
116    /// (wire `changeVsL1Bps`). Positive means it beat the original swap. Absent when either side
117    /// is missing or zero.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub change_vs_l1_bps: Option<i64>,
120}
121
122impl L1Score {
123    /// Score `measured` against what the original swap moved on the same side. ExactIn measures
124    /// output, so more is better; ExactOut measures the input charged, so the sign is flipped and
125    /// positive always means the stand-in beat what traded. A historical fill of zero is no
126    /// baseline: dividing by it would clamp to a number rather than say nothing.
127    ///
128    /// A measured zero is left unscored for the same reason. Some venues decline by returning
129    /// zero rather than by reverting, which is a refusal to quote and not a quote of nothing;
130    /// scored, it lands at [`CHANGE_CLAMP_BPS`] and a handful of declines sink a venue's mean far
131    /// below what it actually paid.
132    pub fn new(measured: Option<u64>, l1_fill: u64, mode: SwapMode) -> Self {
133        let l1_fill = (l1_fill > 0).then_some(l1_fill);
134        Self {
135            l1_fill,
136            change_vs_l1_bps: measured.filter(|&measured| measured > 0).zip(l1_fill).map(
137                |(measured, l1)| {
138                    let change = clamped_change_bps(measured, l1).bps;
139                    match mode {
140                        SwapMode::ExactIn => change,
141                        SwapMode::ExactOut => -change,
142                    }
143                },
144            ),
145        }
146    }
147}
148
149/// What simulating the stand-in cost. Flattened into the notification's top level.
150///
151/// Only the kinds that simulate a whole transaction carry it; a venue probe does not.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153#[serde(rename_all = "camelCase")]
154pub struct SimCost {
155    #[expect(missing_docs, reason = "self-explanatory")]
156    pub compute_units_consumed: u64,
157    /// The transaction fee, in lamports. `None` when it was not recorded.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub fee: Option<u64>,
160}
161
162/// One swap of a transaction rerouted through the router.
163#[serde_as]
164#[derive(Debug, Clone, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166pub struct RerouteLegNotification {
167    /// The mint the swap sells, base58.
168    #[serde_as(as = "serde_with::DisplayFromStr")]
169    pub input_mint: Address,
170    /// The mint the swap buys, base58.
171    #[serde_as(as = "serde_with::DisplayFromStr")]
172    pub output_mint: Address,
173    /// The swap's fixed amount, in raw base units: of `input_mint` for `ExactIn`, of
174    /// `output_mint` for `ExactOut`.
175    pub amount: u64,
176    /// `ExactIn` or `ExactOut`, as [`SwapMode`] spells them.
177    pub swap_mode: String,
178    /// The output the original swap's instruction quoted, in raw base units of `output_mint`.
179    pub original_quoted_out: u64,
180    /// The output the router quoted for the reroute, in raw base units of `output_mint`.
181    pub metis_quoted_out: u64,
182    /// The router's route as text: `Raydium → Orca` for a path, `60% Raydium | 40% Orca` for a split,
183    /// `(no route)` when it named no venue.
184    pub route_summary: String,
185    /// The route the router quoted, when it returned one.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub route_plan: Option<RoutePlan>,
188    /// The route the original swap took, which the reroute displaced.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub original_route_plan: Option<RoutePlan>,
191    /// What each hop actually moved. `route_plan` is the quote; this is the fill, and the side
192    /// to compare `original_route_plan` against.
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub realized_route_plan: Option<RoutePlan>,
195}
196
197/// A transaction rerouted through the router (`kind: "requote"`): the original swap's transaction
198/// re-quoted and simulated. The original still executed onchain; this
199/// result is never committed.
200#[derive(Debug, Clone, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct RequoteNotification {
203    /// The fields every kind carries, flattened into this object on the wire.
204    #[serde(flatten)]
205    pub core: ReplacementCore,
206    /// Scored at whole-transaction scope: what the original realized against what the routed
207    /// stand-in did, output against output in both swap modes. Absent for a multi-swap
208    /// transaction, where no single pair names the fill; read [`Self::legs`] instead.
209    #[serde(flatten)]
210    pub comparison: L1Score,
211    /// What simulating the routed transaction cost, flattened into this object on the wire.
212    #[serde(flatten)]
213    pub cost: SimCost,
214    /// One per detected swap in the original, in order.
215    #[serde(default)]
216    pub legs: Vec<RerouteLegNotification>,
217    /// The routed transaction that was simulated. Decode with
218    /// `simulator_client::decode_transaction` (base64 wincode of `VersionedTransaction`) to inspect
219    /// its instructions.
220    pub routed_transaction: EncodedBinary,
221    /// Program logs from simulating the routed transaction.
222    #[serde(default)]
223    pub logs: Vec<String>,
224    /// What the routed swap produced, in raw output-mint base units. `None` for a multi-swap
225    /// transaction, a missing output balance record, or a reverted simulation.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub realized_output_amount: Option<u64>,
228    /// What the original swap produced onchain, from its recorded balance changes, in raw
229    /// output-mint base units. `None` under the same conditions, but set whatever the
230    /// simulation's outcome, so it is present even when the core carries an error.
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub original_realized_output_amount: Option<u64>,
233}
234
235/// The hop a venue probe re-priced, as the original swap ran it onchain and as the replay ran it.
236#[serde_as]
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238#[serde(rename_all = "camelCase")]
239pub struct ProbedHop {
240    /// The block the hop executed in. The probe itself ran at [`ReplacementCore::slot`], which is
241    /// earlier by [`VenueNotification::quote_lag_blocks`].
242    pub slot: u64,
243    /// That block's Unix timestamp, in seconds.
244    pub block_time: i64,
245    /// The transaction's position in that block.
246    pub tx_index: u32,
247    /// Which swap of the transaction this hop belongs to.
248    pub ix_index: u32,
249    /// Which hop of that swap this is.
250    pub leg_index: u32,
251    /// The venue program that priced the original hop. `None` when the route events attribute it to
252    /// none.
253    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
254    #[serde(default)]
255    pub program: Option<Address>,
256    /// What the original hop took in, in raw base units.
257    pub input_amount: u64,
258    /// What the original hop paid out, in raw base units.
259    pub output_amount: u64,
260    /// The same hop as the replayed original took it. `None` when the replay did not recover the
261    /// hop - it reverted, its route decoded without that hop, or it split the hop differently. Its
262    /// input can differ from `input_amount` when an earlier hop filled differently, so compare
263    /// output per unit of input.
264    #[serde(default)]
265    pub replay_input_amount: Option<u64>,
266    /// What the replayed hop paid out, in raw base units. `None` under the same conditions as
267    /// `replay_input_amount`.
268    #[serde(default)]
269    pub replay_output_amount: Option<u64>,
270}
271
272/// A venue probe (`kind: "directFill"`): one hop rerouted directly to a venue through your
273/// template, simulated against the state it would have traded on.
274///
275/// A probe prices ONE hop, so the mints and amount here are the hop's, never the enclosing
276/// swap's.
277#[serde_as]
278#[derive(Debug, Clone, Serialize, Deserialize)]
279#[serde(rename_all = "camelCase")]
280pub struct VenueNotification {
281    /// The fields every kind carries, flattened into this object on the wire.
282    #[serde(flatten)]
283    pub core: ReplacementCore,
284    /// Scored at hop scope, against the probed hop's own onchain output.
285    #[serde(flatten)]
286    pub comparison: L1Score,
287    /// The template the hop was rebuilt through.
288    pub template: String,
289    /// The program that template's instruction calls: for one built from an aggregator's route,
290    /// the aggregator's, which several venues share.
291    #[serde_as(as = "serde_with::DisplayFromStr")]
292    pub program: Address,
293    /// The hop this priced, as the original swap and the replay ran it.
294    pub hop: ProbedHop,
295    /// The transaction of block [`ReplacementCore::slot`] the pass that priced this probe ran
296    /// just before; 0 at the block's start, its transaction count at its end.
297    pub quote_tx_index: u32,
298    /// Blocks between the block the hop executes in and the one it was priced at.
299    pub quote_lag_blocks: u32,
300    /// The mint the hop sells, base58.
301    #[serde_as(as = "serde_with::DisplayFromStr")]
302    pub input_mint: Address,
303    /// The mint the hop buys, base58.
304    #[serde_as(as = "serde_with::DisplayFromStr")]
305    pub output_mint: Address,
306    /// The hop's fixed amount, in raw base units: its input for `ExactIn`, its output for
307    /// `ExactOut`.
308    pub amount: u64,
309    /// `ExactIn` or `ExactOut`, as [`SwapMode`] spells them.
310    pub swap_mode: String,
311    /// What the template filled, in raw base units of the measured mint. `None` unless the probe
312    /// filled attributably.
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub template_fill: Option<u64>,
315    /// What the probed template spent of its input; `None` unless the probe filled attributably.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub spent_amount: Option<u64>,
318}
319
320/// The original swap replayed as the baseline (`kind: "original"`): the historical transaction
321/// re-run against the state it was quoted at, so the other kinds can be scored against a number
322/// produced the same way rather than against the chain's.
323#[derive(Debug, Clone, Serialize, Deserialize)]
324#[serde(rename_all = "camelCase")]
325pub struct OriginalNotification {
326    /// The fields every kind carries, flattened into this object on the wire.
327    #[serde(flatten)]
328    pub core: ReplacementCore,
329    /// Scored at swap scope: the original swap's net route flow across the whole swap's pair.
330    #[serde(flatten)]
331    pub comparison: L1Score,
332    /// What replaying the original cost, flattened into this object on the wire.
333    #[serde(flatten)]
334    pub cost: SimCost,
335    /// The hops this replay produced.
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub route_plan: Option<RoutePlan>,
338    /// The hops the original swap took, decoded the same way, so the two are read against each
339    /// other rather than against differently-derived numbers.
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub l1_route_plan: Option<RoutePlan>,
342    /// What the replay produced, in raw output-mint base units, when a single swap's output could
343    /// be read off it.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub simulated_output_amount: Option<u64>,
346}
347
348/// One reroute result for an original swap, streamed over `replacementSubscribe`: through
349/// the router, directly to a venue, or the original swap replayed as the baseline. Nothing stands
350/// in for the original. Tagged by `kind`, with the variant's fields at the top level beside it.
351#[derive(Debug, Clone, Serialize, Deserialize)]
352#[serde(tag = "kind", rename_all = "camelCase")]
353pub enum ReplacementNotification {
354    /// A reroute through the router: the whole transaction re-quoted
355    /// (`"kind": "requote"`).
356    Requote(RequoteNotification),
357    /// A reroute directly to a venue: one hop re-priced through a venue template
358    /// (`"kind": "directFill"`).
359    #[serde(rename = "directFill")]
360    Venue(VenueNotification),
361    /// The original swap replayed as the baseline (`"kind": "original"`).
362    Original(OriginalNotification),
363}
364
365impl ReplacementNotification {
366    /// What every kind carries, whichever shape it arrived in.
367    pub const fn core(&self) -> &ReplacementCore {
368        match self {
369            Self::Requote(requote) => &requote.core,
370            Self::Venue(probe) => &probe.core,
371            Self::Original(original) => &original.core,
372        }
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use rstest::rstest;
379
380    use super::*;
381
382    #[rstest]
383    #[case::total_loss(0, 1_000, -10_000, false)]
384    #[case::unchanged(1_000, 1_000, 0, false)]
385    #[case::a_real_improvement(1_100, 1_000, 1_000, false)]
386    #[case::ten_x_is_the_last_unclamped(101_000, 10_000, 91_000, false)]
387    #[case::eleven_x_is_the_bound_itself(110_000, 10_000, 100_000, true)]
388    #[case::dust_base(1_000_000, 1, 100_000, true)]
389    fn a_change_reports_whether_the_clamp_bound_it(
390        #[case] new: u64,
391        #[case] base: u64,
392        #[case] bps: i64,
393        #[case] clamped: bool,
394    ) {
395        assert_eq!(clamped_change_bps(new, base), ChangeBps { bps, clamped });
396    }
397
398    #[rstest]
399    #[case::no_baseline(Some(1_000), 0, SwapMode::ExactIn, None, None)]
400    #[case::no_measurement(None, 1_000, SwapMode::ExactIn, Some(1_000), None)]
401    #[case::beat_it(Some(1_100), 1_000, SwapMode::ExactIn, Some(1_000), Some(1_000))]
402    #[case::lost_to_it(Some(900), 1_000, SwapMode::ExactIn, Some(1_000), Some(-1_000))]
403    #[case::tiny_baseline_clamps(
404        Some(u64::MAX),
405        1,
406        SwapMode::ExactIn,
407        Some(1),
408        Some(i64::try_from(CHANGE_CLAMP_BPS).unwrap())
409    )]
410    // ExactOut measures the input charged, so paying less is the win and the sign flips.
411    #[case::exact_out_paid_less(Some(900), 1_000, SwapMode::ExactOut, Some(1_000), Some(1_000))]
412    #[case::exact_out_paid_more(Some(1_100), 1_000, SwapMode::ExactOut, Some(1_000), Some(-1_000))]
413    // A venue declining with a zero is a refusal to quote, not a quote of nothing.
414    #[case::a_declined_quote_is_unscored(Some(0), 1_000, SwapMode::ExactIn, Some(1_000), None)]
415    fn scoring_a_fill_against_l1(
416        #[case] measured: Option<u64>,
417        #[case] l1_fill: u64,
418        #[case] mode: SwapMode,
419        #[case] expected_l1: Option<u64>,
420        #[case] expected_bps: Option<i64>,
421    ) {
422        let scored = L1Score::new(measured, l1_fill, mode);
423        assert_eq!(scored.l1_fill, expected_l1);
424        assert_eq!(scored.change_vs_l1_bps, expected_bps);
425    }
426
427    /// The absent halves have to vanish rather than serialize as nulls: a consumer distinguishes
428    /// "no baseline" from "scored zero", and both sides skip on `None`.
429    #[test]
430    fn an_unscored_comparison_emits_no_keys() {
431        let empty = serde_json::to_value(L1Score::new(None, 0, SwapMode::ExactIn))
432            .expect("a score serializes");
433        assert_eq!(empty, serde_json::json!({}));
434    }
435}