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