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    pub disconnect_timeout_secs: Option<u16>,
69
70    /// Extra compute units to add to each transaction's SetComputeUnitLimit budget.
71    pub extra_compute_units: Option<u32>,
72
73    #[builder(default)]
74    pub agents: Vec<AgentParams>,
75
76    /// Batch discovery filters registered at session creation. For each
77    /// filter, the server emits [`BacktestResponse::DiscoveryBatch`] ahead
78    /// of every matching batch so the caller can pause via
79    /// [`BacktestSession::advance_to_discovery`] before it executes.
80    #[builder(default)]
81    pub discoveries: Vec<DiscoveryFilter>,
82
83    /// Transactions the server runs automatically during the session, with
84    /// results streamed over `actionSubscribe`.
85    #[builder(default)]
86    pub actions: Vec<ScheduledAction>,
87
88    /// When true, replay the account states for this range instead of
89    /// executing transactions (state-only acceleration).
90    #[builder(default)]
91    pub replay_account_state: bool,
92}
93
94impl CreateSession {
95    /// Add an account to the signer filter.
96    pub fn add_signer_filter(mut self, address: Address) -> Self {
97        self.signer_filter.insert(address);
98        self
99    }
100
101    /// Convert the builder into API parameters, validating slot options.
102    pub fn into_params(self) -> Result<CreateSessionParams, BacktestClientError> {
103        let end_slot = match (self.end_slot, self.slot_count) {
104            (Some(_), Some(_)) => {
105                return Err(BacktestClientError::InvalidParams {
106                    message: "CreateSession: set only one of end_slot or slot_count".to_string(),
107                });
108            }
109            (Some(end_slot), None) => end_slot,
110            (None, Some(slot_count)) => {
111                self.start_slot.checked_add(slot_count).ok_or_else(|| {
112                    BacktestClientError::InvalidParams {
113                        message: "CreateSession: start_slot + slot_count overflow".to_string(),
114                    }
115                })?
116            }
117            (None, None) => {
118                return Err(BacktestClientError::InvalidParams {
119                    message: "CreateSession: must set end_slot or slot_count".to_string(),
120                });
121            }
122        };
123
124        if end_slot < self.start_slot {
125            return Err(BacktestClientError::InvalidParams {
126                message: format!(
127                    "CreateSession: end_slot ({end_slot}) must be >= start_slot ({})",
128                    self.start_slot
129                ),
130            });
131        }
132
133        Ok(CreateSessionParams::builder()
134            .start_slot(self.start_slot)
135            .end_slot(end_slot)
136            .signer_filter(self.signer_filter)
137            .send_summary(self.send_summary)
138            .reroute_order_flow(self.reroute_order_flow)
139            .maybe_capacity_wait_timeout_secs(self.capacity_wait_timeout_secs)
140            .maybe_disconnect_timeout_secs(self.disconnect_timeout_secs)
141            .maybe_extra_compute_units(self.extra_compute_units)
142            .agents(self.agents)
143            .discoveries(self.discoveries)
144            .actions(self.actions)
145            .replay_account_state(self.replay_account_state)
146            .detect_failed_l1_swaps(self.detect_failed_l1_swaps)
147            .build())
148    }
149
150    /// Convert the builder into versioned create request payload.
151    pub fn into_request(self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
152        let parallel = self.parallel;
153        let request = self.into_params()?;
154        if parallel {
155            Ok(CreateBacktestSessionRequestV1 { request, parallel }.into())
156        } else {
157            Ok(request.into())
158        }
159    }
160}
161
162/// Builder for `Continue` requests.
163///
164/// Use this to advance the simulation, inject transactions, or patch accounts.
165#[derive(Debug, Builder)]
166pub struct Continue {
167    #[builder(default = ContinueParams::default_advance_count())]
168    pub advance_count: u64,
169
170    #[builder(default)]
171    pub transactions: Vec<String>,
172
173    #[builder(default)]
174    pub modify_accounts: BTreeMap<Address, AccountData>,
175}
176
177impl Continue {
178    /// Append a base64-encoded transaction payload.
179    pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
180        self.transactions.push(data.into());
181        self
182    }
183
184    /// Append a raw transaction payload encoded as base64.
185    pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
186        self.transactions.push(BinaryEncoding::Base64.encode(bytes));
187        self
188    }
189
190    /// Append a serializable transaction encoded as base64.
191    pub fn push_transaction(
192        mut self,
193        transaction: &impl SerializableTransaction,
194    ) -> Result<Self, SerializeEncodeError> {
195        self.transactions.push(serialize_to_base64(&transaction)?);
196        Ok(self)
197    }
198
199    /// Modify an account state prior to execution.
200    pub fn modify_account(mut self, address: Address, account: AccountData) -> Self {
201        self.modify_accounts.insert(address, account);
202        self
203    }
204
205    /// Convert the builder into API parameters.
206    pub fn into_params(self) -> ContinueParams {
207        ContinueParams {
208            advance_count: self.advance_count,
209            transactions: self.transactions,
210            modify_account_states: AccountModifications(self.modify_accounts),
211        }
212    }
213}