1#![warn(missing_docs)]
136
137use std::{
138 collections::{BTreeMap, BTreeSet, HashMap, HashSet},
139 fmt,
140 num::{NonZeroU64, NonZeroUsize},
141 str::FromStr,
142 sync::Arc,
143};
144
145use base64::{
146 DecodeError as Base64DecodeError, Engine as _, engine::general_purpose::STANDARD as BASE64,
147};
148use parking_lot::RwLock;
149use serde::{Deserialize, Serialize};
150use session_name::{CreateToken, InvalidSessionName, RequestedName};
151use solana_account::AccountSharedData;
152
153mod dataset_jobs;
154mod datasets;
155mod session_id;
156mod session_type;
157mod slot_range;
158
159pub use dataset_jobs::{
160 DatasetJobListResponse, DatasetJobPhase, DatasetJobRequest, DatasetJobSpec,
161 DatasetJobStatusResponse, DatasetLocation, PredictTable, Progress,
162};
163pub use datasets::{
164 DatasetContents, DatasetDate, DatasetDeleteRequest, DatasetDeleteResponse, DatasetFile,
165 DatasetListQuery, DatasetListResponse, DatasetPartition, DatasetParts, DatasetScope,
166 DatasetSummary, DatasetVersion, HeldSlots,
167};
168pub use reroute_report::SwapMode;
169pub use session_id::{ControlSessionId, SessionId};
170pub use session_type::SessionType;
171pub use slot_range::{InvertedSlotRange, SlotRange};
172pub use solana_address::Address;
175pub use solana_address::error::ParseAddressError;
177pub use venue::{
178 AMOUNT_WIDTH, DerivedAccount, ParseVenueTemplateError, Seed, TakerSlots, TemplateAccount,
179 TemplateInstruction, TemplateResolver, VenueTemplate,
180};
181
182#[doc(hidden)]
183pub mod client_identity;
184pub mod geyser_route;
185pub mod mints;
186pub mod replacement;
187pub mod reroute_report;
188pub mod route_plan;
189pub mod session_name;
190pub mod subscribe_config;
191pub mod token;
192pub mod usage;
193pub mod venue;
194#[doc(hidden)]
195pub mod ws_compression;
196
197#[allow(
216 clippy::large_enum_variant,
217 reason = "decoded once per message and consumed by value; boxing the create variant would \
218 change every caller's construction for no measurable gain"
219)]
220#[derive(Debug, Serialize, Deserialize)]
221#[serde(tag = "method", content = "params", rename_all = "camelCase")]
222pub enum BacktestRequest {
223 CreateBacktestSession(CreateBacktestSessionRequest),
225 Continue(ContinueParams),
227 ContinueTo(ContinueToParams),
229 ContinueSessionV1(ContinueSessionRequestV1),
231 ContinueToSessionV1(ContinueToSessionRequestV1),
233 CloseBacktestSession,
237 CloseSessionV1(CloseSessionRequestV1),
239 AttachBacktestSession {
243 session_id: SessionId,
245 last_sequence: Option<u64>,
248 },
249 ResumeAttachedSession,
252 AttachParallelControlSessionV2 {
255 control_session_id: ControlSessionId,
257 #[serde(default)]
261 last_sequences: BTreeMap<SessionId, u64>,
262 },
263}
264
265#[derive(Debug, Clone, Serialize, Deserialize)]
268#[serde(untagged)]
269pub enum CreateBacktestSessionRequest {
270 V1(CreateBacktestSessionRequestV1),
272 V0(CreateSessionParams),
274}
275
276impl CreateBacktestSessionRequest {
277 #[doc(hidden)]
278 pub fn try_into_request_options(
279 self,
280 ) -> Result<CreateBacktestSessionRequestOptions, InvalidSessionName> {
281 match self {
282 Self::V0(request) => Ok(CreateBacktestSessionRequestOptions {
283 request,
284 parallel: false,
285 name: None,
286 }),
287 Self::V1(CreateBacktestSessionRequestV1 {
288 request,
289 parallel,
290 name,
291 create_token,
292 }) => {
293 let name = name
294 .map(|name| {
295 name.try_into()
296 .map(|name| RequestedName { name, create_token })
297 })
298 .transpose()?;
299 Ok(CreateBacktestSessionRequestOptions {
300 request,
301 parallel,
302 name,
303 })
304 }
305 }
306 }
307
308 pub fn into_request_and_parallel(self) -> (CreateSessionParams, bool) {
310 match self {
311 Self::V0(request) => (request, false),
312 Self::V1(CreateBacktestSessionRequestV1 {
313 request,
314 parallel,
315 name: _,
316 create_token: _,
317 }) => (request, parallel),
318 }
319 }
320}
321
322impl From<CreateSessionParams> for CreateBacktestSessionRequest {
323 fn from(value: CreateSessionParams) -> Self {
324 Self::V0(value)
325 }
326}
327
328impl From<CreateBacktestSessionRequestV1> for CreateBacktestSessionRequest {
329 fn from(value: CreateBacktestSessionRequestV1) -> Self {
330 Self::V1(value)
331 }
332}
333
334#[derive(Debug, Clone, Serialize, Deserialize)]
360#[serde(rename_all = "camelCase")]
361pub struct CreateBacktestSessionRequestV1 {
362 #[serde(flatten)]
364 pub request: CreateSessionParams,
365 #[serde(default)]
368 pub parallel: bool,
369 #[serde(default, skip_serializing_if = "Option::is_none")]
376 pub name: Option<String>,
377 #[serde(default, skip_serializing_if = "Option::is_none")]
383 pub create_token: Option<CreateToken>,
384}
385
386#[doc(hidden)]
387#[derive(Debug, Clone)]
388pub struct CreateBacktestSessionRequestOptions {
389 pub request: CreateSessionParams,
390 pub parallel: bool,
391 pub name: Option<RequestedName>,
392}
393
394#[derive(Debug, Serialize, Deserialize)]
396#[serde(rename_all = "camelCase")]
397pub struct ContinueSessionRequestV1 {
398 pub session_id: SessionId,
400 #[allow(missing_docs)]
401 pub request: ContinueParams,
402}
403
404#[derive(Debug, Clone, Serialize, Deserialize)]
406#[serde(rename_all = "camelCase")]
407pub struct ContinueToSessionRequestV1 {
408 pub session_id: SessionId,
410 #[allow(missing_docs)]
411 pub request: ContinueToParams,
412}
413
414#[derive(Debug, Serialize, Deserialize)]
416#[serde(rename_all = "camelCase")]
417pub struct CloseSessionRequestV1 {
418 pub session_id: SessionId,
420}
421
422#[serde_with::serde_as]
429#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
430#[serde(tag = "kind", content = "value", rename_all = "camelCase")]
431pub enum DiscoveryFilter {
432 ProgramExecuted(#[serde_as(as = "serde_with::DisplayFromStr")] Address),
434 OracleUpdate {
439 #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
441 programs: BTreeSet<Address>,
442 #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
445 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
446 accounts: BTreeSet<Address>,
447 },
448 ProgramWrite {
452 #[serde_as(as = "serde_with::DisplayFromStr")]
454 program: Address,
455 #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
457 accounts: BTreeSet<Address>,
458 },
459}
460
461#[doc(hidden)]
466pub struct TxMatchContext {
467 pub invoked_programs: HashSet<Address>,
469 pub moves_tokens: bool,
471 pub written_accounts: Vec<Address>,
474 pub writes_via_unresolved_lookup: bool,
477}
478
479impl DiscoveryFilter {
480 #[doc(hidden)]
483 pub fn matches(&self, ctx: &TxMatchContext) -> bool {
484 match self {
485 Self::ProgramExecuted(target) => ctx.invoked_programs.contains(target),
486 Self::OracleUpdate { programs, accounts } => {
487 !ctx.moves_tokens
488 && ctx
489 .invoked_programs
490 .iter()
491 .any(|program| programs.contains(program))
492 && (accounts.is_empty() || writes_one_of(ctx, accounts))
493 }
494 Self::ProgramWrite { program, accounts } => {
495 ctx.invoked_programs.contains(program) && writes_one_of(ctx, accounts)
496 }
497 }
498 }
499}
500
501fn writes_one_of(ctx: &TxMatchContext, accounts: &BTreeSet<Address>) -> bool {
502 !accounts.is_empty()
503 && (ctx.writes_via_unresolved_lookup
504 || ctx
505 .written_accounts
506 .iter()
507 .any(|account| accounts.contains(account)))
508}
509
510#[derive(Debug, Clone, PartialEq, Eq, Hash)]
512pub struct NonEmptyAccounts(BTreeSet<Address>);
513
514impl NonEmptyAccounts {
515 pub fn iter(&self) -> impl Iterator<Item = &Address> {
517 self.0.iter()
518 }
519}
520
521impl Serialize for NonEmptyAccounts {
522 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
523 serde_with::As::<BTreeSet<serde_with::DisplayFromStr>>::serialize(&self.0, serializer)
524 }
525}
526
527impl<'de> Deserialize<'de> for NonEmptyAccounts {
528 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
529 let accounts: BTreeSet<Address> =
530 serde_with::As::<BTreeSet<serde_with::DisplayFromStr>>::deserialize(deserializer)?;
531 Self::try_from(accounts).map_err(serde::de::Error::custom)
532 }
533}
534
535#[derive(Debug, thiserror::Error)]
537#[error("no accounts listed")]
538pub struct EmptyAccounts;
539
540impl TryFrom<BTreeSet<Address>> for NonEmptyAccounts {
541 type Error = EmptyAccounts;
542
543 fn try_from(accounts: BTreeSet<Address>) -> Result<Self, Self::Error> {
544 if accounts.is_empty() {
545 Err(EmptyAccounts)
546 } else {
547 Ok(Self(accounts))
548 }
549 }
550}
551
552#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
557#[serde(try_from = "[String; 2]", into = "[String; 2]")]
558pub struct MintPair([Address; 2]);
559
560impl MintPair {
561 pub fn new(one: Address, other: Address) -> Self {
563 Self(if one <= other {
564 [one, other]
565 } else {
566 [other, one]
567 })
568 }
569
570 pub fn mints(&self) -> (Address, Address) {
572 (self.0[0], self.0[1])
573 }
574}
575
576#[derive(Debug, thiserror::Error)]
578#[error("invalid mint {mint} in pair")]
579pub struct ParseMintPairError {
580 mint: String,
581 source: ParseAddressError,
582}
583
584impl TryFrom<[String; 2]> for MintPair {
585 type Error = ParseMintPairError;
586
587 fn try_from([one, other]: [String; 2]) -> Result<Self, Self::Error> {
588 fn parse(mint: String) -> Result<Address, ParseMintPairError> {
589 Address::from_str(&mint).map_err(|source| ParseMintPairError { mint, source })
590 }
591 Ok(Self::new(parse(one)?, parse(other)?))
592 }
593}
594
595impl From<MintPair> for [String; 2] {
596 fn from(pair: MintPair) -> Self {
597 let (one, other) = pair.mints();
598 [one.to_string(), other.to_string()]
599 }
600}
601
602#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
606#[serde(rename_all = "camelCase")]
607pub struct RerouteFilter {
608 #[serde(default)]
610 pub pairs: BTreeSet<MintPair>,
611}
612
613impl RerouteFilter {
614 pub fn is_empty(&self) -> bool {
617 self.pairs.is_empty()
618 }
619
620 pub fn matches_mints(&self, input: &Address, output: &Address) -> bool {
622 self.pairs.contains(&MintPair::new(*input, *output))
623 }
624
625 pub fn mentions_mint(&self, mint: &Address) -> bool {
628 self.pairs.iter().any(|pair| {
629 let (one, other) = pair.mints();
630 one == *mint || other == *mint
631 })
632 }
633}
634
635#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
638#[serde(rename_all = "camelCase")]
639pub enum ActionKind {
640 #[default]
644 Simulate,
645 Send,
650}
651
652#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
656#[serde(tag = "at", rename_all = "camelCase")]
657pub enum ActionAnchor {
658 BeforeSlot {
661 #[serde(default, with = "compressed")]
665 slots: Vec<u64>,
666 },
667 AfterSlot {
670 #[serde(default, with = "compressed")]
672 slots: Vec<u64>,
673 },
674 #[serde(rename_all = "camelCase")]
679 BeforeEverySlot {
680 #[serde(default = "every_slot")]
682 every_n_slots: NonZeroU64,
683 },
684 #[serde(rename_all = "camelCase")]
688 AfterEverySlot {
689 #[serde(default = "every_slot")]
691 every_n_slots: NonZeroU64,
692 },
693 BeforeBatch {
695 #[serde(default, with = "compressed")]
697 batches: Vec<BatchPosition>,
698 },
699 BeforeMatch {
702 filter: DiscoveryFilter,
704 },
705 AfterMatch {
708 filter: DiscoveryFilter,
710 },
711 AfterChange {
716 accounts: NonEmptyAccounts,
718 },
719}
720
721const fn every_slot() -> NonZeroU64 {
722 NonZeroU64::MIN
723}
724
725#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
726#[serde(rename_all = "camelCase")]
727pub struct BatchPosition {
729 pub slot: u64,
731 pub batch_index: u32,
733}
734
735const MAX_ACTION_TRANSACTIONS_BYTES: u64 = 256 * 1024 * 1024;
739const PROGRAM_OWNERS: [Address; 4] = [
740 solana_sdk_ids::bpf_loader_upgradeable::ID,
741 solana_sdk_ids::bpf_loader::ID,
742 solana_sdk_ids::bpf_loader_deprecated::ID,
743 solana_sdk_ids::loader_v4::ID,
744];
745
746mod compressed {
751 use std::io::Read;
752
753 use base64::Engine as _;
754 use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned};
755
756 use super::{BASE64, MAX_ACTION_TRANSACTIONS_BYTES};
757
758 const COMPRESSION_LEVEL: i32 = 0;
760
761 pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
762 where
763 T: Serialize,
764 S: Serializer,
765 {
766 let json = serde_json::to_vec(value).map_err(serde::ser::Error::custom)?;
767 let compressed = zstd::stream::encode_all(json.as_slice(), COMPRESSION_LEVEL)
768 .map_err(serde::ser::Error::custom)?;
769 serializer.serialize_str(&BASE64.encode(compressed))
770 }
771
772 pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
773 where
774 T: DeserializeOwned,
775 D: Deserializer<'de>,
776 {
777 let blob = String::deserialize(deserializer)?;
778 let compressed = BASE64
779 .decode(blob.as_bytes())
780 .map_err(serde::de::Error::custom)?;
781 let json = decode_capped(&compressed, MAX_ACTION_TRANSACTIONS_BYTES)
782 .map_err(serde::de::Error::custom)?;
783 serde_json::from_slice(&json).map_err(serde::de::Error::custom)
784 }
785
786 fn decode_capped(compressed: &[u8], cap: u64) -> std::io::Result<Vec<u8>> {
789 let mut json = Vec::new();
790 zstd::stream::read::Decoder::new(compressed)
791 .and_then(|d| Read::take(d, cap + 1).read_to_end(&mut json))?;
792 match json.len() as u64 > cap {
793 true => Err(std::io::Error::other(format!(
794 "decompressed blob is over the {cap} byte ceiling"
795 ))),
796 false => Ok(json),
797 }
798 }
799
800 #[cfg(test)]
801 mod tests {
802 use super::*;
803
804 #[test]
805 fn a_blob_over_the_ceiling_names_it_instead_of_truncating() {
806 let compressed = zstd::stream::encode_all([b'a'; 1024].as_slice(), 0).unwrap();
807 let error = decode_capped(&compressed, 64).unwrap_err();
808 assert!(error.to_string().contains("64 byte ceiling"), "{error}");
809 }
810
811 #[test]
812 fn a_blob_at_the_ceiling_is_kept_whole() {
813 let compressed = zstd::stream::encode_all([b'a'; 64].as_slice(), 0).unwrap();
814 assert_eq!(decode_capped(&compressed, 64).unwrap().len(), 64);
815 }
816 }
817}
818
819#[serde_with::serde_as]
881#[derive(Debug, Clone, Serialize, Deserialize)]
882#[serde(rename_all = "camelCase")]
883pub struct ScheduledAction {
884 pub anchor: ActionAnchor,
886 #[serde(default)]
888 pub kind: ActionKind,
889 #[serde(default, with = "compressed")]
900 pub transactions: Vec<String>,
901 #[serde(default)]
906 pub account_overrides: AccountModifications,
907 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
912 pub feeds_reroute: bool,
913 #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
917 #[serde(default)]
918 pub return_accounts: Vec<Address>,
919 #[serde(default)]
921 pub label: Option<String>,
922 #[serde(default, skip_serializing_if = "Option::is_none")]
925 pub resolve: Option<TxResolver>,
926 #[serde(default, skip_serializing_if = "Option::is_none")]
929 pub within: Option<SlotRange>,
930}
931
932impl ScheduledAction {
933 pub fn is_computed_override(&self) -> bool {
936 self.feeds_reroute && !self.transactions.is_empty()
937 }
938
939 pub fn asks_router(&self) -> bool {
941 matches!(self.resolve, Some(TxResolver::Requote { .. }))
942 }
943
944 fn validate_resolve(&self) -> Result<(), TxResolverError> {
945 let Some(resolver) = &self.resolve else {
946 return Ok(());
947 };
948 match self.kind {
949 ActionKind::Send => return Err(TxResolverError::Send),
950 ActionKind::Simulate => {}
951 }
952 match resolver {
953 TxResolver::LiquidityArrays { .. } if self.transactions.len() != 1 => {
954 return Err(TxResolverError::TransactionCount {
955 got: self.transactions.len(),
956 });
957 }
958 TxResolver::QuoteStamp | TxResolver::Requote { .. } if self.transactions.is_empty() => {
959 return Err(TxResolverError::NoTransactions);
960 }
961 TxResolver::LiquidityArrays { .. }
962 | TxResolver::QuoteStamp
963 | TxResolver::Requote { .. } => {}
964 }
965 if self.feeds_reroute {
966 return Err(TxResolverError::FeedsReroute);
967 }
968 Ok(())
969 }
970}
971
972pub fn validate_resolvers(actions: &[ScheduledAction]) -> Result<(), ActionResolveError> {
975 actions
976 .iter()
977 .enumerate()
978 .try_for_each(|(action, scheduled)| {
979 scheduled
980 .validate_resolve()
981 .map_err(|source| ActionResolveError { action, source })
982 })
983}
984
985pub const RESOLVE_FAILURE_PREFIX: &str = "resolve: ";
988
989#[serde_with::serde_as]
995#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
996#[serde(
997 tag = "type",
998 rename_all = "camelCase",
999 rename_all_fields = "camelCase"
1000)]
1001#[allow(missing_docs)]
1002pub enum TxResolver {
1003 LiquidityArrays {
1008 #[serde_as(as = "serde_with::DisplayFromStr")]
1010 pool: Address,
1011 #[serde_as(as = "serde_with::DisplayFromStr")]
1013 input_mint: Address,
1014 array_key_indices: ArrayKeyIndices,
1017 },
1018 QuoteStamp,
1023 Requote {
1029 #[serde_as(as = "serde_with::DisplayFromStr")]
1031 dex: Address,
1032 #[serde_as(as = "serde_with::DisplayFromStr")]
1033 input_mint: Address,
1034 #[serde_as(as = "serde_with::DisplayFromStr")]
1035 output_mint: Address,
1036 amount: u64,
1038 slippage_bps: u16,
1039 },
1040}
1041
1042#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1045#[serde(try_from = "Vec<u8>", into = "Vec<u8>")]
1046pub struct ArrayKeyIndices {
1047 first: u8,
1048 rest: Vec<u8>,
1049}
1050
1051impl ArrayKeyIndices {
1052 pub fn iter(&self) -> impl Iterator<Item = u8> + '_ {
1054 std::iter::once(self.first).chain(self.rest.iter().copied())
1055 }
1056
1057 #[allow(missing_docs)]
1058 pub fn count(&self) -> NonZeroUsize {
1059 NonZeroUsize::MIN.saturating_add(self.rest.len())
1060 }
1061}
1062
1063#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1065#[allow(missing_docs)]
1066pub enum ArrayKeyIndicesError {
1067 #[error("no arrayKeyIndices")]
1068 Empty,
1069 #[error("arrayKeyIndex {index} repeated")]
1070 Duplicate { index: u8 },
1071}
1072
1073impl TryFrom<Vec<u8>> for ArrayKeyIndices {
1074 type Error = ArrayKeyIndicesError;
1075
1076 fn try_from(indices: Vec<u8>) -> Result<Self, Self::Error> {
1077 let Some((&first, rest)) = indices.split_first() else {
1078 return Err(ArrayKeyIndicesError::Empty);
1079 };
1080 let mut seen = [false; 256];
1081 match indices
1082 .iter()
1083 .find(|&&index| std::mem::replace(&mut seen[usize::from(index)], true))
1084 {
1085 Some(&index) => Err(ArrayKeyIndicesError::Duplicate { index }),
1086 None => Ok(Self {
1087 first,
1088 rest: rest.to_vec(),
1089 }),
1090 }
1091 }
1092}
1093
1094impl From<ArrayKeyIndices> for Vec<u8> {
1095 fn from(indices: ArrayKeyIndices) -> Self {
1096 std::iter::once(indices.first).chain(indices.rest).collect()
1097 }
1098}
1099
1100#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1102pub enum TxResolverError {
1103 #[error("resolve is not valid for kind: send")]
1105 Send,
1106 #[error("resolve rewrites exactly one transaction, and the action carries {got}")]
1108 TransactionCount {
1109 got: usize,
1111 },
1112 #[error("resolve needs a transaction to rewrite")]
1114 NoTransactions,
1115 #[error("resolve cannot be combined with feedsReroute")]
1117 FeedsReroute,
1118}
1119
1120#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1122#[error("action {action}: {source}")]
1123pub struct ActionResolveError {
1124 pub action: usize,
1126 #[source]
1128 pub source: TxResolverError,
1129}
1130
1131pub const MAX_DIAGNOSTIC_MARKETS: usize = 64;
1133pub const MAX_DIAGNOSTIC_USD_VALUES: usize = 16;
1135pub const MAX_DIAGNOSTIC_MARKET_PAIRS: usize = 16;
1137
1138#[serde_with::serde_as]
1145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1146#[serde(rename_all = "camelCase")]
1147pub struct DiagnosticProbeParams {
1148 pub anchor: ActionAnchor,
1150 #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
1153 pub markets: Vec<Address>,
1154 pub usd_values: Vec<u32>,
1157 #[serde(default)]
1159 pub label: Option<String>,
1160 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1164 pub pairs: Vec<DiagnosticMarketPairs>,
1165 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1167 pub candidates: Vec<DiagnosticCandidate>,
1168 #[serde_as(as = "Vec<[serde_with::DisplayFromStr; 2]>")]
1171 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1172 pub candidate_pairs: Vec<[Address; 2]>,
1173}
1174
1175#[serde_with::serde_as]
1177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1178#[serde(rename_all = "camelCase")]
1179pub struct DiagnosticCandidate {
1180 #[serde_as(as = "serde_with::DisplayFromStr")]
1181 #[allow(missing_docs)]
1182 pub market: Address,
1183 #[serde_as(as = "serde_with::DisplayFromStr")]
1185 pub owner: Address,
1186 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
1188 #[serde(default, skip_serializing_if = "Option::is_none")]
1189 pub address_lookup_table: Option<Address>,
1190}
1191
1192#[serde_with::serde_as]
1194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1195#[serde(rename_all = "camelCase")]
1196pub struct DiagnosticMarketPairs {
1197 #[serde_as(as = "serde_with::DisplayFromStr")]
1199 pub market: Address,
1200 #[serde_as(as = "Vec<[serde_with::DisplayFromStr; 2]>")]
1202 pub pairs: Vec<[Address; 2]>,
1203}
1204
1205#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1207#[allow(missing_docs)]
1208pub enum DiagnosticProbeError {
1209 #[error("a diagnostic probe names no markets")]
1211 NoMarkets,
1212 #[error("a diagnostic probe names no usdValues")]
1213 NoUsdValues,
1214 #[error("a diagnostic probe names {got} markets, over the ceiling of {MAX_DIAGNOSTIC_MARKETS}")]
1216 TooManyMarkets {
1217 got: usize,
1219 },
1220 #[error(
1222 "a diagnostic probe names {got} usdValues, over the ceiling of {MAX_DIAGNOSTIC_USD_VALUES}"
1223 )]
1224 TooManyUsdValues {
1225 got: usize,
1227 },
1228 #[error("a diagnostic probe names usdValue 0, which the router reads as no size at all")]
1230 ZeroUsdValue,
1231 #[error("a diagnostic probe names market {market} more than once")]
1233 DuplicateMarket { market: Address },
1234 #[error("a diagnostic probe names pairs for market {market}, which it does not probe")]
1236 PairsOfUnprobedMarket {
1237 market: Address,
1239 },
1240 #[error("a diagnostic probe names pairs for market {market} more than once")]
1241 DuplicatePairsMarket { market: Address },
1242 #[error(
1244 "a diagnostic probe names {got} pairs for market {market}, outside \
1245 1..={MAX_DIAGNOSTIC_MARKET_PAIRS}"
1246 )]
1247 PairCount {
1248 market: Address,
1249 got: usize,
1251 },
1252 #[error("a diagnostic probe pairs mint {mint} with itself on market {market}")]
1254 SelfPair { market: Address, mint: Address },
1255 #[error(
1258 "a diagnostic probe names {got} candidate pairs for its candidates, outside \
1259 1..={MAX_DIAGNOSTIC_MARKET_PAIRS}"
1260 )]
1261 CandidatePairCount {
1262 got: usize,
1264 },
1265 #[error("a diagnostic probe pairs mint {mint} with itself for its candidates")]
1267 CandidateSelfPair {
1268 mint: Address,
1270 },
1271 #[error(
1273 "a diagnostic probe anchors at {anchor}; probing the router is an await, and only the \
1274 slot-end hook has a point for one, so only afterSlot and afterEverySlot are supported"
1275 )]
1276 UnsupportedAnchor {
1277 anchor: &'static str,
1279 },
1280}
1281
1282impl DiagnosticProbeParams {
1283 pub fn fires(&self) -> usize {
1285 self.pools() * self.usd_values.len()
1286 }
1287
1288 fn pools(&self) -> usize {
1289 self.markets.len() + self.candidates.len()
1290 }
1291
1292 pub fn validate(&self) -> Result<(), DiagnosticProbeError> {
1294 if self.pools() == 0 {
1295 return Err(DiagnosticProbeError::NoMarkets);
1296 }
1297 if self.usd_values.is_empty() {
1298 return Err(DiagnosticProbeError::NoUsdValues);
1299 }
1300 if self.pools() > MAX_DIAGNOSTIC_MARKETS {
1301 return Err(DiagnosticProbeError::TooManyMarkets { got: self.pools() });
1302 }
1303 if self.usd_values.len() > MAX_DIAGNOSTIC_USD_VALUES {
1304 return Err(DiagnosticProbeError::TooManyUsdValues {
1305 got: self.usd_values.len(),
1306 });
1307 }
1308 if self.usd_values.contains(&0) {
1309 return Err(DiagnosticProbeError::ZeroUsdValue);
1310 }
1311 let mut seen = HashSet::with_capacity(self.markets.len());
1312 if let Some(market) = self.markets.iter().find(|market| !seen.insert(**market)) {
1313 return Err(DiagnosticProbeError::DuplicateMarket { market: *market });
1314 }
1315 let mut paired = HashSet::with_capacity(self.pairs.len());
1316 for DiagnosticMarketPairs { market, pairs } in &self.pairs {
1317 let market = *market;
1318 if !seen.contains(&market) {
1319 return Err(DiagnosticProbeError::PairsOfUnprobedMarket { market });
1320 }
1321 if !paired.insert(market) {
1322 return Err(DiagnosticProbeError::DuplicatePairsMarket { market });
1323 }
1324 match pairs_fault(pairs) {
1325 Some(PairsFault::Count(got)) => {
1326 return Err(DiagnosticProbeError::PairCount { market, got });
1327 }
1328 Some(PairsFault::SelfPair(mint)) => {
1329 return Err(DiagnosticProbeError::SelfPair { market, mint });
1330 }
1331 None => {}
1332 }
1333 }
1334 if let Some(DiagnosticCandidate { market, .. }) = self
1335 .candidates
1336 .iter()
1337 .find(|candidate| !seen.insert(candidate.market))
1338 {
1339 return Err(DiagnosticProbeError::DuplicateMarket { market: *market });
1340 }
1341 if !self.candidates.is_empty() {
1342 match pairs_fault(&self.candidate_pairs) {
1343 Some(PairsFault::Count(got)) => {
1344 return Err(DiagnosticProbeError::CandidatePairCount { got });
1345 }
1346 Some(PairsFault::SelfPair(mint)) => {
1347 return Err(DiagnosticProbeError::CandidateSelfPair { mint });
1348 }
1349 None => {}
1350 }
1351 }
1352 match &self.anchor {
1353 ActionAnchor::AfterSlot { .. } | ActionAnchor::AfterEverySlot { .. } => Ok(()),
1354 ActionAnchor::BeforeSlot { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1355 anchor: "beforeSlot",
1356 }),
1357 ActionAnchor::BeforeEverySlot { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1358 anchor: "beforeEverySlot",
1359 }),
1360 ActionAnchor::BeforeBatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1361 anchor: "beforeBatch",
1362 }),
1363 ActionAnchor::BeforeMatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1364 anchor: "beforeMatch",
1365 }),
1366 ActionAnchor::AfterMatch { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1367 anchor: "afterMatch",
1368 }),
1369 ActionAnchor::AfterChange { .. } => Err(DiagnosticProbeError::UnsupportedAnchor {
1370 anchor: "afterChange",
1371 }),
1372 }
1373 }
1374}
1375
1376enum PairsFault {
1377 Count(usize),
1378 SelfPair(Address),
1379}
1380
1381fn pairs_fault(pairs: &[[Address; 2]]) -> Option<PairsFault> {
1382 if !(1..=MAX_DIAGNOSTIC_MARKET_PAIRS).contains(&pairs.len()) {
1383 return Some(PairsFault::Count(pairs.len()));
1384 }
1385 pairs
1386 .iter()
1387 .find(|[a, b]| a == b)
1388 .map(|[mint, _]| PairsFault::SelfPair(*mint))
1389}
1390
1391#[derive(Debug, Clone)]
1393enum OverrideContribution {
1394 Static(HashMap<Address, AccountSharedData>),
1395 Pending,
1396 Resolved(HashMap<Address, AccountSharedData>),
1397 Failed,
1398}
1399
1400#[derive(Debug, Clone, Default)]
1401struct OverrideScheduleInner {
1402 entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>>,
1403 keys: HashSet<Address>,
1407}
1408
1409impl OverrideScheduleInner {
1410 fn new(entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>>) -> Self {
1411 let keys = entries
1412 .values()
1413 .flatten()
1414 .filter_map(|(_, contribution)| match contribution {
1415 OverrideContribution::Static(accounts)
1416 | OverrideContribution::Resolved(accounts) => Some(accounts.keys().copied()),
1417 OverrideContribution::Pending | OverrideContribution::Failed => None,
1418 })
1419 .flatten()
1420 .collect();
1421 Self { entries, keys }
1422 }
1423}
1424
1425#[doc(hidden)]
1428#[derive(Debug, Clone, Default)]
1429pub struct OverrideSchedule {
1430 inner: Arc<RwLock<OverrideScheduleInner>>,
1431}
1432
1433impl From<BTreeMap<u64, HashMap<Address, AccountSharedData>>> for OverrideSchedule {
1434 fn from(entries: BTreeMap<u64, HashMap<Address, AccountSharedData>>) -> Self {
1435 Self {
1436 inner: Arc::new(RwLock::new(OverrideScheduleInner::new(
1437 entries
1438 .into_iter()
1439 .map(|(slot, accounts)| {
1440 (slot, vec![(0, OverrideContribution::Static(accounts))])
1441 })
1442 .collect(),
1443 ))),
1444 }
1445 }
1446}
1447
1448impl OverrideSchedule {
1449 pub fn is_empty(&self) -> bool {
1450 self.inner.read().entries.is_empty()
1451 }
1452
1453 pub fn slots(&self) -> impl Iterator<Item = u64> + '_ {
1455 self.inner
1456 .read()
1457 .entries
1458 .keys()
1459 .copied()
1460 .collect::<Vec<_>>()
1461 .into_iter()
1462 }
1463
1464 pub fn active_at(&self, slot: u64) -> HashMap<Address, AccountSharedData> {
1466 self.inner.read().entries.range(..=slot).fold(
1467 HashMap::new(),
1468 |mut active, (_, contributions)| {
1469 active.extend(fold_contributions(contributions));
1470 active
1471 },
1472 )
1473 }
1474
1475 pub fn active_for(&self, key: &Address, slot: u64) -> Option<AccountSharedData> {
1477 let inner = self.inner.read();
1478 if !inner.keys.contains(key) {
1479 return None;
1480 }
1481 inner
1482 .entries
1483 .range(..=slot)
1484 .rev()
1485 .find_map(|(_, contributions)| {
1486 contributions
1487 .iter()
1488 .rev()
1489 .find_map(|(_, contribution)| match contribution {
1490 OverrideContribution::Static(accounts)
1491 | OverrideContribution::Resolved(accounts) => accounts.get(key).cloned(),
1492 OverrideContribution::Pending | OverrideContribution::Failed => None,
1493 })
1494 })
1495 }
1496
1497 pub fn newly_active(
1499 &self,
1500 after: Option<u64>,
1501 up_to: u64,
1502 ) -> Vec<(Address, AccountSharedData)> {
1503 let lower = after.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Excluded);
1504 self.inner
1505 .read()
1506 .entries
1507 .range((lower, std::ops::Bound::Included(up_to)))
1508 .flat_map(|(_, contributions)| fold_contributions(contributions))
1509 .collect::<HashMap<_, _>>()
1510 .into_iter()
1511 .collect()
1512 }
1513
1514 pub fn resolve(
1517 &self,
1518 slot: u64,
1519 action_index: u32,
1520 accounts: Option<HashMap<Address, AccountSharedData>>,
1521 ) -> Result<(), String> {
1522 let mut inner = self.inner.write();
1523 let OverrideScheduleInner { entries, keys } = &mut *inner;
1524 let contribution = entries
1525 .get_mut(&slot)
1526 .and_then(|contributions| {
1527 contributions
1528 .iter_mut()
1529 .find(|(index, _)| *index == action_index)
1530 .map(|(_, contribution)| contribution)
1531 })
1532 .ok_or_else(|| {
1533 format!("override action {action_index} has no contribution at slot {slot}")
1534 })?;
1535 if !matches!(contribution, OverrideContribution::Pending) {
1536 return Err(format!(
1537 "override action {action_index} at slot {slot} is not pending"
1538 ));
1539 }
1540 *contribution = match accounts {
1541 Some(accounts) => {
1542 keys.extend(accounts.keys().copied());
1543 OverrideContribution::Resolved(accounts)
1544 }
1545 None => OverrideContribution::Failed,
1546 };
1547 Ok(())
1548 }
1549}
1550
1551fn fold_contributions(
1552 contributions: &[(u32, OverrideContribution)],
1553) -> HashMap<Address, AccountSharedData> {
1554 let mut accounts = HashMap::new();
1555 for (_, contribution) in contributions {
1556 match contribution {
1557 OverrideContribution::Static(next) | OverrideContribution::Resolved(next) => {
1558 accounts.extend(next.iter().map(|(key, account)| (*key, account.clone())));
1559 }
1560 OverrideContribution::Pending | OverrideContribution::Failed => {}
1561 }
1562 }
1563 accounts
1564}
1565
1566fn decode_override_actions(actions: &[ScheduledAction]) -> Result<OverrideSchedule, String> {
1575 let mut entries: BTreeMap<u64, Vec<(u32, OverrideContribution)>> = BTreeMap::new();
1576 for (action_index, action) in actions.iter().enumerate().filter(|(_, action)| {
1577 action.feeds_reroute
1578 || (action.transactions.is_empty() && !action.account_overrides.0.is_empty())
1579 }) {
1580 if action.kind == ActionKind::Send {
1582 return Err("account overrides are not valid for kind: send".to_string());
1583 }
1584 if action.transactions.is_empty() && action.account_overrides.0.is_empty() {
1585 return Err(
1586 "feedsReroute needs something to feed: transactions to simulate, or \
1587 accountOverrides"
1588 .to_string(),
1589 );
1590 }
1591 let ActionAnchor::BeforeSlot { slots } = &action.anchor else {
1592 return Err("scheduled account overrides require a beforeSlot anchor".to_string());
1593 };
1594 if action.within.is_some() {
1595 return Err("scheduled account overrides cannot be bounded by within".to_string());
1596 }
1597 let accounts = decode_account_modifications(&action.account_overrides)?;
1598 let contribution = if action.transactions.is_empty() {
1599 OverrideContribution::Static(accounts)
1600 } else {
1601 OverrideContribution::Pending
1602 };
1603 for slot in slots.iter().copied().collect::<BTreeSet<_>>() {
1606 entries
1607 .entry(slot)
1608 .or_default()
1609 .push((action_index as u32, contribution.clone()));
1610 }
1611 }
1612 Ok(OverrideSchedule {
1613 inner: Arc::new(RwLock::new(OverrideScheduleInner::new(entries))),
1614 })
1615}
1616
1617#[allow(
1621 deprecated,
1622 reason = "`PROGRAM_OWNERS` remains the canonical loader-owner list"
1623)]
1624#[doc(hidden)]
1625pub fn decode_account_modifications(
1626 modifications: &AccountModifications,
1627) -> Result<HashMap<Address, AccountSharedData>, String> {
1628 modifications
1629 .0
1630 .iter()
1631 .map(|(address, data)| {
1632 let account = data
1633 .to_account()
1634 .map_err(|error| format!("invalid account data for {address}: {error}"))?;
1635 if account.executable || PROGRAM_OWNERS.contains(&account.owner) {
1636 return Err(format!(
1637 "overriding executable/program accounts is not supported (account {address})"
1638 ));
1639 }
1640 Ok((*address, AccountSharedData::from(account)))
1641 })
1642 .collect()
1643}
1644
1645pub const MAX_DISCONNECT_TIMEOUT_SECS: u16 = 900;
1649
1650#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1653#[serde(rename_all = "lowercase", try_from = "String")]
1654pub enum SwapAggregator {
1655 Jupiter,
1657 Okx,
1659 Titan,
1661 Dflow,
1663}
1664
1665impl SwapAggregator {
1666 pub const ALL: [Self; 4] = [Self::Jupiter, Self::Okx, Self::Titan, Self::Dflow];
1668
1669 pub const fn as_str(self) -> &'static str {
1671 match self {
1672 Self::Jupiter => "jupiter",
1673 Self::Okx => "okx",
1674 Self::Titan => "titan",
1675 Self::Dflow => "dflow",
1676 }
1677 }
1678}
1679
1680impl std::fmt::Display for SwapAggregator {
1681 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1682 f.write_str(self.as_str())
1683 }
1684}
1685
1686#[derive(Debug, thiserror::Error)]
1688pub enum ParseAggregatorError {
1689 #[error("unknown swap aggregator {0:?}; expected one of jupiter, okx, titan, dflow")]
1691 Unknown(String),
1692 #[error("name at least one aggregator (jupiter, okx, titan, dflow)")]
1694 NoAggregator,
1695}
1696
1697impl TryFrom<String> for SwapAggregator {
1698 type Error = ParseAggregatorError;
1699
1700 fn try_from(value: String) -> Result<Self, Self::Error> {
1701 value.parse()
1702 }
1703}
1704
1705impl std::str::FromStr for SwapAggregator {
1706 type Err = ParseAggregatorError;
1707
1708 fn from_str(s: &str) -> Result<Self, Self::Err> {
1709 match s.trim().to_ascii_lowercase().as_str() {
1710 "jupiter" => Ok(Self::Jupiter),
1711 "okx" => Ok(Self::Okx),
1712 "titan" => Ok(Self::Titan),
1713 "dflow" => Ok(Self::Dflow),
1714 _ => Err(ParseAggregatorError::Unknown(s.to_string())),
1715 }
1716 }
1717}
1718
1719#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1724#[serde(transparent)]
1725pub struct RerouteAggregators(BTreeSet<SwapAggregator>);
1726
1727impl Default for RerouteAggregators {
1728 fn default() -> Self {
1729 Self([SwapAggregator::Jupiter].into_iter().collect())
1730 }
1731}
1732
1733impl RerouteAggregators {
1734 pub fn new(aggregators: impl IntoIterator<Item = SwapAggregator>) -> Self {
1736 Self(aggregators.into_iter().collect())
1737 }
1738
1739 pub fn all() -> Self {
1741 Self::new(SwapAggregator::ALL)
1742 }
1743
1744 #[allow(missing_docs)]
1745 pub fn contains(&self, aggregator: SwapAggregator) -> bool {
1746 self.0.contains(&aggregator)
1747 }
1748
1749 #[allow(missing_docs)]
1750 pub fn is_empty(&self) -> bool {
1751 self.0.is_empty()
1752 }
1753}
1754
1755impl std::fmt::Display for RerouteAggregators {
1756 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1757 let mut aggregators = self.0.iter();
1758 if let Some(first) = aggregators.next() {
1759 write!(f, "{first}")?;
1760 }
1761 aggregators.try_for_each(|aggregator| write!(f, ",{aggregator}"))
1762 }
1763}
1764
1765impl std::str::FromStr for RerouteAggregators {
1766 type Err = ParseAggregatorError;
1767
1768 fn from_str(s: &str) -> Result<Self, Self::Err> {
1769 let aggregators: BTreeSet<SwapAggregator> = s
1770 .split(',')
1771 .filter(|aggregator| !aggregator.trim().is_empty())
1772 .map(str::parse)
1773 .collect::<Result<_, _>>()?;
1774 if aggregators.is_empty() {
1775 return Err(ParseAggregatorError::NoAggregator);
1776 }
1777 Ok(Self(aggregators))
1778 }
1779}
1780
1781#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1783#[serde(rename_all = "kebab-case", try_from = "String")]
1784pub enum SwapScope {
1785 TopLevel,
1787 Nested,
1789 Venue,
1792}
1793
1794impl SwapScope {
1795 pub const fn as_str(self) -> &'static str {
1797 match self {
1798 Self::TopLevel => "top-level",
1799 Self::Nested => "nested",
1800 Self::Venue => "venue",
1801 }
1802 }
1803}
1804
1805impl std::fmt::Display for SwapScope {
1806 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1807 f.write_str(self.as_str())
1808 }
1809}
1810
1811#[derive(Debug, thiserror::Error)]
1813pub enum ParseScopeError {
1814 #[error("unknown swap scope {0:?}; expected one of top-level, nested, venue")]
1816 Unknown(String),
1817 #[error("name at least one swap scope (top-level, nested, venue)")]
1819 NoScope,
1820}
1821
1822impl TryFrom<String> for SwapScope {
1823 type Error = ParseScopeError;
1824
1825 fn try_from(value: String) -> Result<Self, Self::Error> {
1826 value.parse()
1827 }
1828}
1829
1830impl std::str::FromStr for SwapScope {
1831 type Err = ParseScopeError;
1832
1833 fn from_str(s: &str) -> Result<Self, Self::Err> {
1834 match s.trim().to_ascii_lowercase().as_str() {
1835 "top-level" => Ok(Self::TopLevel),
1836 "nested" => Ok(Self::Nested),
1837 "venue" => Ok(Self::Venue),
1838 _ => Err(ParseScopeError::Unknown(s.to_string())),
1839 }
1840 }
1841}
1842
1843#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1846#[serde(transparent)]
1847pub struct RerouteScopes(BTreeSet<SwapScope>);
1848
1849impl Default for RerouteScopes {
1850 fn default() -> Self {
1851 Self([SwapScope::TopLevel].into_iter().collect())
1852 }
1853}
1854
1855impl RerouteScopes {
1856 pub fn new(scopes: impl IntoIterator<Item = SwapScope>) -> Self {
1858 Self(scopes.into_iter().collect())
1859 }
1860
1861 #[allow(missing_docs)]
1862 pub fn contains(&self, scope: SwapScope) -> bool {
1863 self.0.contains(&scope)
1864 }
1865
1866 #[allow(missing_docs)]
1867 pub fn is_empty(&self) -> bool {
1868 self.0.is_empty()
1869 }
1870
1871 pub fn is_default(&self) -> bool {
1873 *self == Self::default()
1874 }
1875}
1876
1877impl std::fmt::Display for RerouteScopes {
1878 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1879 let mut scopes = self.0.iter();
1880 if let Some(first) = scopes.next() {
1881 write!(f, "{first}")?;
1882 }
1883 scopes.try_for_each(|scope| write!(f, ",{scope}"))
1884 }
1885}
1886
1887impl std::str::FromStr for RerouteScopes {
1888 type Err = ParseScopeError;
1889
1890 fn from_str(s: &str) -> Result<Self, Self::Err> {
1891 let scopes: BTreeSet<SwapScope> = s
1892 .split(',')
1893 .filter(|scope| !scope.trim().is_empty())
1894 .map(str::parse)
1895 .collect::<Result<_, _>>()?;
1896 if scopes.is_empty() {
1897 return Err(ParseScopeError::NoScope);
1898 }
1899 Ok(Self(scopes))
1900 }
1901}
1902
1903#[serde_with::serde_as]
1915#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1916#[serde(rename_all = "camelCase")]
1917pub struct RerouteParams {
1918 #[serde(default)]
1921 pub aggregators: RerouteAggregators,
1922 #[serde(default, skip_serializing_if = "RerouteScopes::is_default")]
1926 pub scopes: RerouteScopes,
1927 #[serde(default, skip_serializing_if = "Option::is_none")]
1930 pub filter: Option<RerouteFilter>,
1931 #[serde(default)]
1939 pub detect_failed_l1_swaps: bool,
1940 #[serde(default)]
1945 pub circular_arbs: bool,
1946 #[serde(default = "RerouteParams::default_requote")]
1952 pub requote: bool,
1953 #[serde(rename = "directFill", default, skip_serializing_if = "Vec::is_empty")]
1964 pub venue_templates: Vec<VenueTemplate>,
1965 #[serde_as(as = "BTreeSet<serde_with::DisplayFromStr>")]
1969 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
1970 pub extra_markets: BTreeSet<Address>,
1971 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1975 pub quote_late_in_slot: bool,
1976}
1977
1978impl Default for RerouteParams {
1981 fn default() -> Self {
1982 Self {
1983 aggregators: RerouteAggregators::default(),
1984 scopes: RerouteScopes::default(),
1985 filter: None,
1986 detect_failed_l1_swaps: false,
1987 circular_arbs: false,
1988 requote: Self::default_requote(),
1989 venue_templates: Vec::new(),
1990 extra_markets: BTreeSet::new(),
1991 quote_late_in_slot: false,
1992 }
1993 }
1994}
1995
1996impl std::str::FromStr for MintPair {
1998 type Err = String;
1999
2000 fn from_str(s: &str) -> Result<Self, Self::Err> {
2001 let (base, quote) = s
2002 .split_once(',')
2003 .ok_or_else(|| format!("expected two comma-separated mints, got {s:?}"))?;
2004 Self::try_from([base.trim().to_owned(), quote.trim().to_owned()])
2005 .map_err(|error| error.to_string())
2006 }
2007}
2008
2009impl std::fmt::Display for MintPair {
2010 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2011 let (one, other) = self.mints();
2012 write!(f, "{one},{other}")
2013 }
2014}
2015
2016impl RerouteParams {
2017 const fn default_requote() -> bool {
2018 true
2019 }
2020
2021 pub const fn is_noop(&self) -> bool {
2024 !self.requote && self.venue_templates.is_empty()
2025 }
2026}
2027
2028#[serde_with::serde_as]
2034#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
2035#[serde(rename_all = "camelCase")]
2036pub struct CreateSessionParams {
2037 pub start_slot: u64,
2041 pub end_slot: u64,
2043 #[serde(default)]
2045 #[builder(default)]
2046 pub send_summary: bool,
2047 #[serde(default, skip_serializing_if = "Option::is_none")]
2049 pub reroute: Option<RerouteParams>,
2050 #[serde(default)]
2053 pub capacity_wait_timeout_secs: Option<u16>,
2054 #[serde(default)]
2059 pub disconnect_timeout_secs: Option<u16>,
2060 #[serde(default)]
2065 pub extra_compute_units: Option<u32>,
2066 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2073 #[builder(default)]
2074 pub discoveries: Vec<DiscoveryFilter>,
2075 #[serde(default, with = "compressed", skip_serializing_if = "Vec::is_empty")]
2084 #[builder(default)]
2085 pub actions: Vec<ScheduledAction>,
2086 #[serde(default)]
2091 #[builder(default)]
2092 pub replay_account_state: bool,
2093 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2096 #[builder(default)]
2097 pub diagnostic_probes: Vec<DiagnosticProbeParams>,
2098}
2099
2100#[doc(hidden)]
2104pub mod replay_support {
2105 use super::{ActionKind, CreateSessionParams};
2106
2107 pub const NO_TRANSACTIONS: &str =
2109 "Create the session without replayAccountState to execute and persist transactions.";
2110
2111 pub const SEND_TRANSACTION: &str = "Use simulateTransaction to run it against the replayed state, or create the session \
2112 without replayAccountState.";
2113
2114 pub const SEND_ACTION: &str = "Use kind: simulate, which runs against the replayed state without committing, post state \
2115 directly with an action carrying accountOverrides and no transactions, or create the \
2116 session without replayAccountState.";
2117
2118 pub fn unsupported(operation: &str, remedy: &str) -> String {
2120 format!(
2121 "{operation} is not supported while account state replay is enabled: replay \
2122 reconstructs account state from the recorded delta bundle instead of executing \
2123 transactions, so this session never executes or persists any. {remedy}"
2124 )
2125 }
2126
2127 pub fn send_action_conflict(params: &CreateSessionParams) -> Option<String> {
2130 (params.replay_account_state
2131 && params
2132 .actions
2133 .iter()
2134 .any(|action| action.kind == ActionKind::Send))
2135 .then(|| unsupported("A scheduled action with kind: send", SEND_ACTION))
2136 }
2137}
2138
2139impl CreateSessionParams {
2140 #[doc(hidden)]
2144 pub fn requires_sidecar(&self) -> bool {
2145 self.reroute.as_ref().is_some_and(|reroute| {
2146 reroute.requote
2147 || reroute
2148 .venue_templates
2149 .iter()
2150 .any(|template| template.resolve == Some(TemplateResolver::Requote))
2151 }) || !self.diagnostic_probes.is_empty()
2152 || self.actions.iter().any(ScheduledAction::asks_router)
2153 }
2154
2155 pub fn requires_diagnostic_endpoint(&self) -> bool {
2159 !self.diagnostic_probes.is_empty()
2160 }
2161
2162 pub fn validate_diagnostic_probes(&self) -> Result<(), DiagnosticProbeError> {
2164 self.diagnostic_probes
2165 .iter()
2166 .try_for_each(DiagnosticProbeParams::validate)
2167 }
2168
2169 pub fn validate_action_resolvers(&self) -> Result<(), ActionResolveError> {
2171 validate_resolvers(&self.actions)
2172 }
2173
2174 #[doc(hidden)]
2176 pub fn warms_account_universe(&self) -> bool {
2177 self.requires_sidecar()
2178 || self
2179 .reroute
2180 .as_ref()
2181 .is_some_and(|reroute| !reroute.venue_templates.is_empty())
2182 }
2183
2184 pub fn reroute_order_flow(&self) -> bool {
2186 self.reroute.is_some()
2187 }
2188
2189 #[doc(hidden)]
2192 pub fn override_schedule(&self) -> Result<OverrideSchedule, String> {
2193 decode_override_actions(&self.actions)
2194 }
2195
2196 pub fn reroute_filter(&self) -> Option<&RerouteFilter> {
2198 self.reroute.as_ref()?.filter.as_ref()
2199 }
2200}
2201
2202#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
2205#[serde(rename_all = "kebab-case")]
2206pub enum FailFastDivergenceKind {
2207 #[default]
2210 AnyNonBenign,
2211 Tracked,
2214}
2215
2216impl FailFastDivergenceKind {
2217 pub fn as_str(self) -> &'static str {
2220 match self {
2221 Self::AnyNonBenign => "any-non-benign",
2222 Self::Tracked => "tracked",
2223 }
2224 }
2225
2226 pub fn from_str_opt(value: &str) -> Option<Self> {
2228 match value {
2229 "any-non-benign" => Some(Self::AnyNonBenign),
2230 "tracked" => Some(Self::Tracked),
2231 _ => None,
2232 }
2233 }
2234}
2235
2236#[serde_with::serde_as]
2238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
2239pub struct AccountModifications(
2240 #[serde_as(as = "BTreeMap<serde_with::DisplayFromStr, _>")]
2241 #[serde(default)]
2242 pub BTreeMap<Address, AccountData>,
2243);
2244
2245impl From<BTreeMap<Address, AccountData>> for AccountModifications {
2246 fn from(value: BTreeMap<Address, AccountData>) -> Self {
2247 Self(value)
2248 }
2249}
2250
2251impl AccountModifications {
2252 #[allow(missing_docs)]
2253 pub fn is_empty(&self) -> bool {
2254 self.0.is_empty()
2255 }
2256}
2257
2258#[serde_with::serde_as]
2265#[derive(Debug, Clone, Serialize, Deserialize)]
2266#[serde(rename_all = "camelCase")]
2267pub struct ContinueParams {
2268 #[serde(default = "ContinueParams::default_advance_count")]
2269 pub advance_count: u64,
2272 #[serde(default)]
2273 pub transactions: Vec<String>,
2278 #[serde(default)]
2279 pub modify_account_states: AccountModifications,
2282}
2283
2284impl Default for ContinueParams {
2285 fn default() -> Self {
2286 Self {
2287 advance_count: Self::default_advance_count(),
2288 transactions: Vec::new(),
2289 modify_account_states: AccountModifications(BTreeMap::new()),
2290 }
2291 }
2292}
2293
2294impl ContinueParams {
2295 pub fn default_advance_count() -> u64 {
2297 1
2298 }
2299}
2300
2301#[derive(Debug, Clone, Serialize, Deserialize)]
2308#[serde(rename_all = "camelCase")]
2309pub struct PausedEvent {
2310 #[allow(missing_docs)]
2311 pub slot: u64,
2312 #[serde(default, skip_serializing_if = "Option::is_none")]
2315 pub batch_index: Option<u32>,
2316}
2317
2318#[serde_with::serde_as]
2349#[derive(Debug, Clone, Serialize, Deserialize)]
2350#[serde(rename_all = "camelCase")]
2351pub struct DiscoveryBatchEvent {
2352 pub slot: u64,
2354 pub batch_index: u32,
2356 pub matched: Vec<DiscoveryFilter>,
2358 pub transactions: Vec<EncodedBinary>,
2361 #[serde(default)]
2364 pub transaction_indices: Vec<u32>,
2365}
2366
2367#[derive(Debug, Clone, Serialize, Deserialize)]
2380#[serde(rename_all = "camelCase")]
2381pub struct ContinueToParams {
2382 pub slot: u64,
2384 #[serde(default)]
2390 pub batch_index: Option<u32>,
2391}
2392
2393#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2395#[serde(rename_all = "lowercase")]
2396pub enum BinaryEncoding {
2397 Base64,
2399}
2400
2401impl BinaryEncoding {
2402 #[allow(missing_docs)]
2403 pub fn encode(self, bytes: &[u8]) -> String {
2404 match self {
2405 Self::Base64 => BASE64.encode(bytes),
2406 }
2407 }
2408
2409 #[allow(missing_docs)]
2410 pub fn decode(self, data: &str) -> Result<Vec<u8>, Base64DecodeError> {
2411 match self {
2412 Self::Base64 => BASE64.decode(data),
2413 }
2414 }
2415}
2416
2417#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2419#[serde(rename_all = "camelCase")]
2420pub struct EncodedBinary {
2421 pub data: String,
2423 pub encoding: BinaryEncoding,
2425}
2426
2427impl EncodedBinary {
2428 pub fn new(data: String, encoding: BinaryEncoding) -> Self {
2430 Self { data, encoding }
2431 }
2432
2433 #[allow(missing_docs)]
2434 pub fn from_bytes(bytes: &[u8], encoding: BinaryEncoding) -> Self {
2435 Self {
2436 data: encoding.encode(bytes),
2437 encoding,
2438 }
2439 }
2440
2441 #[allow(missing_docs)]
2442 pub fn decode(&self) -> Result<Vec<u8>, Base64DecodeError> {
2443 self.encoding.decode(&self.data)
2444 }
2445}
2446
2447#[serde_with::serde_as]
2458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2459#[serde(rename_all = "camelCase")]
2460pub struct AccountData {
2461 pub data: EncodedBinary,
2463 pub executable: bool,
2465 pub lamports: u64,
2467 #[serde_as(as = "serde_with::DisplayFromStr")]
2468 pub owner: Address,
2470 pub space: u64,
2473}
2474
2475impl AccountData {
2476 pub fn to_account(&self) -> Result<solana_account::Account, Base64DecodeError> {
2479 Ok(solana_account::Account {
2480 data: self.data.decode()?,
2481 lamports: self.lamports,
2482 owner: self.owner,
2483 executable: self.executable,
2484 rent_epoch: 0,
2485 })
2486 }
2487
2488 pub fn system_account(lamports: u64) -> Self {
2490 Self {
2491 data: EncodedBinary::new(String::new(), BinaryEncoding::Base64),
2492 executable: false,
2493 lamports,
2494 owner: solana_sdk_ids::system_program::ID,
2495 space: 0,
2496 }
2497 }
2498}
2499
2500impl From<&solana_account::Account> for AccountData {
2503 fn from(account: &solana_account::Account) -> Self {
2504 Self {
2505 data: EncodedBinary::from_bytes(&account.data, BinaryEncoding::Base64),
2506 executable: account.executable,
2507 lamports: account.lamports,
2508 owner: account.owner,
2509 space: account.data.len() as u64,
2510 }
2511 }
2512}
2513
2514#[derive(Debug, Clone, Serialize, Deserialize)]
2520#[serde(tag = "method", content = "params", rename_all = "camelCase")]
2521#[allow(missing_docs)]
2522pub enum BacktestResponse {
2523 SessionCreated {
2525 session_id: SessionId,
2527 rpc_endpoint: String,
2530 #[serde(default, skip_serializing_if = "Option::is_none")]
2533 task_id: Option<String>,
2534 #[serde(default, skip_serializing_if = "Option::is_none")]
2536 session_name: Option<String>,
2537 },
2538 SessionAttached {
2541 session_id: SessionId,
2543 rpc_endpoint: String,
2545 #[serde(default, skip_serializing_if = "Option::is_none")]
2547 task_id: Option<String>,
2548 #[serde(default, skip_serializing_if = "Option::is_none")]
2550 session_name: Option<String>,
2551 },
2552 SessionsCreatedV2 {
2555 control_session_id: ControlSessionId,
2557 #[serde(default, skip_serializing_if = "Option::is_none")]
2559 control_session_name: Option<String>,
2560 session_ids: Vec<SessionId>,
2562 #[serde(default)]
2564 task_ids: Vec<Option<String>>,
2565 #[serde(default)]
2570 start_slots: Vec<u64>,
2571 #[serde(default)]
2573 end_slots: Vec<u64>,
2574 },
2575 ParallelSessionAttachedV2 {
2578 control_session_id: ControlSessionId,
2580 session_ids: Vec<SessionId>,
2581 #[serde(default)]
2583 task_ids: Vec<Option<String>>,
2584 },
2585 ReadyForContinue,
2588 SlotNotification(u64),
2590 Paused(PausedEvent),
2592 DiscoveryBatch(DiscoveryBatchEvent),
2595 Error(BacktestError),
2598 Success,
2602 Completed {
2604 #[serde(skip_serializing_if = "Option::is_none")]
2607 summary: Option<SessionSummary>,
2608 },
2609 Status { status: BacktestStatus },
2611 SessionEventV2 {
2613 session_id: SessionId,
2614 seq_id: u64,
2617 event: SessionEventKind,
2618 },
2619}
2620
2621impl BacktestResponse {
2622 #[allow(missing_docs)]
2623 pub fn is_completed(&self) -> bool {
2624 matches!(self, BacktestResponse::Completed { .. })
2625 }
2626
2627 pub fn is_terminal(&self) -> bool {
2630 match self {
2631 BacktestResponse::Completed { .. } => true,
2632 BacktestResponse::Error(e) => e.is_terminal(),
2633 _ => false,
2634 }
2635 }
2636}
2637
2638impl From<BacktestStatus> for BacktestResponse {
2639 fn from(status: BacktestStatus) -> Self {
2640 Self::Status { status }
2641 }
2642}
2643
2644impl From<String> for BacktestResponse {
2645 fn from(message: String) -> Self {
2646 BacktestError::Internal { error: message }.into()
2647 }
2648}
2649
2650impl From<&str> for BacktestResponse {
2651 fn from(message: &str) -> Self {
2652 BacktestError::Internal {
2653 error: message.to_string(),
2654 }
2655 .into()
2656 }
2657}
2658
2659#[derive(Debug, Clone, Serialize, Deserialize)]
2663#[serde(tag = "method", content = "params", rename_all = "camelCase")]
2664#[allow(missing_docs)]
2665pub enum SessionEventKind {
2666 ReadyForContinue,
2668 SlotNotification(u64),
2670 Paused(PausedEvent),
2672 DiscoveryBatch(DiscoveryBatchEvent),
2674 Error(BacktestError),
2676 Success,
2678 Completed {
2680 #[serde(skip_serializing_if = "Option::is_none")]
2682 summary: Option<SessionSummary>,
2683 },
2684 Status { status: BacktestStatus },
2686}
2687
2688impl SessionEventKind {
2689 pub fn is_terminal(&self) -> bool {
2691 match self {
2692 Self::Completed { .. } => true,
2693 Self::Error(e) => e.is_terminal(),
2694 _ => false,
2695 }
2696 }
2697}
2698
2699#[derive(Debug, Clone, Serialize, Deserialize)]
2703#[serde(rename_all = "camelCase")]
2704pub struct SequencedResponse {
2705 pub seq_id: u64,
2708 #[serde(flatten)]
2710 pub response: BacktestResponse,
2711}
2712
2713#[derive(Debug, Clone, Serialize, Deserialize)]
2721#[serde(rename_all = "camelCase")]
2722pub enum BacktestStatus {
2723 StartingRuntime,
2726 DecodedTransactions,
2728 AppliedAccountModifications,
2730 ReadyToExecuteUserTransactions,
2732 ExecutedUserTransactions,
2734 ExecutingBlockTransactions,
2736 ExecutedBlockTransactions,
2738 ProgramAccountsLoaded,
2740}
2741
2742impl std::fmt::Display for BacktestStatus {
2743 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2744 let s = match self {
2745 Self::StartingRuntime => "starting runtime",
2746 Self::DecodedTransactions => "decoded transactions",
2747 Self::AppliedAccountModifications => "applied account modifications",
2748 Self::ReadyToExecuteUserTransactions => "ready to execute user transactions",
2749 Self::ExecutedUserTransactions => "executed user transactions",
2750 Self::ExecutingBlockTransactions => "executing block transactions",
2751 Self::ExecutedBlockTransactions => "executed block transactions",
2752 Self::ProgramAccountsLoaded => "program accounts loaded",
2753 };
2754 f.write_str(s)
2755 }
2756}
2757
2758#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2767#[serde(rename_all = "camelCase")]
2768pub struct RerouteStatsReport {
2769 #[serde(default)]
2771 pub swaps_detected: u64,
2772 #[serde(default)]
2776 pub swaps_filtered: u64,
2777 #[serde(default)]
2779 pub swaps_rerouted: u64,
2780 #[serde(default)]
2782 pub swaps_simulated: u64,
2783 #[serde(default)]
2785 pub swaps_succeeded: u64,
2786 #[serde(default)]
2788 pub requote_failures: u64,
2789 #[serde(default)]
2791 pub override_setup_failures: u64,
2792 #[serde(default)]
2794 pub metis_unavailable_blocks: u64,
2795 #[serde(default)]
2799 pub quote_attempts_unavailable: u64,
2800 #[serde(rename = "directFillMatched", default)]
2803 pub venue_matched: u64,
2804 #[serde(rename = "directFillOutcomes", default)]
2809 pub venue_outcomes: BTreeMap<String, u64>,
2810 #[serde(rename = "directFillScored", default)]
2812 pub venue_scored: u64,
2813 #[serde(rename = "directFillBpsTotal", default)]
2817 pub venue_bps_total: i64,
2818 #[serde(rename = "directFillTemplates", default)]
2821 pub venue_template_reports: BTreeMap<String, VenueTemplateReport>,
2822 #[serde(default)]
2824 pub originals_scored: u64,
2825 #[serde(default)]
2828 pub originals_bps_total: i64,
2829 #[serde(default)]
2831 pub originals_replayed: u64,
2832 #[serde(default, skip_serializing_if = "Option::is_none")]
2834 pub dataset_uri: Option<String>,
2835}
2836
2837pub const REROUTE_DATASET_RETENTION_DAYS: u32 = 30;
2839
2840#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2843#[serde(rename_all = "camelCase")]
2844pub struct VenueTemplateReport {
2845 pub matched: u64,
2847 pub outcomes: BTreeMap<String, u64>,
2849 pub scored: u64,
2851 pub bps_total: i64,
2854}
2855
2856#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2863#[serde(rename_all = "camelCase")]
2864pub struct SessionSummary {
2865 pub correct_simulation: usize,
2868 pub incorrect_simulation: usize,
2871 pub execution_errors: usize,
2873 pub balance_diff: usize,
2875 pub log_diff: usize,
2877 #[serde(default)]
2880 pub unsanitizable: usize,
2881 #[serde(default, skip_serializing_if = "Option::is_none")]
2884 pub reroute_stats: Option<Box<RerouteStatsReport>>,
2885}
2886
2887impl SessionSummary {
2888 pub fn has_deviations(&self) -> bool {
2892 self.incorrect_simulation > 0 || self.execution_errors > 0 || self.balance_diff > 0
2893 }
2894
2895 pub fn total_transactions(&self) -> usize {
2898 self.correct_simulation
2899 + self.incorrect_simulation
2900 + self.execution_errors
2901 + self.balance_diff
2902 + self.log_diff
2903 }
2904
2905 pub fn deviation_details(&self, balance_label: &str, log_label: &str) -> String {
2910 format!(
2911 "{} incorrect simulations, {} execution errors, {} {balance_label}, {} {log_label}",
2912 self.incorrect_simulation, self.execution_errors, self.balance_diff, self.log_diff,
2913 )
2914 }
2915}
2916
2917impl std::fmt::Display for SessionSummary {
2918 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2919 let total = self.total_transactions();
2920 write!(
2921 f,
2922 "Session summary: {total} transactions\n\
2923 \x20 - {} correct simulation\n\
2924 \x20 - {} incorrect simulation\n\
2925 \x20 - {} execution errors\n\
2926 \x20 - {} unsanitizable\n\
2927 \x20 - {} balance diffs\n\
2928 \x20 - {} log diffs",
2929 self.correct_simulation,
2930 self.incorrect_simulation,
2931 self.execution_errors,
2932 self.unsanitizable,
2933 self.balance_diff,
2934 self.log_diff,
2935 )
2936 }
2937}
2938
2939#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2948#[serde(rename_all = "camelCase")]
2949#[allow(missing_docs)]
2950pub enum BacktestError {
2951 InvalidTransactionEncoding {
2954 index: usize,
2956 error: String,
2957 },
2958 InvalidTransactionFormat {
2962 index: usize,
2964 error: String,
2965 },
2966 InvalidAccountEncoding {
2969 address: String,
2971 encoding: BinaryEncoding,
2973 error: String,
2974 },
2975 InvalidAccountOwner {
2977 address: String,
2979 error: String,
2980 },
2981 InvalidAccountPubkey {
2983 address: String,
2985 error: String,
2986 },
2987 NoMoreBlocks,
2989 BundleNotFound {
2992 start_slot: u64,
2993 end_slot: u64,
2994 },
2995 AdvanceSlotFailed {
2997 slot: u64,
2998 error: String,
2999 },
3000 FinalizeSlotFailed {
3002 slot: u64,
3003 error: String,
3004 },
3005 InvalidRequest {
3009 error: String,
3011 },
3012 Internal {
3014 error: String,
3015 },
3016 InvalidBlockhashFormat {
3018 slot: u64,
3019 error: String,
3020 },
3021 InitializingSysvarsFailed {
3023 slot: u64,
3024 error: String,
3025 },
3026 ClerkError {
3030 error: String,
3031 },
3032 SimulationError {
3035 error: String,
3036 },
3037 SessionNotFound {
3040 session_id: String,
3042 },
3043 SessionOwnerMismatch,
3046 SessionOwnershipBusy {
3051 reason: String,
3053 },
3054 NoProducedBlocksInRange {
3060 start_slot: u64,
3061 end_slot: u64,
3062 },
3063 SessionNameTaken {
3066 session_name: String,
3068 },
3069 ProgramdataNotDeployed {
3070 address: String,
3071 },
3072}
3073
3074impl BacktestError {
3075 pub fn is_refusal(&self) -> bool {
3077 match self {
3078 BacktestError::NoProducedBlocksInRange { .. }
3079 | BacktestError::ProgramdataNotDeployed { .. } => true,
3080 BacktestError::InvalidTransactionEncoding { .. }
3081 | BacktestError::InvalidTransactionFormat { .. }
3082 | BacktestError::InvalidAccountEncoding { .. }
3083 | BacktestError::InvalidAccountOwner { .. }
3084 | BacktestError::InvalidAccountPubkey { .. }
3085 | BacktestError::NoMoreBlocks
3086 | BacktestError::BundleNotFound { .. }
3087 | BacktestError::AdvanceSlotFailed { .. }
3088 | BacktestError::FinalizeSlotFailed { .. }
3089 | BacktestError::InvalidRequest { .. }
3090 | BacktestError::Internal { .. }
3091 | BacktestError::InvalidBlockhashFormat { .. }
3092 | BacktestError::InitializingSysvarsFailed { .. }
3093 | BacktestError::ClerkError { .. }
3094 | BacktestError::SimulationError { .. }
3095 | BacktestError::SessionNotFound { .. }
3096 | BacktestError::SessionOwnerMismatch
3097 | BacktestError::SessionOwnershipBusy { .. }
3098 | BacktestError::SessionNameTaken { .. } => false,
3099 }
3100 }
3101
3102 pub fn is_terminal(&self) -> bool {
3106 matches!(
3107 self,
3108 BacktestError::NoMoreBlocks
3109 | BacktestError::BundleNotFound { .. }
3110 | BacktestError::AdvanceSlotFailed { .. }
3111 | BacktestError::FinalizeSlotFailed { .. }
3112 | BacktestError::Internal { .. }
3113 | BacktestError::NoProducedBlocksInRange { .. }
3114 | BacktestError::ProgramdataNotDeployed { .. }
3115 )
3116 }
3117
3118 pub fn is_retryable(&self) -> bool {
3125 matches!(
3126 self,
3127 BacktestError::Internal { .. }
3128 | BacktestError::ClerkError { .. }
3129 | BacktestError::SessionOwnershipBusy { .. }
3130 )
3131 }
3132}
3133
3134#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3139pub struct AvailableRange {
3140 pub bundle_start_slot: u64,
3142 pub bundle_start_slot_utc: Option<String>,
3144 pub max_bundle_end_slot: Option<u64>,
3146 pub max_bundle_end_slot_utc: Option<String>,
3148 pub max_bundle_size: Option<u64>,
3150 #[serde(default)]
3153 pub kind: Option<BundleKind>,
3154 #[serde(default)]
3157 pub scope: Option<RangeScope>,
3158}
3159
3160#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3162#[serde(rename_all = "snake_case")]
3163pub enum RangeScope {
3164 Global,
3166 User,
3168}
3169
3170impl RangeScope {
3171 pub fn as_str(self) -> &'static str {
3173 match self {
3174 Self::Global => "global",
3175 Self::User => "user",
3176 }
3177 }
3178}
3179
3180#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
3182#[serde(rename_all = "snake_case")]
3183pub enum BundleKind {
3184 #[default]
3186 Blocks,
3187 AccountState,
3191}
3192
3193pub const REPLAY_RANGE_ADVICE: &str = "replayed state is resolved by the recording that begins \
3197 where the request does, so request a range that begins where one was recorded and ends \
3198 within it";
3199
3200impl BundleKind {
3201 fn coverage_noun(self) -> &'static str {
3203 match self {
3204 Self::Blocks => "bundle range",
3205 Self::AccountState => "account-state bundle",
3206 }
3207 }
3208
3209 fn coverage_nouns(self) -> &'static str {
3211 match self {
3212 Self::Blocks => "bundle ranges",
3213 Self::AccountState => "account-state bundles",
3214 }
3215 }
3216
3217 pub fn as_str(self) -> &'static str {
3219 match self {
3220 Self::Blocks => "blocks",
3221 Self::AccountState => "account_state",
3222 }
3223 }
3224
3225 pub fn from_str_opt(value: &str) -> Option<Self> {
3227 match value {
3228 "blocks" => Some(Self::Blocks),
3229 "account_state" => Some(Self::AccountState),
3230 _ => None,
3231 }
3232 }
3233}
3234
3235impl fmt::Display for BundleKind {
3238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3239 let label = match self {
3240 Self::Blocks => "transactions",
3241 Self::AccountState => "account_state",
3242 };
3243 f.pad(label)
3244 }
3245}
3246
3247#[doc(hidden)]
3252#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3253#[serde(rename_all = "snake_case")]
3254pub enum JobKind {
3255 #[default]
3257 BundleBuild,
3258 Depth,
3260 EstimatedFills,
3261 Predict,
3262}
3263
3264impl JobKind {
3265 pub fn as_str(self) -> &'static str {
3267 match self {
3268 Self::BundleBuild => "bundle_build",
3269 Self::Depth => "depth",
3270 Self::EstimatedFills => "estimated_fills",
3271 Self::Predict => "predict",
3272 }
3273 }
3274
3275 pub fn from_str_opt(value: &str) -> Option<Self> {
3277 match value {
3278 "bundle_build" => Some(Self::BundleBuild),
3279 "depth" => Some(Self::Depth),
3280 "estimated_fills" => Some(Self::EstimatedFills),
3281 "predict" => Some(Self::Predict),
3282 _ => None,
3283 }
3284 }
3285}
3286
3287#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3292#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
3293#[serde(rename_all = "snake_case")]
3294pub enum DepthSource {
3295 #[default]
3297 Onchain,
3298 Router,
3300}
3301
3302impl DepthSource {
3303 pub const fn as_str(self) -> &'static str {
3305 match self {
3306 Self::Onchain => "onchain",
3307 Self::Router => "router",
3308 }
3309 }
3310
3311 pub fn from_str_opt(value: &str) -> Option<Self> {
3313 match value {
3314 "onchain" => Some(Self::Onchain),
3315 "router" => Some(Self::Router),
3316 _ => None,
3317 }
3318 }
3319
3320 #[doc(hidden)]
3325 pub const fn discriminant(self) -> u8 {
3326 match self {
3327 Self::Onchain => 0,
3328 Self::Router => 1,
3329 }
3330 }
3331}
3332
3333impl fmt::Display for DepthSource {
3334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3335 f.write_str(self.as_str())
3336 }
3337}
3338
3339#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3341#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
3342#[serde(rename_all = "snake_case")]
3343pub enum DepthGranularity {
3344 #[default]
3346 Slot,
3347 Oracle,
3350}
3351
3352impl DepthGranularity {
3353 pub const fn as_str(self) -> &'static str {
3355 match self {
3356 Self::Slot => "slot",
3357 Self::Oracle => "oracle",
3358 }
3359 }
3360
3361 pub fn is_default(&self) -> bool {
3363 *self == Self::default()
3364 }
3365
3366 #[doc(hidden)]
3368 pub const fn discriminant(self) -> u8 {
3369 match self {
3370 Self::Slot => 0,
3371 Self::Oracle => 1,
3372 }
3373 }
3374}
3375
3376impl fmt::Display for DepthGranularity {
3377 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3378 f.write_str(self.as_str())
3379 }
3380}
3381
3382#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
3384#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
3385#[serde(rename_all = "snake_case")]
3386pub enum DepthKind {
3387 OnchainSlot,
3389 OnchainOracle,
3391 RouterSlot,
3393}
3394
3395impl DepthKind {
3396 pub const fn source(self) -> DepthSource {
3398 match self {
3399 Self::OnchainSlot | Self::OnchainOracle => DepthSource::Onchain,
3400 Self::RouterSlot => DepthSource::Router,
3401 }
3402 }
3403
3404 pub const fn granularity(self) -> DepthGranularity {
3406 match self {
3407 Self::OnchainSlot | Self::RouterSlot => DepthGranularity::Slot,
3408 Self::OnchainOracle => DepthGranularity::Oracle,
3409 }
3410 }
3411}
3412
3413#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
3415#[error("the {0} source cannot be measured at {1} granularity")]
3416pub struct UnmeasuredDepth(pub DepthSource, pub DepthGranularity);
3417
3418impl TryFrom<(DepthSource, DepthGranularity)> for DepthKind {
3419 type Error = UnmeasuredDepth;
3420
3421 fn try_from(
3422 (source, granularity): (DepthSource, DepthGranularity),
3423 ) -> Result<Self, Self::Error> {
3424 match (source, granularity) {
3425 (DepthSource::Onchain, DepthGranularity::Slot) => Ok(Self::OnchainSlot),
3426 (DepthSource::Onchain, DepthGranularity::Oracle) => Ok(Self::OnchainOracle),
3427 (DepthSource::Router, DepthGranularity::Slot) => Ok(Self::RouterSlot),
3428 (DepthSource::Router, DepthGranularity::Oracle) => {
3429 Err(UnmeasuredDepth(source, granularity))
3430 }
3431 }
3432 }
3433}
3434
3435pub const fn depth_dataset_prefix(
3437 source: DepthSource,
3438 granularity: DepthGranularity,
3439) -> &'static str {
3440 match (source, granularity) {
3441 (DepthSource::Onchain, DepthGranularity::Slot) => "depth/onchain/slot",
3442 (DepthSource::Onchain, DepthGranularity::Oracle) => "depth/onchain/oracle",
3443 (DepthSource::Router, DepthGranularity::Slot) => "depth/router/slot",
3444 (DepthSource::Router, DepthGranularity::Oracle) => "depth/router/oracle",
3445 }
3446}
3447
3448pub fn modified_dataset_root(dataset: &str, digest: &str) -> String {
3451 format!("{MODIFIED_PREFIX}/{dataset}/{digest}")
3452}
3453
3454pub const MODIFIED_PREFIX: &str = "modified";
3456
3457#[derive(Debug, Clone, Serialize, Deserialize)]
3459pub struct DepthCoverageResponse {
3460 pub sources: Vec<DepthSourceCoverage>,
3462}
3463
3464#[derive(Debug, Clone, Serialize, Deserialize)]
3466pub struct DepthSourceCoverage {
3467 pub source: DepthSource,
3469 pub revision: u16,
3472 pub markets: Vec<String>,
3474 pub venues: Vec<String>,
3476 pub size_rungs: usize,
3478 pub completed_ranges: Vec<SlotRange>,
3485}
3486
3487pub const MAX_PROGRAM_OVERRIDES: usize = 8;
3489pub const MAX_ACCOUNT_OVERRIDES: usize = 64;
3491pub const MAX_TOTAL_ELF_BYTES: usize = 8 * 1024 * 1024;
3493pub const MAX_RPC_REQUEST_BODY_BYTES: u32 = 16 * 1024 * 1024;
3495pub const MAX_ACCOUNT_OVERRIDE_BYTES: usize = 128 * 1024;
3498
3499#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3505pub struct DepthRequest {
3506 pub start_slot: u64,
3509 pub end_slot: u64,
3511 #[serde(flatten)]
3513 pub selection: DepthSelection,
3514}
3515
3516#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
3518pub struct DepthSelection {
3519 #[serde(default)]
3522 pub source: DepthSource,
3523 #[serde(default, skip_serializing_if = "DepthGranularity::is_default")]
3525 pub granularity: DepthGranularity,
3526 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3528 pub markets: Vec<String>,
3529 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3531 pub program_overrides: Vec<ProgramOverride>,
3532 #[serde(default, skip_serializing_if = "AccountModifications::is_empty")]
3535 pub account_overrides: AccountModifications,
3536}
3537
3538#[serde_with::serde_as]
3541#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3542pub struct ProgramOverride {
3543 #[serde_as(as = "serde_with::DisplayFromStr")]
3545 pub program_id: Address,
3546 #[serde_as(as = "serde_with::base64::Base64")]
3548 pub elf: Vec<u8>,
3549}
3550
3551#[derive(Debug, Clone, Serialize, Deserialize)]
3553#[allow(missing_docs)]
3554pub struct DepthStatusResponse {
3555 pub request_id: String,
3557 pub start_slot: u64,
3558 pub end_slot: u64,
3559 pub source: DepthSource,
3560 #[serde(default, skip_serializing_if = "DepthGranularity::is_default")]
3562 pub granularity: DepthGranularity,
3563 pub status: BundleBuildStatus,
3564 #[serde(default, skip_serializing_if = "Option::is_none")]
3567 pub capture: Option<SlotRange>,
3568 #[serde(default, skip_serializing_if = "Option::is_none")]
3572 pub modification_digest: Option<String>,
3573}
3574
3575#[doc(hidden)]
3579#[serde_with::serde_as]
3580#[derive(Debug, Clone, Serialize, Deserialize)]
3581pub struct DepthModifications {
3582 #[serde_as(as = "BTreeMap<serde_with::DisplayFromStr, serde_with::base64::Base64>")]
3583 pub programs: BTreeMap<Address, Vec<u8>>,
3584 pub accounts: AccountModifications,
3585}
3586
3587#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3591pub struct BundleBuildRequest {
3592 pub start_slot: u64,
3594 pub end_slot: u64,
3596 #[serde(default)]
3599 pub bundle_size: Option<u64>,
3600 #[serde(default)]
3603 pub idempotency_key: Option<String>,
3604 #[serde(default)]
3606 pub kind: BundleKind,
3607}
3608
3609#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3611#[serde(rename_all = "snake_case")]
3612pub enum BundleBuildStatus {
3613 Completed,
3615 Failed,
3617 InProgress,
3619 NeedsInvestigation,
3622}
3623
3624impl BundleBuildStatus {
3625 pub fn as_str(self) -> &'static str {
3627 match self {
3628 Self::Completed => "completed",
3629 Self::Failed => "failed",
3630 Self::InProgress => "in_progress",
3631 Self::NeedsInvestigation => "needs_investigation",
3632 }
3633 }
3634}
3635
3636#[derive(Debug, Clone, Serialize, Deserialize)]
3638#[allow(missing_docs)]
3639pub struct BundleBuildStatusResponse {
3640 pub request_id: String,
3642 pub start_slot: u64,
3643 pub end_slot: u64,
3644 pub bundle_size: Option<u64>,
3646 pub status: BundleBuildStatus,
3647 pub created_at_unix_ms: u64,
3650 #[serde(default)]
3652 pub kind: BundleKind,
3653 #[serde(default)]
3656 pub eta_secs: Option<u64>,
3657}
3658
3659#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
3661#[allow(missing_docs)]
3662pub struct CompletedBundle {
3663 pub start_slot: u64,
3664 pub end_slot: u64,
3665 pub kind: BundleKind,
3666 #[serde(default)]
3668 pub completed_at_unix_ms: Option<i64>,
3669 #[serde(default)]
3671 pub size_bytes: Option<i64>,
3672}
3673
3674#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3676pub struct BundleDeleteRequest {
3677 #[allow(missing_docs)]
3678 pub start_slot: u64,
3679 #[allow(missing_docs)]
3680 pub end_slot: u64,
3681 #[serde(default)]
3683 pub kind: BundleKind,
3684}
3685
3686#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3688#[allow(missing_docs)]
3689pub struct BundleDeleteResponse {
3690 pub start_slot: u64,
3691 pub end_slot: u64,
3692 pub kind: BundleKind,
3693}
3694
3695#[derive(Debug, Clone, Serialize, Deserialize)]
3697pub struct BundleBuildListResponse {
3698 pub builds: Vec<BundleBuildStatusResponse>,
3701 #[serde(default)]
3706 pub bundles: Option<Vec<CompletedBundle>>,
3707}
3708
3709#[derive(Debug, Clone, Serialize, Deserialize)]
3712pub struct SnapshotSlotResponse {
3713 pub snapshot_slot: u64,
3715}
3716
3717#[derive(Debug, Clone, Serialize, Deserialize)]
3720#[allow(missing_docs)]
3721pub struct DatasetCredentialsResponse {
3722 pub access_key_id: String,
3723 pub secret_access_key: String,
3724 pub session_token: String,
3725 pub expiration: Option<chrono::DateTime<chrono::Utc>>,
3727 pub s3_uri: String,
3729 #[serde(default, skip_serializing_if = "Option::is_none")]
3732 pub user_s3_uri: Option<String>,
3733 pub region: Option<String>,
3734}
3735
3736pub fn split_range(
3759 ranges: &[AvailableRange],
3760 requested: SlotRange,
3761 kind: BundleKind,
3762) -> Result<Vec<(u64, u64)>, String> {
3763 split_range_preferring(ranges, requested, kind, Prefer::Most)
3764}
3765
3766pub fn split_range_fewest(
3770 ranges: &[AvailableRange],
3771 requested: SlotRange,
3772 kind: BundleKind,
3773) -> Result<Vec<(u64, u64)>, String> {
3774 split_range_preferring(ranges, requested, kind, Prefer::Fewest)
3775}
3776
3777#[derive(Clone, Copy)]
3779enum Prefer {
3780 Most,
3781 Fewest,
3782}
3783
3784fn split_range_preferring(
3787 ranges: &[AvailableRange],
3788 requested: SlotRange,
3789 kind: BundleKind,
3790 prefer: Prefer,
3791) -> Result<Vec<(u64, u64)>, String> {
3792 let (requested_start, requested_end) = (requested.start(), requested.end());
3793
3794 let ends_by_start = ranges
3801 .iter()
3802 .filter(|r| r.kind.unwrap_or_default() == kind)
3803 .filter_map(|r| {
3804 r.max_bundle_end_slot
3805 .filter(|&end| end >= r.bundle_start_slot)
3806 .map(|end| (r.bundle_start_slot, end))
3807 })
3808 .fold(
3809 BTreeMap::<u64, BTreeSet<u64>>::new(),
3810 |mut ends_by_start, (start, end)| {
3811 ends_by_start.entry(start).or_default().insert(end);
3812 ends_by_start
3813 },
3814 );
3815
3816 let Some((&anchor_start, _)) = ends_by_start.range(..=requested_start).rfind(|(_, ends)| {
3824 ends.iter()
3825 .next_back()
3826 .is_some_and(|&end| end >= requested_start)
3827 }) else {
3828 return Err(format!(
3829 "start_slot {requested_start} is not covered by any available {}",
3830 kind.coverage_noun()
3831 ));
3832 };
3833
3834 let mut best_from: BTreeMap<u64, Vec<(u64, u64)>> = BTreeMap::new();
3838 for (&start, ends) in ends_by_start.range(anchor_start..=requested_end).rev() {
3839 let mut best: Option<Vec<(u64, u64)>> = None;
3840 for &end in ends {
3841 let candidate = if end >= requested_end {
3842 Some(vec![(start, requested_end)])
3843 } else {
3844 best_from.get(&(end + 1)).map(|rest| {
3845 std::iter::once((start, end))
3846 .chain(rest.iter().copied())
3847 .collect()
3848 })
3849 };
3850 if let Some(candidate) = candidate
3851 && best.as_ref().is_none_or(|b| match prefer {
3852 Prefer::Most => candidate.len() > b.len(),
3853 Prefer::Fewest => candidate.len() < b.len(),
3854 })
3855 {
3856 best = Some(candidate);
3857 }
3858 }
3859 if let Some(best) = best {
3860 best_from.insert(start, best);
3861 }
3862 }
3863
3864 best_from.remove(&anchor_start).ok_or_else(|| {
3865 let mut covered_to = anchor_start.saturating_sub(1);
3869 for (&start, ends) in ends_by_start.range(anchor_start..=requested_end) {
3870 if start > covered_to.saturating_add(1) {
3871 break;
3872 }
3873 if let Some(&end) = ends.iter().next_back() {
3874 covered_to = covered_to.max(end);
3875 }
3876 }
3877 if covered_to < requested_end {
3878 format!("gap in coverage at slot {}", covered_to + 1)
3879 } else {
3880 format!(
3881 "no gap-free split of [{requested_start}, {requested_end}] aligns with the available {}",
3882 kind.coverage_nouns()
3883 )
3884 }
3885 })
3886}
3887
3888impl From<BacktestError> for BacktestResponse {
3889 fn from(error: BacktestError) -> Self {
3890 Self::Error(error)
3891 }
3892}
3893
3894impl std::error::Error for BacktestError {}
3895
3896impl fmt::Display for BacktestError {
3897 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3898 match self {
3899 BacktestError::InvalidTransactionEncoding { index, error } => {
3900 write!(f, "invalid transaction encoding at index {index}: {error}")
3901 }
3902 BacktestError::InvalidTransactionFormat { index, error } => {
3903 write!(f, "invalid transaction format at index {index}: {error}")
3904 }
3905 BacktestError::InvalidAccountEncoding {
3906 address,
3907 encoding,
3908 error,
3909 } => write!(
3910 f,
3911 "invalid encoding for account {address} ({encoding:?}): {error}"
3912 ),
3913 BacktestError::InvalidAccountOwner { address, error } => {
3914 write!(f, "invalid owner for account {address}: {error}")
3915 }
3916 BacktestError::InvalidAccountPubkey { address, error } => {
3917 write!(f, "invalid account pubkey {address}: {error}")
3918 }
3919 BacktestError::NoMoreBlocks => write!(f, "no more blocks available"),
3920 BacktestError::BundleNotFound {
3921 start_slot,
3922 end_slot,
3923 } => write!(
3924 f,
3925 "block bundle not found for start_slot={start_slot}, end_slot={end_slot}"
3926 ),
3927 BacktestError::AdvanceSlotFailed { slot, error } => {
3928 write!(f, "failed to advance to slot {slot}: {error}")
3929 }
3930 BacktestError::FinalizeSlotFailed { slot, error } => {
3931 write!(f, "failed to finalize slot {slot}: {error}")
3932 }
3933 BacktestError::InvalidRequest { error } => write!(f, "invalid request: {error}"),
3934 BacktestError::Internal { error } => write!(f, "internal error: {error}"),
3935 BacktestError::InvalidBlockhashFormat { slot, error } => {
3936 write!(f, "invalid blockhash at slot {slot}: {error}")
3937 }
3938 BacktestError::InitializingSysvarsFailed { slot, error } => {
3939 write!(f, "failed to initialize sysvars at slot {slot}: {error}")
3940 }
3941 BacktestError::ClerkError { error } => write!(f, "clerk error: {error}"),
3942 BacktestError::SimulationError { error } => {
3943 write!(f, "simulation error: {error}")
3944 }
3945 BacktestError::SessionNotFound { session_id } => {
3946 write!(f, "session not found: {session_id}")
3947 }
3948 BacktestError::SessionOwnerMismatch => {
3949 write!(f, "session owner mismatch")
3950 }
3951 BacktestError::SessionOwnershipBusy { reason } => {
3952 write!(f, "session ownership busy: {reason}")
3953 }
3954 BacktestError::NoProducedBlocksInRange {
3955 start_slot,
3956 end_slot,
3957 } => write!(
3958 f,
3959 "no produced blocks in requested range {start_slot}..={end_slot}; \
3960 slot(s) may be skipped onchain"
3961 ),
3962 BacktestError::ProgramdataNotDeployed { address } => write!(
3963 f,
3964 "{address} is not a deployed upgradeable program's programdata, so its \
3965 replacement would never run"
3966 ),
3967 BacktestError::SessionNameTaken { session_name } => {
3968 write!(f, "session name '{session_name}' is already in use")
3969 }
3970 }
3971 }
3972}
3973
3974#[cfg(test)]
3975mod tests {
3976 use rstest::rstest;
3977 use solana_account::ReadableAccount;
3978
3979 use super::*;
3980
3981 #[rstest]
3982 #[case::onchain_slot(
3983 DepthSource::Onchain,
3984 DepthGranularity::Slot,
3985 Some(DepthKind::OnchainSlot)
3986 )]
3987 #[case::onchain_oracle(
3988 DepthSource::Onchain,
3989 DepthGranularity::Oracle,
3990 Some(DepthKind::OnchainOracle)
3991 )]
3992 #[case::router_slot(
3993 DepthSource::Router,
3994 DepthGranularity::Slot,
3995 Some(DepthKind::RouterSlot)
3996 )]
3997 #[case::router_oracle(DepthSource::Router, DepthGranularity::Oracle, None)]
3998 fn only_a_source_at_a_granularity_it_measures_names_a_depth_kind(
3999 #[case] source: DepthSource,
4000 #[case] granularity: DepthGranularity,
4001 #[case] kind: Option<DepthKind>,
4002 ) {
4003 let named = DepthKind::try_from((source, granularity));
4004 assert_eq!(named.ok(), kind);
4005 if let Some(kind) = kind {
4006 assert_eq!((kind.source(), kind.granularity()), (source, granularity));
4007 }
4008 }
4009
4010 #[test]
4013 fn a_sources_discriminant_is_frozen_independently_of_its_label() {
4014 assert_eq!(DepthSource::Onchain.discriminant(), 0);
4015 assert_eq!(DepthSource::Router.discriminant(), 1);
4016 }
4017
4018 #[test]
4021 fn a_source_spells_itself_the_same_way_three_times() {
4022 for source in [DepthSource::Onchain, DepthSource::Router] {
4023 assert_eq!(
4024 serde_json::to_value(source).expect("a source serialises"),
4025 serde_json::json!(source.as_str())
4026 );
4027 assert_eq!(DepthSource::from_str_opt(source.as_str()), Some(source));
4028 }
4029 }
4030
4031 #[rstest]
4033 #[case::continue_params(r#"{"method": "continue", "params": {"advanceCount": 10}}"#)]
4034 #[case::attach(
4035 r#"{"method": "attachBacktestSession", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "last_sequence": 7}}"#
4036 )]
4037 #[case::attach_parallel(
4038 r#"{"method": "attachParallelControlSessionV2", "params": {"control_session_id": "parallel_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "last_sequences": {"backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b": 7}}}"#
4039 )]
4040 #[case::continue_v1(
4041 r#"{"method": "continueSessionV1", "params": {"sessionId": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "request": {"advanceCount": 1}}}"#
4042 )]
4043 #[case::resume(r#"{"method": "resumeAttachedSession"}"#)]
4044 fn a_documented_request_parses(#[case] wire: &str) {
4045 serde_json::from_str::<BacktestRequest>(wire).expect("documented request parses");
4046 }
4047
4048 #[rstest]
4050 #[case::session_created(
4051 r#"{"method": "sessionCreated", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "rpc_endpoint": "https://host/backtest/backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b"}}"#
4052 )]
4053 #[case::sequenced(r#"{"seqId": 7, "method": "slotNotification", "params": 1234}"#)]
4054 #[case::ready(r#"{"method": "readyForContinue"}"#)]
4055 #[case::error(
4056 r#"{"method": "error", "params": {"bundleNotFound": {"start_slot": 1, "end_slot": 2}}}"#
4057 )]
4058 #[case::session_event(
4059 r#"{"method": "sessionEventV2", "params": {"session_id": "backtest_0198f3a1c2d34e5f8a9b0c1d2e3f4a5b", "seq_id": 3, "event": {"method": "readyForContinue"}}}"#
4060 )]
4061 fn a_documented_response_round_trips(#[case] wire: &str) {
4062 let expected: serde_json::Value = serde_json::from_str(wire).expect("valid JSON");
4063 let actual = match expected.get("seqId") {
4064 Some(_) => serde_json::to_value(
4065 serde_json::from_str::<SequencedResponse>(wire)
4066 .expect("documented response parses"),
4067 ),
4068 None => serde_json::to_value(
4069 serde_json::from_str::<BacktestResponse>(wire).expect("documented response parses"),
4070 ),
4071 }
4072 .expect("response serialises");
4073 assert_eq!(actual, expected);
4074 }
4075
4076 #[rstest]
4077 #[case::empty(solana_account::Account { lamports: 1, rent_epoch: 7, ..Default::default() })]
4078 #[case::executable_with_data(solana_account::Account {
4079 lamports: 2,
4080 data: vec![1, 2, 3],
4081 owner: Address::from([9; 32]),
4082 executable: true,
4083 rent_epoch: u64::MAX,
4084 })]
4085 fn an_account_survives_the_wire_round_trip_apart_from_its_rent_epoch(
4086 #[case] account: solana_account::Account,
4087 ) {
4088 let wire = AccountData::from(&account);
4089
4090 assert_eq!(wire.space, account.data.len() as u64);
4091 assert_eq!(wire.data.encoding, BinaryEncoding::Base64);
4092 assert_eq!(
4093 wire.to_account().expect("base64 decodes"),
4094 solana_account::Account {
4095 rent_epoch: 0,
4096 ..account
4097 }
4098 );
4099 }
4100
4101 #[rstest]
4102 #[case::nonexistent(0)]
4103 #[case::funded(1_000_000)]
4104 fn system_account_is_an_empty_system_owned_account(#[case] lamports: u64) {
4105 assert_eq!(
4106 AccountData::system_account(lamports)
4107 .to_account()
4108 .expect("base64 decodes"),
4109 solana_account::Account {
4110 lamports,
4111 ..Default::default()
4112 }
4113 );
4114 }
4115
4116 fn address(byte: u8) -> Address {
4117 Address::from([byte; 32])
4118 }
4119
4120 #[rstest]
4121 #[case::one("jupiter", Some(&[SwapAggregator::Jupiter][..]))]
4122 #[case::several("jupiter,okx", Some(&[SwapAggregator::Jupiter, SwapAggregator::Okx][..]))]
4123 #[case::spaced_and_uppercased(" Jupiter , OKX ", Some(&[SwapAggregator::Jupiter, SwapAggregator::Okx][..]))]
4124 #[case::repeats_collapse("okx,okx", Some(&[SwapAggregator::Okx][..]))]
4125 #[case::trailing_separator("okx,", Some(&[SwapAggregator::Okx][..]))]
4126 #[case::unknown("jupiter,bogus", None)]
4127 #[case::empty("", None)]
4128 #[case::separators_only(",,", None)]
4129 fn reroute_aggregators_parse_the_shapes_a_flag_carries(
4130 #[case] input: &str,
4131 #[case] expected: Option<&[SwapAggregator]>,
4132 ) {
4133 assert_eq!(
4134 input.parse::<RerouteAggregators>().ok(),
4135 expected.map(|aggregators| RerouteAggregators::new(aggregators.iter().copied()))
4136 );
4137 }
4138
4139 #[test]
4141 fn reroute_aggregators_round_trip_through_their_rendering() {
4142 let aggregators = RerouteAggregators::new([SwapAggregator::Dflow, SwapAggregator::Jupiter]);
4143
4144 assert_eq!(aggregators.to_string(), "jupiter,dflow");
4145 assert_eq!(
4146 aggregators
4147 .to_string()
4148 .parse::<RerouteAggregators>()
4149 .unwrap(),
4150 aggregators
4151 );
4152 assert_eq!(RerouteAggregators::default().to_string(), "jupiter");
4153 }
4154
4155 #[test]
4156 fn all_lists_every_aggregator_once_in_order() {
4157 let _tripwire = |aggregator: SwapAggregator| match aggregator {
4159 SwapAggregator::Jupiter
4160 | SwapAggregator::Okx
4161 | SwapAggregator::Titan
4162 | SwapAggregator::Dflow => (),
4163 };
4164
4165 assert!(SwapAggregator::ALL.is_sorted_by(|a, b| a < b));
4167 }
4168
4169 #[test]
4170 fn all_aggregators_render_and_parse_back() {
4171 let all = RerouteAggregators::all();
4172
4173 assert_eq!(all.to_string(), "jupiter,okx,titan,dflow");
4174 assert_eq!(all.to_string().parse::<RerouteAggregators>().unwrap(), all);
4175 }
4176
4177 #[test]
4180 fn aggregators_deserialize_through_the_same_parser_the_flag_uses() {
4181 let params: CreateSessionParams = serde_json::from_value(
4182 serde_json::json!({"startSlot": 1, "endSlot": 2, "reroute": {"aggregators": ["Jupiter", "OKX"]}}),
4183 )
4184 .expect("decode");
4185
4186 assert_eq!(
4187 params.reroute.expect("rerouting requested").aggregators,
4188 RerouteAggregators::new([SwapAggregator::Jupiter, SwapAggregator::Okx])
4189 );
4190 }
4191
4192 #[test]
4195 fn params_without_the_new_reroute_fields_decode_to_the_narrow_defaults() {
4196 let params: CreateSessionParams = serde_json::from_value(
4197 serde_json::json!({"startSlot": 1, "endSlot": 2, "reroute": {}}),
4198 )
4199 .expect("decode");
4200
4201 let reroute = params.reroute.expect("rerouting requested");
4202 assert_eq!(reroute.aggregators, RerouteAggregators::default());
4203 assert!(reroute.aggregators.contains(SwapAggregator::Jupiter));
4204 assert!(!reroute.aggregators.contains(SwapAggregator::Okx));
4205 assert!(!reroute.circular_arbs);
4206 assert!(!reroute.detect_failed_l1_swaps);
4207 assert_eq!(reroute.scopes, RerouteScopes::default());
4208 }
4209
4210 #[rstest]
4211 #[case::top_level("top-level", Some(&[SwapScope::TopLevel][..]))]
4212 #[case::both(" Nested , top-level ", Some(&[SwapScope::TopLevel, SwapScope::Nested][..]))]
4213 #[case::all(
4214 "venue,nested,top-level",
4215 Some(&[SwapScope::TopLevel, SwapScope::Nested, SwapScope::Venue][..])
4216 )]
4217 #[case::unknown("nested,bogus", None)]
4218 #[case::empty(",", None)]
4219 fn reroute_scopes_parse_the_shapes_a_flag_carries(
4220 #[case] input: &str,
4221 #[case] expected: Option<&[SwapScope]>,
4222 ) {
4223 assert_eq!(
4224 input.parse::<RerouteScopes>().ok(),
4225 expected.map(|scopes| RerouteScopes::new(scopes.iter().copied()))
4226 );
4227 }
4228
4229 #[test]
4232 fn reroute_scopes_round_trip_and_keep_the_default_off_the_wire() {
4233 let scopes = RerouteScopes::new([SwapScope::Nested, SwapScope::TopLevel]);
4234
4235 assert_eq!(scopes.to_string(), "top-level,nested");
4236 assert_eq!(scopes.to_string().parse::<RerouteScopes>().unwrap(), scopes);
4237 assert_eq!(
4238 serde_json::to_value(RerouteParams::default()).unwrap()["scopes"],
4239 serde_json::Value::Null
4240 );
4241 assert_eq!(
4242 serde_json::to_value(RerouteParams {
4243 scopes,
4244 ..RerouteParams::default()
4245 })
4246 .unwrap()["scopes"],
4247 serde_json::json!(["top-level", "nested"])
4248 );
4249 }
4250
4251 #[test]
4253 fn a_request_without_reroute_reserves_no_sidecar() {
4254 let params: CreateSessionParams =
4255 serde_json::from_value(serde_json::json!({"startSlot": 1, "endSlot": 2}))
4256 .expect("decode");
4257
4258 assert!(!params.requires_sidecar());
4259 }
4260
4261 #[test]
4266 fn a_per_slot_action_schedule_compresses_across_actions() {
4267 let slots = 2_000u64;
4268 let actions = (0..slots)
4269 .map(|slot| ScheduledAction {
4270 anchor: ActionAnchor::AfterSlot { slots: vec![slot] },
4271 kind: ActionKind::Simulate,
4272 feeds_reroute: false,
4273 transactions: Vec::new(),
4274 account_overrides: AccountModifications(BTreeMap::from([(
4275 address(7),
4276 AccountData {
4277 data: EncodedBinary::new(
4279 BASE64.encode(
4280 [&slot.to_le_bytes()[..], &[0xAB; 2040][..]]
4281 .concat()
4282 .as_slice(),
4283 ),
4284 BinaryEncoding::Base64,
4285 ),
4286 executable: false,
4287 lamports: 15_144_966,
4288 owner: address(9),
4289 space: 2048,
4290 },
4291 )])),
4292 return_accounts: Vec::new(),
4293 label: None,
4294 resolve: None,
4295 within: None,
4296 })
4297 .collect::<Vec<_>>();
4298 let params = CreateSessionParams::builder()
4299 .start_slot(1)
4300 .end_slot(slots)
4301 .actions(actions.clone())
4302 .build();
4303
4304 let encoded = serde_json::to_string(¶ms).expect("serialize");
4305 let raw = serde_json::to_string(&actions).expect("serialize raw actions");
4306 assert!(
4307 encoded.len() * 8 < raw.len(),
4308 "expected the schedule to compress well; got {} bytes from {} raw",
4309 encoded.len(),
4310 raw.len()
4311 );
4312
4313 let decoded: CreateSessionParams = serde_json::from_str(&encoded).expect("round trip");
4314 assert_eq!(
4315 serde_json::to_string(&decoded.actions).expect("serialize decoded"),
4316 raw
4317 );
4318 }
4319
4320 #[test]
4323 fn an_empty_action_list_is_omitted_entirely() {
4324 let params = CreateSessionParams::builder()
4325 .start_slot(1)
4326 .end_slot(2)
4327 .build();
4328 let json = serde_json::to_value(¶ms).expect("serialize");
4329 assert!(json.get("actions").is_none(), "{json}");
4330 let decoded: CreateSessionParams = serde_json::from_value(json).expect("round trip");
4331 assert!(decoded.actions.is_empty());
4332 }
4333
4334 #[test]
4337 fn send_actions_conflict_with_replay_only_together() {
4338 let params = |replay, kind| {
4339 CreateSessionParams::builder()
4340 .start_slot(1)
4341 .end_slot(2)
4342 .replay_account_state(replay)
4343 .actions(vec![ScheduledAction {
4344 anchor: ActionAnchor::BeforeSlot { slots: vec![1] },
4345 kind,
4346 feeds_reroute: false,
4347 transactions: vec!["dGVzdA==".to_string()],
4348 account_overrides: Default::default(),
4349 return_accounts: Default::default(),
4350 label: None,
4351 resolve: None,
4352 within: None,
4353 }])
4354 .build()
4355 };
4356 assert!(replay_support::send_action_conflict(¶ms(false, ActionKind::Send)).is_none());
4357 assert!(
4358 replay_support::send_action_conflict(¶ms(true, ActionKind::Simulate)).is_none()
4359 );
4360 let mut publishing = params(true, ActionKind::Simulate);
4361 publishing.actions[0].feeds_reroute = true;
4362 assert!(replay_support::send_action_conflict(&publishing).is_none());
4363
4364 let conflict = replay_support::send_action_conflict(¶ms(true, ActionKind::Send))
4365 .expect("send under replay conflicts");
4366 assert!(conflict.contains("kind: send"), "{conflict}");
4367 assert!(conflict.contains(replay_support::SEND_ACTION), "{conflict}");
4368 }
4369
4370 fn override_entry(owner: Address, executable: bool) -> AccountData {
4371 AccountData {
4372 data: EncodedBinary::from_bytes(&[1, 2, 3], BinaryEncoding::Base64),
4373 executable,
4374 lamports: 1,
4375 owner,
4376 space: 3,
4377 }
4378 }
4379
4380 fn before() -> ActionAnchor {
4381 ActionAnchor::BeforeSlot { slots: vec![1] }
4382 }
4383
4384 fn valid() -> ScheduledAction {
4385 override_action(before(), address(3), override_entry(address(4), false))
4386 }
4387
4388 fn override_action(
4389 anchor: ActionAnchor,
4390 account: Address,
4391 data: AccountData,
4392 ) -> ScheduledAction {
4393 ScheduledAction {
4394 anchor,
4395 kind: ActionKind::default(),
4396 transactions: Vec::new(),
4397 account_overrides: AccountModifications(BTreeMap::from([(account, data)])),
4398 return_accounts: Vec::new(),
4399 label: None,
4400 feeds_reroute: true,
4401 resolve: None,
4402 within: None,
4403 }
4404 }
4405
4406 #[test]
4407 fn override_action_round_trips() {
4408 let key = address(1);
4409 let entry = override_entry(address(2), false);
4410 let action = override_action(
4411 ActionAnchor::BeforeSlot { slots: vec![5, 9] },
4412 key,
4413 entry.clone(),
4414 );
4415 let json = serde_json::to_value(&action).unwrap();
4416 assert!(
4417 json["anchor"]["slots"].is_string(),
4418 "slots travel as a compressed blob: {json}"
4419 );
4420 let back: ScheduledAction = serde_json::from_value(json).unwrap();
4421 assert_eq!(back.anchor, ActionAnchor::BeforeSlot { slots: vec![5, 9] });
4422 assert!(back.feeds_reroute);
4423 assert!(!back.is_computed_override(), "no transactions to simulate");
4424 let survived = &back.account_overrides.0[&key];
4425 assert_eq!(survived.lamports, entry.lamports);
4426 assert_eq!(survived.data.data, entry.data.data);
4427 }
4428
4429 #[rstest]
4430 #[case::unbounded(None)]
4431 #[case::bounded(Some(SlotRange::new_unchecked(5, 9)))]
4432 fn a_slot_bound_round_trips_and_stays_off_the_wire_when_absent(
4433 #[case] within: Option<SlotRange>,
4434 ) {
4435 let action = ScheduledAction {
4436 within,
4437 ..resolved_action()
4438 };
4439 let json = serde_json::to_value(&action).unwrap();
4440 assert_eq!(json.get("within").is_some(), within.is_some(), "{json}");
4441 let back: ScheduledAction = serde_json::from_value(json).unwrap();
4442 assert_eq!(back.within, within);
4443 }
4444
4445 #[test]
4446 fn a_before_batch_anchor_round_trips_its_batches_compressed() {
4447 let anchor = ActionAnchor::BeforeBatch {
4448 batches: vec![
4449 BatchPosition {
4450 slot: 5,
4451 batch_index: 2,
4452 },
4453 BatchPosition {
4454 slot: 5,
4455 batch_index: 2,
4456 },
4457 ],
4458 };
4459
4460 let json = serde_json::to_value(&anchor).unwrap();
4461
4462 assert_eq!(json["at"], "beforeBatch");
4463 assert!(json["batches"].is_string(), "{json}");
4464 assert_eq!(
4465 serde_json::from_value::<ActionAnchor>(json).unwrap(),
4466 anchor
4467 );
4468 }
4469
4470 #[test]
4471 fn an_every_slot_anchor_round_trips_and_defaults_to_every_slot() {
4472 let anchor = ActionAnchor::AfterEverySlot {
4473 every_n_slots: NonZeroU64::new(10).unwrap(),
4474 };
4475 let json = serde_json::to_value(&anchor).unwrap();
4476 assert_eq!(
4477 json,
4478 serde_json::json!({ "at": "afterEverySlot", "everyNSlots": 10 })
4479 );
4480 assert_eq!(
4481 serde_json::from_value::<ActionAnchor>(json).unwrap(),
4482 anchor
4483 );
4484
4485 assert_eq!(
4486 serde_json::from_value::<ActionAnchor>(serde_json::json!({ "at": "beforeEverySlot" }))
4487 .unwrap(),
4488 ActionAnchor::BeforeEverySlot {
4489 every_n_slots: NonZeroU64::MIN
4490 }
4491 );
4492 assert!(
4493 serde_json::from_value::<ActionAnchor>(
4494 serde_json::json!({ "at": "beforeEverySlot", "everyNSlots": 0 })
4495 )
4496 .is_err(),
4497 "a zero cadence names no slot"
4498 );
4499 }
4500
4501 fn context(
4502 invoked: &[u8],
4503 moves_tokens: bool,
4504 written: &[u8],
4505 writes_via_unresolved_lookup: bool,
4506 ) -> TxMatchContext {
4507 TxMatchContext {
4508 invoked_programs: invoked.iter().copied().map(address).collect(),
4509 moves_tokens,
4510 written_accounts: written.iter().copied().map(address).collect(),
4511 writes_via_unresolved_lookup,
4512 }
4513 }
4514
4515 #[rstest]
4517 #[case::update(&[], context(&[1], false, &[11], false), true)]
4518 #[case::moves_tokens(&[], context(&[1], true, &[11], false), false)]
4519 #[case::second_program_of_the_set(&[], context(&[2], false, &[11], false), true)]
4520 #[case::other_program(&[], context(&[3], false, &[11], false), false)]
4521 #[case::write_to_the_scope(&[10], context(&[1], false, &[11, 10], false), true)]
4522 #[case::write_elsewhere(&[10], context(&[1], false, &[11], false), false)]
4523 #[case::unresolved_write_through_a_lookup_table(&[10], context(&[1], false, &[11], true), true)]
4524 fn an_oracle_update_is_a_token_free_write_by_a_listed_program(
4525 #[case] accounts: &[u8],
4526 #[case] ctx: TxMatchContext,
4527 #[case] expected: bool,
4528 ) {
4529 let filter = DiscoveryFilter::OracleUpdate {
4530 programs: BTreeSet::from([address(1), address(2)]),
4531 accounts: accounts.iter().copied().map(address).collect(),
4532 };
4533 assert_eq!(filter.matches(&ctx), expected);
4534 }
4535
4536 #[rstest]
4537 #[case::write_to_the_scope(&[10], context(&[1], true, &[11, 10], false), true)]
4538 #[case::another_market_s_write(&[10], context(&[1], false, &[11], false), false)]
4539 #[case::unresolved_write_through_a_lookup_table(&[10], context(&[1], false, &[11], true), true)]
4540 #[case::program_did_not_run(&[10], context(&[2], false, &[10], false), false)]
4541 #[case::empty_scope(&[], context(&[1], false, &[10], true), false)]
4542 fn a_program_write_is_a_call_to_the_program_writing_its_scope(
4543 #[case] accounts: &[u8],
4544 #[case] ctx: TxMatchContext,
4545 #[case] expected: bool,
4546 ) {
4547 let filter = DiscoveryFilter::ProgramWrite {
4548 program: address(1),
4549 accounts: accounts.iter().copied().map(address).collect(),
4550 };
4551 assert_eq!(filter.matches(&ctx), expected);
4552 }
4553
4554 #[rstest]
4555 #[case::unscoped(
4556 &[],
4557 serde_json::json!({ "kind": "oracleUpdate", "value": { "programs": [address(1).to_string()] } })
4558 )]
4559 #[case::scoped(
4560 &[2],
4561 serde_json::json!({
4562 "kind": "oracleUpdate",
4563 "value": { "programs": [address(1).to_string()], "accounts": [address(2).to_string()] }
4564 })
4565 )]
4566 fn an_oracle_update_filter_round_trips_as_kind_and_value(
4567 #[case] accounts: &[u8],
4568 #[case] expected: serde_json::Value,
4569 ) {
4570 let filter = DiscoveryFilter::OracleUpdate {
4571 programs: BTreeSet::from([address(1)]),
4572 accounts: accounts.iter().copied().map(address).collect(),
4573 };
4574 let json = serde_json::to_value(&filter).unwrap();
4575
4576 assert_eq!(json, expected);
4577 assert_eq!(
4578 serde_json::from_value::<DiscoveryFilter>(json).unwrap(),
4579 filter
4580 );
4581 }
4582
4583 #[test]
4584 fn an_after_change_anchor_round_trips_with_its_accounts() {
4585 let anchor = ActionAnchor::AfterChange {
4586 accounts: BTreeSet::from([address(1), address(2)]).try_into().unwrap(),
4587 };
4588 let json = serde_json::to_value(&anchor).unwrap();
4589
4590 assert_eq!(
4591 json,
4592 serde_json::json!({
4593 "at": "afterChange",
4594 "accounts": [address(1).to_string(), address(2).to_string()]
4595 })
4596 );
4597 assert_eq!(
4598 serde_json::from_value::<ActionAnchor>(json).unwrap(),
4599 anchor
4600 );
4601 }
4602
4603 #[rstest]
4604 #[case::empty(serde_json::json!([]))]
4605 #[case::not_an_address(serde_json::json!(["not-an-address"]))]
4606 fn an_after_change_anchor_rejects_an_unusable_account_list(
4607 #[case] accounts: serde_json::Value,
4608 ) {
4609 let json = serde_json::json!({ "at": "afterChange", "accounts": accounts });
4610 assert!(serde_json::from_value::<ActionAnchor>(json).is_err());
4611 }
4612
4613 #[test]
4618 fn a_token_account_override_is_accepted() {
4619 let action = override_action(
4620 before(),
4621 address(3),
4622 override_entry(spl_token_interface::ID, false),
4623 );
4624 let schedule = decode_override_actions(&[action]).expect("token overrides decode");
4625 assert!(!schedule.active_at(1).is_empty());
4626 }
4627
4628 #[rstest]
4629 #[case::executable(override_action(before(), address(3), override_entry(address(10), true)))]
4630 #[case::program_owned(override_action(
4631 before(),
4632 address(3),
4633 override_entry(PROGRAM_OWNERS[0], false),
4634 ))]
4635 #[case::after_slot_anchor(override_action(
4636 ActionAnchor::AfterSlot { slots: vec![1] },
4637 address(3),
4638 override_entry(address(4), false),
4639 ))]
4640 #[case::every_slot_anchor(override_action(
4641 ActionAnchor::BeforeEverySlot { every_n_slots: NonZeroU64::MIN },
4642 address(3),
4643 override_entry(address(4), false),
4644 ))]
4645 #[case::nothing_to_post(ScheduledAction {
4646 account_overrides: AccountModifications::default(),
4647 ..valid()
4648 })]
4649 #[case::send(ScheduledAction {
4651 kind: ActionKind::Send,
4652 ..valid()
4653 })]
4654 #[case::bounded(ScheduledAction {
4655 within: Some(SlotRange::new_unchecked(0, 9)),
4656 ..valid()
4657 })]
4658 #[allow(deprecated, reason = "exercise the loader-owner rejection path")]
4659 fn override_actions_reject_invalid_accounts_and_shapes(#[case] action: ScheduledAction) {
4660 assert!(decode_override_actions(&[action]).is_err());
4661 }
4662
4663 fn liquidity_arrays(array_key_indices: Vec<u8>) -> TxResolver {
4664 TxResolver::LiquidityArrays {
4665 pool: address(1),
4666 input_mint: address(2),
4667 array_key_indices: array_key_indices.try_into().unwrap(),
4668 }
4669 }
4670
4671 fn resolved_action() -> ScheduledAction {
4672 ScheduledAction {
4673 anchor: ActionAnchor::AfterSlot { slots: vec![5] },
4674 kind: ActionKind::Simulate,
4675 transactions: vec!["dGVzdA==".to_string()],
4676 account_overrides: AccountModifications::default(),
4677 feeds_reroute: false,
4678 return_accounts: Vec::new(),
4679 label: None,
4680 resolve: Some(liquidity_arrays(vec![6, 7, 8])),
4681 within: None,
4682 }
4683 }
4684
4685 fn requote() -> TxResolver {
4686 TxResolver::Requote {
4687 dex: address(1),
4688 input_mint: address(2),
4689 output_mint: address(3),
4690 amount: 1_000_000_000,
4691 slippage_bps: 9900,
4692 }
4693 }
4694
4695 fn validate_session_resolvers(actions: Vec<ScheduledAction>) -> Result<(), ActionResolveError> {
4696 CreateSessionParams::builder()
4697 .start_slot(1)
4698 .end_slot(10)
4699 .actions(actions)
4700 .build()
4701 .validate_action_resolvers()
4702 }
4703
4704 #[test]
4705 fn a_liquidity_arrays_resolver_serializes_as_a_type_tagged_camel_case_object() {
4706 let resolver = liquidity_arrays(vec![6, 7, 8]);
4707 let json = serde_json::to_value(&resolver).unwrap();
4708 assert_eq!(
4709 json,
4710 serde_json::json!({
4711 "type": "liquidityArrays",
4712 "pool": address(1).to_string(),
4713 "inputMint": address(2).to_string(),
4714 "arrayKeyIndices": [6, 7, 8],
4715 })
4716 );
4717 assert_eq!(
4718 serde_json::from_value::<TxResolver>(json).unwrap(),
4719 resolver
4720 );
4721 }
4722
4723 #[test]
4724 fn a_quote_stamp_resolver_serializes_as_its_type_tag_alone() {
4725 let json = serde_json::to_value(TxResolver::QuoteStamp).unwrap();
4726 assert_eq!(json, serde_json::json!({ "type": "quoteStamp" }));
4727 assert_eq!(
4728 serde_json::from_value::<TxResolver>(json).unwrap(),
4729 TxResolver::QuoteStamp
4730 );
4731 }
4732
4733 #[test]
4734 fn a_requote_resolver_round_trips_its_terms() {
4735 let resolver = requote();
4736 let json = serde_json::to_value(&resolver).unwrap();
4737 assert_eq!(
4738 json,
4739 serde_json::json!({
4740 "type": "requote",
4741 "dex": address(1).to_string(),
4742 "inputMint": address(2).to_string(),
4743 "outputMint": address(3).to_string(),
4744 "amount": 1_000_000_000_u64,
4745 "slippageBps": 9900,
4746 })
4747 );
4748 assert_eq!(
4749 serde_json::from_value::<TxResolver>(json).unwrap(),
4750 resolver
4751 );
4752 }
4753
4754 #[test]
4755 fn only_an_action_that_requotes_needs_the_sidecar() {
4756 let params = |resolve| {
4757 CreateSessionParams::builder()
4758 .start_slot(1)
4759 .end_slot(10)
4760 .actions(vec![ScheduledAction {
4761 resolve,
4762 ..resolved_action()
4763 }])
4764 .build()
4765 };
4766 assert!(params(Some(requote())).requires_sidecar());
4767 assert!(!params(Some(TxResolver::QuoteStamp)).requires_sidecar());
4768 }
4769
4770 #[test]
4771 fn an_action_without_a_resolver_omits_the_key_and_reads_back_as_none() {
4772 let action = ScheduledAction {
4773 resolve: None,
4774 ..resolved_action()
4775 };
4776 let json = serde_json::to_value(&action).unwrap();
4777 assert!(json.get("resolve").is_none(), "{json}");
4778 let back: ScheduledAction = serde_json::from_value(json).unwrap();
4779 assert_eq!(back.resolve, None);
4780 }
4781
4782 #[test]
4783 fn a_well_formed_resolver_and_an_unresolved_action_pass_validation() {
4784 let unresolved = ScheduledAction {
4785 resolve: None,
4786 kind: ActionKind::Send,
4787 ..resolved_action()
4788 };
4789 assert_eq!(
4790 validate_session_resolvers(vec![unresolved, resolved_action()]),
4791 Ok(())
4792 );
4793 }
4794
4795 #[test]
4796 fn a_quote_stamp_may_rewrite_a_transaction_repeated_per_slot() {
4797 let stamped = ScheduledAction {
4798 anchor: ActionAnchor::BeforeSlot { slots: vec![5, 6] },
4799 transactions: vec!["dGVzdA==".to_string(); 2],
4800 resolve: Some(TxResolver::QuoteStamp),
4801 ..resolved_action()
4802 };
4803 assert_eq!(validate_session_resolvers(vec![stamped]), Ok(()));
4804 }
4805
4806 #[rstest]
4807 #[case::send(
4808 ScheduledAction { kind: ActionKind::Send, ..resolved_action() },
4809 TxResolverError::Send,
4810 )]
4811 #[case::no_transactions(
4812 ScheduledAction { transactions: Vec::new(), ..resolved_action() },
4813 TxResolverError::TransactionCount { got: 0 },
4814 )]
4815 #[case::two_transactions(
4816 ScheduledAction { transactions: vec!["dGVzdA==".to_string(); 2], ..resolved_action() },
4817 TxResolverError::TransactionCount { got: 2 },
4818 )]
4819 #[case::feeds_reroute(
4820 ScheduledAction { feeds_reroute: true, ..resolved_action() },
4821 TxResolverError::FeedsReroute,
4822 )]
4823 #[case::quote_stamp_without_transactions(
4824 ScheduledAction { transactions: Vec::new(), resolve: Some(TxResolver::QuoteStamp), ..resolved_action() },
4825 TxResolverError::NoTransactions,
4826 )]
4827 #[case::requote_without_transactions(
4828 ScheduledAction { transactions: Vec::new(), resolve: Some(requote()), ..resolved_action() },
4829 TxResolverError::NoTransactions,
4830 )]
4831 #[case::requote_feeding_reroute(
4832 ScheduledAction { feeds_reroute: true, resolve: Some(requote()), ..resolved_action() },
4833 TxResolverError::FeedsReroute,
4834 )]
4835 fn a_resolver_on_an_action_it_cannot_rewrite_is_rejected_at_its_index(
4836 #[case] action: ScheduledAction,
4837 #[case] expected: TxResolverError,
4838 ) {
4839 assert_eq!(
4840 validate_session_resolvers(vec![resolved_action(), action]),
4841 Err(ActionResolveError {
4842 action: 1,
4843 source: expected,
4844 })
4845 );
4846 }
4847
4848 #[rstest]
4849 #[case::empty(Vec::new(), ArrayKeyIndicesError::Empty)]
4850 #[case::duplicate(vec![6, 7, 6], ArrayKeyIndicesError::Duplicate { index: 6 })]
4851 fn array_key_indices_refuse_an_empty_or_repeating_list(
4852 #[case] indices: Vec<u8>,
4853 #[case] expected: ArrayKeyIndicesError,
4854 ) {
4855 assert_eq!(ArrayKeyIndices::try_from(indices), Err(expected));
4856 }
4857
4858 #[test]
4859 fn a_resolver_with_unusable_array_key_indices_fails_to_deserialize() {
4860 let json = serde_json::json!({
4861 "type": "liquidityArrays",
4862 "pool": address(1).to_string(),
4863 "inputMint": address(2).to_string(),
4864 "arrayKeyIndices": [6, 7, 6],
4865 });
4866 assert!(serde_json::from_value::<TxResolver>(json).is_err());
4867 }
4868
4869 fn diagnostic_probe() -> DiagnosticProbeParams {
4870 DiagnosticProbeParams {
4871 anchor: ActionAnchor::AfterEverySlot {
4872 every_n_slots: NonZeroU64::MIN,
4873 },
4874 markets: vec![address(1), address(2)],
4875 usd_values: vec![100, 25_000],
4876 label: Some("depth-0".to_owned()),
4877 pairs: Vec::new(),
4878 candidates: Vec::new(),
4879 candidate_pairs: Vec::new(),
4880 }
4881 }
4882
4883 fn with_candidate(market: u8, pairs: Vec<[Address; 2]>) -> DiagnosticProbeParams {
4884 DiagnosticProbeParams {
4885 candidates: vec![DiagnosticCandidate {
4886 market: address(market),
4887 owner: address(20),
4888 address_lookup_table: None,
4889 }],
4890 candidate_pairs: pairs,
4891 ..diagnostic_probe()
4892 }
4893 }
4894
4895 fn paired(market: u8, pairs: Vec<[Address; 2]>) -> DiagnosticProbeParams {
4896 DiagnosticProbeParams {
4897 pairs: vec![DiagnosticMarketPairs {
4898 market: address(market),
4899 pairs,
4900 }],
4901 ..diagnostic_probe()
4902 }
4903 }
4904
4905 #[rstest]
4906 #[case::no_markets(DiagnosticProbeParams { markets: Vec::new(), ..diagnostic_probe() })]
4907 #[case::no_usd_values(DiagnosticProbeParams { usd_values: Vec::new(), ..diagnostic_probe() })]
4908 #[case::too_many_markets(DiagnosticProbeParams {
4909 markets: (0..=MAX_DIAGNOSTIC_MARKETS as u8).map(address).collect(),
4910 ..diagnostic_probe()
4911 })]
4912 #[case::too_many_usd_values(DiagnosticProbeParams {
4913 usd_values: (1..=MAX_DIAGNOSTIC_USD_VALUES as u32 + 1).collect(),
4914 ..diagnostic_probe()
4915 })]
4916 #[case::zero_usd_value(DiagnosticProbeParams { usd_values: vec![0, 100], ..diagnostic_probe() })]
4917 #[case::duplicate_market(DiagnosticProbeParams {
4918 markets: vec![address(1), address(1)],
4919 ..diagnostic_probe()
4920 })]
4921 #[case::before_slot(DiagnosticProbeParams {
4922 anchor: ActionAnchor::BeforeSlot { slots: vec![1] },
4923 ..diagnostic_probe()
4924 })]
4925 #[case::before_every_slot(DiagnosticProbeParams {
4926 anchor: ActionAnchor::BeforeEverySlot { every_n_slots: NonZeroU64::MIN },
4927 ..diagnostic_probe()
4928 })]
4929 #[case::pairs_of_an_unprobed_market(paired(3, vec![[address(7), address(8)]]))]
4930 #[case::no_pairs(paired(1, Vec::new()))]
4931 #[case::too_many_pairs(paired(
4932 1,
4933 (0..=MAX_DIAGNOSTIC_MARKET_PAIRS as u8)
4934 .map(|mint| [address(7), address(mint + 8)])
4935 .collect(),
4936 ))]
4937 #[case::self_pair(paired(1, vec![[address(7), address(7)]]))]
4938 #[case::market_paired_twice(DiagnosticProbeParams {
4939 pairs: [
4940 paired(1, vec![[address(7), address(8)]]).pairs,
4941 paired(1, vec![[address(7), address(9)]]).pairs,
4942 ]
4943 .concat(),
4944 ..diagnostic_probe()
4945 })]
4946 #[case::candidate_repeating_a_market(with_candidate(1, vec![[address(7), address(8)]]))]
4947 #[case::candidate_without_pairs(with_candidate(3, Vec::new()))]
4948 #[case::candidate_self_pair(with_candidate(3, vec![[address(7), address(7)]]))]
4949 #[case::markets_and_candidates_over_the_ceiling(DiagnosticProbeParams {
4950 markets: (0..MAX_DIAGNOSTIC_MARKETS as u8).map(address).collect(),
4951 ..with_candidate(200, vec![[address(7), address(8)]])
4952 })]
4953 fn diagnostic_probes_reject_invalid_shapes(#[case] probe: DiagnosticProbeParams) {
4954 assert!(probe.validate().is_err());
4955 }
4956
4957 #[rstest]
4958 #[case::without_pairs(diagnostic_probe(), serde_json::json!({
4959 "anchor": diagnostic_probe().anchor,
4960 "markets": [address(1).to_string(), address(2).to_string()],
4961 "usdValues": [100, 25_000],
4962 "label": "depth-0",
4963 }))]
4964 #[case::with_pairs(paired(1, vec![[address(7), address(8)]]), serde_json::json!({
4965 "anchor": diagnostic_probe().anchor,
4966 "markets": [address(1).to_string(), address(2).to_string()],
4967 "usdValues": [100, 25_000],
4968 "label": "depth-0",
4969 "pairs": [{
4970 "market": address(1).to_string(),
4971 "pairs": [[address(7).to_string(), address(8).to_string()]],
4972 }],
4973 }))]
4974 #[case::with_candidates(with_candidate(3, vec![[address(7), address(8)]]), serde_json::json!({
4975 "anchor": diagnostic_probe().anchor,
4976 "markets": [address(1).to_string(), address(2).to_string()],
4977 "usdValues": [100, 25_000],
4978 "label": "depth-0",
4979 "candidates": [{
4980 "market": address(3).to_string(),
4981 "owner": address(20).to_string(),
4982 }],
4983 "candidatePairs": [[address(7).to_string(), address(8).to_string()]],
4984 }))]
4985 fn a_diagnostic_probe_round_trips_its_wire_json(
4986 #[case] probe: DiagnosticProbeParams,
4987 #[case] wire: serde_json::Value,
4988 ) {
4989 assert_eq!(serde_json::to_value(&probe).unwrap(), wire);
4990 assert_eq!(
4991 serde_json::from_value::<DiagnosticProbeParams>(wire).unwrap(),
4992 probe
4993 );
4994 }
4995
4996 #[rstest]
4997 #[case::markets_only(diagnostic_probe())]
4998 #[case::paired(paired(1, vec![[address(7), address(8)]]))]
4999 #[case::candidates_only(DiagnosticProbeParams {
5000 markets: Vec::new(),
5001 ..with_candidate(3, vec![[address(7), address(8)]])
5002 })]
5003 #[case::after_slot(DiagnosticProbeParams {
5004 anchor: ActionAnchor::AfterSlot { slots: vec![1, 2] },
5005 ..diagnostic_probe()
5006 })]
5007 fn diagnostic_probes_accept_valid_shapes(#[case] probe: DiagnosticProbeParams) {
5008 assert!(probe.validate().is_ok());
5009 }
5010
5011 #[test]
5013 fn override_actions_accept_a_static_and_a_computed_shape() {
5014 assert!(decode_override_actions(&[valid()]).is_ok());
5015 assert!(
5018 decode_override_actions(&[ScheduledAction {
5019 transactions: vec!["dGVzdA==".to_string()],
5020 ..valid()
5021 }])
5022 .is_ok()
5023 );
5024 }
5025
5026 #[test]
5027 fn override_actions_merge_account_wise_later_wins() {
5028 let entry = |lamports| AccountData {
5029 lamports,
5030 ..override_entry(address(9), false)
5031 };
5032 let slot_action = |slots, account, lamports| {
5033 override_action(ActionAnchor::BeforeSlot { slots }, account, entry(lamports))
5034 };
5035 let actions = [
5036 slot_action(vec![5, 7], address(1), 1),
5037 slot_action(vec![5], address(2), 2),
5038 slot_action(vec![5], address(1), 3),
5039 ScheduledAction {
5040 anchor: ActionAnchor::AfterSlot { slots: vec![5] },
5041 kind: ActionKind::Simulate,
5042 feeds_reroute: false,
5043 transactions: vec!["dGVzdA==".to_string()],
5044 account_overrides: AccountModifications::default(),
5045 return_accounts: Vec::new(),
5046 label: None,
5047 resolve: None,
5048 within: None,
5049 },
5050 ];
5051 let schedule = decode_override_actions(&actions).unwrap();
5052 assert_eq!(schedule.slots().collect::<Vec<_>>(), vec![5, 7]);
5053 let lamports_at = |key, slot| {
5054 schedule
5055 .active_for(&key, slot)
5056 .map(|account| account.lamports())
5057 };
5058 assert_eq!(lamports_at(address(1), 5), Some(3));
5059 assert_eq!(lamports_at(address(2), 5), Some(2));
5060 assert_eq!(lamports_at(address(1), 7), Some(1));
5061 }
5062
5063 #[test]
5064 fn computed_override_resolution_preserves_action_order_and_failure() {
5065 let key = address(1);
5066 let static_action = |lamports| {
5067 override_action(
5068 ActionAnchor::BeforeSlot { slots: vec![5] },
5069 key,
5070 AccountData {
5071 lamports,
5072 ..override_entry(address(9), false)
5073 },
5074 )
5075 };
5076 let computed_action = || ScheduledAction {
5077 transactions: vec!["dGVzdA==".to_string()],
5078 ..static_action(2)
5079 };
5080
5081 let computed_last =
5082 decode_override_actions(&[static_action(1), computed_action()]).unwrap();
5083 computed_last
5084 .resolve(5, 1, Some(HashMap::from([(key, shared_account(2))])))
5085 .unwrap();
5086 assert_eq!(
5087 computed_last.active_for(&key, 5).map(|a| a.lamports()),
5088 Some(2)
5089 );
5090
5091 let static_last = decode_override_actions(&[computed_action(), static_action(3)]).unwrap();
5092 static_last
5093 .resolve(5, 0, Some(HashMap::from([(key, shared_account(2))])))
5094 .unwrap();
5095 assert_eq!(
5096 static_last.active_for(&key, 5).map(|a| a.lamports()),
5097 Some(3)
5098 );
5099
5100 let failed = decode_override_actions(&[static_action(1), computed_action()]).unwrap();
5101 failed.resolve(5, 1, None).unwrap();
5102 assert_eq!(failed.active_for(&key, 5).map(|a| a.lamports()), Some(1));
5103 assert!(failed.resolve(5, 1, None).is_err(), "resolving twice");
5104 }
5105
5106 fn shared_account(lamports: u64) -> AccountSharedData {
5107 AccountSharedData::from(solana_account::Account {
5108 lamports,
5109 data: vec![1],
5110 owner: address(9),
5111 executable: false,
5112 rent_epoch: 0,
5113 })
5114 }
5115
5116 fn carry_forward_schedule() -> (Address, Address, OverrideSchedule) {
5117 let (a, b) = (address(1), address(2));
5118 let schedule = OverrideSchedule::from(BTreeMap::from([
5119 (10, HashMap::from([(a, shared_account(1))])),
5120 (
5121 20,
5122 HashMap::from([(a, shared_account(2)), (b, shared_account(9))]),
5123 ),
5124 ]));
5125 (a, b, schedule)
5126 }
5127
5128 #[test]
5129 fn override_schedule_resolves_carry_forward_per_account() {
5130 let (a, b, schedule) = carry_forward_schedule();
5131
5132 assert!(schedule.active_for(&a, 9).is_none());
5133 let cases = [
5134 (9, None, None),
5135 (10, Some(1), None),
5136 (15, Some(1), None),
5137 (20, Some(2), Some(9)),
5138 (u64::MAX, Some(2), Some(9)),
5139 ];
5140 for (slot, want_a, want_b) in cases {
5141 assert_eq!(
5142 schedule
5143 .active_for(&a, slot)
5144 .map(|account| account.lamports()),
5145 want_a,
5146 "active_for a at {slot}"
5147 );
5148 let active = schedule.active_at(slot);
5149 assert_eq!(
5150 active.get(&a).map(ReadableAccount::lamports),
5151 want_a,
5152 "active_at a at {slot}"
5153 );
5154 assert_eq!(
5155 active.get(&b).map(ReadableAccount::lamports),
5156 want_b,
5157 "active_at b at {slot}"
5158 );
5159 }
5160 }
5161
5162 #[test]
5163 fn newly_active_yields_final_values_in_window() {
5164 let (a, b, schedule) = carry_forward_schedule();
5165
5166 let newly: HashMap<_, _> = schedule.newly_active(Some(10), 20).into_iter().collect();
5167 assert_eq!(newly.len(), 2);
5168 assert_eq!(newly[&a].lamports(), 2);
5169 assert_eq!(newly[&b].lamports(), 9);
5170 let spanning: HashMap<_, _> = schedule.newly_active(None, 20).into_iter().collect();
5171 assert_eq!(spanning[&a].lamports(), 2, "later slot wins");
5172 assert_eq!(schedule.newly_active(None, 15).len(), 1);
5173 }
5174
5175 #[test]
5176 fn reroute_filter_round_trips_camel_case() {
5177 let filter = RerouteFilter {
5178 pairs: BTreeSet::from([MintPair::new(address(1), address(2))]),
5179 };
5180 let json = serde_json::to_value(&filter).unwrap();
5181 assert!(
5182 json["pairs"][0][0].is_string() && json["pairs"][0][1].is_string(),
5183 "a pair serializes as two base58 strings: {json}"
5184 );
5185 let back: RerouteFilter = serde_json::from_value(json).unwrap();
5186 assert_eq!(back, filter);
5187 }
5188
5189 #[test]
5192 fn mint_pairs_are_normalized_however_they_are_built() {
5193 let (one, other) = (address(1), address(2));
5194 assert_eq!(MintPair::new(one, other), MintPair::new(other, one));
5195
5196 let reversed: MintPair =
5197 serde_json::from_value(serde_json::json!([other.to_string(), one.to_string()]))
5198 .unwrap();
5199 assert_eq!(reversed, MintPair::new(one, other));
5200 }
5201
5202 #[test]
5203 fn fail_fast_divergence_kind_str_round_trips() {
5204 for kind in [
5205 FailFastDivergenceKind::AnyNonBenign,
5206 FailFastDivergenceKind::Tracked,
5207 ] {
5208 assert_eq!(
5209 FailFastDivergenceKind::from_str_opt(kind.as_str()),
5210 Some(kind)
5211 );
5212 }
5213 assert_eq!(FailFastDivergenceKind::from_str_opt("nonsense"), None);
5214 assert_eq!(
5215 FailFastDivergenceKind::default(),
5216 FailFastDivergenceKind::AnyNonBenign
5217 );
5218 }
5219
5220 #[test]
5221 fn bundle_not_found_is_terminal_and_descriptive() {
5222 let error = BacktestError::BundleNotFound {
5223 start_slot: 100,
5224 end_slot: 600,
5225 };
5226
5227 assert!(error.is_terminal());
5228 assert_eq!(
5229 error.to_string(),
5230 "block bundle not found for start_slot=100, end_slot=600"
5231 );
5232 }
5233
5234 #[test]
5235 fn no_produced_blocks_is_terminal_and_descriptive() {
5236 let error = BacktestError::NoProducedBlocksInRange {
5237 start_slot: 100,
5238 end_slot: 100,
5239 };
5240
5241 assert!(error.is_terminal());
5242 assert_eq!(
5245 error.to_string(),
5246 "no produced blocks in requested range 100..=100; slot(s) may be skipped onchain"
5247 );
5248 }
5249
5250 #[test]
5251 fn session_name_taken_is_not_terminal_and_names_the_session() {
5252 let error = BacktestError::SessionNameTaken {
5253 session_name: "my-run".to_string(),
5254 };
5255
5256 assert!(!error.is_terminal());
5257 assert_eq!(error.to_string(), "session name 'my-run' is already in use");
5258 }
5259
5260 #[rstest]
5261 #[case::no_produced_blocks(BacktestError::NoProducedBlocksInRange { start_slot: 1, end_slot: 2 }, true)]
5262 #[case::programdata_not_deployed(BacktestError::ProgramdataNotDeployed { address: "x".into() }, true)]
5263 #[case::bundle_not_found(BacktestError::BundleNotFound { start_slot: 1, end_slot: 2 }, false)]
5264 #[case::internal(BacktestError::Internal { error: "x".into() }, false)]
5265 fn refusals_are_the_terminal_errors_a_fresh_session_meets_again(
5266 #[case] error: BacktestError,
5267 #[case] refusal: bool,
5268 ) {
5269 assert!(error.is_terminal());
5270 assert_eq!(error.is_refusal(), refusal);
5271 }
5272
5273 fn create_request(
5274 body: serde_json::Value,
5275 ) -> Result<CreateBacktestSessionRequestOptions, InvalidSessionName> {
5276 serde_json::from_value::<CreateBacktestSessionRequest>(body)
5277 .expect("decode create request")
5278 .try_into_request_options()
5279 }
5280
5281 #[test]
5282 fn create_requests_from_older_clients_decode_without_a_name() {
5283 let v0 = create_request(serde_json::json!({"startSlot": 1, "endSlot": 2})).expect("v0");
5284 assert!(!v0.parallel);
5285 assert_eq!(v0.name, None);
5286
5287 let v1 =
5288 create_request(serde_json::json!({"startSlot": 1, "endSlot": 2, "parallel": true}))
5289 .expect("v1");
5290 assert!(v1.parallel);
5291 assert_eq!(v1.name, None);
5292 }
5293
5294 #[test]
5295 fn named_create_request_without_parallel_keeps_its_name() {
5296 let options = create_request(serde_json::json!({
5297 "startSlot": 1,
5298 "endSlot": 2,
5299 "name": "my-run",
5300 "createToken": "token-1",
5301 }))
5302 .expect("valid name");
5303
5304 assert!(!options.parallel);
5305 assert_eq!(options.request.end_slot, 2);
5306 let requested = options.name.expect("name");
5307 assert_eq!(requested.name.as_str(), "my-run");
5308 assert_eq!(
5309 requested.create_token.as_ref().map(CreateToken::as_str),
5310 Some("token-1")
5311 );
5312 }
5313
5314 #[test]
5315 fn create_request_with_an_invalid_name_is_rejected() {
5316 let error = create_request(serde_json::json!({
5317 "startSlot": 1,
5318 "endSlot": 2,
5319 "name": "my run",
5320 }))
5321 .expect_err("invalid name");
5322 assert!(error.to_string().contains("'my run'"), "{error}");
5323 }
5324
5325 #[test]
5326 fn create_requests_without_a_name_serialize_as_before() {
5327 let params = CreateSessionParams::builder()
5328 .start_slot(1)
5329 .end_slot(2)
5330 .build();
5331 let params_json = serde_json::to_value(¶ms).expect("encode params");
5332
5333 let v0 = serde_json::to_value(CreateBacktestSessionRequest::from(params.clone()))
5334 .expect("encode v0");
5335 assert_eq!(v0, params_json);
5336
5337 let v1 = serde_json::to_value(CreateBacktestSessionRequest::from(
5338 CreateBacktestSessionRequestV1 {
5339 request: params,
5340 parallel: true,
5341 name: None,
5342 create_token: None,
5343 },
5344 ))
5345 .expect("encode v1");
5346 let mut expected = params_json;
5347 expected["parallel"] = true.into();
5348 assert_eq!(v1, expected);
5349 }
5350
5351 #[test]
5352 fn session_responses_omit_an_absent_name_and_decode_without_one() {
5353 let created = BacktestResponse::SessionCreated {
5354 session_id: SessionId::new(),
5355 rpc_endpoint: "/backtest/s".to_string(),
5356 task_id: None,
5357 session_name: None,
5358 };
5359 let json = serde_json::to_string(&created).expect("encode");
5360 assert!(!json.contains("session_name"), "{json}");
5361 let decoded: BacktestResponse = serde_json::from_str(&json).expect("decode");
5362 assert!(matches!(
5363 decoded,
5364 BacktestResponse::SessionCreated {
5365 session_name: None,
5366 ..
5367 }
5368 ));
5369
5370 let parallel = BacktestResponse::SessionsCreatedV2 {
5371 control_session_id: ControlSessionId::new(),
5372 control_session_name: None,
5373 session_ids: Vec::new(),
5374 task_ids: Vec::new(),
5375 start_slots: Vec::new(),
5376 end_slots: Vec::new(),
5377 };
5378 let json = serde_json::to_string(¶llel).expect("encode");
5379 assert!(!json.contains("control_session_name"), "{json}");
5380 let decoded: BacktestResponse = serde_json::from_str(&json).expect("decode");
5381 assert!(matches!(
5382 decoded,
5383 BacktestResponse::SessionsCreatedV2 {
5384 control_session_name: None,
5385 ..
5386 }
5387 ));
5388 }
5389
5390 #[test]
5391 fn bundle_build_request_optional_fields_default_to_none() {
5392 let req: BundleBuildRequest =
5393 serde_json::from_str(r#"{"start_slot":1,"end_slot":2}"#).expect("parse");
5394 assert_eq!((req.start_slot, req.end_slot), (1, 2));
5395 assert_eq!(req.bundle_size, None);
5396 assert_eq!(req.idempotency_key, None);
5397 }
5398
5399 #[test]
5400 fn bundle_build_request_parses_optional_fields() {
5401 let req: BundleBuildRequest = serde_json::from_str(
5402 r#"{"start_slot":1,"end_slot":2,"bundle_size":500,"idempotency_key":"abc"}"#,
5403 )
5404 .expect("parse");
5405 assert_eq!(req.bundle_size, Some(500));
5406 assert_eq!(req.idempotency_key.as_deref(), Some("abc"));
5407 }
5408
5409 #[test]
5410 fn bundle_build_status_serde_round_trips_with_snake_case() {
5411 let cases = [
5412 (BundleBuildStatus::Completed, "\"completed\""),
5413 (BundleBuildStatus::Failed, "\"failed\""),
5414 (BundleBuildStatus::InProgress, "\"in_progress\""),
5415 (
5416 BundleBuildStatus::NeedsInvestigation,
5417 "\"needs_investigation\"",
5418 ),
5419 ];
5420 for (status, expected) in cases {
5421 assert_eq!(serde_json::to_string(&status).unwrap(), expected);
5422 assert_eq!(
5423 serde_json::from_str::<BundleBuildStatus>(expected).unwrap(),
5424 status
5425 );
5426 assert_eq!(status.as_str(), expected.trim_matches('"'));
5427 }
5428 assert!(serde_json::from_str::<BundleBuildStatus>("\"queued\"").is_err());
5429 }
5430
5431 #[test]
5432 fn bundle_build_request_without_kind_deserializes_as_blocks() {
5433 let request: BundleBuildRequest =
5435 serde_json::from_str(r#"{"start_slot":100,"end_slot":200}"#).unwrap();
5436 assert_eq!(request.kind, BundleKind::Blocks);
5437 }
5438
5439 #[test]
5440 fn bundle_kind_round_trips_over_serde_and_as_str() {
5441 for kind in [BundleKind::Blocks, BundleKind::AccountState] {
5442 let json = serde_json::to_string(&kind).unwrap();
5443 assert_eq!(json, format!("\"{}\"", kind.as_str()));
5444 assert_eq!(serde_json::from_str::<BundleKind>(&json).unwrap(), kind);
5445 assert_eq!(BundleKind::from_str_opt(kind.as_str()), Some(kind));
5448 }
5449 assert!(serde_json::from_str::<BundleKind>("\"accountState\"").is_err());
5450 assert_eq!(BundleKind::from_str_opt("accountState"), None);
5451 }
5452
5453 #[test]
5454 fn bundle_build_request_carries_kind_through_serde() {
5455 let request = BundleBuildRequest {
5456 start_slot: 100,
5457 end_slot: 200,
5458 kind: BundleKind::AccountState,
5459 ..Default::default()
5460 };
5461 let json = serde_json::to_string(&request).unwrap();
5462 assert!(json.contains(r#""kind":"account_state""#), "{json}");
5463 let parsed: BundleBuildRequest = serde_json::from_str(&json).unwrap();
5464 assert_eq!(parsed.kind, BundleKind::AccountState);
5465 }
5466
5467 #[test]
5468 fn bundle_build_status_response_serializes_request_and_status() {
5469 let response = BundleBuildStatusResponse {
5470 request_id: "r".to_string(),
5471 start_slot: 100,
5472 end_slot: 200,
5473 bundle_size: Some(50),
5474 status: BundleBuildStatus::InProgress,
5475 created_at_unix_ms: 0,
5476 kind: BundleKind::Blocks,
5477 eta_secs: Some(600),
5478 };
5479 let json = serde_json::to_value(&response).unwrap();
5480 assert_eq!(json["request_id"].as_str(), Some("r"));
5481 assert_eq!(json["start_slot"].as_u64(), Some(100));
5482 assert_eq!(json["bundle_size"].as_u64(), Some(50));
5483 assert_eq!(json["status"].as_str(), Some("in_progress"));
5484 assert_eq!(json["created_at_unix_ms"].as_u64(), Some(0));
5485 assert_eq!(json["eta_secs"].as_u64(), Some(600));
5486 }
5487
5488 #[test]
5489 fn an_empty_bundles_list_is_distinct_from_an_absent_one() {
5490 let absent: BundleBuildListResponse = serde_json::from_str(r#"{"builds":[]}"#).unwrap();
5492 let empty: BundleBuildListResponse =
5493 serde_json::from_str(r#"{"builds":[],"bundles":[]}"#).unwrap();
5494 assert_eq!(absent.bundles, None);
5495 assert_eq!(empty.bundles, Some(Vec::new()));
5496 }
5497
5498 #[test]
5499 fn completed_bundle_round_trips() {
5500 let bundle = CompletedBundle {
5501 start_slot: 100,
5502 end_slot: 200,
5503 kind: BundleKind::AccountState,
5504 completed_at_unix_ms: Some(1_700_000_000_000),
5505 size_bytes: Some(4_096),
5506 };
5507 let json = serde_json::to_string(&bundle).unwrap();
5508 assert!(json.contains(r#""kind":"account_state""#), "{json}");
5509 assert_eq!(
5510 serde_json::from_str::<CompletedBundle>(&json).unwrap(),
5511 bundle
5512 );
5513
5514 let sparse = r#"{"start_slot":1,"end_slot":2,"kind":"blocks"}"#;
5515 let parsed: CompletedBundle = serde_json::from_str(sparse).unwrap();
5516 assert_eq!(parsed.completed_at_unix_ms, None);
5517 assert_eq!(parsed.size_bytes, None);
5518 }
5519
5520 #[test]
5521 fn available_range_reads_a_server_that_predates_kind_and_scope() {
5522 let json = r#"{
5524 "bundle_start_slot": 100,
5525 "bundle_start_slot_utc": null,
5526 "max_bundle_end_slot": 200,
5527 "max_bundle_end_slot_utc": null,
5528 "max_bundle_size": 101
5529 }"#;
5530 let parsed: AvailableRange = serde_json::from_str(json).unwrap();
5531 assert_eq!(parsed.bundle_start_slot, 100);
5532 assert_eq!(parsed.kind, None);
5533 assert_eq!(parsed.scope, None);
5534 }
5535
5536 #[test]
5537 fn available_range_ignores_fields_it_does_not_know() {
5538 let json = r#"{"bundle_start_slot": 1, "some_future_field": "x"}"#;
5540 assert_eq!(
5541 serde_json::from_str::<AvailableRange>(json)
5542 .unwrap()
5543 .bundle_start_slot,
5544 1
5545 );
5546 }
5547
5548 #[test]
5549 fn available_range_labels_round_trip() {
5550 let range = AvailableRange {
5551 bundle_start_slot: 100,
5552 max_bundle_end_slot: Some(200),
5553 kind: Some(BundleKind::AccountState),
5554 scope: Some(RangeScope::User),
5555 ..Default::default()
5556 };
5557 let json = serde_json::to_string(&range).unwrap();
5558 assert!(json.contains(r#""kind":"account_state""#), "{json}");
5559 assert!(json.contains(r#""scope":"user""#), "{json}");
5560 let parsed: AvailableRange = serde_json::from_str(&json).unwrap();
5561 assert_eq!(parsed.kind, Some(BundleKind::AccountState));
5562 assert_eq!(parsed.scope, Some(RangeScope::User));
5563 }
5564
5565 #[rstest]
5567 #[case::from_a_server_predating_it(None, None)]
5568 #[case::snapped_outward(Some(SlotRange::new_unchecked(90, 210)), None)]
5569 #[case::modified(Some(SlotRange::new_unchecked(90, 210)), Some("ab"))]
5570 fn a_depth_status_carries_its_optional_fields_only_when_it_has_them(
5571 #[case] capture: Option<SlotRange>,
5572 #[case] digest: Option<&str>,
5573 ) {
5574 let mut wire = serde_json::json!({
5575 "request_id": "r",
5576 "start_slot": 100,
5577 "end_slot": 200,
5578 "source": "onchain",
5579 "status": "in_progress",
5580 });
5581 if let Some(capture) = capture {
5582 wire["capture"] = serde_json::json!({"start": capture.start(), "end": capture.end()});
5583 }
5584 if let Some(digest) = digest {
5585 wire["modification_digest"] = digest.into();
5586 }
5587 let status: DepthStatusResponse =
5588 serde_json::from_value(wire.clone()).expect("deserialize");
5589 assert_eq!(status.capture, capture);
5590 assert_eq!(status.modification_digest.as_deref(), digest);
5591 assert_eq!(serde_json::to_value(&status).expect("serialize"), wire);
5592 }
5593
5594 #[rstest]
5597 #[case::unmodified(
5598 serde_json::json!({"start_slot": 100, "end_slot": 199, "source": "onchain"})
5599 )]
5600 #[case::at_oracle_updates(serde_json::json!({
5601 "start_slot": 100,
5602 "end_slot": 199,
5603 "source": "onchain",
5604 "granularity": "oracle",
5605 }))]
5606 #[case::modified(serde_json::json!({
5607 "start_slot": 100,
5608 "end_slot": 199,
5609 "source": "onchain",
5610 "program_overrides": [{"program_id": address(7).to_string(), "elf": "f0VMRg=="}],
5611 "account_overrides": {
5612 address(8).to_string(): {
5613 "data": {"data": "AQID", "encoding": "base64"},
5614 "executable": false,
5615 "lamports": 1,
5616 "owner": address(9).to_string(),
5617 "space": 3,
5618 },
5619 },
5620 }))]
5621 fn a_depth_request_keeps_its_wire_shape(#[case] wire: serde_json::Value) {
5622 let req: DepthRequest = serde_json::from_value(wire.clone()).expect("deserialize");
5623 assert_eq!(serde_json::to_value(&req).expect("serialize"), wire);
5624 }
5625
5626 #[rstest]
5629 #[case::accounts_only(BTreeMap::new(), r#"{"programs":{},"accounts":{}}"#.to_owned())]
5630 #[case::one_program(
5631 BTreeMap::from([(address(7), b"\x7fELF".to_vec())]),
5632 format!(r#"{{"programs":{{"{}":"f0VMRg=="}},"accounts":{{}}}}"#, address(7))
5633 )]
5634 fn a_depth_modifications_manifest_keeps_its_pinned_shape(
5635 #[case] programs: BTreeMap<Address, Vec<u8>>,
5636 #[case] expected: String,
5637 ) {
5638 let modifications = DepthModifications {
5639 programs,
5640 accounts: AccountModifications::default(),
5641 };
5642 assert_eq!(
5643 serde_json::to_string(&modifications).expect("serialize"),
5644 expected
5645 );
5646 }
5647
5648 fn range(start: u64, end: u64) -> AvailableRange {
5649 AvailableRange {
5650 bundle_start_slot: start,
5651 max_bundle_end_slot: Some(end),
5652 ..Default::default()
5653 }
5654 }
5655
5656 #[rstest::rstest]
5660 #[case::single(vec![range(100, 300)], 100, 300, Some(vec![(100, 300)]))]
5661 #[case::multi(
5662 vec![range(100, 200), range(201, 300), range(301, 400)],
5663 100, 300, Some(vec![(100, 200), (201, 300)])
5664 )]
5665 #[case::nested(
5668 vec![range(100, 500), range(110, 150), range(150, 190), range(501, 900)],
5669 100, 900, Some(vec![(100, 500), (501, 900)])
5670 )]
5671 #[case::prefers_finer_grid(
5675 vec![range(1_000, 1_999), range(1_500, 3_400), range(2_000, 2_999), range(3_000, 3_999)],
5676 1_000, 3_999, Some(vec![(1_000, 1_999), (2_000, 2_999), (3_000, 3_999)])
5677 )]
5678 #[case::shared_start_prefers_finer(
5682 vec![range(100, 150), range(100, 120), range(121, 140), range(141, 160)],
5683 100, 160, Some(vec![(100, 120), (121, 140), (141, 160)])
5684 )]
5685 #[case::coarse_overlap_prefers_finer_pair(
5689 vec![range(100, 200), range(100, 150), range(151, 160)],
5690 100, 160, Some(vec![(100, 150), (151, 160)])
5691 )]
5692 #[case::falls_back_to_coarse(
5696 vec![range(100, 160), range(100, 120), range(121, 140)],
5697 100, 160, Some(vec![(100, 160)])
5698 )]
5699 #[case::clamps_final_bundle(vec![range(100, 199), range(200, 999)], 100, 450, Some(vec![(100, 199), (200, 450)]))]
5701 #[case::anchors_mid_bundle(vec![range(150, 350)], 200, 300, Some(vec![(150, 300)]))]
5704 #[case::anchors_then_continues(
5705 vec![range(150, 350), range(351, 600)],
5706 200, 600, Some(vec![(150, 350), (351, 600)])
5707 )]
5708 #[case::start_inside_bundle_anchors(vec![range(200, 400)], 300, 400, Some(vec![(200, 400)]))]
5709 #[case::start_before_first_bundle(vec![range(200, 400)], 100, 400, None)]
5711 #[case::end_not_covered(vec![range(100, 200)], 100, 300, None)]
5713 #[case::gap_in_coverage(vec![range(100, 200), range(210, 300)], 100, 300, None)]
5714 #[case::user_and_global_ranges_not_collapsed(
5719 vec![range(100, 200), range(100, 150), range(151, 200)],
5720 100, 200, Some(vec![(100, 150), (151, 200)])
5721 )]
5722 fn split_range_cases(
5723 #[case] ranges: Vec<AvailableRange>,
5724 #[case] start: u64,
5725 #[case] end: u64,
5726 #[case] expected: Option<Vec<(u64, u64)>>,
5727 ) {
5728 match expected {
5729 Some(expected) => assert_eq!(
5730 split_range(
5731 &ranges,
5732 SlotRange::new_unchecked(start, end),
5733 BundleKind::Blocks
5734 )
5735 .unwrap(),
5736 expected
5737 ),
5738 None => assert!(
5739 split_range(
5740 &ranges,
5741 SlotRange::new_unchecked(start, end),
5742 BundleKind::Blocks
5743 )
5744 .is_err()
5745 ),
5746 }
5747 }
5748
5749 #[rstest]
5751 #[case::rides_a_coarse_bundle_over_a_finer_pair(
5752 vec![range(100, 200), range(100, 150), range(151, 160)],
5753 100, 160, vec![(100, 160)]
5754 )]
5755 #[case::never_strands_the_walk(
5756 vec![range(100, 150), range(100, 120), range(121, 140), range(141, 160)],
5757 100, 160, vec![(100, 120), (121, 140), (141, 160)]
5758 )]
5759 fn split_range_fewest_cases(
5760 #[case] ranges: Vec<AvailableRange>,
5761 #[case] start: u64,
5762 #[case] end: u64,
5763 #[case] expected: Vec<(u64, u64)>,
5764 ) {
5765 assert_eq!(
5766 split_range_fewest(
5767 &ranges,
5768 SlotRange::new_unchecked(start, end),
5769 BundleKind::Blocks
5770 ),
5771 Ok(expected)
5772 );
5773 }
5774
5775 fn account_state_range(start: u64, end: u64) -> AvailableRange {
5776 AvailableRange {
5777 kind: Some(BundleKind::AccountState),
5778 ..range(start, end)
5779 }
5780 }
5781
5782 #[test]
5783 fn a_replay_split_rides_the_recordings_not_a_finer_block_grid() {
5784 let ranges = vec![
5787 range(100, 149),
5788 range(150, 199),
5789 account_state_range(100, 199),
5790 ];
5791 let requested = SlotRange::new_unchecked(100, 199);
5792
5793 assert_eq!(
5794 split_range(&ranges, requested, BundleKind::Blocks).unwrap(),
5795 [(100, 149), (150, 199)]
5796 );
5797 assert_eq!(
5798 split_range(&ranges, requested, BundleKind::AccountState).unwrap(),
5799 [(100, 199)]
5800 );
5801 }
5802
5803 #[test]
5804 fn a_replay_split_tiles_consecutive_recordings() {
5805 let ranges = vec![account_state_range(100, 199), account_state_range(200, 299)];
5806 assert_eq!(
5807 split_range(
5808 &ranges,
5809 SlotRange::new_unchecked(100, 299),
5810 BundleKind::AccountState
5811 )
5812 .unwrap(),
5813 [(100, 199), (200, 299)]
5814 );
5815 }
5816
5817 #[test]
5818 fn a_replay_split_ends_short_of_a_recording() {
5819 let requested = SlotRange::new_unchecked(100, 150);
5822 assert_eq!(
5823 split_range(&[range(100, 199)], requested, BundleKind::Blocks).unwrap(),
5824 [(100, 150)]
5825 );
5826 assert_eq!(
5827 split_range(
5828 &[account_state_range(100, 199)],
5829 requested,
5830 BundleKind::AccountState
5831 )
5832 .unwrap(),
5833 [(100, 150)]
5834 );
5835 }
5836
5837 #[test]
5838 fn a_replay_split_ends_short_of_its_last_recording() {
5839 let ranges = vec![account_state_range(100, 199), account_state_range(200, 299)];
5842 assert_eq!(
5843 split_range(
5844 &ranges,
5845 SlotRange::new_unchecked(100, 250),
5846 BundleKind::AccountState
5847 )
5848 .unwrap(),
5849 [(100, 199), (200, 250)]
5850 );
5851 }
5852
5853 #[test]
5854 fn a_replay_split_tiles_a_one_slot_recording() {
5855 let ranges = vec![account_state_range(100, 249), account_state_range(250, 250)];
5858 assert_eq!(
5859 split_range(
5860 &ranges,
5861 SlotRange::new_unchecked(100, 250),
5862 BundleKind::AccountState
5863 )
5864 .unwrap(),
5865 [(100, 249), (250, 250)]
5866 );
5867 }
5868
5869 #[test]
5870 fn a_replay_split_anchors_a_mid_recording_start() {
5871 let requested = SlotRange::new_unchecked(150, 199);
5875 assert_eq!(
5876 split_range(&[range(100, 199)], requested, BundleKind::Blocks).unwrap(),
5877 [(100, 199)]
5878 );
5879 assert_eq!(
5880 split_range(
5881 &[account_state_range(100, 199)],
5882 requested,
5883 BundleKind::AccountState
5884 )
5885 .unwrap(),
5886 [(100, 199)]
5887 );
5888 }
5889
5890 #[test]
5891 fn a_replay_split_refuses_a_start_no_recording_covers() {
5892 let error = split_range(
5893 &[account_state_range(200, 299)],
5894 SlotRange::new_unchecked(100, 299),
5895 BundleKind::AccountState,
5896 )
5897 .expect_err("no recording covers 100");
5898 assert!(
5899 error.contains("is not covered by any available account-state bundle"),
5900 "{error}"
5901 );
5902 }
5903
5904 #[test]
5905 fn a_replay_split_ignores_block_ranges() {
5906 let error = split_range(
5907 &[range(100, 199)],
5908 SlotRange::new_unchecked(100, 199),
5909 BundleKind::AccountState,
5910 )
5911 .expect_err("owns no recordings");
5912 assert!(error.contains("account-state bundle"), "{error}");
5913 }
5914
5915 #[test]
5916 fn blocks_mode_admits_ranges_from_a_server_that_predates_kind() {
5917 let unlabelled = range(100, 199);
5920 assert_eq!(unlabelled.kind, None);
5921 assert_eq!(
5922 split_range(
5923 &[unlabelled],
5924 SlotRange::new_unchecked(100, 150),
5925 BundleKind::Blocks
5926 )
5927 .unwrap(),
5928 [(100, 150)]
5929 );
5930 }
5931
5932 fn ends_by_start(ranges: &[AvailableRange]) -> BTreeMap<u64, BTreeSet<u64>> {
5935 let mut ends: BTreeMap<u64, BTreeSet<u64>> = BTreeMap::new();
5936 for r in ranges {
5937 if let Some(end) = r.max_bundle_end_slot
5938 && end >= r.bundle_start_slot
5939 {
5940 ends.entry(r.bundle_start_slot).or_default().insert(end);
5941 }
5942 }
5943 ends
5944 }
5945
5946 fn split_lengths(
5950 ends: &BTreeMap<u64, BTreeSet<u64>>,
5951 cursor: u64,
5952 end: u64,
5953 ) -> BTreeSet<usize> {
5954 ends.get(&cursor)
5955 .into_iter()
5956 .flatten()
5957 .flat_map(|&bundle_end| {
5958 if bundle_end >= end {
5959 BTreeSet::from([1])
5960 } else {
5961 split_lengths(ends, bundle_end + 1, end)
5962 .into_iter()
5963 .map(|rest| rest + 1)
5964 .collect()
5965 }
5966 })
5967 .collect()
5968 }
5969
5970 fn is_valid_split(
5974 split: &[(u64, u64)],
5975 ends: &BTreeMap<u64, BTreeSet<u64>>,
5976 start: u64,
5977 end: u64,
5978 ) -> bool {
5979 split.first().is_some_and(|&(s, _)| s == start)
5980 && split.last().is_some_and(|&(_, e)| e == end)
5981 && split.windows(2).all(|w| w[1].0 == w[0].1 + 1)
5982 && split.iter().all(|&(s, e)| {
5983 e >= s
5984 && ends
5985 .get(&s)
5986 .and_then(|bundle_ends| bundle_ends.iter().next_back())
5987 .is_some_and(|&max_end| e <= max_end)
5988 })
5989 }
5990
5991 type SplitFn = fn(&[AvailableRange], SlotRange, BundleKind) -> Result<Vec<(u64, u64)>, String>;
5992 type OptimumFn = fn(&BTreeSet<usize>) -> Option<&usize>;
5993
5994 #[rstest]
6000 #[case::most(split_range as SplitFn, BTreeSet::last as OptimumFn)]
6001 #[case::fewest(split_range_fewest as SplitFn, BTreeSet::first as OptimumFn)]
6002 fn split_range_matches_reference(#[case] walk: SplitFn, #[case] optimum: OptimumFn) {
6003 let mut seed: u64 = 0x9E3779B97F4A7C15;
6004 let mut next = || {
6005 seed = seed
6006 .wrapping_mul(6364136223846793005)
6007 .wrapping_add(1442695040888963407);
6008 seed >> 33
6009 };
6010
6011 for _ in 0..50_000 {
6012 let ranges: Vec<AvailableRange> = (0..next() % 6)
6015 .map(|_| {
6016 let start = next() % 12;
6017 range(start, start + next() % 6) })
6019 .collect();
6020 let start = next() % 12;
6021 let end = start + next() % 6; let got = walk(
6024 &ranges,
6025 SlotRange::new_unchecked(start, end),
6026 BundleKind::Blocks,
6027 );
6028 let ends = ends_by_start(&ranges);
6029 let anchor = ends
6032 .range(..=start)
6033 .rfind(|(_, e)| e.iter().next_back().is_some_and(|&x| x >= start))
6034 .map(|(&s, _)| s);
6035 let reference = anchor.and_then(|a| optimum(&split_lengths(&ends, a, end)).copied());
6036
6037 let layout: Vec<_> = ranges
6038 .iter()
6039 .map(|r| (r.bundle_start_slot, r.max_bundle_end_slot))
6040 .collect();
6041 match (&got, reference) {
6042 (Ok(split), Some(best)) => {
6043 assert!(
6044 is_valid_split(split, &ends, anchor.unwrap(), end),
6045 "invalid split {split:?} for {layout:?} [{start},{end}]"
6046 );
6047 assert_eq!(
6048 split.len(),
6049 best,
6050 "suboptimal split {split:?} vs {best} sub-ranges for {layout:?} [{start},{end}]"
6051 );
6052 }
6053 (Err(_), None) => {}
6054 _ => panic!(
6055 "disagreement: walk={got:?}, reference={reference:?} sub-ranges for {layout:?} [{start},{end}]"
6056 ),
6057 }
6058 }
6059 }
6060
6061 #[test]
6062 fn a_reroute_without_templates_omits_venue() {
6063 let json = serde_json::to_value(RerouteParams::default()).expect("serialize");
6064 assert!(json.get("directFill").is_none(), "{json}");
6065 }
6066
6067 #[test]
6068 fn venue_fields_keep_their_venue_wire_names() {
6069 let reroute = RerouteParams {
6070 venue_templates: vec![template("t")],
6071 ..Default::default()
6072 };
6073 let json = serde_json::to_value(&reroute).expect("serialize");
6074 assert_eq!(json["directFill"][0]["label"], "t", "{json}");
6075
6076 let json = serde_json::to_value(RerouteStatsReport::default()).expect("serialize");
6077 for key in [
6078 "directFillMatched",
6079 "directFillOutcomes",
6080 "directFillScored",
6081 "directFillBpsTotal",
6082 "directFillTemplates",
6083 ] {
6084 assert!(json.get(key).is_some(), "{key} missing from {json}");
6085 }
6086 }
6087
6088 #[test]
6089 fn extra_markets_cross_the_wire_as_base58() {
6090 let json = serde_json::to_value(RerouteParams::default()).expect("serialize");
6091 assert!(json.get("extraMarkets").is_none(), "{json}");
6092
6093 let reroute = RerouteParams {
6094 extra_markets: BTreeSet::from([address(7)]),
6095 ..Default::default()
6096 };
6097 let json = serde_json::to_value(&reroute).expect("serialize");
6098 assert_eq!(
6099 json["extraMarkets"],
6100 serde_json::json!([address(7).to_string()])
6101 );
6102 assert_eq!(
6103 serde_json::from_value::<RerouteParams>(json).expect("deserialize"),
6104 reroute
6105 );
6106
6107 serde_json::from_value::<RerouteParams>(serde_json::json!({
6108 "extraMarkets": ["not-an-address"]
6109 }))
6110 .expect_err("an invalid address is rejected");
6111 }
6112
6113 fn template(label: &str) -> VenueTemplate {
6115 let placeholder = Address::default();
6116 VenueTemplate {
6117 label: label.to_owned(),
6118 mode: SwapMode::ExactIn,
6119 input_mint: mints::SOL,
6120 output_mint: mints::USDC,
6121 instruction: TemplateInstruction {
6122 program_id: address(7),
6123 accounts: vec![
6124 TemplateAccount {
6125 address: placeholder,
6126 writable: true,
6127 signer: true,
6128 },
6129 TemplateAccount {
6130 address: placeholder,
6131 writable: true,
6132 signer: false,
6133 },
6134 TemplateAccount {
6135 address: placeholder,
6136 writable: true,
6137 signer: false,
6138 },
6139 TemplateAccount {
6140 address: address(8),
6141 writable: false,
6142 signer: false,
6143 },
6144 ],
6145 data: vec![0; 16],
6146 },
6147 amount_offset: 2,
6148 taker: TakerSlots {
6149 user: vec![0],
6150 input_token_account: vec![1],
6151 output_token_account: vec![2],
6152 derived: Vec::new(),
6153 },
6154 resolve: None,
6155 }
6156 }
6157
6158 #[rstest]
6160 #[case::requote_alone(true, 0, false)]
6161 #[case::templates_alone(false, 1, false)]
6162 #[case::both(true, 2, false)]
6163 #[case::neither(false, 0, true)]
6164 fn a_reroute_is_a_noop_only_with_nothing_to_ask(
6165 #[case] requote: bool,
6166 #[case] templates: usize,
6167 #[case] noop: bool,
6168 ) {
6169 let reroute = RerouteParams {
6170 requote,
6171 venue_templates: (0..templates).map(|i| template(&format!("t{i}"))).collect(),
6172 ..Default::default()
6173 };
6174 assert_eq!(reroute.is_noop(), noop);
6175 }
6176
6177 #[rstest]
6179 #[case::templates_without_requote(false, 1, true)]
6180 #[case::requote_without_templates(true, 0, true)]
6181 #[case::nothing(false, 0, false)]
6182 fn the_account_universe_warms_for_templates_as_for_requoting(
6183 #[case] requote: bool,
6184 #[case] templates: usize,
6185 #[case] warms: bool,
6186 ) {
6187 let params = CreateSessionParams::builder()
6188 .start_slot(1)
6189 .end_slot(2)
6190 .reroute(RerouteParams {
6191 requote,
6192 venue_templates: (0..templates).map(|i| template(&format!("t{i}"))).collect(),
6193 ..Default::default()
6194 })
6195 .build();
6196 assert_eq!(params.warms_account_universe(), warms);
6197 }
6198
6199 #[rstest]
6200 #[case::a_requoted_template_without_requote(false, Some(TemplateResolver::Requote), true)]
6201 #[case::an_array_template_without_requote(
6202 false,
6203 Some(TemplateResolver::LiquidityArrays),
6204 false
6205 )]
6206 #[case::a_fixed_template_without_requote(false, None, false)]
6207 #[case::requote(true, None, true)]
6208 fn only_requoting_or_a_requoted_template_needs_the_sidecar(
6209 #[case] requote: bool,
6210 #[case] resolve: Option<TemplateResolver>,
6211 #[case] needs: bool,
6212 ) {
6213 let params = CreateSessionParams::builder()
6214 .start_slot(1)
6215 .end_slot(2)
6216 .reroute(RerouteParams {
6217 requote,
6218 venue_templates: vec![VenueTemplate {
6219 resolve,
6220 ..template("t")
6221 }],
6222 ..Default::default()
6223 })
6224 .build();
6225 assert_eq!(params.requires_sidecar(), needs);
6226 }
6227
6228 #[rstest]
6230 #[case::capacity(BacktestError::Internal { error: "unable to start session: insufficient capacity".into() }, true)]
6231 #[case::clerk(BacktestError::ClerkError { error: "timeout".into() }, true)]
6232 #[case::ownership_busy(BacktestError::SessionOwnershipBusy { reason: "draining".into() }, true)]
6233 #[case::invalid_request(BacktestError::InvalidRequest { error: "bad range".into() }, false)]
6234 #[case::bundle_not_found(BacktestError::BundleNotFound { start_slot: 1, end_slot: 2 }, false)]
6235 #[case::name_taken(BacktestError::SessionNameTaken { session_name: "a".into() }, false)]
6236 #[case::no_more_blocks(BacktestError::NoMoreBlocks, false)]
6237 fn only_server_side_failures_are_retryable(
6238 #[case] error: BacktestError,
6239 #[case] retryable: bool,
6240 ) {
6241 assert_eq!(error.is_retryable(), retryable);
6242 }
6243}