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