use std::borrow::Cow;
use crate::order_router::{OrderRouter, MAX_EXECUTED_PLAN_IDS, NO_CAP, TOLERANCE};
use crate::value::{HashMap, Value};
fn fixture() -> Result<Value, String> {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../ts/src/test/base/fixtures/orderRouter.json"
);
let raw = std::fs::read_to_string(path)
.map_err(|e| format!("reading the shared fixture at {path}: {e}"))?;
let parsed: serde_json::Value =
serde_json::from_str(&raw).map_err(|e| format!("parsing the shared fixture: {e}"))?;
Ok(Value::from_json(&parsed))
}
fn router() -> Result<OrderRouter, String> {
let mut config = HashMap::new();
config.insert("apiKey".to_string(), Value::Str("test-key".to_string().into()));
OrderRouter::new(&Value::Map(config)).map_err(|e| e.to_string())
}
fn section(fixture: &Value, name: &str) -> Result<Value, String> {
match fixture.as_map().and_then(|m| m.get(name)) {
Some(found) => Ok(found.clone()),
None => Err(format!("the shared fixture has no `{name}` section")),
}
}
fn cases(fixture: &Value, name: &str) -> Result<Vec<Value>, String> {
match section(fixture, name)? {
Value::Arr(items) if !items.is_empty() => Ok(items.as_ref().clone()),
Value::Arr(_) => Err(format!("the fixture's `{name}` section is empty")),
_ => Err(format!("the fixture's `{name}` section is not an array")),
}
}
fn named(fixture: &Value, section_name: &str, key: &str) -> Result<Value, String> {
let holder = section(fixture, section_name)?;
match holder.as_map().and_then(|m| m.get(key)) {
Some(found) => Ok(found.clone()),
None => Err(format!("`{section_name}` has no entry named `{key}`")),
}
}
fn text(container: &Value, key: &str) -> String {
match container.as_map().and_then(|m| m.get(key)) {
Some(Value::Str(s)) => s.to_string(),
_ => String::new(),
}
}
fn at<'a>(container: &'a Value, key: &str) -> Option<&'a Value> {
container.as_map().and_then(|m| m.get(key))
}
fn numbers_match(a: f64, b: f64) -> bool {
if a == b {
return true;
}
if !a.is_finite() || !b.is_finite() {
return false;
}
let mut scale = 1.0f64;
if a.abs() > scale {
scale = a.abs();
}
if b.abs() > scale {
scale = b.abs();
}
(a - b).abs() <= TOLERANCE * scale
}
fn as_number(value: &Value) -> Option<f64> {
match value {
Value::Int(n) => Some(*n as f64),
Value::Float(n) => Some(*n),
_ => None,
}
}
fn assert_matches(actual: &Value, expected: &Value, whereat: &str) -> Result<(), String> {
match expected {
Value::Arr(expected_items) => {
let actual_items = match actual {
Value::Arr(items) => items,
other => return Err(format!("{whereat}: expected an array, got {other:?}")),
};
if actual_items.len() != expected_items.len() {
return Err(format!(
"{whereat}: array length — expected {}, got {}",
expected_items.len(),
actual_items.len()
));
}
for (i, expected_item) in expected_items.iter().enumerate() {
assert_matches(&actual_items[i], expected_item, &format!("{whereat}[{i}]"))?;
}
Ok(())
}
Value::Dict(expected_map) => {
let actual_map = match actual {
Value::Dict(map) => map,
other => return Err(format!("{whereat}: expected an object, got {other:?}")),
};
let mut expected_keys: Vec<&String> = expected_map.keys().collect();
let mut actual_keys: Vec<&String> = actual_map.keys().collect();
expected_keys.sort();
actual_keys.sort();
if expected_keys != actual_keys {
return Err(format!(
"{whereat}: key set — expected {expected_keys:?}, got {actual_keys:?}"
));
}
for key in expected_keys {
assert_matches(
actual_map.get(key).unwrap_or(&Value::Null),
expected_map.get(key).unwrap_or(&Value::Null),
&format!("{whereat}.{key}"),
)?;
}
Ok(())
}
_ => {
if let Some(expected_number) = as_number(expected) {
let actual_number = as_number(actual).ok_or_else(|| {
format!("{whereat}: expected the number {expected_number}, got {actual:?}")
})?;
if !numbers_match(actual_number, expected_number) {
return Err(format!(
"{whereat}: expected {expected_number}, got {actual_number}"
));
}
return Ok(());
}
if actual != expected {
return Err(format!("{whereat}: expected {expected:?}, got {actual:?}"));
}
Ok(())
}
}
}
fn fixture_build_execution_plan(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "planCases")? {
let route = named(f, "routes", &text(&test_case, "route"))?;
let options = at(&test_case, "options").cloned().unwrap_or(Value::Null);
let plan = r.build_execution_plan(&route, &options).map_err(|e| e.to_string())?;
let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
assert_matches(&plan, &expected, &format!("planCase {}", text(&test_case, "id")))?;
}
Ok(())
}
fn fixture_plan_is_deterministic(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "planCases")? {
let route = named(f, "routes", &text(&test_case, "route"))?;
let options = at(&test_case, "options").cloned().unwrap_or(Value::Null);
let before = serde_json::to_string(&route.to_json()).map_err(|e| e.to_string())?;
let first = r.build_execution_plan(&route, &options).map_err(|e| e.to_string())?;
let second = r.build_execution_plan(&route, &options).map_err(|e| e.to_string())?;
let id = text(&test_case, "id");
assert_matches(&second, &first, &format!("planCase {id} repeated"))?;
let after = serde_json::to_string(&route.to_json()).map_err(|e| e.to_string())?;
if before != after {
return Err(format!("planCase {id}: the route was mutated"));
}
}
Ok(())
}
fn fixture_check_execution_plan_safety(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "safetyCases")? {
let route = named(f, "routes", &text(&test_case, "route"))?;
let markets = named(f, "marketSets", &text(&test_case, "markets"))?;
let plan_options = at(&test_case, "planOptions").cloned().unwrap_or(Value::Null);
let options = at(&test_case, "options").cloned().unwrap_or(Value::Null);
let plan = r.build_execution_plan(&route, &plan_options).map_err(|e| e.to_string())?;
let violations = r.check_execution_plan_safety(&plan, &markets, &options);
let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
assert_matches(
&Value::List(violations),
&expected,
&format!("safetyCase {}", text(&test_case, "id")),
)?;
}
Ok(())
}
fn fixture_reconcile_execution_step(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "reconcileCases")? {
let plan = if at(&test_case, "plan").is_some() {
named(f, "plans", &text(&test_case, "plan"))?
} else {
let route = named(f, "routes", &text(&test_case, "route"))?;
let plan_options = at(&test_case, "planOptions").cloned().unwrap_or(Value::Null);
r.build_execution_plan(&route, &plan_options).map_err(|e| e.to_string())?
};
let step_index = r.number_at(&test_case, "stepIndex", 0.0) as i64;
let realised_out = r.number_at(&test_case, "realisedOut", 0.0);
let verdict = r
.reconcile_execution_step(&plan, step_index, realised_out)
.map_err(|e| e.to_string())?;
let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
assert_matches(&verdict, &expected, &format!("reconcileCase {}", text(&test_case, "id")))?;
}
Ok(())
}
fn fixture_reconcile_sequence(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "reconcileSequenceCases")? {
let id = text(&test_case, "id");
let mut steps: Vec<Value> = match at(&test_case, "steps") {
Some(Value::Arr(items)) => items.as_ref().clone(),
_ => return Err(format!("reconcileSequenceCase {id}: no steps")),
};
let tolerance = r.number_at(&test_case, "reconcileToleranceRatio", 0.0);
let calls = match at(&test_case, "calls") {
Some(Value::Arr(items)) => items.as_ref().clone(),
_ => Vec::new(),
};
let expected_scales = match at(&test_case, "expectedScales") {
Some(Value::Arr(items)) => items.as_ref().clone(),
_ => Vec::new(),
};
for (index, call) in calls.iter().enumerate() {
let mut plan = HashMap::new();
plan.insert("steps".to_string(), Value::List(steps.clone()));
plan.insert("reconcileToleranceRatio".to_string(), Value::Float(tolerance));
let plan = Value::Map(plan);
let step_index = r.number_at(call, "stepIndex", 0.0) as i64;
let realised_out = r.number_at(call, "realisedOut", 0.0);
let reconciliation = r
.reconcile_execution_step(&plan, step_index, realised_out)
.map_err(|e| e.to_string())?;
let scale = r.number_at(&reconciliation, "scale", f64::NAN);
let expected = as_number(&expected_scales[index]).unwrap_or(f64::NAN);
if !numbers_match(scale, expected) {
return Err(format!(
"reconcileSequenceCase {id} call {index}: scale — expected {expected}, got {scale}"
));
}
r.apply_resize(&mut steps, &reconciliation);
}
let expected_amounts = match at(&test_case, "expectedAmounts") {
Some(Value::Arr(items)) => items.as_ref().clone(),
_ => Vec::new(),
};
for (index, step) in steps.iter().enumerate() {
let amount = r.number_at(step, "amount", f64::NAN);
let expected = as_number(&expected_amounts[index]).unwrap_or(f64::NAN);
if !numbers_match(amount, expected) {
return Err(format!(
"reconcileSequenceCase {id} step {index}: amount — expected {expected}, got {amount}"
));
}
}
}
Ok(())
}
fn fixture_build_unwind_plan(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "unwindCases")? {
let report = named(f, "reports", &text(&test_case, "report"))?;
let unwind = r.build_unwind_plan(&report);
let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
assert_matches(&unwind, &expected, &format!("unwindCase {}", text(&test_case, "id")))?;
}
Ok(())
}
fn fixture_number_at(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "numberCases")? {
let container = at(&test_case, "container").cloned().unwrap_or(Value::Null);
let key = text(&test_case, "key");
let default_value = r.number_at(&test_case, "default", 0.0);
let actual = r.number_at(&container, &key, default_value);
let expected = at(&test_case, "expected")
.and_then(as_number)
.ok_or_else(|| format!("numberCase {}: no expected number", text(&test_case, "id")))?;
if !numbers_match(actual, expected) {
return Err(format!(
"numberCase {}: expected {expected}, got {actual}",
text(&test_case, "id")
));
}
}
Ok(())
}
fn config_with(entries: &[(&str, Value)]) -> Value {
let mut config = HashMap::new();
for (key, value) in entries {
config.insert((*key).to_string(), value.clone());
}
Value::Map(config)
}
fn capture_one_request(r: &OrderRouter) -> Result<String, String> {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
let address = listener.local_addr().map_err(|e| e.to_string())?;
let server = std::thread::spawn(move || -> String {
let mut head = Vec::new();
if let Ok((mut stream, _)) = listener.accept() {
let mut buffer = [0u8; 1024];
while !head.windows(4).any(|w| w == b"\r\n\r\n") {
match stream.read(&mut buffer) {
Ok(0) | Err(_) => break,
Ok(n) => head.extend_from_slice(&buffer[..n]),
}
}
let body = "{\"status\":\"ok\"}";
let reply = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = stream.write_all(reply.as_bytes());
}
String::from_utf8_lossy(&head).to_string()
});
let url = format!("http://{address}/health");
block_on(r.request(&url, "GET", &Value::Null, "")).map_err(|e| e.to_string())?;
server.join().map_err(|_| "the loopback server panicked".to_string())
}
fn capture_stream_handshake(r: &OrderRouter) -> Result<String, String> {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
let address = listener.local_addr().map_err(|e| e.to_string())?;
let server = std::thread::spawn(move || -> String {
let mut head = Vec::new();
if let Ok((mut stream, _)) = listener.accept() {
let mut buffer = [0u8; 1024];
while !head.windows(4).any(|w| w == b"\r\n\r\n") {
match stream.read(&mut buffer) {
Ok(0) | Err(_) => break,
Ok(n) => head.extend_from_slice(&buffer[..n]),
}
}
let _ = stream.write_all(b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
}
String::from_utf8_lossy(&head).to_string()
});
let streamer = OrderRouter::new(&config_with(&[
("baseUrl", Value::Str(format!("http://{address}").into())),
("userAgent", Value::Str(r.user_agent().to_string().into())),
]))
.map_err(|e| e.to_string())?;
let mut params = HashMap::new();
params.insert("amountIn".to_string(), Value::Float(10.0));
let mut stop = |_: &Value| "stop".to_string();
if block_on(streamer.watch_route("USDT", "BTC", &Value::Map(params), &mut stop)).is_ok() {
return Err("the refused upgrade surfaces as an error".to_string());
}
server.join().map_err(|_| "the loopback server panicked".to_string())
}
fn header_line(head: &str, name: &str) -> String {
let prefix = format!("{}:", name.to_lowercase());
for line in head.split("\r\n") {
if line.to_lowercase().starts_with(&prefix) {
return line[prefix.len()..].trim().to_string();
}
}
String::new()
}
fn user_agent_is_sent_only_when_configured() -> Result<(), String> {
let plain = OrderRouter::new(&config_with(&[])).map_err(|e| e.to_string())?;
if !plain.user_agent().is_empty() {
return Err("no User-Agent override by default".to_string());
}
let head = capture_one_request(&plain)?;
if header_line(&head, "User-Agent") != "" {
return Err(format!("the default request sends no custom User-Agent, got {head:?}"));
}
let configured = OrderRouter::new(&config_with(&[("userAgent", Value::Str("ccxt-mcp/1.0.0 (ccxt 4.0.0)".into()))]))
.map_err(|e| e.to_string())?;
if configured.user_agent() != "ccxt-mcp/1.0.0 (ccxt 4.0.0)" {
return Err("the configured userAgent is stored".to_string());
}
let head = capture_one_request(&configured)?;
if header_line(&head, "User-Agent") != "ccxt-mcp/1.0.0 (ccxt 4.0.0)" {
return Err(format!("the configured userAgent is sent, got {head:?}"));
}
let handshake = capture_stream_handshake(&configured)?;
if header_line(&handshake, "User-Agent") != "ccxt-mcp/1.0.0 (ccxt 4.0.0)" {
return Err(format!("the configured userAgent is sent on the stream handshake, got {handshake:?}"));
}
Ok(())
}
fn capped_client(cap: f64) -> Result<OrderRouter, String> {
let config = config_with(&[
("apiKey", Value::Str("k".into())),
("maxNotionalUsd", Value::Float(cap)),
]);
OrderRouter::new(&config).map_err(|e| e.to_string())
}
fn constructor_guards() -> Result<(), String> {
let keyless = OrderRouter::new(&config_with(&[])).map_err(|e| e.to_string())?;
if !keyless.api_key().is_empty() {
return Err("a keyless client holds an empty apiKey".to_string());
}
let keyed = OrderRouter::new(&config_with(&[("apiKey", Value::Str("still-works".into()))]))
.map_err(|e| e.to_string())?;
if keyed.api_key() != "still-works" {
return Err("a supplied apiKey is carried, not dropped".to_string());
}
let large = capped_client(250000.0)?;
if !numbers_match(large.max_notional_usd(), 250000.0) {
return Err(format!(
"a large cap is honoured exactly, not clamped, got {}",
large.max_notional_usd()
));
}
let small = capped_client(0.05)?;
if !numbers_match(small.max_notional_usd(), 0.05) {
return Err("cents are a legitimate trade size".to_string());
}
let standard = OrderRouter::new(&config_with(&[("apiKey", Value::Str("k".into()))]))
.map_err(|e| e.to_string())?;
if !numbers_match(standard.max_notional_usd(), NO_CAP) || !numbers_match(NO_CAP, 0.0) {
return Err(format!(
"the default is NO_CAP, which is 0, got {}",
standard.max_notional_usd()
));
}
if !numbers_match(capped_client(0.0)?.max_notional_usd(), 0.0) {
return Err("0 is the explicit spelling of no cap".to_string());
}
let negative = config_with(&[
("apiKey", Value::Str("k".into())),
("maxNotionalUsd", Value::Float(-1.0)),
]);
match OrderRouter::new(&negative) {
Ok(_) => return Err("a negative cap is refused, not ignored".to_string()),
Err(e) if e.is("BadRequest") => {}
Err(e) => return Err(format!("a negative cap is a BadRequest, got {e}")),
}
let slashed = config_with(&[
("apiKey", Value::Str("k".into())),
("baseUrl", Value::Str("https://example.test/router///".into())),
]);
let client = OrderRouter::new(&slashed).map_err(|e| e.to_string())?;
if client.base_url() != "https://example.test/router" {
return Err(format!("trailing slashes are stripped, got {}", client.base_url()));
}
Ok(())
}
static TEST_REQUEST_ID_COUNTER: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
fn next_test_request_id() -> Value {
let next = TEST_REQUEST_ID_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
Value::Str(format!("test-req-{next}").into())
}
fn one_leg_route(side: &str, base_code: &str, quote: &str, amount: f64, price: f64) -> Value {
let mut leg = HashMap::new();
leg.insert("exchangeId".to_string(), Value::Str("stub".into()));
leg.insert("amount".to_string(), Value::Float(amount));
leg.insert("averagePrice".to_string(), Value::Float(price));
leg.insert("effectivePrice".to_string(), Value::Float(price));
let mut hop = HashMap::new();
hop.insert("pair".to_string(), Value::Str(format!("{base_code}/{quote}").into()));
hop.insert("side".to_string(), Value::Str(side.to_string().into()));
hop.insert("base".to_string(), Value::Str(base_code.to_string().into()));
hop.insert("quote".to_string(), Value::Str(quote.to_string().into()));
hop.insert("legs".to_string(), Value::List(vec![Value::Map(leg)]));
let mut route = HashMap::new();
route.insert("requestId".to_string(), next_test_request_id());
route.insert("from".to_string(), Value::Str(quote.to_string().into()));
route.insert("to".to_string(), Value::Str(base_code.to_string().into()));
route.insert("strategy".to_string(), Value::Str("best_single".into()));
route.insert("exactSide".to_string(), Value::Str("in".into()));
route.insert("fullyFillable".to_string(), Value::Bool(true));
route.insert("fillRatio".to_string(), Value::Float(1.0));
route.insert("hops".to_string(), Value::List(vec![Value::Map(hop)]));
Value::Map(route)
}
fn two_hop_route() -> Value {
let hop = |base_code: &str, quote: &str, side: &str, amount: f64, price: f64| {
let mut leg = HashMap::new();
leg.insert("exchangeId".to_string(), Value::Str("stub".into()));
leg.insert("amount".to_string(), Value::Float(amount));
leg.insert("averagePrice".to_string(), Value::Float(price));
leg.insert("effectivePrice".to_string(), Value::Float(price));
let mut hop = HashMap::new();
hop.insert("pair".to_string(), Value::Str(format!("{base_code}/{quote}").into()));
hop.insert("side".to_string(), Value::Str(side.to_string().into()));
hop.insert("base".to_string(), Value::Str(base_code.to_string().into()));
hop.insert("quote".to_string(), Value::Str(quote.to_string().into()));
hop.insert("legs".to_string(), Value::List(vec![Value::Map(leg)]));
Value::Map(hop)
};
let mut route = HashMap::new();
route.insert("requestId".to_string(), next_test_request_id());
route.insert("from".to_string(), Value::Str("USDT".into()));
route.insert("to".to_string(), Value::Str("ETH".into()));
route.insert("strategy".to_string(), Value::Str("best_single".into()));
route.insert("exactSide".to_string(), Value::Str("in".into()));
route.insert("fullyFillable".to_string(), Value::Bool(true));
route.insert("fillRatio".to_string(), Value::Float(1.0));
route.insert("hops".to_string(), Value::List(vec![
hop("BTC", "USDT", "buy", 0.2, 100.0),
hop("BTC", "ETH", "sell", 0.2, 10.0),
]));
Value::Map(route)
}
fn a_report_is_summarised_in_the_assets_it_names(r: &OrderRouter) -> Result<(), String> {
let route = two_hop_route();
let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
let venue = StubVenue::new("stub");
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let mut options = execute_options(true, "sequential");
let mut btc_usdt = HashMap::new();
btc_usdt.insert("symbol".to_string(), Value::Str("BTC/USDT".into()));
btc_usdt.insert("base".to_string(), Value::Str("BTC".into()));
btc_usdt.insert("quote".to_string(), Value::Str("USDT".into()));
let mut btc_eth = HashMap::new();
btc_eth.insert("symbol".to_string(), Value::Str("BTC/ETH".into()));
btc_eth.insert("base".to_string(), Value::Str("BTC".into()));
btc_eth.insert("quote".to_string(), Value::Str("ETH".into()));
let mut by_symbol = HashMap::new();
by_symbol.insert("BTC/USDT".to_string(), Value::Map(btc_usdt));
by_symbol.insert("BTC/ETH".to_string(), Value::Map(btc_eth));
let mut markets = HashMap::new();
markets.insert("stub".to_string(), Value::Map(by_symbol));
OrderRouter::set_key(&mut options, "markets", Value::Map(markets));
let mut usd_rates = HashMap::new();
usd_rates.insert("USDT".to_string(), Value::Float(1.0));
usd_rates.insert("ETH".to_string(), Value::Float(10.0));
OrderRouter::set_key(&mut options, "usdRates", Value::Map(usd_rates));
let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if results.len() != 2 {
return Err(format!("the two-hop route must place two orders, got {results:?}"));
}
let first_in = r.number_at(&results[0], "inAmount", 0.0);
let second_in = r.number_at(&results[1], "inAmount", 0.0);
let first_out = r.number_at(&results[0], "outAmount", 0.0);
let second_out = r.number_at(&results[1], "outAmount", 0.0);
let filled_in = r.number_at(&report, "filledIn", -1.0);
let filled_out = r.number_at(&report, "filledOut", -1.0);
if (filled_in - first_in).abs() > 1e-9 {
return Err(format!("filledIn is the FIRST hop's spend alone ({first_in} USDT), got {filled_in}"));
}
if (filled_out - second_out).abs() > 1e-9 {
return Err(format!("filledOut is the LAST hop's proceeds alone ({second_out} ETH), got {filled_out}"));
}
if second_in <= 0.0 || first_out <= 0.0 {
return Err("the fixture route must have a real middle asset for this to mean anything".to_string());
}
if r.number_at(&report, "ordersPlaced", 0.0) != 2.0 {
return Err(format!("both placements are counted, got {}", r.number_at(&report, "ordersPlaced", 0.0)));
}
for result in &results {
for flag in ["filledKnown", "averageKnown", "costKnown"] {
if !r.bool_at(result, flag, false) {
return Err(format!("{flag} must be reported, and true when the stub answered fully: {result:?}"));
}
}
}
Ok(())
}
fn bounded_stub_markets() -> Value {
let mut limits = HashMap::new();
limits.insert("amount".to_string(), config_with(&[("min", Value::Float(0.0001)), ("max", Value::Float(0.0))]));
limits.insert("price".to_string(), config_with(&[("min", Value::Float(1.0)), ("max", Value::Float(1000000.0))]));
limits.insert("cost".to_string(), config_with(&[("min", Value::Float(10.0)), ("max", Value::Float(0.0))]));
let mut market = HashMap::new();
market.insert("symbol".to_string(), Value::Str("BTC/USDT".into()));
market.insert("base".to_string(), Value::Str("BTC".into()));
market.insert("quote".to_string(), Value::Str("USDT".into()));
market.insert("precision".to_string(), config_with(&[("amount", Value::Float(0.0)), ("price", Value::Float(0.0))]));
market.insert("limits".to_string(), Value::Map(limits));
let mut venue = HashMap::new();
venue.insert("BTC/USDT".to_string(), Value::Map(market));
let mut markets = HashMap::new();
markets.insert("stub".to_string(), Value::Map(venue));
Value::Map(markets)
}
fn a_hand_built_plan_with_only_the_required_fields_is_executable(r: &OrderRouter) -> Result<(), String> {
let step = config_with(&[
("exchangeId", Value::Str("stub".into())),
("symbol", Value::Str("BTC/USDT".into())),
("side", Value::Str("buy".into())),
("amount", Value::Float(1.0)),
("base", Value::Str("BTC".into())),
("quote", Value::Str("USDT".into())),
("hopIndex", Value::Float(0.0)),
("expectedPrice", Value::Float(100.0)),
]);
let plan = config_with(&[
("requestId", Value::Str("hand-built-0001".into())),
("calculatedAt", Value::Float(1700000000000.0)),
("steps", Value::List(vec![step])),
]);
let violations = r.check_execution_plan_safety(&plan, &bounded_stub_markets(), &uncapped_options(&[("USDT", 1.0)]));
let blocking: Vec<String> = violations
.iter()
.filter(|v| r.bool_at(v, "blocking", false))
.map(|v| text(v, "code"))
.collect();
if !blocking.is_empty() {
return Err(format!("the manual's own minimal plan must not be refused: {}", blocking.join(", ")));
}
Ok(())
}
fn derived_limit_price_and_notional_follow_amount_and_expected_price(r: &OrderRouter) -> Result<(), String> {
let step = config_with(&[("amount", Value::Float(2.0)), ("expectedPrice", Value::Float(100.0))]);
if !numbers_match(r.step_limit_price(&step), 100.0) {
return Err("no limitPrice falls back to expectedPrice".to_string());
}
if !numbers_match(r.step_notional_quote(&step), 200.0) {
return Err("no notionalQuote is amount * expectedPrice".to_string());
}
let explicit = config_with(&[
("amount", Value::Float(2.0)),
("expectedPrice", Value::Float(100.0)),
("limitPrice", Value::Float(99.0)),
("notionalQuote", Value::Float(1.0)),
]);
if !numbers_match(r.step_limit_price(&explicit), 99.0) {
return Err("an explicit limitPrice wins".to_string());
}
if !numbers_match(r.step_notional_quote(&explicit), 1.0) {
return Err("an explicit notionalQuote wins".to_string());
}
Ok(())
}
fn limit_price_side(r: &OrderRouter) -> Result<(), String> {
let options = config_with(&[("slippageBps", Value::Float(100.0))]);
let buy = r
.build_execution_plan(&one_leg_route("buy", "BTC", "USDT", 1.0, 100.0), &options)
.map_err(|e| e.to_string())?;
let buy_steps = r.list_at(&buy, "steps");
let buy_limit = r.number_at(&buy_steps[0], "limitPrice", 0.0);
if !numbers_match(buy_limit, 101.0) {
return Err(format!("a buy limit sits ABOVE the expected price, got {buy_limit}"));
}
let sell = r
.build_execution_plan(&one_leg_route("sell", "BTC", "USDT", 1.0, 100.0), &options)
.map_err(|e| e.to_string())?;
let sell_steps = r.list_at(&sell, "steps");
let sell_limit = r.number_at(&sell_steps[0], "limitPrice", 0.0);
if !numbers_match(sell_limit, 99.0) {
return Err(format!("a sell limit sits BELOW the expected price, got {sell_limit}"));
}
Ok(())
}
fn unwind_buy_is_fundable(r: &OrderRouter, f: &Value) -> Result<(), String> {
let report = named(f, "reports", "haltedCrossVenue")?;
let unwind = r.build_unwind_plan(&report);
let steps = r.list_at(&unwind, "steps");
if steps.len() != 2 {
return Err(format!("the cross-venue report strands two positions, got {}", steps.len()));
}
let buy = &steps[1];
if text(buy, "side") != "buy" {
return Err("the mexc leg is the buy".to_string());
}
let residual = 44.5f64;
let spend = r.number_at(buy, "amount", 0.0) * r.number_at(buy, "limitPrice", 0.0);
if spend > residual + 1e-9 {
return Err(format!("the buy spends {spend} of a {residual} residual"));
}
if spend < residual - 1e-9 {
return Err(format!("the buy spends {spend}, short of the {residual} residual"));
}
if !numbers_match(r.number_at(buy, "notionalQuote", 0.0), spend) {
return Err("notionalQuote is priced at the limit the order is placed at".to_string());
}
let sell = &steps[0];
if text(sell, "side") != "sell" {
return Err("the binance leg is the sell".to_string());
}
if !numbers_match(r.number_at(sell, "amount", 0.0), 0.2) {
return Err("the whole 0.2 SOL residual is sold".to_string());
}
if !numbers_match(
r.number_at(sell, "notionalQuote", 0.0),
0.2 * r.number_at(sell, "limitPrice", 0.0),
) {
return Err("the sell notional is priced at its limit too".to_string());
}
Ok(())
}
fn empty_plan_is_not_safe(r: &OrderRouter) -> Result<(), String> {
let mut plan = HashMap::new();
plan.insert("steps".to_string(), Value::List(vec![]));
let violations = r.check_execution_plan_safety(
&Value::Map(plan),
&Value::Map(HashMap::new()),
&Value::Map(HashMap::new()),
);
if violations.len() != 1 {
return Err(format!("an empty plan yields one finding, got {}", violations.len()));
}
if text(&violations[0], "code") != "empty_plan" {
return Err("an empty plan is flagged empty_plan".to_string());
}
Ok(())
}
fn permissive_stub_markets() -> Value {
let mut market = HashMap::new();
market.insert("symbol".to_string(), Value::Str("BTC/USDT".into()));
market.insert("base".to_string(), Value::Str("BTC".into()));
market.insert("quote".to_string(), Value::Str("USDT".into()));
let mut venue = HashMap::new();
venue.insert("BTC/USDT".to_string(), Value::Map(market));
let mut markets = HashMap::new();
markets.insert("stub".to_string(), Value::Map(venue));
Value::Map(markets)
}
fn rates(entries: &[(&str, f64)]) -> Value {
let mut usd_rates = HashMap::new();
for (code, rate) in entries {
usd_rates.insert((*code).to_string(), Value::Float(*rate));
}
Value::Map(usd_rates)
}
fn capped_options(cap: f64, usd_rates: &[(&str, f64)]) -> Value {
config_with(&[
("usdRates", rates(usd_rates)),
("maxNotionalUsd", Value::Float(cap)),
])
}
fn uncapped_options(usd_rates: &[(&str, f64)]) -> Value {
config_with(&[("usdRates", rates(usd_rates))])
}
fn codes(violations: &[Value]) -> Vec<String> {
violations.iter().map(|v| text(v, "code")).collect()
}
fn planned(r: &OrderRouter, amount: f64, price: f64, slippage_bps: f64) -> Result<Value, String> {
let options = config_with(&[("slippageBps", Value::Float(slippage_bps))]);
r.build_execution_plan(&one_leg_route("buy", "BTC", "USDT", amount, price), &options)
.map_err(|e| e.to_string())
}
fn a_cap_that_is_set_binds_exactly(r: &OrderRouter) -> Result<(), String> {
let markets = permissive_stub_markets();
let capped = capped_options(25.0, &[("USDT", 1.0)]);
let under = planned(r, 0.24, 100.0, 0.0)?;
if !codes(&r.check_execution_plan_safety(&under, &markets, &capped)).is_empty() {
return Err("24 USD passes a 25 USD cap".to_string());
}
let at_the_cap = planned(r, 0.25, 100.0, 0.0)?;
if !codes(&r.check_execution_plan_safety(&at_the_cap, &markets, &capped)).is_empty() {
return Err("exactly at the cap passes".to_string());
}
let over = planned(r, 0.2501, 100.0, 0.0)?;
if codes(&r.check_execution_plan_safety(&over, &markets, &capped)) != ["notional_exceeds_cap"] {
return Err("25.01 USD trips a 25 USD cap".to_string());
}
let slipped = planned(r, 0.249, 100.0, 100.0)?;
if codes(&r.check_execution_plan_safety(&slipped, &markets, &capped)) != ["notional_exceeds_cap"]
{
return Err("24.90 USD at 1% slippage is 25.15 USD of risk".to_string());
}
let large = planned(r, 20.0, 100.0, 0.0)?;
let generous = capped_options(5000.0, &[("USDT", 1.0)]);
if !codes(&r.check_execution_plan_safety(&large, &markets, &generous)).is_empty() {
return Err("2,000 USD under a 5,000 USD cap".to_string());
}
let tighter = capped_options(1000.0, &[("USDT", 1.0)]);
if codes(&r.check_execution_plan_safety(&large, &markets, &tighter)) != ["notional_exceeds_cap"]
{
return Err("and the same 2,000 USD trips a 1,000 USD cap".to_string());
}
Ok(())
}
fn with_no_cap_no_notional_check_runs(r: &OrderRouter) -> Result<(), String> {
let markets = permissive_stub_markets();
let large = planned(r, 1000.0, 100.0, 0.0)?;
let found = codes(&r.check_execution_plan_safety(&large, &markets, &uncapped_options(&[("USDT", 1.0)])));
if !found.is_empty() {
return Err(format!("100,000 USD passes when no cap is set, got {found:?}"));
}
let bare = codes(&r.check_execution_plan_safety(&large, &markets, &Value::Map(HashMap::new())));
if !bare.is_empty() {
return Err(format!("and needs no usdRates at all, got {bare:?}"));
}
Ok(())
}
fn usdt_is_not_a_dollar(r: &OrderRouter) -> Result<(), String> {
let markets = permissive_stub_markets();
let plan = planned(r, 0.001, 100.0, 25.0)?;
let violations =
r.check_execution_plan_safety(&plan, &markets, &capped_options(25.0, &[("USD", 1.0)]));
let blocked = violations
.iter()
.any(|v| text(v, "code") == "notional_unvaluable" && r.bool_at(v, "blocking", false));
if !blocked {
return Err("an unvaluable step BLOCKS rather than being skipped".to_string());
}
let unrelated =
r.check_execution_plan_safety(&plan, &markets, &capped_options(25.0, &[("ETH", 3000.0)]));
if codes(&unrelated) != ["notional_unvaluable"] {
return Err("a rate for another currency does not value this step".to_string());
}
for resolving in [("USDT", 0.4), ("BTC", 100.0)] {
let resolved =
r.check_execution_plan_safety(&plan, &markets, &capped_options(25.0, &[resolving]));
if !codes(&resolved).is_empty() {
return Err(format!("a rate for {} values the step", resolving.0));
}
}
let uncapped = r.check_execution_plan_safety(&plan, &markets, &uncapped_options(&[]));
if !codes(&uncapped).is_empty() {
return Err("an unvaluable step passes when no cap is set".to_string());
}
Ok(())
}
fn a_per_call_cap_overrides_the_client_one() -> Result<(), String> {
let client = capped_client(100.0)?;
let markets = permissive_stub_markets();
let plan = planned(&client, 0.005, 100000.0, 0.0)?;
let against_the_client_cap =
client.check_execution_plan_safety(&plan, &markets, &uncapped_options(&[("USDT", 1.0)]));
if codes(&against_the_client_cap) != ["notional_exceeds_cap"] {
return Err("500 USD trips the client cap of 100".to_string());
}
if !numbers_match(client.number_at(&against_the_client_cap[0], "limit", 0.0), 100.0) {
return Err("the client cap is the limit reported".to_string());
}
let raised =
client.check_execution_plan_safety(&plan, &markets, &capped_options(1000.0, &[("USDT", 1.0)]));
if !codes(&raised).is_empty() {
return Err("a per-call cap of 1000 lets it through".to_string());
}
let tightened =
client.check_execution_plan_safety(&plan, &markets, &capped_options(10.0, &[("USDT", 1.0)]));
if !numbers_match(client.number_at(&tightened[0], "limit", 0.0), 10.0) {
return Err("a per-call cap of 10 is the limit reported".to_string());
}
Ok(())
}
fn refuses_incoherent_routes(r: &OrderRouter) -> Result<(), String> {
let mut route = one_leg_route("buy", "BTC", "USDT", 0.1, 100.0);
OrderRouter::set_key(&mut route, "clientRequestedFrom", Value::Str("USDT".into()));
OrderRouter::set_key(&mut route, "clientRequestedTo", Value::Str("ETH".into()));
match r.build_execution_plan(&route, &Value::Null) {
Ok(_) => return Err("a route that produces the wrong asset is refused".to_string()),
Err(e) => {
if !e.message.contains("produces BTC, not the requested ETH") {
return Err(format!("wrong refusal for a produces mismatch: {e}"));
}
}
}
let mut route = one_leg_route("buy", "BTC", "USDT", 0.1, 100.0);
OrderRouter::set_key(&mut route, "clientRequestedFrom", Value::Str("EUR".into()));
OrderRouter::set_key(&mut route, "clientRequestedTo", Value::Str("BTC".into()));
match r.build_execution_plan(&route, &Value::Null) {
Ok(_) => return Err("a route that spends an unoffered asset is refused".to_string()),
Err(e) => {
if !e.message.contains("spends USDT, not the requested EUR") {
return Err(format!("wrong refusal for a spends mismatch: {e}"));
}
}
}
let mut route = one_leg_route("buy", "BTC", "USDT", 0.1, 100.0);
OrderRouter::set_key(&mut route, "clientRequestedFrom", Value::Str("USDT".into()));
OrderRouter::set_key(&mut route, "clientRequestedTo", Value::Str("BTC".into()));
let plan = r.build_execution_plan(&route, &Value::Null).map_err(|e| e.to_string())?;
if r.list_at(&plan, "steps").len() != 1 {
return Err("a coherent route still plans".to_string());
}
Ok(())
}
fn format_number_never_uses_exponents(r: &OrderRouter) -> Result<(), String> {
for probe in [0.0000001f64, 1234.5, 0.1, 1e17] {
let rendered = r.format_number(probe).map_err(|e| e.to_string())?;
if rendered.contains('e') || rendered.contains('E') {
return Err(format!("format_number emitted an exponent for {probe}: {rendered}"));
}
}
if r.format_number(0.0).map_err(|e| e.to_string())? != "0" {
return Err("zero renders as 0".to_string());
}
if r.format_number(1e18).is_ok() {
return Err("a number too large to render identically is refused".to_string());
}
Ok(())
}
fn route_url_is_deterministic(r: &OrderRouter) -> Result<(), String> {
let mut config = HashMap::new();
config.insert("apiKey".to_string(), Value::Str("k".to_string().into()));
config.insert("baseUrl".to_string(), Value::Str("https://example.test/api/".to_string().into()));
let client = OrderRouter::new(&Value::Map(config)).map_err(|e| e.to_string())?;
let mut params = HashMap::new();
params.insert("amountIn".to_string(), Value::Float(0.001));
params.insert("strategy".to_string(), Value::Str("split_capped".to_string().into()));
params.insert("maxVenues".to_string(), Value::Int(3));
params.insert(
"exchanges".to_string(),
Value::List(vec![Value::Str("binance".into()), Value::Str("kraken".into())]),
);
params.insert("certified".to_string(), Value::Bool(true));
let url = client
.build_route_url("usdt", "btc", &Value::Map(params))
.map_err(|e| e.to_string())?;
let expected = "https://example.test/api/route?from=USDT&to=BTC&amountIn=0.001&strategy=split_capped&maxVenues=3&exchanges=binance%2Ckraken&certified=true";
if url != expected {
return Err(format!("expected\n {expected}\ngot\n {url}"));
}
let empty = Value::Map(HashMap::new());
if r.build_route_url("USDT", "BTC", &empty).is_ok() {
return Err("neither amountIn nor amountOut is refused".to_string());
}
let mut both = HashMap::new();
both.insert("amountIn".to_string(), Value::Float(1.0));
both.insert("amountOut".to_string(), Value::Float(1.0));
if r.build_route_url("USDT", "BTC", &Value::Map(both)).is_ok() {
return Err("both amountIn and amountOut is refused".to_string());
}
let mut one = HashMap::new();
one.insert("amountIn".to_string(), Value::Float(1.0));
if r.build_route_url("", "BTC", &Value::Map(one)).is_ok() {
return Err("an empty fromAsset is refused".to_string());
}
Ok(())
}
fn encode_uri_component_matches_javascript(r: &OrderRouter) -> Result<(), String> {
let mut params = HashMap::new();
params.insert("amountIn".to_string(), Value::Float(1.0));
params.insert("bridges".to_string(), Value::Str("a!b'c(d)e*f g".to_string().into()));
let url = r
.build_route_url("USDT", "BTC", &Value::Map(params))
.map_err(|e| e.to_string())?;
if !url.contains("bridges=a!b'c(d)e*f%20g") {
return Err(format!("encodeURIComponent semantics, got {url}"));
}
let mut params = HashMap::new();
params.insert("amountIn".to_string(), Value::Float(1.0));
params.insert("balanceMode".to_string(), Value::Str("cap:strict".to_string().into()));
let url = r
.build_route_url("USDT", "BTC", &Value::Map(params))
.map_err(|e| e.to_string())?;
if !url.contains("balanceMode=cap%3Astrict") {
return Err(format!("a colon is escaped, got {url}"));
}
Ok(())
}
fn stream_url_and_close_codes(r: &OrderRouter) -> Result<(), String> {
let mut config = HashMap::new();
config.insert("apiKey".to_string(), Value::Str("k".to_string().into()));
config.insert("baseUrl".to_string(), Value::Str("https://example.test/api".to_string().into()));
let streamer = OrderRouter::new(&Value::Map(config)).map_err(|e| e.to_string())?;
let mut params = HashMap::new();
params.insert("amountIn".to_string(), Value::Float(0.001));
params.insert("strategy".to_string(), Value::Str("split_capped".to_string().into()));
params.insert("maxVenues".to_string(), Value::Int(3));
params.insert(
"exchanges".to_string(),
Value::List(vec![Value::Str("binance".into()), Value::Str("kraken".into())]),
);
params.insert("certified".to_string(), Value::Bool(true));
let url = streamer
.stream_url("usdt", "btc", &Value::Map(params))
.map_err(|e| e.to_string())?;
let expected = "wss://example.test/api/stream/route?from=USDT&to=BTC&amountIn=0.001&strategy=split_capped&maxVenues=3&exchanges=binance%2Ckraken&certified=true";
if url != expected {
return Err(format!("expected\n {expected}\ngot\n {url}"));
}
if url.contains("includeQuotes") {
return Err("includeQuotes is left to the endpoint default".to_string());
}
let mut plain_config = HashMap::new();
plain_config.insert("apiKey".to_string(), Value::Str("k".to_string().into()));
plain_config.insert("baseUrl".to_string(), Value::Str("http://localhost:8080".to_string().into()));
let insecure = OrderRouter::new(&Value::Map(plain_config)).map_err(|e| e.to_string())?;
let mut one = HashMap::new();
one.insert("amountIn".to_string(), Value::Float(1.0));
let plain = insecure
.stream_url("USDT", "BTC", &Value::Map(one.clone()))
.map_err(|e| e.to_string())?;
if !plain.starts_with("ws://localhost:8080/stream/route?") {
return Err(format!("http becomes ws, got {plain}"));
}
let mut with_balances = one.clone();
with_balances.insert("balances".to_string(), Value::Str("binance.USDT:1000".to_string().into()));
if streamer.stream_url("USDT", "BTC", &Value::Map(with_balances)).is_ok() {
return Err("balances are refused on the stream".to_string());
}
let mut with_mode = one.clone();
with_mode.insert("balanceMode".to_string(), Value::Str("require".to_string().into()));
if streamer.stream_url("USDT", "BTC", &Value::Map(with_mode)).is_ok() {
return Err("balanceMode is refused with them".to_string());
}
if streamer.stream_url("USDT", "BTC", &Value::Map(HashMap::new())).is_ok() {
return Err("neither amount is refused".to_string());
}
if streamer.stream_url("", "BTC", &Value::Map(one)).is_ok() {
return Err("an empty fromAsset is refused".to_string());
}
let mut refusal_frame = HashMap::new();
refusal_frame.insert(
"error".to_string(),
Value::Str("exact_out_multi_hop_unsupported".to_string().into()),
);
match r.stream_close_error(1008, &Value::Map(refusal_frame)) {
Some(e) => {
if e.kind != "BadRequest" || !e.to_string().contains("exact_out_multi_hop_unsupported") {
return Err(format!("1008 is the same refusal a 400 is, got {e}"));
}
}
None => return Err("1008 must refuse".to_string()),
}
let mut cold_frame = HashMap::new();
cold_frame.insert("error".to_string(), Value::Str("cache is cold".to_string().into()));
cold_frame.insert("bookCount".to_string(), Value::Int(12));
cold_frame.insert("freshCount".to_string(), Value::Int(0));
cold_frame.insert("minFreshBooksForReady".to_string(), Value::Int(1));
match r.stream_close_error(1013, &Value::Map(cold_frame)) {
Some(e) => {
if e.kind != "ExchangeNotAvailable" || !e.to_string().contains("0 of 12 books fresh") {
return Err(format!("1013 is a cold cache, got {e}"));
}
}
None => return Err("1013 must refuse".to_string()),
}
if r.stream_close_error(1000, &Value::Map(HashMap::new())).is_some() {
return Err("a clean close is not an error".to_string());
}
match r.stream_close_error(1011, &Value::Map(HashMap::new())) {
Some(e) if e.kind == "ExchangeNotAvailable" => {}
other => return Err(format!("an unexpected close raises, got {other:?}")),
}
if r.stream_handshake_error("Unexpected server response: 401").kind != "AuthenticationError" {
return Err("401 at the handshake is an auth error".to_string());
}
if r.stream_handshake_error("Unexpected server response: 429").kind != "RateLimitExceeded" {
return Err("429 at the handshake is a rate limit".to_string());
}
Ok(())
}
fn balances_echo_is_verified(r: &OrderRouter) -> Result<(), String> {
let asked = |balances: &str| -> Value {
let mut params = HashMap::new();
params.insert("balances".to_string(), Value::Str(balances.to_string().into()));
Value::Map(params)
};
let empty_route = Value::Map(HashMap::new());
if r.assert_balances_applied(&empty_route, &asked("binance.USDT:1000")).is_ok() {
return Err("a non-empty wallet the server ignored must be refused".to_string());
}
if r.assert_balances_applied(&empty_route, &asked("")).is_ok() {
return Err("an EMPTY wallet the server ignored must be refused".to_string());
}
let mut echoed = HashMap::new();
echoed.insert("balancesApplied".to_string(), Value::Str("binance.USDT:1000".to_string().into()));
if r.assert_balances_applied(&Value::Map(echoed), &asked("binance.USDT:1000")).is_err() {
return Err("an echoed wallet is accepted".to_string());
}
let mut counted = HashMap::new();
counted.insert("balanceEntryCount".to_string(), Value::Int(0));
if r.assert_balances_applied(&Value::Map(counted), &asked("")).is_err() {
return Err("balanceEntryCount 0 confirms an empty wallet".to_string());
}
let mut opted = HashMap::new();
opted.insert("balances".to_string(), Value::Str("binance.USDT:1000".to_string().into()));
opted.insert("requireBalancesApplied".to_string(), Value::Bool(false));
if r.assert_balances_applied(&empty_route, &Value::Map(opted)).is_err() {
return Err("the opt-out is honoured".to_string());
}
Ok(())
}
fn fee_is_not_subtracted_twice(r: &OrderRouter) -> Result<(), String> {
let fixture = fixture()?;
let routes = r.dict_at(&fixture, "routes");
let route = r.dict_at(&routes, "multiHop");
let hops = r.list_at(&route, "hops");
let hop_zero = &hops[0];
let hop_one = &hops[1];
let hop_zero_out = r.number_at(hop_zero, "amountOut", 0.0);
let hop_zero_fee = r.number_at(hop_zero, "feeCost", 0.0);
if (hop_zero_out - (500.0 * 0.089 - hop_zero_fee)).abs() > TOLERANCE {
return Err(format!("the hop amountOut is net of its fee, got {hop_zero_out}"));
}
if (r.number_at(hop_one, "amountIn", 0.0) - hop_zero_out).abs() > TOLERANCE {
return Err("hop 1 was sized from the NET proceeds of hop 0".to_string());
}
let plan = r
.build_execution_plan(&route, &Value::Map(HashMap::new()))
.map_err(|e| e.to_string())?;
let steps = r.list_at(&plan, "steps");
let leg_fee = r.number_at(&r.list_at(hop_zero, "legs")[0], "feeCost", 0.0);
if (r.number_at(&steps[0], "expectedFeeCost", -1.0) - leg_fee).abs() > TOLERANCE {
return Err("the step carries the predicted fee".to_string());
}
let verdict = r
.reconcile_execution_step(&plan, 0, hop_zero_out)
.map_err(|e| e.to_string())?;
if (r.number_at(&verdict, "expectedOut", 0.0) - hop_zero_out).abs() > TOLERANCE {
return Err("expected equals what the router said the hop produces".to_string());
}
if r.number_at(&verdict, "shortfall", -1.0).abs() > TOLERANCE {
return Err("a perfect fill is not a shortfall".to_string());
}
if (r.number_at(&verdict, "scale", 0.0) - 1.0).abs() > TOLERANCE {
return Err("and does not resize anything".to_string());
}
for entry in r.list_at(&verdict, "resizedSteps") {
let before = r.number_at(&entry, "previousAmount", 0.0);
let after = r.number_at(&entry, "amount", 0.0);
if (before - after).abs() > TOLERANCE {
return Err("hop 1 keeps the size the router gave it".to_string());
}
}
if (r.number_at(&steps[0], "notionalQuote", 0.0) - 44.5).abs() > TOLERANCE {
return Err("the order notional stays gross".to_string());
}
if (r.step_expected_out(&steps[1]) - r.number_at(hop_one, "amountOut", 0.0)).abs() > TOLERANCE {
return Err("a buy is unaffected".to_string());
}
let mut hand = HashMap::new();
hand.insert("side".to_string(), Value::Str("sell".to_string().into()));
hand.insert("amount".to_string(), Value::Float(10.0));
hand.insert("expectedPrice".to_string(), Value::Float(2.0));
if (r.step_expected_out(&Value::Map(hand)) - 20.0).abs() > TOLERANCE {
return Err("a hand-built plan is unchanged".to_string());
}
Ok(())
}
fn route_body_carries_the_holdings_and_the_url_never_does(r: &OrderRouter) -> Result<(), String> {
let mut params = HashMap::new();
params.insert("amountIn".to_string(), Value::Float(10.0));
params.insert("balances".to_string(), Value::Str("binance.USDT:1000,binance.BTC:1".to_string().into()));
params.insert("certified".to_string(), Value::Bool(true));
params.insert("maxVenues".to_string(), Value::Int(2));
let body = r
.build_route_body("usdt", "btc", &Value::Map(params))
.map_err(|e| e.to_string())?;
if r.string_at(&body, "from", "") != "USDT" || r.string_at(&body, "to", "") != "BTC" {
return Err("the body carries from and to, uppercased".to_string());
}
if r.string_at(&body, "balances", "") != "binance.USDT:1000,binance.BTC:1" {
return Err("the body carries the holdings verbatim, unescaped".to_string());
}
let encoded = body.to_json().to_string();
for expected in ["\"amountIn\":10.0", "\"certified\":true", "\"maxVenues\":2"] {
if !encoded.contains(expected) {
return Err(format!("{expected} in the encoded body, got {encoded}"));
}
}
if encoded.contains("\"amountIn\":\"") {
return Err(format!("amountIn must not be quoted into a string, got {encoded}"));
}
let empty = Value::Map(HashMap::new());
if r.build_route_body("USDT", "BTC", &empty).is_ok() {
return Err("neither amountIn nor amountOut is refused".to_string());
}
Ok(())
}
fn stub_fee(cost: f64, currency: &str) -> Value {
let mut fee = HashMap::new();
fee.insert("cost".to_string(), Value::Float(cost));
fee.insert("currency".to_string(), Value::Str(currency.to_string().into()));
Value::Map(fee)
}
fn fixture_format_number(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "formatNumberCases")? {
let id = text(&test_case, "id");
let value = at(&test_case, "value")
.and_then(as_number)
.ok_or_else(|| format!("formatNumberCase {id}: no value"))?;
let expected = text(&test_case, "expected");
let actual = r.format_number(value).map_err(|e| e.to_string())?;
if actual != expected {
return Err(format!("formatNumberCase {id}: expected {expected}, got {actual}"));
}
}
Ok(())
}
fn fee_netting_route(side: &str, base_code: &str, quote: &str, amount: f64, price: f64) -> Value {
let buying = side == "buy";
let amount_in = if buying { amount * price } else { amount };
let amount_out = if buying { amount } else { amount * price };
let mut leg = HashMap::new();
leg.insert("exchangeId".to_string(), Value::Str("stub".into()));
leg.insert("amount".to_string(), Value::Float(amount));
leg.insert("averagePrice".to_string(), Value::Float(price));
leg.insert("takerFeeRate".to_string(), Value::Float(0.0));
leg.insert("feeCost".to_string(), Value::Float(0.0));
leg.insert("effectivePrice".to_string(), Value::Float(price));
let mut hop = HashMap::new();
hop.insert("pair".to_string(), Value::Str(format!("{base_code}/{quote}").into()));
hop.insert("side".to_string(), Value::Str(side.to_string().into()));
hop.insert("base".to_string(), Value::Str(base_code.to_string().into()));
hop.insert("quote".to_string(), Value::Str(quote.to_string().into()));
hop.insert("amountIn".to_string(), Value::Float(amount_in));
hop.insert("amountOut".to_string(), Value::Float(amount_out));
hop.insert("legs".to_string(), Value::List(vec![Value::Map(leg)]));
hop.insert("fullyFillable".to_string(), Value::Bool(true));
let mut route = HashMap::new();
route.insert("requestId".to_string(), next_test_request_id());
route.insert("from".to_string(), Value::Str((if buying { quote.to_string() } else { base_code.to_string() }).into()));
route.insert("to".to_string(), Value::Str((if buying { base_code.to_string() } else { quote.to_string() }).into()));
route.insert("strategy".to_string(), Value::Str("best_single".into()));
route.insert("exactSide".to_string(), Value::Str("in".into()));
route.insert("amountIn".to_string(), Value::Float(amount_in));
route.insert("amountOut".to_string(), Value::Float(amount_out));
route.insert("fullyFillable".to_string(), Value::Bool(true));
route.insert("fillRatio".to_string(), Value::Float(1.0));
route.insert("hops".to_string(), Value::List(vec![Value::Map(hop)]));
Value::Map(route)
}
fn fixture_fee_netting(r: &OrderRouter, f: &Value) -> Result<(), String> {
for test_case in cases(f, "feeNettingCases")? {
let id = text(&test_case, "id");
let route = fee_netting_route(
&text(&test_case, "side"),
&text(&test_case, "base"),
&text(&test_case, "quote"),
r.number_at(&test_case, "amount", 0.0),
r.number_at(&test_case, "price", 0.0),
);
let plan_options = at(&test_case, "planOptions").cloned().unwrap_or(Value::Null);
let plan = r.build_execution_plan(&route, &plan_options).map_err(|e| e.to_string())?;
let mut venue = StubVenue::new("stub");
let fee = at(&test_case, "fee").cloned().unwrap_or(Value::Null);
let currency = r.string_at(&fee, "currency", "");
if !currency.is_empty() {
venue.fee_to_charge = Some((r.number_at(&fee, "cost", 0.0), currency));
}
for entry in r.list_at(&test_case, "tradeFees") {
venue.trade_fees_to_charge.push((
r.number_at(&entry, "cost", 0.0),
r.string_at(&entry, "currency", ""),
));
}
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let steps = r.list_at(&report, "steps");
if steps.len() != 1 {
return Err(format!("feeNettingCase {id}: expected one step, got {}", steps.len()));
}
let step = &steps[0];
let expected = at(&test_case, "expected").cloned().unwrap_or(Value::Null);
for field in ["filledAmount", "grossOutAmount", "outAmount", "feeCost"] {
let actual = r.number_at(step, field, 0.0);
let want = r.number_at(&expected, field, 0.0);
if !numbers_match(actual, want) {
return Err(format!("feeNettingCase {id}: {field} expected {want}, got {actual}"));
}
}
}
Ok(())
}
fn two_hop_execute_options() -> Value {
let mut options = execute_options(true, "sequential");
let market = |symbol: &str, base_code: &str, quote: &str| {
let mut m = HashMap::new();
m.insert("symbol".to_string(), Value::Str(symbol.to_string().into()));
m.insert("base".to_string(), Value::Str(base_code.to_string().into()));
m.insert("quote".to_string(), Value::Str(quote.to_string().into()));
Value::Map(m)
};
let mut by_symbol = HashMap::new();
by_symbol.insert("BTC/USDT".to_string(), market("BTC/USDT", "BTC", "USDT"));
by_symbol.insert("BTC/ETH".to_string(), market("BTC/ETH", "BTC", "ETH"));
let mut markets = HashMap::new();
markets.insert("stub".to_string(), Value::Map(by_symbol));
OrderRouter::set_key(&mut options, "markets", Value::Map(markets));
let mut usd_rates = HashMap::new();
usd_rates.insert("USDT".to_string(), Value::Float(1.0));
usd_rates.insert("ETH".to_string(), Value::Float(10.0));
OrderRouter::set_key(&mut options, "usdRates", Value::Map(usd_rates));
options
}
fn on_step_sees_every_step_and_can_stop_the_route() -> Result<(), String> {
let mut r = router()?;
let plan = r.build_execution_plan(&two_hop_route(), &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
let steps_total = r.list_at(&plan, "steps").len();
let seen: StdArc<std::sync::Mutex<Vec<Value>>> = StdArc::new(std::sync::Mutex::new(Vec::new()));
let recorded = StdArc::clone(&seen);
r.set_on_step(std::sync::Arc::new(move |event: &Value| {
recorded.lock().unwrap().push(event.clone());
match event.as_map().and_then(|m| m.get("stepIndex")) {
Some(Value::Float(index)) if *index == 0.0 => "halt".to_string(),
_ => String::new(),
}
}));
let venue = StubVenue::new("stub");
let counter = StdArc::clone(&venue.orders_placed);
let venues = stub_venues(venue);
let report = block_on(r.execute(&plan, &venues, &two_hop_execute_options())).map_err(|e| e.to_string())?;
let events = seen.lock().unwrap().clone();
if events.len() != 1 {
return Err(format!("the hook is not called for steps that never ran, got {} calls", events.len()));
}
if r.number_at(&events[0], "stepIndex", -1.0) != 0.0 {
return Err("the event names the step".to_string());
}
if r.string_at(&events[0], "status", "") != "filled" {
return Err(format!("the event carries the outcome, got {}", r.string_at(&events[0], "status", "")));
}
if r.number_at(&events[0], "stepsRemaining", -1.0) != (steps_total - 1) as f64 {
return Err("the event says how much of the route is left".to_string());
}
if events[0].as_map().and_then(|m| m.get("reconciliation")).is_none() {
return Err("the verdict it is judging is in the event".to_string());
}
if !r.bool_at(&report, "halted", false) {
return Err("the hook stopped the route".to_string());
}
if r.string_at(&report, "haltReason", "") != "halted_by_on_step" {
return Err(format!("the halt names the hook, got {}", r.string_at(&report, "haltReason", "")));
}
if r.number_at(&report, "haltStepIndex", -1.0) != 0.0 {
return Err("and the step it halted at".to_string());
}
let results = r.list_at(&report, "steps");
if r.string_at(&results[1], "status", "") != "skipped" {
return Err("the rest of the route is skipped".to_string());
}
if r.number_at(&report, "ordersPlaced", -1.0) != 1.0 || counter.load(Ordering::SeqCst) != 1 {
return Err("the step after the halt was never placed".to_string());
}
Ok(())
}
fn an_on_step_that_panics_is_recorded_and_does_not_take_the_run_down() -> Result<(), String> {
let mut r = router()?;
let plan = one_leg_plan(&r)?;
r.set_on_step(std::sync::Arc::new(|_event: &Value| -> String {
panic!("hook is broken");
}));
let venues = stub_venues(StubVenue::new("stub"));
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let executed = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")));
std::panic::set_hook(previous);
let report = executed.map_err(|e| e.to_string())?;
if r.bool_at(&report, "halted", true) {
return Err("the route finished".to_string());
}
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "filled" {
return Err("and the order it placed is still reported".to_string());
}
let errors = r.list_at(&report, "errors");
let mut found = false;
for entry in &errors {
if r.string_at(entry, "code", "").starts_with("on_step_hook_failed") {
found = true;
}
}
if !found {
return Err(format!("the broken hook is reported rather than swallowed, got {errors:?}"));
}
Ok(())
}
fn on_step_can_only_narrow_and_cannot_resume_a_halted_route() -> Result<(), String> {
let mut r = router()?;
let plan = r.build_execution_plan(&two_hop_route(), &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
r.set_on_step(std::sync::Arc::new(|_event: &Value| "continue".to_string()));
let mut starved = StubVenue::new("stub");
starved.fill_ratio = 0.1;
let counter = StdArc::clone(&starved.orders_placed);
let venues = stub_venues(starved);
let report = block_on(r.execute(&plan, &venues, &two_hop_execute_options())).map_err(|e| e.to_string())?;
if !r.bool_at(&report, "halted", false) {
return Err("the reconciliation halt stands".to_string());
}
if r.string_at(&report, "haltReason", "") != "shortfall_exceeds_tolerance" {
return Err(format!(
"the reconciliation reason survives, it is not replaced by the hook; got {}",
r.string_at(&report, "haltReason", "")
));
}
if r.number_at(&report, "ordersPlaced", -1.0) != 1.0 || counter.load(Ordering::SeqCst) != 1 {
return Err("the hook did not wave the route onward".to_string());
}
let results = r.list_at(&report, "steps");
if r.string_at(&results[1], "status", "") != "skipped" {
return Err("the second hop never ran".to_string());
}
Ok(())
}
fn retry_replaces_under_a_new_id_and_never_retries_an_unknown_outcome() -> Result<(), String> {
let r = router()?;
let plan = one_leg_plan(&r)?;
let relents = StubVenue::new("stub");
relents.fail_create_times.store(1, Ordering::SeqCst);
let seen = StdArc::clone(&relents.params_seen);
let venues = stub_venues(relents);
let mut options = options_with(
&execute_options(true, "sequential"),
"retryFailedSteps",
Value::Float(2.0),
);
options = options_with(&options, "retryDelayMs", Value::Float(0.0));
let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "filled" {
return Err(format!("the retry succeeded, got {}", r.string_at(&results[0], "status", "")));
}
if r.number_at(&results[0], "attempt", -1.0) != 1.0 {
return Err(format!("the report says which attempt won, got {}", r.number_at(&results[0], "attempt", -1.0)));
}
let params = seen.lock().unwrap().clone();
if params.len() != 2 {
return Err(format!("one rejection and one retry, got {} calls", params.len()));
}
for (index, params_seen) in params.iter().enumerate() {
let injected = r.string_at(params_seen, "clientOrderId", "");
if !injected.is_empty() {
return Err(format!("no client order id is injected, found {injected} on placement {index}"));
}
}
let plan2 = r
.build_execution_plan(&one_leg_route("buy", "BTC", "USDT", 0.2, 100.0), &Value::Map(HashMap::new()))
.map_err(|e| e.to_string())?;
let mut unknown = StubVenue::new("stub");
unknown.fail_with = Some("RequestTimeout");
let attempts = StdArc::clone(&unknown.orders_placed);
let venues = stub_venues(unknown);
let second_options = options_with(&options, "retryFailedSteps", Value::Float(5.0));
let second_report = block_on(r.execute(&plan2, &venues, &second_options)).map_err(|e| e.to_string())?;
let results = r.list_at(&second_report, "steps");
if r.string_at(&results[0], "status", "") != "outcome_unknown" {
return Err("a timed-out placement stays outcome_unknown".to_string());
}
if attempts.load(Ordering::SeqCst) != 1 {
return Err(format!(
"an order whose outcome is unknown may already be live; it is never re-placed, saw {} calls",
attempts.load(Ordering::SeqCst)
));
}
Ok(())
}
pub fn run() -> Result<usize, String> {
let f = fixture()?;
let r = router()?;
let mut passed = 0usize;
let checks: Vec<(&str, Box<dyn Fn() -> Result<(), String>>)> = vec![
("fixture: buildExecutionPlan", Box::new(|| fixture_build_execution_plan(&router()?, &fixture()?))),
("fixture: buildExecutionPlan is deterministic and does not mutate its input", Box::new(|| fixture_plan_is_deterministic(&router()?, &fixture()?))),
("fixture: checkExecutionPlanSafety", Box::new(|| fixture_check_execution_plan_safety(&router()?, &fixture()?))),
("fixture: reconcileExecutionStep", Box::new(|| fixture_reconcile_execution_step(&router()?, &fixture()?))),
("fixture: a sequence of reconciliations on one hop", Box::new(|| fixture_reconcile_sequence(&router()?, &fixture()?))),
("fixture: buildUnwindPlan", Box::new(|| fixture_build_unwind_plan(&router()?, &fixture()?))),
("a buy-side unwind order never spends more quote than the residual actually holds", Box::new(|| unwind_buy_is_fundable(&router()?, &fixture()?))),
("fixture: numberAt reads one number grammar in all six languages", Box::new(|| fixture_number_at(&router()?, &fixture()?))),
("fixture: formatNumber spells one number one way in all six languages", Box::new(|| fixture_format_number(&router()?, &fixture()?))),
("fixture: a fee in the acquired asset resizes what the next hop is sized on", Box::new(|| fixture_fee_netting(&router()?, &fixture()?))),
("constructor: the service is public, and maxNotionalUsd is an opt-in guardrail at any size", Box::new(constructor_guards)),
("userAgent is sent as User-Agent only when configured", Box::new(user_agent_is_sent_only_when_configured)),
("a hand-built plan carrying only the required fields is executable", Box::new(|| a_hand_built_plan_with_only_the_required_fields_is_executable(&router()?))),
("the derived limit price and notional follow amount and expectedPrice", Box::new(|| derived_limit_price_and_notional_follow_amount_and_expected_price(&router()?))),
("the limit price sits on the side that costs you, and only there", Box::new(|| limit_price_side(&router()?))),
("an empty plan is not a safe plan", Box::new(|| empty_plan_is_not_safe(&router()?))),
("a cap that IS set binds exactly, at whatever size, and includes the slippage", Box::new(|| a_cap_that_is_set_binds_exactly(&router()?))),
("with no cap set, no notional check runs at all", Box::new(|| with_no_cap_no_notional_check_runs(&router()?))),
("a per-call cap overrides the client-level one, in both directions", Box::new(a_per_call_cap_overrides_the_client_one)),
("USDT is not assumed to be one dollar, and an unvaluable step blocks only under a cap", Box::new(|| usdt_is_not_a_dollar(&router()?))),
("a route that does not match the question asked is refused", Box::new(|| refuses_incoherent_routes(&router()?))),
("formatNumber never emits exponent notation", Box::new(|| format_number_never_uses_exponents(&router()?))),
("fetchRoute builds a deterministic query", Box::new(|| route_url_is_deterministic(&router()?))),
("the query escaping is encodeURIComponent's, not form-urlencoded's", Box::new(|| encode_uri_component_matches_javascript(&router()?))),
("a route carrying balances is POSTed, and the holdings never appear in the url", Box::new(|| route_body_carries_the_holdings_and_the_url_never_does(&router()?))),
("a fee the router already subtracted is not subtracted a second time", Box::new(|| fee_is_not_subtracted_twice(&router()?))),
("a router that ignored the balances is caught, including when the wallet is empty", Box::new(|| balances_echo_is_verified(&router()?))),
("streamUrl upgrades the scheme, and close codes keep the REST vocabulary", Box::new(|| stream_url_and_close_codes(&router()?))),
("balances accept the shape a caller actually writes", Box::new(|| balances_shapes(&router()?))),
("plan-shaping options with a built plan are refused, not ignored", Box::new(|| plan_shaping_refused(&router()?))),
("execute: a rehearsal is asked for by dryRun and places nothing", Box::new(|| dry_run_places_nothing(&router()?))),
("options.live is refused, not ignored: the old knob cannot silently place orders", Box::new(|| live_option_is_refused(&router()?))),
("watchRoute applies the same venue filter fetchRoute does", Box::new(|| stream_url_applies_the_venue_filter(&router()?))),
("joinBalances spells an unqualified holding without a leading dot", Box::new(|| join_balances_separator(&router()?))),
("execute: an unknown strategy is refused even in dry run", Box::new(|| an_unknown_strategy_is_refused_even_in_dry_run(&router()?))),
("execute: sequential places IOC limit orders in plan order", Box::new(|| sequential_places_and_fills(&router()?))),
("execute: a failure BEFORE dispatch records no open order", Box::new(|| a_failure_before_dispatch_records_no_open_order(&router()?))),
("execute: a createOrder that times out is outcome-unknown, not a plain failure", Box::new(|| a_timeout_is_outcome_unknown_not_a_plain_failure(&router()?))),
("execute: a definite rejection stays a plain failure and reports no open order", Box::new(|| a_definite_rejection_stays_a_plain_failure(&router()?))),
("execute: a throttled request is a plain failure, not a possibly-live order", Box::new(|| a_rate_limit_rejection_is_a_plain_failure(&router()?))),
("execute: limit_protected refuses a non-positive pollIntervalMs before placing anything", Box::new(|| limit_protected_refuses_a_zero_poll_interval(&router()?))),
("execute: a fill that stays unknown after the re-read halts instead of guessing", Box::new(|| a_fill_that_stays_unknown_halts_instead_of_guessing(&router()?))),
("execute: refuses to go live above a cap the caller set", Box::new(|| execute_refuses_to_go_live_above_the_cap(&router()?))),
("execute: the same trade goes through when nobody asked for a cap", Box::new(|| execute_places_the_same_trade_with_no_cap(&router()?))),
("execute: a resting order is cancelled, and a cancel that fails halts the route", Box::new(|| a_resting_order_is_cancelled(&router()?))),
("execute: a throw after createOrder still reports the id and an open order", Box::new(|| a_known_order_id_survives_a_throw_after_create(&router()?))),
("execute: a spend the venue DID report survives an unknown fill", Box::new(|| a_reported_spend_survives_an_unknown_fill(&router()?))),
("execute: a report is summarised in the assets it names, not across currencies", Box::new(|| a_report_is_summarised_in_the_assets_it_names(&router()?))),
("execute: a plan carries its age, and a stale one is refused only when asked", Box::new(|| plan_age_is_reported_and_refused_only_when_asked(&router()?))),
("execute: a market order and a notional cap are refused together", Box::new(|| a_market_order_and_a_cap_are_refused_together(&router()?))),
("execute: atomic_ish demands the whole route pre-funded", Box::new(|| atomic_ish_demands_the_whole_route_prefunded(&router()?))),
("execute: best_effort demands both of its acknowledgements", Box::new(|| best_effort_demands_its_acknowledgements(&router()?))),
("execute: a live plan with no identity is refused, and an idempotencyKey supplies one", Box::new(|| live_requires_an_identity(&router()?))),
("execute: no clientOrderId is injected, and a caller-supplied one travels untouched", Box::new(|| client_order_id_is_never_injected(&router()?))),
("execute: the same plan is refused on a second live execution unless the caller opts in", Box::new(|| reexecution_is_refused(&router()?))),
("execute: a dry run never consumes a plan, and a halted live run always does", Box::new(|| a_dry_run_does_not_consume_a_plan(&router()?))),
("execute: onStep sees every step and can stop the route", Box::new(on_step_sees_every_step_and_can_stop_the_route)),
("execute: an onStep that panics is recorded, and does not take the run down with it", Box::new(an_on_step_that_panics_is_recorded_and_does_not_take_the_run_down)),
("execute: onStep can only narrow — it cannot resume a route the reconciliation already halted", Box::new(on_step_can_only_narrow_and_cannot_resume_a_halted_route)),
("execute: retryFailedSteps re-places a rejected step under a NEW client order id, and never retries an unknown outcome", Box::new(retry_replaces_under_a_new_id_and_never_retries_an_unknown_outcome)),
("execute: the re-execution ledger is bounded, evicts oldest-first, and re-allows an evicted plan", Box::new(|| the_ledger_is_bounded(&router()?))),
];
let _ = (&f, &r);
for (name, check) in checks {
match check() {
Ok(()) => {
println!("ok {name}");
passed += 1;
}
Err(message) => return Err(format!("{name} — {message}")),
}
}
Ok(passed)
}
#[cfg(test)]
mod tests {
#[test]
fn order_router_matches_the_shared_fixture() {
match super::run() {
Ok(passed) => assert!(passed > 0, "the suite ran no checks"),
Err(message) => panic!("{message}"),
}
}
}
use crate::order_router::RouterVenue;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc as StdArc;
struct StubVenue {
id: String,
supports_ioc: bool,
orders_placed: StdArc<AtomicUsize>,
fail_with: Option<&'static str>,
omit_filled: bool,
created_open: bool,
reread_cost: Option<(f64, f64)>,
free_balances: Option<Vec<(String, f64)>>,
cancel_fails: bool,
cancels: StdArc<AtomicUsize>,
reread_order: Option<(String, f64, f64, f64)>,
fee_to_charge: Option<(f64, String)>,
trade_fees_to_charge: Vec<(f64, String)>,
params_seen: StdArc<std::sync::Mutex<Vec<Value>>>,
fail_create_times: StdArc<AtomicUsize>,
fill_ratio: f64,
}
impl StubVenue {
fn new(id: &str) -> Self {
StubVenue {
id: id.to_string(),
supports_ioc: true,
orders_placed: StdArc::new(AtomicUsize::new(0)),
fail_with: None,
omit_filled: false,
created_open: false,
reread_cost: None,
free_balances: None,
cancel_fails: false,
cancels: StdArc::new(AtomicUsize::new(0)),
reread_order: None,
fee_to_charge: None,
trade_fees_to_charge: Vec::new(),
params_seen: StdArc::new(std::sync::Mutex::new(Vec::new())),
fail_create_times: StdArc::new(AtomicUsize::new(0)),
fill_ratio: 1.0,
}
}
}
#[async_trait::async_trait]
impl RouterVenue for StubVenue {
fn id(&self) -> String {
self.id.clone()
}
fn amount_to_precision(&self, _symbol: &str, amount: f64) -> String {
format!("{amount}")
}
fn price_to_precision(&self, _symbol: &str, price: f64) -> String {
format!("{price}")
}
fn supports_ioc(&self) -> bool {
self.supports_ioc
}
async fn create_order(
&self,
_symbol: &str,
_order_type: &str,
_side: &str,
amount: f64,
price: f64,
params: &Value,
) -> Result<Value, crate::error::ExchangeError> {
self.orders_placed.fetch_add(1, Ordering::SeqCst);
self.params_seen.lock().unwrap().push(params.clone());
if let Some(kind) = self.fail_with {
return Err(crate::error::ExchangeError::new(kind, "stub refuses"));
}
if self.fail_create_times.load(Ordering::SeqCst) > 0 {
self.fail_create_times.fetch_sub(1, Ordering::SeqCst);
return Err(crate::error::ExchangeError::new("ExchangeError", "stub refuses, for now"));
}
let mut order = HashMap::new();
order.insert("id".to_string(), Value::Str("stub-1".to_string().into()));
if let Value::Dict(given) = params {
if let Some(client_order_id) = given.get("clientOrderId") {
order.insert("clientOrderId".to_string(), client_order_id.clone());
}
}
if self.created_open {
order.insert("status".to_string(), Value::Str("open".to_string().into()));
} else {
order.insert("status".to_string(), Value::Str("closed".to_string().into()));
}
if !self.omit_filled {
let filled = amount * self.fill_ratio;
order.insert("filled".to_string(), Value::Float(filled));
order.insert("average".to_string(), Value::Float(price));
order.insert("cost".to_string(), Value::Float(filled * price));
}
if let Some((cost, currency)) = &self.fee_to_charge {
order.insert("fee".to_string(), stub_fee(*cost, currency));
}
if !self.trade_fees_to_charge.is_empty() {
let mut trades = Vec::new();
for (cost, currency) in &self.trade_fees_to_charge {
let mut trade = HashMap::new();
trade.insert("fee".to_string(), stub_fee(*cost, currency));
trades.push(Value::Map(trade));
}
order.insert("trades".to_string(), Value::List(trades));
}
Ok(Value::Map(order))
}
async fn fetch_order(&self, _id: &str, _symbol: &str) -> Result<Value, crate::error::ExchangeError> {
if let Some((status, filled, average, cost)) = &self.reread_order {
let mut order = HashMap::new();
order.insert("id".to_string(), Value::Str("stub-1".to_string().into()));
order.insert("status".to_string(), Value::Str(status.clone().into()));
order.insert("filled".to_string(), Value::Float(*filled));
order.insert("average".to_string(), Value::Float(*average));
order.insert("cost".to_string(), Value::Float(*cost));
return Ok(Value::Map(order));
}
if self.omit_filled {
let mut order = HashMap::new();
order.insert("id".to_string(), Value::Str("stub-1".to_string().into()));
order.insert("status".to_string(), Value::Str("closed".to_string().into()));
if let Some((cost, average)) = self.reread_cost {
order.insert("cost".to_string(), Value::Float(cost));
order.insert("average".to_string(), Value::Float(average));
}
return Ok(Value::Map(order));
}
Err(crate::error::ExchangeError::new("ExchangeError", "stub cannot read the order back"))
}
async fn cancel_order(&self, _id: &str, _symbol: &str) -> Result<Value, crate::error::ExchangeError> {
self.cancels.fetch_add(1, Ordering::SeqCst);
if self.cancel_fails {
return Err(crate::error::ExchangeError::new("ExchangeError", "stub refuses to cancel"));
}
Ok(Value::Map(HashMap::new()))
}
async fn fetch_balance(&self) -> Result<Value, crate::error::ExchangeError> {
let mut free = HashMap::new();
match &self.free_balances {
Some(entries) => {
for (asset, amount) in entries {
free.insert(asset.clone(), Value::Float(*amount));
}
}
None => {
free.insert("USDT".to_string(), Value::Float(1_000_000.0));
free.insert("BTC".to_string(), Value::Float(1_000_000.0));
free.insert("ETH".to_string(), Value::Float(1_000_000.0));
}
}
let mut balance = HashMap::new();
balance.insert("free".to_string(), Value::Map(free));
Ok(Value::Map(balance))
}
}
fn one_leg_plan(r: &OrderRouter) -> Result<Value, String> {
let route = one_leg_route("buy", "BTC", "USDT", 0.2, 100.0);
r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())
}
fn block_on<F: std::future::Future>(future: F) -> F::Output {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("a tokio runtime")
.block_on(future)
}
fn execute_options(live: bool, strategy: &str) -> Value {
let mut usd_rates = HashMap::new();
usd_rates.insert("USDT".to_string(), Value::Float(1.0));
let mut market = HashMap::new();
market.insert("symbol".to_string(), Value::Str("BTC/USDT".to_string().into()));
market.insert("base".to_string(), Value::Str("BTC".to_string().into()));
market.insert("quote".to_string(), Value::Str("USDT".to_string().into()));
let mut by_symbol = HashMap::new();
by_symbol.insert("BTC/USDT".to_string(), Value::Map(market));
let mut markets = HashMap::new();
markets.insert("stub".to_string(), Value::Map(by_symbol));
let mut options = HashMap::new();
options.insert("strategy".to_string(), Value::Str(strategy.to_string().into()));
options.insert("dryRun".to_string(), Value::Bool(!live));
options.insert("usdRates".to_string(), Value::Map(usd_rates));
options.insert("markets".to_string(), Value::Map(markets));
Value::Map(options)
}
fn balances_shapes(r: &OrderRouter) -> Result<(), String> {
let mut inner = HashMap::new();
inner.insert("USDT".to_string(), Value::Float(100.0));
inner.insert("BTC".to_string(), Value::Float(0.5));
let mut nested = HashMap::new();
nested.insert("mexc".to_string(), Value::Map(inner));
let rendered = r.render_balances(&Value::Map(nested)).map_err(|e| e.to_string())?;
if rendered != "mexc.BTC:0.5,mexc.USDT:100" {
return Err(format!("the nested wallet renders sorted, got {rendered}"));
}
let mut flat = HashMap::new();
flat.insert("USDT".to_string(), Value::Float(100.0));
let flat_text = r.render_balances(&Value::Map(flat)).map_err(|e| e.to_string())?;
if flat_text != "USDT:100" {
return Err(format!("a flat wallet renders without a venue, got {flat_text}"));
}
let passthrough = r
.render_balances(&Value::Str("mexc.USDT:100".to_string().into()))
.map_err(|e| e.to_string())?;
if passthrough != "mexc.USDT:100" {
return Err("a rendered string passes through untouched".to_string());
}
if r.render_balances(&Value::Float(12345.0)).is_ok() {
return Err("a number is not a wallet".to_string());
}
Ok(())
}
fn plan_shaping_refused(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let venue = StubVenue::new("stub");
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let mut options = match execute_options(true, "sequential").as_map() {
Some(map) => map.clone(),
None => HashMap::new(),
};
options.insert("slippageBps".to_string(), Value::Float(1000.0));
match block_on(r.execute(&plan, &venues, &Value::Map(options))) {
Err(e) if e.message.contains("slippageBps") => Ok(()),
Err(e) => Err(format!("wrong refusal: {e}")),
Ok(_) => Err("shaping an already-built plan is refused".to_string()),
}
}
fn live_option_is_refused(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let venue = StubVenue::new("stub");
let counter = StdArc::clone(&venue.orders_placed);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
for flag in [false, true] {
let mut options = execute_options(true, "sequential").as_map().cloned().unwrap_or_default();
options.shift_remove("dryRun");
options.insert("live".to_string(), Value::Bool(flag));
match block_on(r.execute(&plan, &venues, &Value::map(options))) {
Ok(_) => return Err(format!("options.live = {flag} must be refused, not ignored")),
Err(error) => {
if !error.to_string().contains("options.live is gone") {
return Err(format!("the refusal must name the replacement, got {error}"));
}
}
}
}
if counter.load(Ordering::SeqCst) != 0 {
return Err("refused before a single order reached the venue".to_string());
}
Ok(())
}
fn stream_url_applies_the_venue_filter(_r: &OrderRouter) -> Result<(), String> {
let mut config = HashMap::new();
config.insert("baseUrl".to_string(), Value::Str("https://example.test/api".to_string().into()));
let mut held = OrderRouter::new(&Value::Map(config)).map_err(|e| e.to_string())?;
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(StubVenue::new("stub")));
venues.insert("other".to_string(), Box::new(StubVenue::new("other")));
held.set_venues(venues);
let mut params = HashMap::new();
params.insert("amountIn".to_string(), Value::Float(1.0));
let url = held
.stream_url("USDT", "BTC", &Value::Map(params.clone()))
.map_err(|e| e.to_string())?;
if !url.contains("exchanges=other%2Cstub") {
return Err(format!("the held venues are the default filter, got {url}"));
}
let mut explicit = params.clone();
explicit.insert("exchanges".to_string(), Value::List(vec![Value::Str("kraken".into())]));
let chosen = held
.stream_url("USDT", "BTC", &Value::Map(explicit))
.map_err(|e| e.to_string())?;
if !chosen.contains("kraken") || chosen.contains("stub") {
return Err(format!("an explicit exchanges parameter wins, got {chosen}"));
}
held.clear_venues();
let plain = held
.stream_url("USDT", "BTC", &Value::Map(params))
.map_err(|e| e.to_string())?;
if plain.contains("exchanges=") {
return Err(format!("a router holding nothing adds nothing, got {plain}"));
}
Ok(())
}
fn join_balances_separator(r: &OrderRouter) -> Result<(), String> {
let mut unqualified = HashMap::new();
unqualified.insert("asset".to_string(), Value::Str("USDT".to_string().into()));
unqualified.insert("amount".to_string(), Value::Float(100.0));
let bare = r
.join_balances(&[Value::Map(unqualified)])
.map_err(|e| e.to_string())?;
if bare != "USDT:100" {
return Err(format!("an unqualified holding carries no leading dot, got {bare}"));
}
let mut qualified = HashMap::new();
qualified.insert("exchangeId".to_string(), Value::Str("mexc".to_string().into()));
qualified.insert("asset".to_string(), Value::Str("USDT".to_string().into()));
qualified.insert("amount".to_string(), Value::Float(100.0));
let scoped = r
.join_balances(&[Value::Map(qualified)])
.map_err(|e| e.to_string())?;
if scoped != "mexc.USDT:100" {
return Err(format!("a qualified one does, got {scoped}"));
}
Ok(())
}
fn dry_run_places_nothing(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let venue = StubVenue::new("stub");
let counter = StdArc::clone(&venue.orders_placed);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(false, "sequential")))
.map_err(|e| e.to_string())?;
if counter.load(Ordering::SeqCst) != 0 {
return Err("a non-live execute placed an order".to_string());
}
if r.string_at(&report, "strategy", "") != "sequential" {
return Err("the strategy survives the rehearsal: how is not what".to_string());
}
if !r.bool_at(&report, "dryRun", false) {
return Err("the report must say it was a dry run".to_string());
}
if r.number_at(&report, "wouldPlaceOrders", 0.0) != 1.0 {
return Err("a dry run reports what it would have placed".to_string());
}
Ok(())
}
fn an_unknown_strategy_is_refused_even_in_dry_run(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
let outcome = block_on(r.execute(&plan, &venues, &execute_options(false, "sideways")));
match outcome {
Err(e) if e.message.contains("unknown execution strategy") => Ok(()),
Err(e) => Err(format!("wrong refusal: {e}")),
Ok(_) => Err("an unknown strategy is refused before anything else".to_string()),
}
}
fn sequential_places_and_fills(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let venue = StubVenue::new("stub");
let counter = StdArc::clone(&venue.orders_placed);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
if counter.load(Ordering::SeqCst) != 1 {
return Err(format!("expected 1 order, placed {}", counter.load(Ordering::SeqCst)));
}
let results = r.list_at(&report, "steps");
let status = r.string_at(&results[0], "status", "");
if status != "filled" {
return Err(format!("expected filled, got {status}"));
}
if !r.bool_at(&results[0], "placementAttempted", false) {
return Err("a dispatched order records placementAttempted".to_string());
}
Ok(())
}
fn a_failure_before_dispatch_records_no_open_order(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let venue = StubVenue::new("other");
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("other".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.bool_at(&results[0], "placementAttempted", true) {
return Err("nothing was dispatched, so placementAttempted must be false".to_string());
}
if r.string_at(&results[0], "errorCode", "") != "venue_missing" {
return Err("the missing venue is named".to_string());
}
if !r.list_at(&report, "openOrders").is_empty() {
return Err("a failure before dispatch records NO open order".to_string());
}
if r.string_at(&report, "haltReason", "") != "order_failed" {
return Err("a definite failure halts as order_failed".to_string());
}
Ok(())
}
fn a_timeout_is_outcome_unknown_not_a_plain_failure(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.fail_with = Some("RequestTimeout");
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "outcome_unknown" {
return Err(format!("expected outcome_unknown, got {}", r.string_at(&results[0], "status", "")));
}
if r.string_at(&report, "haltReason", "") != "outcome_unknown" {
return Err("the halt reason must not claim nothing_filled".to_string());
}
let open = r.list_at(&report, "openOrders");
if open.len() != 1 || r.string_at(&open[0], "reason", "") != "placement_unconfirmed" {
return Err("an unconfirmed placement is recorded".to_string());
}
Ok(())
}
fn a_definite_rejection_stays_a_plain_failure(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.fail_with = Some("ExchangeError");
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "failed" {
return Err("a definite rejection is a plain failure".to_string());
}
if !r.list_at(&report, "openOrders").is_empty() {
return Err("a definite rejection leaves no open order".to_string());
}
Ok(())
}
fn limit_protected_refuses_a_zero_poll_interval(r: &OrderRouter) -> Result<(), String> {
for interval in [0.0_f64, -1.0_f64] {
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.created_open = true;
let placed = StdArc::clone(&venue.orders_placed);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let mut options = execute_options(true, "limit_protected");
OrderRouter::set_key(&mut options, "orderTimeoutMs", Value::Float(4.0));
OrderRouter::set_key(&mut options, "pollIntervalMs", Value::Float(interval));
if block_on(r.execute(&plan, &venues, &options)).is_ok() {
return Err(format!("pollIntervalMs {interval} must be refused"));
}
if placed.load(Ordering::SeqCst) != 0 {
return Err("nothing may reach the venue".to_string());
}
}
Ok(())
}
fn a_rate_limit_rejection_is_a_plain_failure(r: &OrderRouter) -> Result<(), String> {
for kind in ["RateLimitExceeded", "DDoSProtection", "InvalidNonce"] {
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.fail_with = Some(kind);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
let status = r.string_at(&results[0], "status", "");
if status != "failed" {
return Err(format!("{kind} is the venue answering; expected failed, got {status}"));
}
if !r.list_at(&report, "openOrders").is_empty() {
return Err(format!("{kind} left an open order behind"));
}
}
for kind in ["RequestTimeout", "ExchangeNotAvailable", "NetworkError", "OnMaintenance"] {
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.fail_with = Some(kind);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
let status = r.string_at(&results[0], "status", "");
if status != "outcome_unknown" {
return Err(format!("{kind} may still have reached the venue; got {status}"));
}
}
Ok(())
}
fn a_fill_that_stays_unknown_halts_instead_of_guessing(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.omit_filled = true;
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "outcome_unknown" {
return Err(format!("expected outcome_unknown, got {}", r.string_at(&results[0], "status", "")));
}
let open = r.list_at(&report, "openOrders");
if open.len() != 1 || r.string_at(&open[0], "reason", "") != "fill_unconfirmed" {
return Err("the unconfirmed fill is recorded".to_string());
}
Ok(())
}
fn execute_refuses_to_go_live_above_the_cap(r: &OrderRouter) -> Result<(), String> {
let route = one_leg_route("buy", "BTC", "USDT", 1.0, 100.0);
let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
let venue = StubVenue::new("stub");
let counter = StdArc::clone(&venue.orders_placed);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let mut options = execute_options(true, "sequential");
OrderRouter::set_key(&mut options, "maxNotionalUsd", Value::Float(25.0));
let outcome = block_on(r.execute(&plan, &venues, &options));
match outcome {
Err(e) if e.message.contains("blocking safety violations") => {
if counter.load(Ordering::SeqCst) != 0 {
return Err("the cap must be refused BEFORE any order goes out".to_string());
}
Ok(())
}
Err(e) => Err(format!("wrong refusal: {e}")),
Ok(_) => Err("a 100 USD notional is over a 25 USD cap the caller set".to_string()),
}
}
fn execute_places_the_same_trade_with_no_cap(r: &OrderRouter) -> Result<(), String> {
let route = one_leg_route("buy", "BTC", "USDT", 1.0, 100.0);
let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
let venue = StubVenue::new("stub");
let counter = StdArc::clone(&venue.orders_placed);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
if counter.load(Ordering::SeqCst) != 1 {
return Err(format!("expected 1 order, placed {}", counter.load(Ordering::SeqCst)));
}
let results = r.list_at(&report, "steps");
let status = r.string_at(&results[0], "status", "");
if status != "filled" {
return Err(format!("100 USD is a normal trade when nobody asked for a cap, got {status}"));
}
let bare_venue = StubVenue::new("stub");
let bare_counter = StdArc::clone(&bare_venue.orders_placed);
let mut bare_venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
bare_venues.insert("stub".to_string(), Box::new(bare_venue));
let mut bare_options = execute_options(true, "sequential");
OrderRouter::set_key(&mut bare_options, "usdRates", Value::Map(HashMap::new()));
OrderRouter::set_key(&mut bare_options, "allowReexecution", Value::Bool(true));
let bare_report = block_on(r.execute(&plan, &bare_venues, &bare_options))
.map_err(|e| e.to_string())?;
if bare_counter.load(Ordering::SeqCst) != 1 {
return Err("no usdRates are needed when no cap was asked for".to_string());
}
let bare_results = r.list_at(&bare_report, "steps");
if r.string_at(&bare_results[0], "status", "") != "filled" {
return Err("the order fills without usdRates when no cap is set".to_string());
}
Ok(())
}
fn a_resting_order_is_cancelled(r: &OrderRouter) -> Result<(), String> {
for strategy in ["sequential", "parallel_within_hop", "best_effort"] {
let mut options = execute_options(true, strategy);
if strategy == "best_effort" {
OrderRouter::set_key(&mut options, "acknowledgeDispersion", Value::Bool(true));
OrderRouter::set_key(&mut options, "maxOrders", Value::Float(4.0));
}
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.created_open = true;
venue.reread_order = Some(("canceled".to_string(), 0.1, 100.0, 10.0));
let cancels = StdArc::clone(&venue.cancels);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
if cancels.load(Ordering::SeqCst) != 1 {
return Err(format!("{strategy}: the resting order is cancelled, not merely noted"));
}
if !r.list_at(&report, "openOrders").is_empty() {
return Err(format!("{strategy}: nothing is left resting after the cancel"));
}
let results = r.list_at(&report, "steps");
if !numbers_match(r.number_at(&results[0], "filledAmount", 0.0), 0.1) {
return Err(format!("{strategy}: the fill observed AFTER the cancel is the one reported"));
}
if text(&results[0], "status") != "partial" {
return Err(format!("{strategy}: a real partial fill, not an unknown"));
}
let plan2 = one_leg_plan(r)?;
let mut stubborn = StubVenue::new("stub");
stubborn.created_open = true;
stubborn.cancel_fails = true;
let mut venues2: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues2.insert("stub".to_string(), Box::new(stubborn));
let failed = block_on(r.execute(&plan2, &venues2, &options)).map_err(|e| e.to_string())?;
let failed_steps = r.list_at(&failed, "steps");
if text(&failed_steps[0], "status") != "outcome_unknown" {
return Err(format!("{strategy}: an uncancellable resting order is never a settled step"));
}
let open = r.list_at(&failed, "openOrders");
if open.len() != 1 || text(&open[0], "reason") != "cancel_failed" {
return Err(format!("{strategy}: the operator is told what is still live"));
}
let plan3 = one_leg_plan(r)?;
let mut ghost = StubVenue::new("stub");
ghost.created_open = true;
ghost.reread_order = Some(("open".to_string(), 0.0, 0.0, 0.0));
let mut venues3: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues3.insert("stub".to_string(), Box::new(ghost));
let ghosted = block_on(r.execute(&plan3, &venues3, &options)).map_err(|e| e.to_string())?;
let ghost_steps = r.list_at(&ghosted, "steps");
if text(&ghost_steps[0], "status") != "outcome_unknown" {
return Err(format!("{strategy}: a cancel the venue ignored leaves the outcome unknown"));
}
let ghost_open = r.list_at(&ghosted, "openOrders");
if ghost_open.len() != 1 || text(&ghost_open[0], "reason") != "still_open" {
return Err(format!("{strategy}: and it is reported as still open"));
}
}
Ok(())
}
fn a_known_order_id_survives_a_throw_after_create(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.created_open = true;
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let mut options = execute_options(true, "limit_protected");
OrderRouter::set_key(&mut options, "orderTimeoutMs", Value::Float(4.0));
OrderRouter::set_key(&mut options, "pollIntervalMs", Value::Float(1.0));
let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
let status = r.string_at(&results[0], "status", "");
if status != "outcome_unknown" {
return Err(format!("a known id means an order exists, so the step is outcome_unknown, got {status}"));
}
if r.string_at(&results[0], "orderId", "") != "stub-1" {
return Err("the id is captured the instant create_order returns, not after the read".to_string());
}
let open_orders = r.list_at(&report, "openOrders");
if open_orders.len() != 1 {
return Err(format!("a live order the caller cannot see is the worst outcome there is, got {open_orders:?}"));
}
if r.string_at(&open_orders[0], "orderId", "") != "stub-1"
|| r.string_at(&open_orders[0], "exchangeId", "") != "stub"
|| r.string_at(&open_orders[0], "reason", "") != "outcome_unknown" {
return Err(format!("the open order must name the venue, the id and why, got {open_orders:?}"));
}
if r.string_at(&report, "haltReason", "") != "outcome_unknown" {
return Err("the halt must name the ambiguity rather than claim an outright failure".to_string());
}
Ok(())
}
fn atomic_ish_demands_the_whole_route_prefunded(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let funded = StubVenue::new("stub");
let funded_counter = StdArc::clone(&funded.orders_placed);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(funded));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "atomic_ish")))
.map_err(|e| e.to_string())?;
if funded_counter.load(Ordering::SeqCst) != 1 {
return Err("a pre-funded route runs end to end".to_string());
}
if r.number_at(&report, "ordersPlaced", 0.0) != 1.0 {
return Err(format!("a pre-funded route places its order, got {report:?}"));
}
let mut broke = StubVenue::new("stub");
broke.free_balances = Some(vec![("USDT".to_string(), 1.0), ("BTC".to_string(), 0.0)]);
let broke_counter = StdArc::clone(&broke.orders_placed);
let mut poor_venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
poor_venues.insert("stub".to_string(), Box::new(broke));
let poor_options =
options_with(&execute_options(true, "atomic_ish"), "allowReexecution", Value::Bool(true));
match block_on(r.execute(&plan, &poor_venues, &poor_options)) {
Err(e) if e.message.contains("pre-funded") => {}
other => return Err(format!("an underfunded route must be refused, got {other:?}")),
}
if broke_counter.load(Ordering::SeqCst) != 0 {
return Err("the refusal must come before the first createOrder".to_string());
}
Ok(())
}
fn a_reported_spend_survives_an_unknown_fill(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let mut venue = StubVenue::new("stub");
venue.omit_filled = true;
venue.reread_cost = Some((10.5, 105.0));
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
let step = &results[0];
if r.string_at(step, "status", "") != "outcome_unknown" {
return Err(format!("the fill is still unknown, got {step:?}"));
}
if r.bool_at(step, "filledKnown", true) {
return Err("filledKnown must be false".to_string());
}
if r.string_at(step, "inAsset", "") != "USDT" {
return Err(format!("the asset actually spent must be named, got {step:?}"));
}
if (r.number_at(step, "inAmount", 0.0) - 10.5).abs() > 1e-9 {
return Err(format!("the amount the venue reported spending must survive, got {step:?}"));
}
if !r.bool_at(step, "costKnown", false) {
return Err("costKnown must be true: the venue really did report it".to_string());
}
if r.number_at(step, "outAmount", -1.0) != 0.0 {
return Err(format!("an unknown fill must not become a number, got {step:?}"));
}
if !r.bool_at(&report, "halted", false) || r.string_at(&report, "haltReason", "") != "outcome_unknown" {
return Err(format!("the route must halt on the ambiguity, got {report:?}"));
}
Ok(())
}
fn a_market_order_and_a_cap_are_refused_together(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let mut capped = StubVenue::new("stub");
capped.supports_ioc = false;
let capped_counter = StdArc::clone(&capped.orders_placed);
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(capped));
let mut options = execute_options(true, "sequential");
OrderRouter::set_key(&mut options, "allowMarketOrders", Value::Bool(true));
OrderRouter::set_key(&mut options, "maxNotionalUsd", Value::Float(1000.0));
let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "failed"
|| r.string_at(&results[0], "errorCode", "") != "NotSupported" {
return Err(format!("a market order under a cap must be refused, got {:?}", results[0]));
}
if capped_counter.load(Ordering::SeqCst) != 0 {
return Err("refused BEFORE dispatch: a cap checked against a price that is then discarded is worse than no cap".to_string());
}
let mut uncapped = StubVenue::new("stub");
uncapped.supports_ioc = false;
let uncapped_counter = StdArc::clone(&uncapped.orders_placed);
let mut open_venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
open_venues.insert("stub".to_string(), Box::new(uncapped));
let mut open_options =
options_with(&execute_options(true, "sequential"), "allowReexecution", Value::Bool(true));
OrderRouter::set_key(&mut open_options, "allowMarketOrders", Value::Bool(true));
let open_report = block_on(r.execute(&plan, &open_venues, &open_options)).map_err(|e| e.to_string())?;
if uncapped_counter.load(Ordering::SeqCst) != 1 {
return Err(format!("with no cap the market order goes out, got {open_report:?}"));
}
Ok(())
}
fn plan_age_is_reported_and_refused_only_when_asked(r: &OrderRouter) -> Result<(), String> {
let mut route = one_leg_route("buy", "BTC", "USDT", 0.2, 100.0);
OrderRouter::set_key(&mut route, "calculatedAt", Value::Float(1_000_000.0));
let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
let mut pinned = router()?;
pinned.set_now_ms(1_060_000.0); let execute_options = |live: bool, strategy: &str| {
options_with(&execute_options(live, strategy), "allowReexecution", Value::Bool(true))
};
let venues = |v: StubVenue| {
let mut m: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
m.insert("stub".to_string(), Box::new(v));
m
};
let report = block_on(pinned.execute(&plan, &venues(StubVenue::new("stub")), &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
if pinned.number_at(&report, "planAgeMs", 0.0) != 60_000.0 {
return Err(format!("the age belongs on the report whether or not it is checked, got {:?}", report));
}
let results = pinned.list_at(&report, "steps");
if pinned.string_at(&results[0], "status", "") != "filled" {
return Err("nothing is refused by default".to_string());
}
let strict = StubVenue::new("stub");
let strict_counter = StdArc::clone(&strict.orders_placed);
let mut strict_options = execute_options(true, "sequential");
OrderRouter::set_key(&mut strict_options, "maxPlanAgeMs", Value::Float(30_000.0));
match block_on(pinned.execute(&plan, &venues(strict), &strict_options)) {
Err(e) if e.message.contains("older than maxPlanAgeMs") => {}
other => return Err(format!("a stale plan must be refused under a limit, got {other:?}")),
}
if strict_counter.load(Ordering::SeqCst) != 0 {
return Err("refused before anything reached the venue".to_string());
}
let mut wide_options = execute_options(true, "sequential");
OrderRouter::set_key(&mut wide_options, "maxPlanAgeMs", Value::Float(120_000.0));
let passed = block_on(pinned.execute(&plan, &venues(StubVenue::new("stub")), &wide_options))
.map_err(|e| e.to_string())?;
let passed_results = pinned.list_at(&passed, "steps");
if pinned.string_at(&passed_results[0], "status", "") != "filled" {
return Err("a limit the plan is inside of lets it through".to_string());
}
let undated = one_leg_plan(r)?;
let undated_report = block_on(pinned.execute(&undated, &venues(StubVenue::new("stub")), &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
if pinned.number_at(&undated_report, "planAgeMs", 0.0) != -1.0 {
return Err("unknown is -1, never 0: 0 would read as fresh".to_string());
}
let mut undated_options = execute_options(true, "sequential");
OrderRouter::set_key(&mut undated_options, "maxPlanAgeMs", Value::Float(30_000.0));
match block_on(pinned.execute(&undated, &venues(StubVenue::new("stub")), &undated_options)) {
Err(e) if e.message.contains("carries no calculatedAt") => Ok(()),
other => Err(format!("an undatable plan must be refused under a limit, got {other:?}")),
}
}
fn best_effort_demands_its_acknowledgements(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let venue = StubVenue::new("stub");
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
match block_on(r.execute(&plan, &venues, &execute_options(true, "best_effort"))) {
Err(e) if e.message.contains("acknowledgeDispersion") => {}
other => return Err(format!("expected an acknowledgeDispersion refusal, got {other:?}")),
}
let mut options = execute_options(true, "best_effort");
OrderRouter::set_key(&mut options, "acknowledgeDispersion", Value::Bool(true));
match block_on(r.execute(&plan, &venues, &options)) {
Err(e) if e.message.contains("maxOrders") => Ok(()),
other => Err(format!("expected a maxOrders refusal, got {other:?}")),
}
}
fn options_with(base: &Value, key: &str, value: Value) -> Value {
let mut map = base.as_map().cloned().unwrap_or_default();
map.insert(key.to_string(), value);
Value::Map(map)
}
fn stub_venues(venue: StubVenue) -> BTreeMap<String, Box<dyn RouterVenue>> {
let mut venues: BTreeMap<String, Box<dyn RouterVenue>> = BTreeMap::new();
venues.insert("stub".to_string(), Box::new(venue));
venues
}
fn live_requires_an_identity(r: &OrderRouter) -> Result<(), String> {
let route = options_with(
&one_leg_route("buy", "BTC", "USDT", 0.2, 100.0),
"requestId",
Value::Str(Cow::Borrowed("")),
);
let plan = r.build_execution_plan(&route, &Value::Map(HashMap::new())).map_err(|e| e.to_string())?;
let venue = StubVenue::new("stub");
let counter = StdArc::clone(&venue.orders_placed);
let venues = stub_venues(venue);
match block_on(r.execute(&plan, &venues, &execute_options(true, "sequential"))) {
Ok(_) => return Err("a live plan with no identity must be refused".to_string()),
Err(e) if e.is("BadRequest") => {}
Err(e) => return Err(format!("expected BadRequest, got {e}")),
}
if counter.load(Ordering::SeqCst) != 0 {
return Err("refused before a single order reached the venue".to_string());
}
let dry = block_on(r.execute(&plan, &venues, &execute_options(false, "sequential")))
.map_err(|e| e.to_string())?;
if !r.bool_at(&dry, "dryRun", false) {
return Err("a dry run needs no identity".to_string());
}
let keyed_options = options_with(
&execute_options(true, "sequential"),
"idempotencyKey",
Value::Str("hand-built-1".to_string().into()),
);
let supplied = StubVenue::new("stub");
let seen = StdArc::clone(&supplied.params_seen);
let venues = stub_venues(supplied);
let report = block_on(r.execute(&plan, &venues, &keyed_options)).map_err(|e| e.to_string())?;
if r.string_at(&report, "planId", "") != "hand-built-1" {
return Err("the supplied key is the identity".to_string());
}
let params = seen.lock().unwrap().clone();
if params.is_empty() || !r.string_at(¶ms[0], "clientOrderId", "").is_empty() {
return Err("no client order id is injected".to_string());
}
let again = stub_venues(StubVenue::new("stub"));
match block_on(r.execute(&plan, &again, &keyed_options)) {
Ok(_) => return Err("the same key must be refused a second time".to_string()),
Err(e) if e.is("BadRequest") => {}
Err(e) => return Err(format!("expected BadRequest, got {e}")),
}
let routed = one_leg_plan(r)?;
let override_options = options_with(
&execute_options(true, "sequential"),
"idempotencyKey",
Value::Str("override-1".to_string().into()),
);
let overridden = StubVenue::new("stub");
let seen = StdArc::clone(&overridden.params_seen);
let venues = stub_venues(overridden);
let report = block_on(r.execute(&routed, &venues, &override_options)).map_err(|e| e.to_string())?;
if r.string_at(&report, "planId", "") != "override-1" {
return Err("the option overrides the plan's requestId".to_string());
}
let params = seen.lock().unwrap().clone();
if !r.string_at(¶ms[0], "clientOrderId", "").is_empty() {
return Err("and no client order id is injected".to_string());
}
Ok(())
}
fn client_order_id_is_never_injected(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let plan_id = r.string_at(&plan, "requestId", "");
let bare = StubVenue::new("stub");
let seen = StdArc::clone(&bare.params_seen);
let venues = stub_venues(bare);
let report = block_on(r.execute(&plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
if r.string_at(&report, "planId", "") != plan_id {
return Err("the report names the plan identity".to_string());
}
let params = seen.lock().unwrap().clone();
if params.is_empty() || !r.string_at(¶ms[0], "clientOrderId", "").is_empty() {
return Err("no client order id is forced onto the order".to_string());
}
let results = r.list_at(&report, "steps");
if !r.string_at(&results[0], "clientOrderId", "").is_empty() {
return Err("the report carries what the venue reported, which is nothing".to_string());
}
let mut caller_params = HashMap::new();
caller_params.insert("clientOrderId".to_string(), Value::Str("caller-supplied".to_string().into()));
caller_params.insert("reduceOnly".to_string(), Value::Bool(true));
let options = options_with(
&execute_options(true, "sequential"),
"orderParams",
Value::Map(caller_params),
);
let second = router()?;
let venue = StubVenue::new("stub");
let seen = StdArc::clone(&venue.params_seen);
let venues = stub_venues(venue);
let report = block_on(second.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
let params = seen.lock().unwrap().clone();
if r.string_at(¶ms[0], "clientOrderId", "") != "caller-supplied" {
return Err("the caller's id travels untouched".to_string());
}
if !r.bool_at(¶ms[0], "reduceOnly", false) {
return Err("the caller's other params still travel".to_string());
}
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "clientOrderId", "") != "caller-supplied" {
return Err("and the report says what the venue recorded".to_string());
}
Ok(())
}
fn reexecution_is_refused(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let options = execute_options(true, "sequential");
let venues = stub_venues(StubVenue::new("stub"));
let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "filled" {
return Err("the first run places the order".to_string());
}
let again = StubVenue::new("stub");
let counter = StdArc::clone(&again.orders_placed);
let venues = stub_venues(again);
match block_on(r.execute(&plan, &venues, &options)) {
Ok(_) => return Err("the second run must be refused".to_string()),
Err(e) if e.is("BadRequest") => {}
Err(e) => return Err(format!("expected BadRequest, got {e}")),
}
if counter.load(Ordering::SeqCst) != 0 {
return Err("not one order may be re-placed".to_string());
}
let allowed = StubVenue::new("stub");
let placed = StdArc::clone(&allowed.orders_placed);
let venues = stub_venues(allowed);
let retry_options = options_with(&options, "allowReexecution", Value::Bool(true));
let retry = block_on(r.execute(&plan, &venues, &retry_options)).map_err(|e| e.to_string())?;
let results = r.list_at(&retry, "steps");
if r.string_at(&results[0], "status", "") != "filled" || placed.load(Ordering::SeqCst) != 1 {
return Err("an explicit opt-in runs it again".to_string());
}
Ok(())
}
fn a_dry_run_does_not_consume_a_plan(r: &OrderRouter) -> Result<(), String> {
let plan = one_leg_plan(r)?;
let rehearsal = stub_venues(StubVenue::new("stub"));
block_on(r.execute(&plan, &rehearsal, &execute_options(false, "sequential")))
.map_err(|e| e.to_string())?;
let real = stub_venues(StubVenue::new("stub"));
let report = block_on(r.execute(&plan, &real, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "filled" {
return Err("the rehearsal must not burn the plan".to_string());
}
let failed_plan = one_leg_plan(r)?;
let mut broken = StubVenue::new("stub");
broken.fail_with = Some("ExchangeError");
let venues = stub_venues(broken);
let failed = block_on(r.execute(&failed_plan, &venues, &execute_options(true, "sequential")))
.map_err(|e| e.to_string())?;
if !r.bool_at(&failed, "halted", false) {
return Err("the failing run halted".to_string());
}
let retry = StubVenue::new("stub");
let counter = StdArc::clone(&retry.orders_placed);
let venues = stub_venues(retry);
match block_on(r.execute(&failed_plan, &venues, &execute_options(true, "sequential"))) {
Ok(_) => return Err("a failed run still consumed the plan".to_string()),
Err(e) if e.is("BadRequest") => {}
Err(e) => return Err(format!("expected BadRequest, got {e}")),
}
if counter.load(Ordering::SeqCst) != 0 {
return Err("and the retry placed nothing".to_string());
}
Ok(())
}
fn the_ledger_is_bounded(r: &OrderRouter) -> Result<(), String> {
let capacity = MAX_EXECUTED_PLAN_IDS;
for i in 0..capacity {
r.record_executed_plan(&format!("plan-{i}"));
}
if r.executed_plan_count() != capacity {
return Err("the ledger fills to exactly the cap".to_string());
}
if !r.has_executed_plan("plan-0") {
return Err("nothing is evicted before it is full".to_string());
}
for i in capacity..(capacity + 100) {
r.record_executed_plan(&format!("plan-{i}"));
}
if r.executed_plan_count() != capacity {
return Err("the ledger never grows past the cap".to_string());
}
for i in 0..100 {
if r.has_executed_plan(&format!("plan-{i}")) {
return Err(format!("the oldest entries are evicted first, plan-{i} survived"));
}
}
if !r.has_executed_plan("plan-100") || !r.has_executed_plan(&format!("plan-{}", capacity + 99)) {
return Err("nothing newer than the evicted window went with them".to_string());
}
if r.executed_plan_at(0) != "plan-100" {
return Err("the queue is still in insertion order".to_string());
}
r.record_executed_plan("plan-100");
if r.executed_plan_count() != capacity || r.executed_plan_at(0) != "plan-100" {
return Err("a duplicate record adds nothing and does not move the entry".to_string());
}
let plan = one_leg_plan(r)?;
let options = execute_options(true, "sequential");
let venues = stub_venues(StubVenue::new("stub"));
block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
let refused = StubVenue::new("stub");
let counter = StdArc::clone(&refused.orders_placed);
let venues = stub_venues(refused);
match block_on(r.execute(&plan, &venues, &options)) {
Ok(_) => return Err("while remembered, the duplicate is refused".to_string()),
Err(e) if e.is("BadRequest") => {}
Err(e) => return Err(format!("expected BadRequest, got {e}")),
}
if counter.load(Ordering::SeqCst) != 0 {
return Err("and it placed nothing".to_string());
}
for i in 0..capacity {
r.record_executed_plan(&format!("flush-{i}"));
}
if r.has_executed_plan(&r.string_at(&plan, "requestId", "")) {
return Err("the plan has aged out of the ledger".to_string());
}
let reexecuted = StubVenue::new("stub");
let placed = StdArc::clone(&reexecuted.orders_placed);
let venues = stub_venues(reexecuted);
let report = block_on(r.execute(&plan, &venues, &options)).map_err(|e| e.to_string())?;
let results = r.list_at(&report, "steps");
if r.string_at(&results[0], "status", "") != "filled" || placed.load(Ordering::SeqCst) == 0 {
return Err("an aged-out plan re-executes without the opt-in, and really places".to_string());
}
Ok(())
}