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