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            transactions: Vec::new(),
125            account_overrides: overrides,
126            return_accounts: Vec::new(),
127            label: None,
128        });
129        self
130    }
131
132    /// Convert the builder into API parameters, validating slot options.
133    pub fn into_params(self) -> Result<CreateSessionParams, BacktestClientError> {
134        let end_slot = match (self.end_slot, self.slot_count) {
135            (Some(_), Some(_)) => {
136                return Err(BacktestClientError::InvalidParams {
137                    message: "CreateSession: set only one of end_slot or slot_count".to_string(),
138                });
139            }
140            (Some(end_slot), None) => end_slot,
141            (None, Some(slot_count)) => {
142                self.start_slot.checked_add(slot_count).ok_or_else(|| {
143                    BacktestClientError::InvalidParams {
144                        message: "CreateSession: start_slot + slot_count overflow".to_string(),
145                    }
146                })?
147            }
148            (None, None) => {
149                return Err(BacktestClientError::InvalidParams {
150                    message: "CreateSession: must set end_slot or slot_count".to_string(),
151                });
152            }
153        };
154
155        if end_slot < self.start_slot {
156            return Err(BacktestClientError::InvalidParams {
157                message: format!(
158                    "CreateSession: end_slot ({end_slot}) must be >= start_slot ({})",
159                    self.start_slot
160                ),
161            });
162        }
163
164        let params = CreateSessionParams::builder()
165            .start_slot(self.start_slot)
166            .end_slot(end_slot)
167            .signer_filter(self.signer_filter)
168            .send_summary(self.send_summary)
169            .maybe_reroute(self.reroute_order_flow.then_some(RerouteParams {
170                venues: self.reroute_venues,
171                filter: self.reroute_filter,
172                detect_failed_l1_swaps: self.detect_failed_l1_swaps,
173                circular_arbs: self.reroute_circular_arbs,
174            }))
175            .maybe_capacity_wait_timeout_secs(self.capacity_wait_timeout_secs)
176            .maybe_disconnect_timeout_secs(self.disconnect_timeout_secs)
177            .maybe_extra_compute_units(self.extra_compute_units)
178            .discoveries(self.discoveries)
179            .actions(self.actions)
180            .replay_account_state(self.replay_account_state)
181            .build();
182
183        // Caught here purely to save the round trip; the manager and the session
184        // enforce the same rule through the same wording.
185        match replay_support::send_action_conflict(&params) {
186            Some(message) => Err(BacktestClientError::InvalidParams { message }),
187            None => Ok(params),
188        }
189    }
190
191    /// Convert the builder into versioned create request payload.
192    pub fn into_request(self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
193        let parallel = self.parallel;
194        let request = self.into_params()?;
195        if parallel {
196            Ok(CreateBacktestSessionRequestV1 { request, parallel }.into())
197        } else {
198            Ok(request.into())
199        }
200    }
201}
202
203/// Builder for `Continue` requests.
204///
205/// Use this to advance the simulation, inject transactions, or patch accounts.
206#[derive(Debug, Builder)]
207pub struct Continue {
208    #[builder(default = ContinueParams::default_advance_count())]
209    pub advance_count: u64,
210
211    #[builder(default)]
212    pub transactions: Vec<String>,
213
214    #[builder(default)]
215    pub modify_accounts: BTreeMap<Address, AccountData>,
216}
217
218impl Continue {
219    /// Append a base64-encoded transaction payload.
220    pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
221        self.transactions.push(data.into());
222        self
223    }
224
225    /// Append a raw transaction payload encoded as base64.
226    pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
227        self.transactions.push(BinaryEncoding::Base64.encode(bytes));
228        self
229    }
230
231    /// Append a serializable transaction encoded as base64.
232    pub fn push_transaction(
233        mut self,
234        transaction: &impl SerializableTransaction,
235    ) -> Result<Self, SerializeEncodeError> {
236        self.transactions.push(serialize_to_base64(&transaction)?);
237        Ok(self)
238    }
239
240    /// Modify an account state prior to execution.
241    pub fn modify_account(mut self, address: Address, account: AccountData) -> Self {
242        self.modify_accounts.insert(address, account);
243        self
244    }
245
246    /// Convert the builder into API parameters.
247    pub fn into_params(self) -> ContinueParams {
248        ContinueParams {
249            advance_count: self.advance_count,
250            transactions: self.transactions,
251            modify_account_states: AccountModifications(self.modify_accounts),
252        }
253    }
254}