use futures::{Stream, StreamExt};
use simulator_api::mints;
pub use simulator_api::{
mints::short_mint,
reroute_report::{
Direction, Flow, LegRecord, Pair, Report, ReportBuilder, RerouteReportError, SwapMode,
Target,
},
};
use crate::{RerouteLegNotification, RerouteNotification};
pub fn leg_records(notification: &RerouteNotification) -> 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: &RerouteNotification,
leg: &RerouteLegNotification,
sole_leg: bool,
) -> LegRecord {
LegRecord {
original_signature: notification.original_signature.clone(),
input_mint: mints::parse_mint(&leg.input_mint),
output_mint: mints::parse_mint(&leg.output_mint),
amount: leg.amount,
swap_mode: SwapMode::parse(&leg.swap_mode),
failed: notification.err.is_some(),
original_failed: notification.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(),
}
}
pub fn from_notifications<'a>(
target: Target,
notifications: impl IntoIterator<Item = &'a RerouteNotification>,
) -> Result<Report, RerouteReportError> {
let mut builder = ReportBuilder::new(target);
for notification in notifications {
for record in leg_records(notification) {
builder.push(&record);
}
}
builder.finish()
}
pub async fn from_stream(
target: Target,
stream: impl Stream<Item = RerouteNotification>,
) -> Result<Report, RerouteReportError> {
let mut builder = ReportBuilder::new(target);
let mut stream = std::pin::pin!(stream);
while let Some(notification) = stream.next().await {
for record in leg_records(¬ification) {
builder.push(&record);
}
}
builder.finish()
}
#[cfg(test)]
mod tests {
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) -> RerouteNotification {
serde_json::from_value(serde_json::json!({
"context": {"slot": 1},
"slot": 1,
"batchIndex": 0,
"originalSignature": "sig",
"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,
"originalFailed": self.original_failed,
}))
.expect("a notification fixture decodes")
}
}
fn anchors() -> Vec<RerouteNotification> {
(1..=3)
.map(|n| Notification::swap(SOL, USDC, n * 1_000_000_000, n * 100_000_000).build())
.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: &[RerouteNotification]) -> Report {
from_notifications(venue(), notifications).expect("the venue appears")
}
fn priced(extra: impl IntoIterator<Item = Notification>) -> Vec<RerouteNotification> {
let mut notifications = anchors();
notifications.extend(extra.into_iter().map(Notification::build));
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, realized)])
}
#[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())
);
}
}