Skip to main content

simulator_api/
route_plan.rs

1//! One route, hop by hop: what the router quotes, what a decoded transaction reports, and what
2//! both are recorded and streamed as. Only the router names a pool; only a transaction's route
3//! events name the program that ran a hop.
4//!
5//! Addresses and amounts stay as strings — nothing here does address arithmetic, and a raw token
6//! amount exceeds what a JSON number holds exactly.
7//!
8//! Every field is concrete and always written. A plan is recorded through bincode, whose decoder
9//! reads fields positionally: `#[serde(flatten)]` and [`serde_json::Value`] cannot cross it, and
10//! `skip_serializing_if` desynchronizes it. An unset value therefore travels as an explicit null,
11//! which costs a JSON reader nothing — `json_extract` answers null for a missing key either way.
12
13use serde::{Deserialize, Serialize};
14
15/// A whole route in the order its hops run. Deserialization bypasses [`RoutePlan::new`], so a
16/// plan read off the wire can still be empty.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(transparent)]
19pub struct RoutePlan(Vec<RouteHop>);
20
21impl RoutePlan {
22    /// `None` for no hops: an empty route is an absence, not a route that filled nothing.
23    pub fn new(hops: Vec<RouteHop>) -> Option<Self> {
24        (!hops.is_empty()).then_some(Self(hops))
25    }
26
27    /// The hops, in the order they run.
28    pub fn hops(&self) -> &[RouteHop] {
29        &self.0
30    }
31
32    /// No hops. Only a plan read off the wire can be empty.
33    pub fn is_empty(&self) -> bool {
34        self.0.is_empty()
35    }
36
37    /// The trade was split across pools; see [`is_split`].
38    pub fn is_split(&self) -> bool {
39        is_split(&self.0)
40    }
41}
42
43/// The trade was split across pools rather than routed as one path, so the hops are branches and
44/// cannot line up positionally against a sequential original.
45pub fn is_split(hops: &[RouteHop]) -> bool {
46    hops.iter().any(|hop| hop.percent != FULL_PERCENT)
47}
48
49/// A route's identity for deduplication: two routes over the same pools fill the same way
50/// whatever order the router lists them in. Skips hops the router gave no pool for.
51pub fn pool_keys(hops: &[RouteHop]) -> impl Iterator<Item = &str> {
52    hops.iter().filter_map(RouteHop::amm_key)
53}
54
55/// The venue labels of the hops that have one, in order.
56pub fn labels(hops: &[RouteHop]) -> impl Iterator<Item = &str> {
57    hops.iter().filter_map(RouteHop::label)
58}
59
60/// The whole trade through one hop; anything less is a split.
61pub const FULL_PERCENT: u64 = 100;
62
63const fn full_percent() -> u64 {
64    FULL_PERCENT
65}
66
67/// One hop of a route: a swap through one venue. Wire keys are camelCase.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "camelCase")]
70pub struct RouteHop {
71    /// Execution order, from a decoded transaction; the router's plan is ordered but unnumbered.
72    #[serde(default)]
73    pub leg: Option<u32>,
74    /// Share of the trade this hop carries, out of 100. Defaults to [`FULL_PERCENT`].
75    #[serde(default = "full_percent")]
76    pub percent: u64,
77    /// The venue program's address, base58. Set by a decoded transaction, where the router sets
78    /// [`RouteHopSwapInfo::amm_key`].
79    #[serde(default)]
80    pub program: Option<String>,
81    /// Sent by the router, null in everything observed.
82    #[serde(default)]
83    pub bps: Option<u64>,
84    /// The venue, pool, mints and amounts.
85    pub swap_info: RouteHopSwapInfo,
86}
87
88/// `percent` starts at [`FULL_PERCENT`]: a hop is the whole trade unless a split says otherwise.
89impl Default for RouteHop {
90    fn default() -> Self {
91        Self {
92            leg: None,
93            percent: FULL_PERCENT,
94            program: None,
95            bps: None,
96            swap_info: RouteHopSwapInfo::default(),
97        }
98    }
99}
100
101impl RouteHop {
102    /// [`RouteHopSwapInfo::label`].
103    pub fn label(&self) -> Option<&str> {
104        self.swap_info.label.as_deref()
105    }
106
107    /// [`RouteHopSwapInfo::amm_key`].
108    pub fn amm_key(&self) -> Option<&str> {
109        self.swap_info.amm_key.as_deref()
110    }
111
112    /// [`RouteHopSwapInfo::input_mint`].
113    pub fn input_mint(&self) -> Option<&str> {
114        self.swap_info.input_mint.as_deref()
115    }
116
117    /// [`RouteHopSwapInfo::output_mint`].
118    pub fn output_mint(&self) -> Option<&str> {
119        self.swap_info.output_mint.as_deref()
120    }
121}
122
123/// What one hop swapped, and where. Wire keys are camelCase.
124#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(rename_all = "camelCase")]
126pub struct RouteHopSwapInfo {
127    /// The venue's name, e.g. `Raydium`. `None` where the hop's program has no known label, which
128    /// is a hop that cannot be compared by venue rather than a hop with no venue.
129    #[serde(default)]
130    pub label: Option<String>,
131    /// The pool crossed, base58. Only the router names it; route events repeat the program id in `amm`.
132    #[serde(default)]
133    pub amm_key: Option<String>,
134    /// The mint the hop takes in, base58.
135    #[serde(default)]
136    pub input_mint: Option<String>,
137    /// What the hop takes in, in raw input-mint base units, as a decimal string.
138    #[serde(default)]
139    pub in_amount: Option<String>,
140    /// The mint the hop pays out, base58.
141    #[serde(default)]
142    pub output_mint: Option<String>,
143    /// What the hop pays out, in raw output-mint base units, as a decimal string.
144    #[serde(default)]
145    pub out_amount: Option<String>,
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    fn hop(percent: u64) -> RouteHop {
153        RouteHop {
154            percent,
155            ..Default::default()
156        }
157    }
158
159    #[test]
160    fn no_hops_is_absent_rather_than_empty() {
161        assert_eq!(RoutePlan::new(Vec::new()), None);
162        assert_eq!(
163            RoutePlan::new(vec![hop(FULL_PERCENT)]).map(|plan| plan.hops().len()),
164            Some(1)
165        );
166    }
167
168    #[test]
169    fn a_route_is_split_when_any_hop_carries_less_than_the_whole_trade() {
170        assert!(
171            !RoutePlan::new(vec![hop(100), hop(100)])
172                .expect("a plan")
173                .is_split()
174        );
175        assert!(
176            RoutePlan::new(vec![hop(60), hop(40)])
177                .expect("a plan")
178                .is_split()
179        );
180    }
181
182    /// Both sources land on the same paths, so one reader covers every column.
183    #[test]
184    fn both_sources_serialize_onto_one_shape() {
185        let quoted = RouteHop {
186            swap_info: RouteHopSwapInfo {
187                label: Some("SolFi".to_string()),
188                amm_key: Some("pool".to_string()),
189                input_mint: Some("sol".to_string()),
190                in_amount: Some("1000".to_string()),
191                output_mint: Some("usdc".to_string()),
192                out_amount: Some("1010".to_string()),
193            },
194            ..Default::default()
195        };
196        let executed = RouteHop {
197            leg: Some(0),
198            program: Some("prog".to_string()),
199            swap_info: RouteHopSwapInfo {
200                amm_key: None,
201                ..quoted.swap_info.clone()
202            },
203            ..quoted
204        };
205
206        let json = |hop: &RouteHop| serde_json::to_value(hop).expect("json");
207        for value in [json(&quoted), json(&executed)] {
208            assert_eq!(value["percent"], 100);
209            assert_eq!(value["swapInfo"]["label"], "SolFi");
210            assert_eq!(value["swapInfo"]["inputMint"], "sol");
211            // Amounts are strings: a raw token amount exceeds what a JSON number holds exactly.
212            assert_eq!(value["swapInfo"]["inAmount"], "1000");
213            assert_eq!(value["swapInfo"]["outAmount"], "1010");
214        }
215        assert_eq!(json(&quoted)["swapInfo"]["ammKey"], "pool");
216        assert_eq!(json(&executed)["program"], "prog");
217    }
218
219    /// A stored column comes back out on the paths a reader queries it by.
220    #[test]
221    fn a_recorded_plan_reads_back_onto_the_paths_it_was_written_with() {
222        let recorded = r#"[{"percent":100,"swapInfo":{"label":"Aquifer","ammKey":"CNC5Tae","inputMint":"EPjFWdd","outputMint":"So11111","inAmount":"385638781","outAmount":"4999931316"},"bps":null}]"#;
223
224        let plan: RoutePlan = serde_json::from_str(recorded).expect("a recorded plan decodes");
225        let rewritten = serde_json::to_value(&plan).expect("json");
226
227        assert_eq!(rewritten[0]["percent"], 100);
228        assert_eq!(rewritten[0]["swapInfo"]["label"], "Aquifer");
229        assert_eq!(rewritten[0]["swapInfo"]["ammKey"], "CNC5Tae");
230        assert_eq!(rewritten[0]["swapInfo"]["inputMint"], "EPjFWdd");
231        assert_eq!(rewritten[0]["swapInfo"]["inAmount"], "385638781");
232        assert_eq!(rewritten[0]["swapInfo"]["outputMint"], "So11111");
233        assert_eq!(rewritten[0]["swapInfo"]["outAmount"], "4999931316");
234        assert_eq!(rewritten[0]["bps"], serde_json::Value::Null);
235    }
236
237    /// The positional decoder reads back exactly what was written, and a JSON reader resolves an
238    /// explicit null and an absent key alike.
239    #[test]
240    fn an_unset_field_is_written_as_null_rather_than_omitted() {
241        let value = serde_json::to_value(hop(FULL_PERCENT)).expect("json");
242
243        assert!(value.get("program").is_some(), "written, not skipped");
244        assert_eq!(value["program"], serde_json::Value::Null);
245        assert_eq!(value["swapInfo"]["ammKey"], serde_json::Value::Null);
246        assert_eq!(value["program"], value["neverWritten"]);
247    }
248}