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, AgentParams, BinaryEncoding, ContinueParams,
7    CreateBacktestSessionRequest, CreateBacktestSessionRequestV1, CreateSessionParams,
8    DiscoveryFilter, ScheduledAction,
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    pub slot_count: Option<u64>,
44
45    #[builder(default)]
46    pub signer_filter: BTreeSet<Address>,
47
48    /// When true, include a session summary with transaction statistics in the Completed response.
49    #[builder(default)]
50    pub send_summary: bool,
51
52    /// When true, replace historical swaps with transactions re-quoted through the
53    /// metis router against the current simulation state.
54    #[builder(default)]
55    pub reroute_order_flow: bool,
56
57    /// When true, also re-quote swaps whose L1 transaction failed in a way re-quoting can
58    /// answer. Tracked as a separate population from the headline reroute funnel.
59    #[builder(default = true)]
60    pub detect_failed_l1_swaps: bool,
61
62    /// When true, ask manager to create all available sessions in the target epoch.
63    #[builder(default)]
64    pub parallel: bool,
65
66    pub capacity_wait_timeout_secs: Option<u16>,
67
68    /// Seconds the server keeps the session alive with no client attached —
69    /// the window a reconnecting client has to reattach and resume. Must cover
70    /// your retry policy: the server's own default is tens of seconds, and it
71    /// caps this at 900. Left unset, [`crate::ManagedBacktestSession`]
72    /// substitutes [`crate::managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`].
73    pub disconnect_timeout_secs: Option<u16>,
74
75    /// Extra compute units to add to each transaction's SetComputeUnitLimit budget.
76    pub extra_compute_units: Option<u32>,
77
78    #[builder(default)]
79    pub agents: Vec<AgentParams>,
80
81    /// Batch discovery filters registered at session creation. For each
82    /// filter, the server emits [`BacktestResponse::DiscoveryBatch`] ahead
83    /// of every matching batch so the caller can pause via
84    /// [`BacktestSession::advance_to_discovery`] before it executes.
85    #[builder(default)]
86    pub discoveries: Vec<DiscoveryFilter>,
87
88    /// Transactions the server runs automatically during the session, with
89    /// results streamed over `actionSubscribe`.
90    #[builder(default)]
91    pub actions: Vec<ScheduledAction>,
92
93    /// When true, replay the account states for this range instead of
94    /// executing transactions (state-only acceleration).
95    #[builder(default)]
96    pub replay_account_state: bool,
97}
98
99impl CreateSession {
100    /// Add an account to the signer filter.
101    pub fn add_signer_filter(mut self, address: Address) -> Self {
102        self.signer_filter.insert(address);
103        self
104    }
105
106    /// Convert the builder into API parameters, validating slot options.
107    pub fn into_params(self) -> Result<CreateSessionParams, BacktestClientError> {
108        let end_slot = match (self.end_slot, self.slot_count) {
109            (Some(_), Some(_)) => {
110                return Err(BacktestClientError::InvalidParams {
111                    message: "CreateSession: set only one of end_slot or slot_count".to_string(),
112                });
113            }
114            (Some(end_slot), None) => end_slot,
115            (None, Some(slot_count)) => {
116                self.start_slot.checked_add(slot_count).ok_or_else(|| {
117                    BacktestClientError::InvalidParams {
118                        message: "CreateSession: start_slot + slot_count overflow".to_string(),
119                    }
120                })?
121            }
122            (None, None) => {
123                return Err(BacktestClientError::InvalidParams {
124                    message: "CreateSession: must set end_slot or slot_count".to_string(),
125                });
126            }
127        };
128
129        if end_slot < self.start_slot {
130            return Err(BacktestClientError::InvalidParams {
131                message: format!(
132                    "CreateSession: end_slot ({end_slot}) must be >= start_slot ({})",
133                    self.start_slot
134                ),
135            });
136        }
137
138        Ok(CreateSessionParams::builder()
139            .start_slot(self.start_slot)
140            .end_slot(end_slot)
141            .signer_filter(self.signer_filter)
142            .send_summary(self.send_summary)
143            .reroute_order_flow(self.reroute_order_flow)
144            .maybe_capacity_wait_timeout_secs(self.capacity_wait_timeout_secs)
145            .maybe_disconnect_timeout_secs(self.disconnect_timeout_secs)
146            .maybe_extra_compute_units(self.extra_compute_units)
147            .agents(self.agents)
148            .discoveries(self.discoveries)
149            .actions(self.actions)
150            .replay_account_state(self.replay_account_state)
151            .detect_failed_l1_swaps(self.detect_failed_l1_swaps)
152            .build())
153    }
154
155    /// Convert the builder into versioned create request payload.
156    pub fn into_request(self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
157        let parallel = self.parallel;
158        let request = self.into_params()?;
159        if parallel {
160            Ok(CreateBacktestSessionRequestV1 { request, parallel }.into())
161        } else {
162            Ok(request.into())
163        }
164    }
165}
166
167/// Builder for `Continue` requests.
168///
169/// Use this to advance the simulation, inject transactions, or patch accounts.
170#[derive(Debug, Builder)]
171pub struct Continue {
172    #[builder(default = ContinueParams::default_advance_count())]
173    pub advance_count: u64,
174
175    #[builder(default)]
176    pub transactions: Vec<String>,
177
178    #[builder(default)]
179    pub modify_accounts: BTreeMap<Address, AccountData>,
180}
181
182impl Continue {
183    /// Append a base64-encoded transaction payload.
184    pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
185        self.transactions.push(data.into());
186        self
187    }
188
189    /// Append a raw transaction payload encoded as base64.
190    pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
191        self.transactions.push(BinaryEncoding::Base64.encode(bytes));
192        self
193    }
194
195    /// Append a serializable transaction encoded as base64.
196    pub fn push_transaction(
197        mut self,
198        transaction: &impl SerializableTransaction,
199    ) -> Result<Self, SerializeEncodeError> {
200        self.transactions.push(serialize_to_base64(&transaction)?);
201        Ok(self)
202    }
203
204    /// Modify an account state prior to execution.
205    pub fn modify_account(mut self, address: Address, account: AccountData) -> Self {
206        self.modify_accounts.insert(address, account);
207        self
208    }
209
210    /// Convert the builder into API parameters.
211    pub fn into_params(self) -> ContinueParams {
212        ContinueParams {
213            advance_count: self.advance_count,
214            transactions: self.transactions,
215            modify_account_states: AccountModifications(self.modify_accounts),
216        }
217    }
218}