Skip to main content

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, DirectFillTemplate, DiscoveryFilter, RerouteAggregators, RerouteFilter,
9    RerouteParams, ScheduledAction, 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    #[error("wincode serialization error: {0}")]
22    Wincode(#[from] wincode::WriteError),
23}
24
25// wincode is the serializer 4.2's transaction types carry; its bytes are the legacy short-vec
26// bincode wire format, so the base64 payload is unchanged.
27fn serialize_to_base64(
28    transaction: &impl SerializableTransaction,
29) -> Result<String, SerializeEncodeError> {
30    Ok(BASE64.encode(wincode::serialize(transaction)?))
31}
32
33/// Builder for `CreateBacktestSession`.
34///
35/// Set either `end_slot` or `slot_count` (not both). Use the helper methods to
36/// add account filters.
37#[derive(Debug, Clone, Builder)]
38pub struct CreateSession {
39    pub start_slot: u64,
40
41    pub end_slot: Option<u64>,
42
43    /// Slots to advance past `start_slot` (alternative to `end_slot`); the
44    /// session replays the inclusive range `[start_slot, start_slot + slot_count]`.
45    /// `slot_count = 0` replays just the start slot.
46    pub slot_count: Option<u64>,
47
48    /// When true, include a session summary with transaction statistics in the Completed response.
49    #[builder(default)]
50    pub send_summary: bool,
51
52    /// When true, replace historical swaps with transactions re-quoted through the
53    /// metis router against the current simulation state.
54    #[builder(default)]
55    pub reroute_order_flow: bool,
56
57    /// When true, also re-quote swaps whose L1 transaction failed in a way re-quoting can
58    /// answer. Tracked as a separate population from the headline reroute funnel.
59    #[builder(default)]
60    pub detect_failed_l1_swaps: bool,
61
62    /// Which aggregators' historical swaps to re-quote; Jupiter alone by default.
63    #[builder(default)]
64    pub reroute_aggregators: RerouteAggregators,
65
66    /// When true, also re-quote arbitrage cycles (same input and output mint).
67    #[builder(default)]
68    pub reroute_circular_arbs: bool,
69
70    /// Restrict rerouting to swaps trading these mint pairs.
71    pub reroute_filter: Option<RerouteFilter>,
72
73    /// Direct-fill templates to probe against the hops the run detects.
74    #[builder(default)]
75    pub reroute_direct_fill: Vec<DirectFillTemplate>,
76
77    /// Re-quote through metis. Off runs `reroute_direct_fill` alone, with no sidecar.
78    #[builder(default = true)]
79    pub reroute_requote: bool,
80
81    /// Pools for the router to consider on top of the markets it already knows. Each must hold
82    /// an account at the start of the range; give a pool that exists nowhere on chain its
83    /// accounts with [`Self::add_override`] at `start_slot`.
84    #[builder(default)]
85    pub reroute_extra_markets: BTreeSet<Address>,
86
87    /// When true, ask manager to create all available sessions in the target epoch.
88    #[builder(default)]
89    pub parallel: bool,
90
91    /// Name for the session, or for the whole run when `parallel` is set; the server assigns
92    /// one when unset. A name is never reused: one an earlier session already took fails with
93    /// [`simulator_api::BacktestError::SessionNameTaken`].
94    pub name: Option<SessionName>,
95
96    pub capacity_wait_timeout_secs: Option<u16>,
97
98    /// Seconds the server keeps the session alive with no client attached —
99    /// the window a reconnecting client has to reattach and resume. Must cover
100    /// your retry policy: the server's own default is tens of seconds, and it
101    /// caps this at 900. Left unset, [`crate::ManagedBacktestSession`]
102    /// substitutes [`crate::managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`].
103    pub disconnect_timeout_secs: Option<u16>,
104
105    /// Extra compute units to add to each transaction's SetComputeUnitLimit budget.
106    pub extra_compute_units: Option<u32>,
107
108    /// Batch discovery filters registered at session creation. For each
109    /// filter, the server emits [`BacktestResponse::DiscoveryBatch`] ahead
110    /// of every matching batch so the caller can pause via
111    /// [`BacktestSession::advance_to_discovery`] before it executes.
112    #[builder(default)]
113    pub discoveries: Vec<DiscoveryFilter>,
114
115    /// Transactions the server runs automatically during the session, with
116    /// results streamed over `actionSubscribe`.
117    #[builder(default)]
118    pub actions: Vec<ScheduledAction>,
119
120    /// When true, replay the account states for this range instead of
121    /// executing transactions (state-only acceleration).
122    #[builder(default)]
123    pub replay_account_state: bool,
124
125    /// Markets the server probes through the sidecar metis' `/diagnostic` endpoint, streamed over
126    /// `diagnosticSubscribe`. Only `afterSlot` and `afterEverySlot` anchors are supported.
127    #[builder(default)]
128    pub diagnostic_probes: Vec<DiagnosticProbeParams>,
129}
130
131impl CreateSession {
132    /// Schedule counterfactual account overrides from `slot` onward, per account until a later
133    /// override names that account. Rerouted swaps, account reads by address and the geyser
134    /// account stream see them; the replay never does. Requires `reroute_order_flow`.
135    pub fn add_override(mut self, slot: u64, overrides: AccountModifications) -> Self {
136        self.actions.push(ScheduledAction {
137            anchor: ActionAnchor::BeforeSlot { slots: vec![slot] },
138            kind: ActionKind::default(),
139            feeds_reroute: true,
140            transactions: Vec::new(),
141            account_overrides: overrides,
142            return_accounts: Vec::new(),
143            label: None,
144            resolve: None,
145        });
146        self
147    }
148
149    /// Convert the builder into API parameters, validating slot options.
150    pub fn into_params(self) -> Result<CreateSessionParams, BacktestClientError> {
151        let end_slot = match (self.end_slot, self.slot_count) {
152            (Some(_), Some(_)) => {
153                return Err(BacktestClientError::InvalidParams {
154                    message: "CreateSession: set only one of end_slot or slot_count".to_string(),
155                });
156            }
157            (Some(end_slot), None) => end_slot,
158            (None, Some(slot_count)) => {
159                self.start_slot.checked_add(slot_count).ok_or_else(|| {
160                    BacktestClientError::InvalidParams {
161                        message: "CreateSession: start_slot + slot_count overflow".to_string(),
162                    }
163                })?
164            }
165            (None, None) => {
166                return Err(BacktestClientError::InvalidParams {
167                    message: "CreateSession: must set end_slot or slot_count".to_string(),
168                });
169            }
170        };
171
172        if end_slot < self.start_slot {
173            return Err(BacktestClientError::InvalidParams {
174                message: format!(
175                    "CreateSession: end_slot ({end_slot}) must be >= start_slot ({})",
176                    self.start_slot
177                ),
178            });
179        }
180
181        let params = CreateSessionParams::builder()
182            .start_slot(self.start_slot)
183            .end_slot(end_slot)
184            .send_summary(self.send_summary)
185            .maybe_reroute(self.reroute_order_flow.then_some(RerouteParams {
186                aggregators: self.reroute_aggregators,
187                filter: self.reroute_filter,
188                detect_failed_l1_swaps: self.detect_failed_l1_swaps,
189                circular_arbs: self.reroute_circular_arbs,
190                requote: self.reroute_requote,
191                direct_fill: self.reroute_direct_fill,
192                extra_markets: self.reroute_extra_markets,
193            }))
194            .maybe_capacity_wait_timeout_secs(self.capacity_wait_timeout_secs)
195            .maybe_disconnect_timeout_secs(self.disconnect_timeout_secs)
196            .maybe_extra_compute_units(self.extra_compute_units)
197            .discoveries(self.discoveries)
198            .actions(self.actions)
199            .replay_account_state(self.replay_account_state)
200            .diagnostic_probes(self.diagnostic_probes)
201            .build();
202
203        // Same reason as the send-action check below: caught here to save the round trip, and
204        // enforced again by the session itself.
205        if let Err(error) = params.validate_diagnostic_probes() {
206            return Err(BacktestClientError::InvalidParams {
207                message: error.to_string(),
208            });
209        }
210        params
211            .validate_action_resolvers()
212            .map_err(|error| BacktestClientError::InvalidParams {
213                message: error.to_string(),
214            })?;
215
216        // Caught here purely to save the round trip; the manager and the session
217        // enforce the same rule through the same wording.
218        match replay_support::send_action_conflict(&params) {
219            Some(message) => Err(BacktestClientError::InvalidParams { message }),
220            None => Ok(params),
221        }
222    }
223
224    /// Convert the builder into versioned create request payload.
225    /// Each call mints a new create token; resend the returned request, not a rebuilt one, to
226    /// reclaim its name.
227    pub fn into_request(mut self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
228        let parallel = self.parallel;
229        let (name, create_token) = self
230            .name
231            .take()
232            .map(|name| (name.to_string(), CreateToken::random()))
233            .unzip();
234        let request = self.into_params()?;
235        if parallel || name.is_some() {
236            Ok(CreateBacktestSessionRequestV1 {
237                request,
238                parallel,
239                name,
240                create_token,
241            }
242            .into())
243        } else {
244            Ok(request.into())
245        }
246    }
247}
248
249/// Builder for `Continue` requests.
250///
251/// Use this to advance the simulation, inject transactions, or patch accounts.
252#[derive(Debug, Builder)]
253pub struct Continue {
254    #[builder(default = ContinueParams::default_advance_count())]
255    pub advance_count: u64,
256
257    #[builder(default)]
258    pub transactions: Vec<String>,
259
260    #[builder(default)]
261    pub modify_accounts: BTreeMap<Address, AccountData>,
262}
263
264impl Continue {
265    /// Append a base64-encoded transaction payload.
266    pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
267        self.transactions.push(data.into());
268        self
269    }
270
271    /// Append a raw transaction payload encoded as base64.
272    pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
273        self.transactions.push(BinaryEncoding::Base64.encode(bytes));
274        self
275    }
276
277    /// Append a serializable transaction encoded as base64.
278    pub fn push_transaction(
279        mut self,
280        transaction: &impl SerializableTransaction,
281    ) -> Result<Self, SerializeEncodeError> {
282        self.transactions.push(serialize_to_base64(transaction)?);
283        Ok(self)
284    }
285
286    /// Modify an account state prior to execution.
287    pub fn modify_account(mut self, address: Address, account: AccountData) -> Self {
288        self.modify_accounts.insert(address, account);
289        self
290    }
291
292    /// Convert the builder into API parameters.
293    pub fn into_params(self) -> ContinueParams {
294        ContinueParams {
295            advance_count: self.advance_count,
296            transactions: self.transactions,
297            modify_account_states: AccountModifications(self.modify_accounts),
298        }
299    }
300}