simulator_client/builders.rs
1use std::collections::{BTreeMap, BTreeSet};
2
3use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
4use bon::Builder;
5use simulator_api::{
6 AccountData, AccountModifications, ActionAnchor, ActionKind, BinaryEncoding, ContinueParams,
7 CreateBacktestSessionRequest, CreateBacktestSessionRequestV1, CreateSessionParams,
8 DiagnosticProbeParams, DiscoveryFilter, RerouteAggregators, RerouteFilter, RerouteParams,
9 RerouteScopes, ScheduledAction, VenueTemplate, replay_support,
10 session_name::{CreateToken, SessionName},
11};
12use solana_address::Address;
13use solana_client::rpc_client::SerializableTransaction;
14use thiserror::Error;
15
16use crate::BacktestClientError;
17
18/// Error serializing a transaction for injection.
19#[derive(Debug, Error)]
20pub enum SerializeEncodeError {
21 /// wincode could not serialize the transaction.
22 #[error("wincode serialization error: {0}")]
23 Wincode(#[from] wincode::WriteError),
24}
25
26/// Encodes a transaction the way [`ScheduledAction::transactions`] and
27/// [`ContinueParams::transactions`] carry it: the standard base64 of its wire bytes, the bytes
28/// `sendTransaction` takes, for a legacy, v0 or v1 transaction.
29///
30/// It serializes with wincode, which writes those bytes. bincode does not: it drops a v1
31/// transaction's version marker, so the server cannot read it back. Errors only if wincode cannot
32/// serialize the transaction.
33pub fn encode_transaction(
34 transaction: &impl SerializableTransaction,
35) -> Result<String, SerializeEncodeError> {
36 Ok(BASE64.encode(wincode::serialize(transaction)?))
37}
38
39/// Builder for the request that creates a session.
40///
41/// Set `start_slot` and exactly one of `end_slot` or `slot_count`; every other field has a
42/// default. Pass the result to [`crate::ManagedBacktestSession`], or turn it into wire params
43/// with [`Self::into_params`].
44#[derive(Debug, Clone, Builder)]
45pub struct CreateSession {
46 #[allow(missing_docs)]
47 pub start_slot: u64,
48
49 /// Last slot of the range to replay, inclusive. Set this or `slot_count`, not both.
50 pub end_slot: Option<u64>,
51
52 /// Slots to advance past `start_slot` (alternative to `end_slot`); the
53 /// session replays the inclusive range `[start_slot, start_slot + slot_count]`.
54 /// `slot_count = 0` replays just the start slot.
55 pub slot_count: Option<u64>,
56
57 /// When true, include a session summary with transaction statistics in the Completed response.
58 #[builder(default)]
59 pub send_summary: bool,
60
61 /// When true, reroute historical swaps: through the router (see
62 /// `reroute_requote`), directly to a venue (see `reroute_venue_templates`), or both.
63 ///
64 /// Each original swap is priced at its pricing point: `quote_lag_blocks` blocks before the
65 /// block it executed in.
66 /// - Through the router: it quotes at the pricing point, and the new transaction is
67 /// simulated just before the original swap, in its block.
68 /// - Directly to a venue: each probe is simulated at the pricing point.
69 /// - Both: the original swap is replayed at the pricing point.
70 ///
71 /// Every simulation is discarded. The original transactions still run, so the replay is
72 /// unchanged. Every other `reroute_*` field needs this.
73 #[builder(default)]
74 pub reroute_order_flow: bool,
75
76 /// When true, also reroute swaps whose original transaction failed on slippage or after the
77 /// swap ran. They are reported apart from the other reroutes. `l1` in the name means the
78 /// original (onchain) swap.
79 #[builder(default)]
80 pub detect_failed_l1_swaps: bool,
81
82 /// Which aggregators' historical swaps to reroute; Jupiter alone by default.
83 #[builder(default)]
84 pub reroute_aggregators: RerouteAggregators,
85
86 /// Where a swap may have run to be rerouted; top-level router instructions alone by default.
87 #[builder(default)]
88 pub reroute_scopes: RerouteScopes,
89
90 /// When true, also reroute atomic arbitrage (same input and output mint).
91 #[builder(default)]
92 pub reroute_circular_arbs: bool,
93
94 /// Restrict rerouting to swaps trading these mint pairs. `sim run` has no flag for this.
95 pub reroute_filter: Option<RerouteFilter>,
96
97 /// Templates for rerouting directly to a venue, probed against the hops the session detects.
98 #[builder(default)]
99 pub reroute_venue_templates: Vec<VenueTemplate>,
100
101 /// When true (the default), reroute through the router. Set it to false to
102 /// reroute only directly to a venue, with `reroute_venue_templates`.
103 #[builder(default = true)]
104 pub reroute_requote: bool,
105
106 /// Pools for the router to consider on top of the markets it already knows. Each must hold
107 /// an account at the start of the range; give a pool that exists nowhere onchain its
108 /// accounts with [`Self::add_override`] at `start_slot`.
109 #[builder(default)]
110 pub reroute_extra_markets: BTreeSet<Address>,
111
112 /// Price swaps at their quote slot's end, or just before their own batch in their land slot.
113 #[builder(default)]
114 pub reroute_quote_late_in_slot: bool,
115
116 /// When true, split the range across concurrent sessions: a parallel run. Start it with
117 /// [`crate::managed::ManagedParallelSession`].
118 #[builder(default)]
119 pub parallel: bool,
120
121 /// Name for the session, or for the whole run when `parallel` is set; the server assigns
122 /// one when unset. A name is never reused: one an earlier session already took fails with
123 /// [`simulator_api::BacktestError::SessionNameTaken`].
124 pub name: Option<SessionName>,
125
126 /// Seconds the server keeps trying to start the session while it has no capacity, before
127 /// it fails the create. Unset or 0 fails at once when the server is busy, so set it for any
128 /// unattended run; `sim run` uses 900.
129 pub capacity_wait_timeout_secs: Option<u16>,
130
131 /// Seconds the server keeps the session alive with no client attached —
132 /// the window a reconnecting client has to reattach and resume. Must cover
133 /// your retry policy. Unset, the server uses 30 (900 for a parallel run),
134 /// and it caps this at 900; 0 ends the session with the connection. For a
135 /// single session left unset, [`crate::ManagedBacktestSession`] substitutes
136 /// [`crate::managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`] (360).
137 pub disconnect_timeout_secs: Option<u16>,
138
139 /// Extra compute units to add to each transaction's SetComputeUnitLimit budget.
140 pub extra_compute_units: Option<u32>,
141
142 /// Batch discovery filters registered at session creation. For each
143 /// filter, the server emits [`simulator_api::BacktestResponse::DiscoveryBatch`] ahead
144 /// of every matching batch.
145 #[builder(default)]
146 pub discoveries: Vec<DiscoveryFilter>,
147
148 /// Transactions the server runs automatically during the session, with
149 /// results streamed over `actionSubscribe`.
150 #[builder(default)]
151 pub actions: Vec<ScheduledAction>,
152
153 /// When true, apply the account states recorded for this range instead of executing its
154 /// transactions, which is faster. The range needs an account-state bundle.
155 #[builder(default)]
156 pub replay_account_state: bool,
157
158 /// Markets the server probes through the router's `/diagnostic` endpoint, streamed over
159 /// `diagnosticSubscribe`. Only `afterSlot` and `afterEverySlot` anchors are supported.
160 #[builder(default)]
161 pub diagnostic_probes: Vec<DiagnosticProbeParams>,
162}
163
164impl CreateSession {
165 /// Schedule counterfactual account overrides from `slot` onward, per account until a later
166 /// override names that account. Rerouted swaps, account reads by address and the geyser
167 /// account stream see them; the replay never does. Requires `reroute_order_flow`.
168 pub fn add_override(mut self, slot: u64, overrides: AccountModifications) -> Self {
169 self.actions.push(ScheduledAction {
170 anchor: ActionAnchor::BeforeSlot { slots: vec![slot] },
171 kind: ActionKind::default(),
172 feeds_reroute: true,
173 transactions: Vec::new(),
174 account_overrides: overrides,
175 return_accounts: Vec::new(),
176 label: None,
177 resolve: None,
178 within: None,
179 });
180 self
181 }
182
183 /// Convert the builder into API parameters.
184 ///
185 /// # Errors
186 ///
187 /// [`BacktestClientError::InvalidParams`], before anything is sent, when:
188 ///
189 /// - both or neither of `end_slot` and `slot_count` are set;
190 /// - `start_slot + slot_count` overflows, or `end_slot` is before `start_slot`;
191 /// - a diagnostic probe or an action's resolver is invalid;
192 /// - a `send` action is scheduled with `replay_account_state` set.
193 pub fn into_params(self) -> Result<CreateSessionParams, BacktestClientError> {
194 let end_slot = match (self.end_slot, self.slot_count) {
195 (Some(_), Some(_)) => {
196 return Err(BacktestClientError::InvalidParams {
197 message: "CreateSession: set only one of end_slot or slot_count".to_string(),
198 });
199 }
200 (Some(end_slot), None) => end_slot,
201 (None, Some(slot_count)) => {
202 self.start_slot.checked_add(slot_count).ok_or_else(|| {
203 BacktestClientError::InvalidParams {
204 message: "CreateSession: start_slot + slot_count overflow".to_string(),
205 }
206 })?
207 }
208 (None, None) => {
209 return Err(BacktestClientError::InvalidParams {
210 message: "CreateSession: must set end_slot or slot_count".to_string(),
211 });
212 }
213 };
214
215 if end_slot < self.start_slot {
216 return Err(BacktestClientError::InvalidParams {
217 message: format!(
218 "CreateSession: end_slot ({end_slot}) must be >= start_slot ({})",
219 self.start_slot
220 ),
221 });
222 }
223
224 let params = CreateSessionParams::builder()
225 .start_slot(self.start_slot)
226 .end_slot(end_slot)
227 .send_summary(self.send_summary)
228 .maybe_reroute(self.reroute_order_flow.then_some(RerouteParams {
229 aggregators: self.reroute_aggregators,
230 scopes: self.reroute_scopes,
231 filter: self.reroute_filter,
232 detect_failed_l1_swaps: self.detect_failed_l1_swaps,
233 circular_arbs: self.reroute_circular_arbs,
234 requote: self.reroute_requote,
235 venue_templates: self.reroute_venue_templates,
236 extra_markets: self.reroute_extra_markets,
237 quote_late_in_slot: self.reroute_quote_late_in_slot,
238 }))
239 .maybe_capacity_wait_timeout_secs(self.capacity_wait_timeout_secs)
240 .maybe_disconnect_timeout_secs(self.disconnect_timeout_secs)
241 .maybe_extra_compute_units(self.extra_compute_units)
242 .discoveries(self.discoveries)
243 .actions(self.actions)
244 .replay_account_state(self.replay_account_state)
245 .diagnostic_probes(self.diagnostic_probes)
246 .build();
247
248 // Same reason as the send-action check below: caught here to save the round trip, and
249 // enforced again by the session itself.
250 if let Err(error) = params.validate_diagnostic_probes() {
251 return Err(BacktestClientError::InvalidParams {
252 message: error.to_string(),
253 });
254 }
255 params
256 .validate_action_resolvers()
257 .map_err(|error| BacktestClientError::InvalidParams {
258 message: error.to_string(),
259 })?;
260
261 // Caught here purely to save the round trip; the manager and the session
262 // enforce the same rule through the same wording.
263 match replay_support::send_action_conflict(¶ms) {
264 Some(message) => Err(BacktestClientError::InvalidParams { message }),
265 None => Ok(params),
266 }
267 }
268
269 /// Convert the builder into a versioned create request.
270 ///
271 /// Emits the V1 request when `parallel` or `name` is set, and V0 otherwise. With a `name`,
272 /// each call generates a new create token, which marks a resent request as the same create.
273 /// To retry, resend the returned request: a rebuilt one fails with
274 /// [`simulator_api::BacktestError::SessionNameTaken`] once the first has taken the name.
275 ///
276 /// # Errors
277 ///
278 /// As [`Self::into_params`].
279 pub fn into_request(mut self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
280 let parallel = self.parallel;
281 let (name, create_token) = self
282 .name
283 .take()
284 .map(|name| (name.to_string(), CreateToken::random()))
285 .unzip();
286 let request = self.into_params()?;
287 if parallel || name.is_some() {
288 Ok(CreateBacktestSessionRequestV1 {
289 request,
290 parallel,
291 name,
292 create_token,
293 }
294 .into())
295 } else {
296 Ok(request.into())
297 }
298 }
299}
300
301/// Builder for a `continue` request.
302///
303/// Use it to advance the session, run user transactions, or apply account overrides. The server
304/// runs the user transactions first, then writes the overrides, then executes the blocks.
305#[derive(Debug, Builder)]
306pub struct Continue {
307 /// Blocks to execute before the session waits again. Default 1. A skipped slot has no
308 /// block and is not counted.
309 #[builder(default = ContinueParams::default_advance_count())]
310 pub advance_count: u64,
311
312 /// User transactions to run before advancing, each the standard base64 of the transaction's
313 /// wire bytes. Add them with [`Self::push_transaction`], which encodes for you.
314 #[builder(default)]
315 pub transactions: Vec<String>,
316
317 /// Account overrides, written after the user transactions and before the first block.
318 #[builder(default)]
319 pub modify_accounts: BTreeMap<Address, AccountData>,
320}
321
322impl Continue {
323 /// Append a transaction that is already encoded as [`encode_transaction`] does.
324 pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
325 self.transactions.push(data.into());
326 self
327 }
328
329 /// Append a transaction's wire bytes, encoding them as base64.
330 pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
331 self.transactions.push(BinaryEncoding::Base64.encode(bytes));
332 self
333 }
334
335 /// Append a transaction, encoded with [`encode_transaction`].
336 ///
337 /// # Errors
338 ///
339 /// [`SerializeEncodeError`] if wincode cannot serialize the transaction.
340 pub fn push_transaction(
341 mut self,
342 transaction: &impl SerializableTransaction,
343 ) -> Result<Self, SerializeEncodeError> {
344 self.transactions.push(encode_transaction(transaction)?);
345 Ok(self)
346 }
347
348 /// Override one account's state, as an entry of `modify_accounts`.
349 pub fn modify_account(mut self, address: Address, account: AccountData) -> Self {
350 self.modify_accounts.insert(address, account);
351 self
352 }
353
354 /// Convert the builder into API parameters.
355 pub fn into_params(self) -> ContinueParams {
356 ContinueParams {
357 advance_count: self.advance_count,
358 transactions: self.transactions,
359 modify_account_states: AccountModifications(self.modify_accounts),
360 }
361 }
362}