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
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,
DirectFillParams, DiscoveryFilter, RerouteAggregators, RerouteFilter, RerouteParams,
ScheduledAction, replay_support,
};
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 {
#[error("bincode serialization error: {0}")]
Bincode(#[from] bincode::error::EncodeError),
}
fn serialize_to_base64(value: &impl serde::Serialize) -> Result<String, SerializeEncodeError> {
let bytes = bincode::serde::encode_to_vec(
value,
bincode::config::standard()
.with_fixed_int_encoding()
.with_little_endian(),
)?;
Ok(BASE64.encode(&bytes))
}
/// Builder for `CreateBacktestSession`.
///
/// Set either `end_slot` or `slot_count` (not both). Use the helper methods to
/// add account filters.
#[derive(Debug, Clone, Builder)]
pub struct CreateSession {
pub start_slot: u64,
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>,
#[builder(default)]
pub signer_filter: BTreeSet<Address>,
/// When true, include a session summary with transaction statistics in the Completed response.
#[builder(default)]
pub send_summary: bool,
/// When true, replace historical swaps with transactions re-quoted through the
/// metis router against the current simulation state.
#[builder(default)]
pub reroute_order_flow: bool,
/// When true, also re-quote swaps whose L1 transaction failed in a way re-quoting can
/// answer. Tracked as a separate population from the headline reroute funnel.
#[builder(default)]
pub detect_failed_l1_swaps: bool,
/// Which aggregators' historical swaps to re-quote; Jupiter alone by default.
#[builder(default)]
pub reroute_aggregators: RerouteAggregators,
/// When true, also re-quote arbitrage cycles (same input and output mint).
#[builder(default)]
pub reroute_circular_arbs: bool,
/// Restrict rerouting to swaps trading these mint pairs.
pub reroute_filter: Option<RerouteFilter>,
/// Price a candidate venue against the hops the run detects.
pub reroute_direct_fill: Option<Box<DirectFillParams>>,
/// Re-quote through metis. Off runs `reroute_direct_fill` alone, with no sidecar.
#[builder(default = true)]
pub reroute_requote: bool,
/// When true, ask manager to create all available sessions in the target epoch.
#[builder(default)]
pub parallel: bool,
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: the server's own default is tens of seconds, and it
/// caps this at 900. Left unset, [`crate::ManagedBacktestSession`]
/// substitutes [`crate::managed::DEFAULT_DISCONNECT_TIMEOUT_SECS`].
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 [`BacktestResponse::DiscoveryBatch`] ahead
/// of every matching batch so the caller can pause via
/// [`BacktestSession::advance_to_discovery`] before it executes.
#[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, replay the account states for this range instead of
/// executing transactions (state-only acceleration).
#[builder(default)]
pub replay_account_state: bool,
}
impl CreateSession {
/// Add an account to the signer filter.
pub fn add_signer_filter(mut self, address: Address) -> Self {
self.signer_filter.insert(address);
self
}
/// Schedule counterfactual account overrides, visible only to the reroute
/// layer from `slot` onward — per account, until a later override names the
/// same account. Requires `reroute_order_flow`.
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,
});
self
}
/// Convert the builder into API parameters, validating slot options.
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)
.signer_filter(self.signer_filter)
.send_summary(self.send_summary)
.maybe_reroute(self.reroute_order_flow.then_some(RerouteParams {
aggregators: self.reroute_aggregators,
filter: self.reroute_filter,
detect_failed_l1_swaps: self.detect_failed_l1_swaps,
circular_arbs: self.reroute_circular_arbs,
requote: self.reroute_requote,
direct_fill: self.reroute_direct_fill,
}))
.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)
.build();
// 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 versioned create request payload.
pub fn into_request(self) -> Result<CreateBacktestSessionRequest, BacktestClientError> {
let parallel = self.parallel;
let request = self.into_params()?;
if parallel {
Ok(CreateBacktestSessionRequestV1 { request, parallel }.into())
} else {
Ok(request.into())
}
}
}
/// Builder for `Continue` requests.
///
/// Use this to advance the simulation, inject transactions, or patch accounts.
#[derive(Debug, Builder)]
pub struct Continue {
#[builder(default = ContinueParams::default_advance_count())]
pub advance_count: u64,
#[builder(default)]
pub transactions: Vec<String>,
#[builder(default)]
pub modify_accounts: BTreeMap<Address, AccountData>,
}
impl Continue {
/// Append a base64-encoded transaction payload.
pub fn push_transaction_base64(mut self, data: impl Into<String>) -> Self {
self.transactions.push(data.into());
self
}
/// Append a raw transaction payload encoded as base64.
pub fn push_transaction_bytes(mut self, bytes: &[u8]) -> Self {
self.transactions.push(BinaryEncoding::Base64.encode(bytes));
self
}
/// Append a serializable transaction encoded as base64.
pub fn push_transaction(
mut self,
transaction: &impl SerializableTransaction,
) -> Result<Self, SerializeEncodeError> {
self.transactions.push(serialize_to_base64(&transaction)?);
Ok(self)
}
/// Modify an account state prior to execution.
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),
}
}
}