1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
use std::collections::{BTreeMap, BTreeSet};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use bon::Builder;
use simulator_api::{
AccountData, AccountModifications, ActionAnchor, ActionKind, BinaryEncoding, ContinueParams,
CreateBacktestSessionRequest, CreateBacktestSessionRequestV1, CreateSessionParams,
DiagnosticProbeParams, DiscoveryFilter, RerouteAggregators, RerouteFilter, RerouteParams,
RerouteScopes, ScheduledAction, VenueTemplate, replay_support,
session_name::{CreateToken, SessionName},
};
use solana_address::Address;
use solana_client::rpc_client::SerializableTransaction;
use thiserror::Error;
use crate::BacktestClientError;
/// Error serializing a transaction for injection.
#[derive(Debug, Error)]
pub enum SerializeEncodeError {
/// wincode could not serialize the transaction.
#[error("wincode serialization error: {0}")]
Wincode(#[from] wincode::WriteError),
}
/// Encodes a transaction the way [`ScheduledAction::transactions`] and
/// [`ContinueParams::transactions`] carry it: the standard base64 of its wire bytes, the bytes
/// `sendTransaction` takes, for a legacy, v0 or v1 transaction.
///
/// It serializes with wincode, which writes those bytes. bincode does not: it drops a v1
/// transaction's version marker, so the server cannot read it back. Errors only if wincode cannot
/// serialize the transaction.
pub fn encode_transaction(
transaction: &impl SerializableTransaction,
) -> Result<String, SerializeEncodeError> {
Ok(BASE64.encode(wincode::serialize(transaction)?))
}
/// Builder for the request that creates a session.
///
/// Set `start_slot` and exactly one of `end_slot` or `slot_count`; every other field has a
/// default. Pass the result to [`crate::ManagedBacktestSession`], or turn it into wire params
/// with [`Self::into_params`].
#[derive(Debug, Clone, Builder)]
pub struct CreateSession {
#[expect(missing_docs, reason = "self-explanatory builder field")]
pub start_slot: u64,
/// Last slot of the range to replay, inclusive. Set this or `slot_count`, not both.
pub end_slot: Option<u64>,
/// Slots to advance past `start_slot` (alternative to `end_slot`); the
/// session replays the inclusive range `[start_slot, start_slot + slot_count]`.
/// `slot_count = 0` replays just the start slot.
pub slot_count: Option<u64>,
/// When true, include a session summary with transaction statistics in the Completed response.
#[builder(default)]
pub send_summary: bool,
/// When true, reroute historical swaps: through the router (see
/// `reroute_requote`), directly to a venue (see `reroute_venue_templates`), or both.
///
/// Each original swap is priced at its pricing point: `quote_lag_blocks` blocks before the
/// block it executed in.
/// - Through the router: it quotes at the pricing point, and the new transaction is
/// simulated just before the original swap, in its block.
/// - Directly to a venue: each probe is simulated at the pricing point.
/// - Both: the original swap is replayed at the pricing point.
///
/// Every simulation is discarded. The original transactions still run, so the replay is
/// unchanged. Every other `reroute_*` field needs this.
#[builder(default)]
pub reroute_order_flow: bool,
/// When true, also reroute swaps whose original transaction failed on slippage or after the
/// swap ran. They are reported apart from the other reroutes. `l1` in the name means the
/// original (onchain) swap.
#[builder(default)]
pub detect_failed_l1_swaps: bool,
/// Which aggregators' historical swaps to reroute; Jupiter alone by default.
#[builder(default)]
pub reroute_aggregators: RerouteAggregators,
/// Where a swap may have run to be rerouted; top-level router instructions alone by default.
#[builder(default)]
pub reroute_scopes: RerouteScopes,
/// When true, also reroute atomic arbitrage (same input and output mint).
#[builder(default)]
pub reroute_circular_arbs: bool,
/// Restrict rerouting to swaps trading these mint pairs. `sim run` has no flag for this.
pub reroute_filter: Option<RerouteFilter>,
/// Templates for rerouting directly to a venue, probed against the hops the session detects.
#[builder(default)]
pub reroute_venue_templates: Vec<VenueTemplate>,
/// When true (the default), reroute through the router. Set it to false to
/// reroute only directly to a venue, with `reroute_venue_templates`.
#[builder(default = true)]
pub reroute_requote: bool,
/// Pools for the router to consider on top of the markets it already knows. Each must hold
/// an account at the start of the range; give a pool that exists nowhere onchain its
/// accounts with [`Self::add_override`] at `start_slot`.
#[builder(default)]
pub reroute_extra_markets: BTreeSet<Address>,
/// Price swaps at their quote slot's end, or just before their own batch in their land slot.
#[builder(default)]
pub reroute_quote_late_in_slot: bool,
/// When true, split the range across concurrent sessions: a parallel run. Start it with
/// [`crate::managed::ManagedParallelSession`].
#[builder(default)]
pub parallel: bool,
/// Name for the session, or for the whole run when `parallel` is set; the server assigns
/// one when unset. A name is never reused: one an earlier session already took fails with
/// [`simulator_api::BacktestError::SessionNameTaken`].
pub name: Option<SessionName>,
/// Seconds the server keeps trying to start the session while it has no capacity, before
/// it fails the create. Unset or 0 fails at once when the server is busy, so set it for any
/// unattended run; `sim run` uses 900.
pub capacity_wait_timeout_secs: Option<u16>,
/// Seconds the server keeps the session alive with no client attached —
/// the window a reconnecting client has to reattach and resume. Must cover
/// your retry policy. Unset, the server uses 30 (900 for a parallel run),
/// and it caps this at 900; 0 ends the session with the connection. For a
/// single session left unset, [`crate::ManagedBacktestSession`] substitutes
/// [`crate::managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`] (360).
pub disconnect_timeout_secs: Option<u16>,
/// Extra compute units to add to each transaction's SetComputeUnitLimit budget.
pub extra_compute_units: Option<u32>,
/// Batch discovery filters registered at session creation. For each
/// filter, the server emits [`simulator_api::BacktestResponse::DiscoveryBatch`] ahead
/// of every matching batch.
#[builder(default)]
pub discoveries: Vec<DiscoveryFilter>,
/// Transactions the server runs automatically during the session, with
/// results streamed over `actionSubscribe`.
#[builder(default)]
pub actions: Vec<ScheduledAction>,
/// When true, apply the account states recorded for this range instead of executing its
/// transactions, which is faster. The range needs an account-state bundle.
#[builder(default)]
pub replay_account_state: bool,
/// Markets the server probes through the router's `/diagnostic` endpoint, streamed over
/// `diagnosticSubscribe`. Only `afterSlot` and `afterEverySlot` anchors are supported.
#[builder(default)]
pub diagnostic_probes: Vec<DiagnosticProbeParams>,
}
impl CreateSession {
/// Schedule counterfactual account overrides from `slot` onward, per account until a later
/// override names that account. Rerouted swaps, account reads by address and the geyser
/// account stream see them; the replay never does. Requires `reroute_order_flow`.
#[must_use]
pub fn add_override(mut self, slot: u64, overrides: AccountModifications) -> Self {
self.actions.push(ScheduledAction {
anchor: ActionAnchor::BeforeSlot { slots: vec![slot] },
kind: ActionKind::default(),
feeds_reroute: true,
transactions: Vec::new(),
account_overrides: overrides,
return_accounts: Vec::new(),
label: None,
resolve: None,
within: None,
});
self
}
/// Convert the builder into API parameters.
///
/// # Errors
///
/// [`BacktestClientError::InvalidParams`], before anything is sent, when:
///
/// - both or neither of `end_slot` and `slot_count` are set;
/// - `start_slot + slot_count` overflows, or `end_slot` is before `start_slot`;
/// - a diagnostic probe or an action's resolver is invalid;
/// - a `send` action is scheduled with `replay_account_state` set.
pub fn into_params(self) -> Result<CreateSessionParams, BacktestClientError> {
let end_slot = match (self.end_slot, self.slot_count) {
(Some(_), Some(_)) => {
return Err(BacktestClientError::InvalidParams {
message: "CreateSession: set only one of end_slot or slot_count".to_string(),
});
}
(Some(end_slot), None) => end_slot,
(None, Some(slot_count)) => {
self.start_slot.checked_add(slot_count).ok_or_else(|| {
BacktestClientError::InvalidParams {
message: "CreateSession: start_slot + slot_count overflow".to_string(),
}
})?
}
(None, None) => {
return Err(BacktestClientError::InvalidParams {
message: "CreateSession: must set end_slot or slot_count".to_string(),
});
}
};
if end_slot < self.start_slot {
return Err(BacktestClientError::InvalidParams {
message: format!(
"CreateSession: end_slot ({end_slot}) must be >= start_slot ({})",
self.start_slot
),
});
}
let params = CreateSessionParams::builder()
.start_slot(self.start_slot)
.end_slot(end_slot)
.send_summary(self.send_summary)
.maybe_reroute(self.reroute_order_flow.then_some(RerouteParams {
aggregators: self.reroute_aggregators,
scopes: self.reroute_scopes,
filter: self.reroute_filter,
detect_failed_l1_swaps: self.detect_failed_l1_swaps,
circular_arbs: self.reroute_circular_arbs,
requote: self.reroute_requote,
venue_templates: self.reroute_venue_templates,
extra_markets: self.reroute_extra_markets,
quote_late_in_slot: self.reroute_quote_late_in_slot,
}))
.maybe_capacity_wait_timeout_secs(self.capacity_wait_timeout_secs)
.maybe_disconnect_timeout_secs(self.disconnect_timeout_secs)
.maybe_extra_compute_units(self.extra_compute_units)
.discoveries(self.discoveries)
.actions(self.actions)
.replay_account_state(self.replay_account_state)
.diagnostic_probes(self.diagnostic_probes)
.build();
// Same reason as the send-action check below: caught here to save the round trip, and
// enforced again by the session itself.
if let Err(error) = params.validate_diagnostic_probes() {
return Err(BacktestClientError::InvalidParams {
message: error.to_string(),
});
}
params
.validate_action_resolvers()
.map_err(|error| BacktestClientError::InvalidParams {
message: error.to_string(),
})?;
// Caught here purely to save the round trip; the manager and the session
// enforce the same rule through the same wording.
match replay_support::send_action_conflict(¶ms) {
Some(message) => Err(BacktestClientError::InvalidParams { message }),
None => Ok(params),
}
}
/// Convert the builder into a versioned create request.
///
/// Emits the V1 request when `parallel` or `name` is set, and V0 otherwise. With a `name`,
/// each call generates a new create token, which marks a resent request as the same create.
/// To retry, resend the returned request: a rebuilt one fails with
/// [`simulator_api::BacktestError::SessionNameTaken`] once the first has taken the name.
///
/// # Errors
///
/// As [`Self::into_params`].
pub fn into_request(mut self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
let parallel = self.parallel;
let (name, create_token) = self
.name
.take()
.map(|name| (name.to_string(), CreateToken::random()))
.unzip();
let request = self.into_params()?;
if parallel || name.is_some() {
Ok(CreateBacktestSessionRequestV1 {
request,
parallel,
name,
create_token,
}
.into())
} else {
Ok(request.into())
}
}
}
/// Builder for a `continue` request.
///
/// Use it to advance the session, run user transactions, or apply account overrides. The server
/// runs the user transactions first, then writes the overrides, then executes the blocks.
#[derive(Debug, Builder)]
pub struct Continue {
/// Blocks to execute before the session waits again. Default 1. A skipped slot has no
/// block and is not counted.
#[builder(default = ContinueParams::default_advance_count())]
pub advance_count: u64,
/// User transactions to run before advancing, each the standard base64 of the transaction's
/// wire bytes. Add them with [`Self::push_transaction`], which encodes for you.
#[builder(default)]
pub transactions: Vec<String>,
/// Account overrides, written after the user transactions and before the first block.
#[builder(default)]
pub modify_accounts: BTreeMap<Address, AccountData>,
}
impl Continue {
/// Append a transaction that is already encoded as [`encode_transaction`] does.
#[must_use]
pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
self.transactions.push(data.into());
self
}
/// Append a transaction's wire bytes, encoding them as base64.
#[must_use]
pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
self.transactions.push(BinaryEncoding::Base64.encode(bytes));
self
}
/// Append a transaction, encoded with [`encode_transaction`].
///
/// # Errors
///
/// [`SerializeEncodeError`] if wincode cannot serialize the transaction.
pub fn push_transaction(
mut self,
transaction: &impl SerializableTransaction,
) -> Result<Self, SerializeEncodeError> {
self.transactions.push(encode_transaction(transaction)?);
Ok(self)
}
/// Override one account's state, as an entry of `modify_accounts`.
#[must_use]
pub fn modify_account(mut self, address: Address, account: AccountData) -> Self {
self.modify_accounts.insert(address, account);
self
}
/// Convert the builder into API parameters.
pub fn into_params(self) -> ContinueParams {
ContinueParams {
advance_count: self.advance_count,
transactions: self.transactions,
modify_account_states: AccountModifications(self.modify_accounts),
}
}
}