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    /// Pools for the router to consider on top of the markets it already knows. Each must hold
84    /// an account at the start of the range; give a pool that exists nowhere on chain its
85    /// accounts with [`Self::add_override`] at `start_slot`.
86    #[builder(default)]
87    pub reroute_extra_markets: BTreeSet<Address>,
88
89    /// When true, ask manager to create all available sessions in the target epoch.
90    #[builder(default)]
91    pub parallel: bool,
92
93    pub capacity_wait_timeout_secs: Option<u16>,
94
95    /// Seconds the server keeps the session alive with no client attached —
96    /// the window a reconnecting client has to reattach and resume. Must cover
97    /// your retry policy: the server's own default is tens of seconds, and it
98    /// caps this at 900. Left unset, [`crate::ManagedBacktestSession`]
99    /// substitutes [`crate::managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`].
100    pub disconnect_timeout_secs: Option<u16>,
101
102    /// Extra compute units to add to each transaction's SetComputeUnitLimit budget.
103    pub extra_compute_units: Option<u32>,
104
105    /// Batch discovery filters registered at session creation. For each
106    /// filter, the server emits [`BacktestResponse::DiscoveryBatch`] ahead
107    /// of every matching batch so the caller can pause via
108    /// [`BacktestSession::advance_to_discovery`] before it executes.
109    #[builder(default)]
110    pub discoveries: Vec<DiscoveryFilter>,
111
112    /// Transactions the server runs automatically during the session, with
113    /// results streamed over `actionSubscribe`.
114    #[builder(default)]
115    pub actions: Vec<ScheduledAction>,
116
117    /// When true, replay the account states for this range instead of
118    /// executing transactions (state-only acceleration).
119    #[builder(default)]
120    pub replay_account_state: bool,
121
122    /// Markets the server probes through the sidecar metis' `/diagnostic` endpoint, streamed over
123    /// `diagnosticSubscribe`. Only `afterSlot` and `afterEverySlot` anchors are supported.
124    #[builder(default)]
125    pub diagnostic_probes: Vec<DiagnosticProbeParams>,
126}
127
128impl CreateSession {
129    /// Add an account to the signer filter.
130    pub fn add_signer_filter(mut self, address: Address) -> Self {
131        self.signer_filter.insert(address);
132        self
133    }
134
135    /// Schedule counterfactual account overrides from `slot` onward, per account until a later
136    /// override names that account. Rerouted swaps, account reads by address and the geyser
137    /// account stream see them; the replay never does. Requires `reroute_order_flow`.
138    pub fn add_override(mut self, slot: u64, overrides: AccountModifications) -> Self {
139        self.actions.push(ScheduledAction {
140            anchor: ActionAnchor::BeforeSlot { slots: vec![slot] },
141            kind: ActionKind::default(),
142            feeds_reroute: true,
143            transactions: Vec::new(),
144            account_overrides: overrides,
145            return_accounts: Vec::new(),
146            label: None,
147        });
148        self
149    }
150
151    /// Convert the builder into API parameters, validating slot options.
152    pub fn into_params(self) -> Result<CreateSessionParams, BacktestClientError> {
153        let end_slot = match (self.end_slot, self.slot_count) {
154            (Some(_), Some(_)) => {
155                return Err(BacktestClientError::InvalidParams {
156                    message: "CreateSession: set only one of end_slot or slot_count".to_string(),
157                });
158            }
159            (Some(end_slot), None) => end_slot,
160            (None, Some(slot_count)) => {
161                self.start_slot.checked_add(slot_count).ok_or_else(|| {
162                    BacktestClientError::InvalidParams {
163                        message: "CreateSession: start_slot + slot_count overflow".to_string(),
164                    }
165                })?
166            }
167            (None, None) => {
168                return Err(BacktestClientError::InvalidParams {
169                    message: "CreateSession: must set end_slot or slot_count".to_string(),
170                });
171            }
172        };
173
174        if end_slot < self.start_slot {
175            return Err(BacktestClientError::InvalidParams {
176                message: format!(
177                    "CreateSession: end_slot ({end_slot}) must be >= start_slot ({})",
178                    self.start_slot
179                ),
180            });
181        }
182
183        let params = CreateSessionParams::builder()
184            .start_slot(self.start_slot)
185            .end_slot(end_slot)
186            .signer_filter(self.signer_filter)
187            .send_summary(self.send_summary)
188            .maybe_reroute(self.reroute_order_flow.then_some(RerouteParams {
189                aggregators: self.reroute_aggregators,
190                filter: self.reroute_filter,
191                detect_failed_l1_swaps: self.detect_failed_l1_swaps,
192                circular_arbs: self.reroute_circular_arbs,
193                requote: self.reroute_requote,
194                direct_fill: self.reroute_direct_fill,
195                extra_markets: self.reroute_extra_markets,
196            }))
197            .maybe_capacity_wait_timeout_secs(self.capacity_wait_timeout_secs)
198            .maybe_disconnect_timeout_secs(self.disconnect_timeout_secs)
199            .maybe_extra_compute_units(self.extra_compute_units)
200            .discoveries(self.discoveries)
201            .actions(self.actions)
202            .replay_account_state(self.replay_account_state)
203            .diagnostic_probes(self.diagnostic_probes)
204            .build();
205
206        // Same reason as the send-action check below: caught here to save the round trip, and
207        // enforced again by the session itself.
208        if let Err(error) = params.validate_diagnostic_probes() {
209            return Err(BacktestClientError::InvalidParams {
210                message: error.to_string(),
211            });
212        }
213
214        // Caught here purely to save the round trip; the manager and the session
215        // enforce the same rule through the same wording.
216        match replay_support::send_action_conflict(&params) {
217            Some(message) => Err(BacktestClientError::InvalidParams { message }),
218            None => Ok(params),
219        }
220    }
221
222    /// Convert the builder into versioned create request payload.
223    pub fn into_request(self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
224        let parallel = self.parallel;
225        let request = self.into_params()?;
226        if parallel {
227            Ok(CreateBacktestSessionRequestV1 { request, parallel }.into())
228        } else {
229            Ok(request.into())
230        }
231    }
232}
233
234/// Builder for `Continue` requests.
235///
236/// Use this to advance the simulation, inject transactions, or patch accounts.
237#[derive(Debug, Builder)]
238pub struct Continue {
239    #[builder(default = ContinueParams::default_advance_count())]
240    pub advance_count: u64,
241
242    #[builder(default)]
243    pub transactions: Vec<String>,
244
245    #[builder(default)]
246    pub modify_accounts: BTreeMap<Address, AccountData>,
247}
248
249impl Continue {
250    /// Append a base64-encoded transaction payload.
251    pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
252        self.transactions.push(data.into());
253        self
254    }
255
256    /// Append a raw transaction payload encoded as base64.
257    pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
258        self.transactions.push(BinaryEncoding::Base64.encode(bytes));
259        self
260    }
261
262    /// Append a serializable transaction encoded as base64.
263    pub fn push_transaction(
264        mut self,
265        transaction: &impl SerializableTransaction,
266    ) -> Result<Self, SerializeEncodeError> {
267        self.transactions.push(serialize_to_base64(transaction)?);
268        Ok(self)
269    }
270
271    /// Modify an account state prior to execution.
272    pub fn modify_account(mut self, address: Address, account: AccountData) -> Self {
273        self.modify_accounts.insert(address, account);
274        self
275    }
276
277    /// Convert the builder into API parameters.
278    pub fn into_params(self) -> ContinueParams {
279        ContinueParams {
280            advance_count: self.advance_count,
281            transactions: self.transactions,
282            modify_account_states: AccountModifications(self.modify_accounts),
283        }
284    }
285}