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