use futures::{Stream, StreamExt};
use simulator_api::reroute_report::probes::bucket;
pub use simulator_api::{
mints::short_mint,
reroute_report::{
Direction, Flow, LegRecord, Pair, Report, ReportBuilder, RerouteReportError, SwapMode,
Target, probes::ProbeReport,
},
};
use crate::{
ReplacementNotification, RequoteNotification, RerouteLegNotification, VenueNotification,
};
pub fn leg_records(notification: &RequoteNotification) -> Vec<LegRecord> {
let sole_leg = notification.legs.len() == 1;
notification
.legs
.iter()
.map(|leg| leg_record(notification, leg, sole_leg))
.collect()
}
fn leg_record(
notification: &RequoteNotification,
leg: &RerouteLegNotification,
sole_leg: bool,
) -> LegRecord {
LegRecord {
original_signature: notification.core.original_signature.to_string(),
input_mint: leg.input_mint,
output_mint: leg.output_mint,
amount: leg.amount,
swap_mode: SwapMode::parse(&leg.swap_mode),
failed: notification.core.error.is_some(),
original_failed: notification.core.original_failed,
realized_output_amount: notification.realized_output_amount,
original_realized_output_amount: sole_leg
.then_some(notification.original_realized_output_amount)
.flatten(),
route_plan: leg.route_plan.clone(),
original_route_plan: leg.original_route_plan.clone(),
realized_route_plan: leg.realized_route_plan.clone(),
quoted_output_amount: Some(leg.original_quoted_out).filter(|"ed| quoted > 0),
template: None,
new_output_amount: None,
error_category: None,
output_bps: None,
}
}
pub fn probe_record(notification: &VenueNotification) -> LegRecord {
let swap_mode = SwapMode::parse(¬ification.swap_mode);
LegRecord {
original_signature: notification.core.original_signature.to_string(),
input_mint: notification.input_mint,
output_mint: notification.output_mint,
amount: notification.amount,
swap_mode,
failed: false,
original_failed: notification.core.original_failed,
realized_output_amount: None,
original_realized_output_amount: None,
route_plan: None,
original_route_plan: None,
realized_route_plan: None,
template: Some(notification.template.clone()),
quoted_output_amount: same_state_fill(notification, swap_mode),
new_output_amount: notification.template_fill,
error_category: bucket(
¬ification.core.outcome,
notification.core.category.as_deref(),
),
output_bps: notification.comparison.change_vs_l1_bps,
}
}
fn same_state_fill(notification: &VenueNotification, swap_mode: SwapMode) -> Option<u64> {
let hop = ¬ification.hop;
let (fixed, measured) = match swap_mode {
SwapMode::ExactIn => (hop.replay_input_amount?, hop.replay_output_amount?),
SwapMode::ExactOut => (hop.replay_output_amount?, hop.replay_input_amount?),
};
let scaled =
(u128::from(measured) * u128::from(notification.amount)).checked_div(u128::from(fixed))?;
u64::try_from(scaled).ok()
}
pub fn from_notifications<'a>(
target: Target,
notifications: impl IntoIterator<Item = &'a ReplacementNotification>,
) -> Result<Report, RerouteReportError> {
let mut builder = ReportBuilder::new(target);
notifications
.into_iter()
.filter_map(|notification| match notification {
ReplacementNotification::Requote(requote) => Some(requote),
ReplacementNotification::Venue(_) | ReplacementNotification::Original(_) => None,
})
.flat_map(leg_records)
.for_each(|record| builder.push(&record));
builder.finish()
}
pub async fn from_stream(
target: Target,
stream: impl Stream<Item = ReplacementNotification>,
) -> Result<Report, RerouteReportError> {
let mut builder = ReportBuilder::new(target);
let mut stream = std::pin::pin!(stream);
while let Some(notification) = stream.next().await {
if let ReplacementNotification::Requote(requote) = notification {
for record in leg_records(&requote) {
builder.push(&record);
}
}
}
builder.finish()
}
pub fn probes_from_notifications<'a>(
notifications: impl IntoIterator<Item = &'a ReplacementNotification>,
) -> ProbeReport {
let records: Vec<LegRecord> = notifications
.into_iter()
.filter_map(|notification| match notification {
ReplacementNotification::Venue(probe) => Some(probe_record(probe)),
ReplacementNotification::Requote(_) | ReplacementNotification::Original(_) => None,
})
.collect();
ProbeReport::from_records(&records, None)
}
pub async fn probes_from_stream(
stream: impl Stream<Item = ReplacementNotification>,
) -> ProbeReport {
let mut report = ProbeReport::default();
let mut stream = std::pin::pin!(stream);
while let Some(notification) = stream.next().await {
if let ReplacementNotification::Venue(probe) = notification {
report.merge(&ProbeReport::from_records(&[probe_record(&probe)], None));
}
}
report
}
#[cfg(test)]
mod tests {
fn fixture_signature() -> String {
simulator_api::replacement::Signature::default().to_string()
}
use rstest::rstest;
use simulator_api::route_plan::{RouteHop, RouteHopSwapInfo, RoutePlan};
use super::*;
const SOL: &str = "So11111111111111111111111111111111111111112";
const USDC: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const VENUE_PROGRAM: &str = "BiSoNHVpsVZW2F7rx2eQ59yQwKxzU5NvBcmKshCSUypi";
const OTHER_PROGRAM: &str = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";
fn hop(
program: Option<&str>,
label: &str,
input_mint: &str,
output_mint: &str,
in_amount: u64,
) -> RouteHop {
RouteHop {
program: program.map(str::to_string),
swap_info: RouteHopSwapInfo {
label: Some(label.to_string()),
amm_key: program.is_none().then(|| "pool".to_string()),
input_mint: Some(input_mint.to_string()),
in_amount: Some(in_amount.to_string()),
output_mint: Some(output_mint.to_string()),
out_amount: None,
},
..RouteHop::default()
}
}
fn plan(hops: Vec<RouteHop>) -> Option<RoutePlan> {
RoutePlan::new(hops)
}
fn leg_of(
input_mint: &str,
output_mint: &str,
amount: u64,
quoted: Option<&RoutePlan>,
original: Option<&RoutePlan>,
realized: Option<&RoutePlan>,
) -> RerouteLegNotification {
serde_json::from_value(serde_json::json!({
"inputMint": input_mint,
"outputMint": output_mint,
"amount": amount,
"swapMode": "ExactIn",
"originalQuotedOut": 0,
"metisQuotedOut": 0,
"routeSummary": "",
"routePlan": quoted,
"originalRoutePlan": original,
"realizedRoutePlan": realized,
}))
.expect("a leg fixture decodes")
}
struct Notification {
legs: Vec<RerouteLegNotification>,
err: Option<String>,
original_failed: bool,
original_realized_output_amount: Option<u64>,
}
impl Notification {
fn new(legs: Vec<RerouteLegNotification>) -> Self {
Self {
legs,
err: None,
original_failed: false,
original_realized_output_amount: None,
}
}
fn swap(input_mint: &str, output_mint: &str, amount: u64, output: u64) -> Self {
let leg = leg_of(input_mint, output_mint, amount, None, None, None);
Self {
original_realized_output_amount: Some(output),
..Self::new(vec![leg])
}
}
fn reverted(mut self) -> Self {
self.err = Some("reverted".to_string());
self
}
fn original_failed(mut self) -> Self {
self.original_failed = true;
self
}
fn build(self) -> RequoteNotification {
serde_json::from_value(serde_json::json!({
"context": {"slot": 1},
"slot": 1,
"batchIndex": 0,
"originalSignature": fixture_signature(),
"originalFailed": self.original_failed,
"outcome": if self.err.is_some() { "reverted" } else { "filled" },
"legs": self.legs,
"routedTransaction": {"data": "AA==", "encoding": "base64"},
"err": self.err,
"logs": [],
"computeUnitsConsumed": 0,
"fee": 5_000,
"realizedOutputAmount": serde_json::Value::Null,
"originalRealizedOutputAmount": self.original_realized_output_amount,
}))
.expect("a notification fixture decodes")
}
fn build_replacement(self) -> ReplacementNotification {
ReplacementNotification::Requote(self.build())
}
}
fn anchors() -> Vec<ReplacementNotification> {
(1..=3)
.map(|n| {
Notification::swap(SOL, USDC, n * 1_000_000_000, n * 100_000_000)
.build_replacement()
})
.collect()
}
fn venue() -> Target {
Target::new(
Some("BisonFi".to_string()),
Some(VENUE_PROGRAM.parse().expect("a venue program")),
)
}
fn fill(
program: &str,
label: &str,
input: &str,
output: &str,
amount: u64,
) -> Option<RoutePlan> {
plan(vec![hop(Some(program), label, input, output, amount)])
}
fn report_of(notifications: &[ReplacementNotification]) -> Report {
from_notifications(venue(), notifications).expect("the venue appears")
}
fn priced(extra: impl IntoIterator<Item = Notification>) -> Vec<ReplacementNotification> {
let mut notifications = anchors();
notifications.extend(extra.into_iter().map(Notification::build_replacement));
notifications
}
fn won_leg(amount: u64) -> Notification {
let realized = fill(VENUE_PROGRAM, "BisonFi", SOL, USDC, amount);
let l1 = fill(OTHER_PROGRAM, "Whirlpool", SOL, USDC, amount);
Notification::new(vec![leg_of(
SOL,
USDC,
amount,
None,
l1.as_ref(),
realized.as_ref(),
)])
}
#[test]
fn deferring_the_conversion_matches_pricing_each_hop_as_it_arrives() {
let report = report_of(&priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]));
let total = report.total();
assert_eq!(report.sol_usd(), Some(100.0));
assert_eq!(total.requoted.legs, 2);
assert_eq!(total.requoted.usd, 500.0);
assert_eq!(total.l1.legs, 0, "L1 had these legs at another venue");
}
#[test]
fn the_result_does_not_depend_on_arrival_order() {
let forward = priced([won_leg(2_000_000_000), won_leg(3_000_000_000)]);
let mut backward = forward.clone();
backward.reverse();
let (forward, backward) = (report_of(&forward), report_of(&backward));
assert_eq!(forward.sol_usd(), backward.sol_usd());
assert_eq!(forward.total().requoted.usd, backward.total().requoted.usd);
assert_eq!(forward.render(None), backward.render(None));
}
#[test]
fn neither_side_counts_flow_that_never_landed() {
let notifications = priced([
won_leg(2_000_000_000),
won_leg(9_000_000_000).reverted(),
won_leg(9_000_000_000).original_failed(),
]);
let total = report_of(¬ifications).total();
assert_eq!(total.requoted.legs, 1, "only the landed leg counts");
assert_eq!(total.requoted.usd, 200.0);
}
#[test]
fn a_multi_leg_notification_prices_nothing() {
let legs = vec![
leg_of(SOL, USDC, 1_000_000_000, None, None, None),
leg_of(USDC, SOL, 100_000_000, None, None, None),
];
let mut notification = Notification::new(legs);
notification.original_realized_output_amount = Some(100_000_000);
let records = leg_records(¬ification.build());
assert_eq!(records.len(), 2);
assert!(
records
.iter()
.all(|r| r.original_realized_output_amount.is_none())
);
}
fn probe(
template: &str,
template_fill: Option<u64>,
l1_fill: Option<u64>,
change_vs_l1_bps: Option<i64>,
outcome: &str,
category: Option<&str>,
) -> VenueNotification {
serde_json::from_value(serde_json::json!({
"context": {"slot": 1},
"slot": 1,
"batchIndex": 0,
"originalSignature": fixture_signature(),
"originalFailed": false,
"template": template,
"program": USDC,
"hop": {
"slot": 1,
"blockTime": 1_767_225_600i64,
"txIndex": 0,
"ixIndex": 0,
"legIndex": 0,
"inputAmount": 1_000_000_000u64,
"outputAmount": l1_fill.unwrap_or_default(),
},
"quoteTxIndex": 0,
"quoteLagBlocks": 0,
"inputMint": SOL,
"outputMint": USDC,
"amount": 1_000_000_000u64,
"swapMode": "ExactIn",
"templateFill": template_fill,
"l1Fill": l1_fill,
"changeVsL1Bps": change_vs_l1_bps,
"outcome": outcome,
"category": category,
}))
.expect("a probe fixture decodes")
}
#[test]
fn probe_record_maps_template_fields_onto_the_shared_record() {
let notification = probe(
"venue-a",
Some(1_010_000_000),
Some(1_000_000_000),
Some(100),
"filled",
None,
);
let record = probe_record(¬ification);
assert_eq!(record.template.as_deref(), Some("venue-a"));
assert_eq!(record.new_output_amount, Some(1_010_000_000));
assert_eq!(
record.quoted_output_amount, None,
"the onchain fill is not the same-state baseline"
);
assert_eq!(record.output_bps, Some(100));
assert_eq!(record.error_category, None);
}
#[rstest]
#[case::exact_in_as_replayed(
"ExactIn",
Some(1_000_000_000),
Some(990_000_000),
Some(990_000_000)
)]
#[case::exact_in_rescaled("ExactIn", Some(500_000_000), Some(495_000_000), Some(990_000_000))]
#[case::exact_out_rescaled("ExactOut", Some(400_000_000), Some(500_000_000), Some(800_000_000))]
#[case::not_replayed("ExactIn", None, None, None)]
#[case::replay_moved_nothing("ExactIn", Some(0), Some(0), None)]
fn probe_record_takes_the_same_state_baseline_from_the_replayed_hop(
#[case] swap_mode: &str,
#[case] replay_input_amount: Option<u64>,
#[case] replay_output_amount: Option<u64>,
#[case] expected: Option<u64>,
) {
let mut notification = probe(
"venue-a",
Some(1_010_000_000),
Some(1_000_000_000),
Some(100),
"filled",
None,
);
notification.swap_mode = swap_mode.to_string();
notification.hop.replay_input_amount = replay_input_amount;
notification.hop.replay_output_amount = replay_output_amount;
assert_eq!(probe_record(¬ification).quoted_output_amount, expected);
}
#[rstest]
#[case::replayed(Some((1_000_000_000, 1_010_000_000)), "+0.00 (1 pairs)")]
#[case::not_replayed(None, "—")]
fn the_same_state_column_scores_against_the_replay_not_the_onchain_fill(
#[case] replay: Option<(u64, u64)>,
#[case] vs_same_state: &str,
) {
let mut notification = probe(
"venue-a",
Some(1_010_000_000),
Some(1_000_000_000),
Some(100),
"filled",
None,
);
notification.hop.replay_input_amount = replay.map(|(input, _)| input);
notification.hop.replay_output_amount = replay.map(|(_, output)| output);
let rendered =
probes_from_notifications(&[ReplacementNotification::Venue(notification)]).render("R1");
assert!(
rendered.contains(&format!(
"| venue-a | 1 | 1 (100.0%) | +100.00 (1 scored) | — | {vs_same_state} |"
)),
"{rendered}"
);
}
#[rstest]
#[case::filled("filled", None, "filled")]
#[case::reverted("reverted", Some("slippage"), "reverted_slippage")]
#[case::unattributed("unattributed", None, "unattributed")]
#[case::unsimulatable("unsimulatable", None, "unsimulatable")]
fn probe_record_reconstructs_the_pre_split_bucket_vocabulary(
#[case] outcome: &str,
#[case] category: Option<&str>,
#[case] expected_bucket: &str,
) {
let notification = probe("venue-a", None, None, None, outcome, category);
let record = probe_record(¬ification);
let report = ProbeReport::from_records(&[record], None);
assert_eq!(
report.by_template["venue-a"].outcomes.get(expected_bucket),
Some(&1)
);
}
#[test]
fn from_notifications_ignores_venue_variants() {
let mut notifications = priced([won_leg(2_000_000_000)]);
notifications.push(ReplacementNotification::Venue(probe(
"venue-a",
Some(1_010_000_000),
Some(1_000_000_000),
Some(100),
"filled",
None,
)));
let total = report_of(¬ifications).total();
assert_eq!(total.requoted.legs, 1, "the probe contributed no leg");
}
#[test]
fn probes_from_notifications_ignores_requote_variants() {
let mut notifications = priced([won_leg(2_000_000_000)]);
notifications.push(ReplacementNotification::Venue(probe(
"venue-a",
Some(1_010_000_000),
Some(1_000_000_000),
Some(100),
"filled",
None,
)));
let probes = probes_from_notifications(¬ifications);
assert_eq!(probes.by_template.len(), 1);
assert_eq!(
probes.by_template["venue-a"].outcomes.get("filled"),
Some(&1)
);
}
#[tokio::test]
async fn from_stream_ignores_venue_variants_in_a_mixed_stream() {
let mut notifications = priced([won_leg(2_000_000_000)]);
notifications.push(ReplacementNotification::Venue(probe(
"venue-a",
Some(1_010_000_000),
Some(1_000_000_000),
Some(100),
"filled",
None,
)));
let from_slice = report_of(¬ifications);
let from_stream = from_stream(venue(), futures::stream::iter(notifications))
.await
.expect("the template appears");
assert_eq!(
from_stream.total().requoted.legs,
1,
"the probe contributed no leg"
);
assert_eq!(from_slice.render(None), from_stream.render(None));
}
#[tokio::test]
async fn probes_from_stream_matches_probes_from_notifications_on_a_mixed_stream() {
let mut notifications = priced([won_leg(2_000_000_000)]);
notifications.push(ReplacementNotification::Venue(probe(
"venue-a",
Some(1_010_000_000),
Some(1_000_000_000),
Some(100),
"filled",
None,
)));
notifications.push(ReplacementNotification::Venue(probe(
"venue-a",
None,
None,
None,
"unattributed",
None,
)));
let from_slice = probes_from_notifications(¬ifications);
let from_stream = probes_from_stream(futures::stream::iter(notifications)).await;
assert_eq!(
from_slice.by_template.len(),
1,
"the Requote notification contributed no template"
);
let slice_template = &from_slice.by_template["venue-a"];
let stream_template = &from_stream.by_template["venue-a"];
assert_eq!(slice_template.outcomes, stream_template.outcomes);
assert_eq!(
slice_template.scored_vs_historical,
stream_template.scored_vs_historical
);
assert_eq!(
slice_template.bps_vs_historical_total,
stream_template.bps_vs_historical_total
);
assert_eq!(
slice_template.pairs_vs_same_state,
stream_template.pairs_vs_same_state
);
assert!(
(slice_template.bps_vs_same_state_total - stream_template.bps_vs_same_state_total)
.abs()
< 1e-9
);
}
}