Files
eventbook-exchange/crates/exchange/tests/market.rs
T

3559 lines
143 KiB
Rust

use exchange::Exchange;
use serde_json::{json, Value};
use std::sync::{Arc, Barrier};
use tempfile::tempdir;
fn setup(e: &mut Exchange) {
for cmd in [
json!({"op":"fund","id":"a","account":"alice","cents":2000}),
json!({"op":"fund","id":"b","account":"bob","cents":2000}),
json!({"op":"list","id":"m","market":"e","rules":"official result"}),
json!({"op":"split","id":"s","market":"e","account":"alice","qty":10}),
] {
e.execute(cmd).unwrap();
}
}
fn order(id: &str, account: &str, side: &str, price: i64, qty: i64) -> Value {
json!({"id":id,"op":"order","account":account,"side":side,"price":price,"qty":qty,"outcome":"YES","market":"e"})
}
fn state(e: &mut Exchange) -> Value {
e.execute(json!({"op":"state"})).unwrap()
}
#[test]
fn auction_fifo_ioc_close_and_redeem() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(order("ask1", "alice", "sell", 40, 2)).unwrap();
e.execute(order("ask2", "alice", "sell", 40, 5)).unwrap();
e.execute(order("bid", "bob", "buy", 60, 4)).unwrap();
assert_eq!(state(&mut e)["fills"], json!([]));
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
let s = state(&mut e);
assert_eq!(
s["fills"],
json!([{"seq":1,"bid":3,"ask":1,"price":40,"quantity":2},{"seq":2,"bid":3,"ask":2,"price":40,"quantity":2}])
);
let mut ioc = order("sweep", "bob", "buy", 45, 6);
ioc["tif"] = json!("IOC");
assert_eq!(
e.execute(ioc).unwrap(),
json!({"order":4,"filled":3,"status":"cancelled"})
);
e.execute(order("rest", "bob", "buy", 10, 8)).unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
e.execute(json!({"id":"resolve","op":"resolve","market":"e","winner":"YES"}))
.unwrap();
let s = state(&mut e);
assert_eq!(
s["accounts"],
json!([{"id":"alice","cash":1580},{"id":"bob","cash":2420}])
);
assert_eq!(s["markets"][0]["collateral"], 0);
}
#[test]
fn retries_reopen_and_no_partial_writes() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let bid = order("repeat", "bob", "buy", 60, 10);
let reply = e.execute(bid.clone()).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(bid).unwrap(), reply);
let before = state(&mut e);
assert!(e.execute(order("repeat", "bob", "buy", 60, 9)).is_err());
assert!(e.execute(order("big", "bob", "buy", 100, 30)).is_err());
assert!(e
.execute(json!({"id":"cancel","op":"cancel","account":"alice","order":1}))
.is_err());
assert_eq!(state(&mut e), before);
e.execute(json!({"id":"cancel","op":"cancel","account":"bob","order":1}))
.unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
e.execute(json!({"id":"void","op":"resolve","market":"e","winner":"VOID"}))
.unwrap();
assert_eq!(state(&mut e)["accounts"][0]["cash"], 2000);
}
#[test]
fn concurrent_connections_cannot_double_spend() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let gate = Arc::new(Barrier::new(2));
let workers: Vec<_> = ["first", "second"]
.into_iter()
.map(|id| {
let mut db = Exchange::open(&path).unwrap();
let gate = Arc::clone(&gate);
std::thread::spawn(move || {
gate.wait();
db.execute(order(id, "bob", "buy", 90, 20)).is_ok()
})
})
.collect();
assert_eq!(
workers
.into_iter()
.map(|w| w.join().unwrap())
.filter(|v| *v)
.count(),
1
);
assert_eq!(state(&mut e)["accounts"][1]["cash"], 200);
}
#[test]
fn market_outcome_and_limit_are_isolated() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"m2","op":"list","market":"other","rules":"other"}))
.unwrap();
for m in ["e", "other"] {
e.execute(json!({"id":format!("open-{m}"),"op":"open","market":m}))
.unwrap();
}
e.execute(order("ask", "alice", "sell", 65, 7)).unwrap();
for (market, outcome, price) in [("e", "YES", 60), ("e", "NO", 70), ("other", "YES", 70)] {
let mut bid = order(&format!("{market}-{outcome}"), "bob", "buy", price, 3);
bid["market"] = json!(market);
bid["outcome"] = json!(outcome);
bid["tif"] = json!("IOC");
assert_eq!(e.execute(bid).unwrap()["filled"], 0);
}
assert_eq!(state(&mut e)["fills"], json!([]));
}
#[test]
fn reboot_restores_partial_fifo_and_excludes_cancelled_orders() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(order("ask-first", "alice", "sell", 40, 4))
.unwrap();
e.execute(order("ask-second", "alice", "sell", 40, 3))
.unwrap();
e.execute(order("cancel-me", "alice", "sell", 30, 1))
.unwrap();
e.execute(json!({"id":"cancel","op":"cancel","account":"alice","order":3}))
.unwrap();
e.execute(order("bid", "bob", "buy", 40, 2)).unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
drop(e);
// A database from the original version has live orders but no revision index.
let legacy = rusqlite::Connection::open(&path).unwrap();
legacy
.execute_batch(
"DROP TRIGGER book_insert; DROP TRIGGER book_update; DROP TABLE book_changes;",
)
.unwrap();
drop(legacy);
let mut e = Exchange::open(&path).unwrap();
e.execute(order("sweep", "bob", "buy", 40, 4)).unwrap();
let s = state(&mut e);
assert_eq!(
s["fills"],
json!([
{"seq":1,"ask":1,"bid":4,"price":40,"quantity":2},
{"seq":2,"ask":1,"bid":5,"price":40,"quantity":2},
{"seq":3,"ask":2,"bid":5,"price":40,"quantity":2}
])
);
}
#[test]
fn two_resident_books_follow_partial_fill_and_cancel() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut a = Exchange::open(&path).unwrap();
setup(&mut a);
let mut b = Exchange::open(&path).unwrap();
a.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
a.execute(order("maker", "alice", "sell", 55, 6)).unwrap();
assert_eq!(
b.execute(order("taker", "bob", "buy", 55, 4)).unwrap()["filled"],
4
);
assert_eq!(
a.execute(json!({"id":"cancel","op":"cancel","order":1,"account":"alice"}))
.unwrap()["cancelled"],
2
);
assert_eq!(
b.execute(order("next", "bob", "buy", 55, 1)).unwrap()["filled"],
0
);
}
#[test]
fn failed_receipt_discards_planned_fill() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
e.execute(order("ask", "alice", "sell", 55, 3)).unwrap();
let db = rusqlite::Connection::open(&path).unwrap();
db.execute_batch("CREATE TRIGGER reject_receipt BEFORE INSERT ON requests WHEN NEW.id='retry' BEGIN SELECT RAISE(ABORT,'injected'); END;").unwrap();
let bid = order("retry", "bob", "buy", 55, 3);
let before = state(&mut e);
assert!(e.execute(bid.clone()).is_err());
assert_eq!(state(&mut e), before);
db.execute_batch("DROP TRIGGER reject_receipt").unwrap();
let reply = e.execute(bid.clone()).unwrap();
assert_eq!(reply["filled"], 3);
assert_eq!(e.execute(bid).unwrap(), reply);
assert_eq!(state(&mut e)["fills"].as_array().unwrap().len(), 1);
}
#[test]
fn sports_catalog_and_trade_curve_survive_retries() {
let mut e = Exchange::open(":memory:").unwrap();
let mut catalog = Value::Null;
for line in include_str!("../../../docs/examples/football.jsonl").lines() {
catalog = e.execute(serde_json::from_str(line).unwrap()).unwrap();
}
assert_eq!(catalog["markets"].as_array().unwrap().len(), 6);
for market in catalog["markets"].as_array().unwrap() {
let direct = e
.execute(json!({"op":"assets","market":market["market"]}))
.unwrap();
assert_eq!(market["outcomes"], direct["outcomes"]);
assert_eq!(market["outcomes"][0]["label"], market["yes_label"]);
assert_eq!(market["outcomes"][1]["label"], market["no_label"]);
}
setup(&mut e);
e.execute(order("ask", "alice", "sell", 50, 2)).unwrap();
e.execute(order("bid", "bob", "buy", 50, 2)).unwrap();
let open = json!({"op":"open","id":"opening","market":"e"});
e.execute(open.clone()).unwrap();
e.execute(open).unwrap();
let query =
json!({"op":"history","market":"e","outcome":"YES","from_ms":0,"to_ms":i64::MAX,"limit":1});
let page = e.execute(query.clone()).unwrap();
let p = &page["points"][0];
assert_eq!(p["price_micros"], 500000);
assert_eq!(p["quantity"], 2);
let mut next = query;
next["after"] = json!([p["at_ms"], p["fill"]]);
assert_eq!(e.execute(next).unwrap()["points"], json!([]));
}
#[test]
fn displayed_quote_uses_midpoint_through_ten_cents_then_last_fill() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
let quote = json!({"op":"quote","market":"e","outcome":"YES"});
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
assert!(e.execute(quote.clone()).unwrap()["display_price_micros"].is_null());
e.execute(order("maker", "alice", "sell", 40, 1)).unwrap();
e.execute(order("trade", "bob", "buy", 40, 1)).unwrap();
e.execute(order("bid", "bob", "buy", 34, 1)).unwrap();
let ask = e.execute(order("ask", "alice", "sell", 44, 1)).unwrap();
assert_eq!(
e.execute(quote.clone()).unwrap()["display_price_micros"],
390000
);
e.execute(json!({"op":"cancel","id":"withdraw","account":"alice","order":ask["order"]}))
.unwrap();
e.execute(order("wider", "alice", "sell", 45, 1)).unwrap();
let display = e.execute(quote).unwrap();
assert_eq!(display["display_price_micros"], 400000);
assert_eq!(display["source"], "last_trade");
}
#[test]
fn merge_preserves_reservations_and_collateral_after_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let mut ask = order("reserved", "alice", "sell", 60, 8);
ask["outcome"] = json!("NO");
let seq = e.execute(ask).unwrap()["order"].clone();
let merge = json!({"op":"merge","id":"merge","market":"e","account":"alice","qty":3});
let before = state(&mut e);
// The YES debit must roll back when the NO side is reserved.
assert!(e.execute(merge.clone()).is_err());
assert_eq!(state(&mut e), before);
e.execute(json!({"op":"cancel","id":"free","account":"alice","order":seq}))
.unwrap();
let reply = e.execute(merge.clone()).unwrap();
assert_eq!(reply, json!({"pairs":3,"released_cents":300}));
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(merge).unwrap(), reply);
let s = state(&mut e);
assert_eq!(s["accounts"][0]["cash"], 1300);
assert_eq!(s["markets"][0]["collateral"], 700);
assert_eq!(s["positions"].as_array().unwrap().len(), 2);
assert!(s["positions"]
.as_array()
.unwrap()
.iter()
.all(|p| p["quantity"] == 7));
assert_eq!(s["fills"], json!([]));
e.execute(json!({"op":"close","id":"close","market":"e"}))
.unwrap();
e.execute(json!({"op":"merge","id":"pending","market":"e","account":"alice","qty":2}))
.unwrap();
let payout = e
.execute(json!({"op":"resolve","id":"resolve","market":"e","winner":"YES"}))
.unwrap();
assert_eq!(payout["paid"], 500);
assert_eq!(state(&mut e)["accounts"][0]["cash"], 2000);
assert!(e
.execute(json!({"op":"merge","id":"late","market":"e","account":"alice","qty":1}))
.is_err());
}
#[test]
fn explicit_redemption_is_account_scoped_and_restart_safe() {
for (winner, bob_payout, alice_payout) in
[("YES", 300, 700), ("NO", 0, 1000), ("VOID", 150, 850)]
{
let dir = tempdir().unwrap();
let path = dir.path().join("redeem.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let claim = json!({"id":"claim","op":"redeem","market":"e","account":"bob"});
assert!(e.execute(claim.clone()).is_err());
e.execute(order("offer", "alice", "sell", 50, 3)).unwrap();
e.execute(order("buy", "bob", "buy", 50, 3)).unwrap();
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
let before = state(&mut e);
let final_result = e
.execute(json!({"id":"final","op":"finalize","market":"e","winner":winner}))
.unwrap();
assert_eq!(final_result["outstanding_cents"], 1000);
let after = state(&mut e);
assert_eq!(before["accounts"], after["accounts"]);
assert_eq!(before["positions"], after["positions"]);
assert!(e
.execute(json!({"id":"again","op":"finalize","market":"e","winner":"VOID"}))
.is_err());
let receipt = e.execute(claim.clone()).unwrap();
assert_eq!(receipt["paid"], bob_payout);
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(claim).unwrap(), receipt);
assert!(e
.execute(json!({"id":"another","op":"redeem","market":"e","account":"bob"}))
.is_err());
assert_eq!(state(&mut e)["markets"][0]["collateral"], alice_payout);
assert_eq!(
e.execute(json!({"id":"alice-claim","op":"redeem","market":"e","account":"alice"}))
.unwrap()["paid"],
alice_payout
);
let final_state = state(&mut e);
assert_eq!(final_state["markets"][0]["collateral"], 0);
assert!(final_state["positions"]
.as_array()
.unwrap()
.iter()
.all(|p| p["quantity"] == 0));
}
}
#[test]
fn immediate_and_post_only_orders_use_the_committed_depth() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
for (id, price) in [("low", 40), ("high", 41)] {
let mut maker = order(id, "alice", "sell", price, 2);
maker["post_only"] = json!(true);
assert_eq!(e.execute(maker).unwrap()["status"], "live");
}
let before = state(&mut e);
for (id, tif, post, price, qty) in [
("short", "FOK", false, 40, 3),
("cross", "GTC", true, 40, 1),
("wrong-combination", "FAK", true, 40, 1),
("no-fill", "FAK", false, 39, 1),
] {
let mut req = order(id, "bob", "buy", price, qty);
req["post_only"] = json!(post);
req["tif"] = json!(tif);
assert!(e.execute(req).is_err());
assert_eq!(state(&mut e), before);
}
let mut full = order("full", "bob", "buy", 41, 3);
full["tif"] = json!("FOK");
let reply = e.execute(full.clone()).unwrap();
assert_eq!(reply["status"], "filled");
assert_eq!(reply["filled"], 3);
assert_eq!(e.execute(full).unwrap(), reply);
let mut partial = order("partial", "bob", "buy", 41, 3);
partial["tif"] = json!("FAK");
let reply = e.execute(partial).unwrap();
assert_eq!(reply["status"], "cancelled");
assert_eq!(reply["filled"], 1);
let s = state(&mut e);
assert_eq!(s["fills"].as_array().unwrap().len(), 3);
assert_eq!(s["accounts"][1]["cash"], 1838);
}
#[test]
fn rejected_sell_fok_releases_inventory() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
let before = state(&mut e);
let mut sell = order("sell", "alice", "sell", 60, 5);
sell["tif"] = json!("FOK");
assert!(e.execute(sell).is_err());
assert_eq!(state(&mut e), before);
}
#[test]
fn complementary_buyers_create_inventory_then_sellers_release_collateral() {
let dir = tempdir().unwrap();
let path = dir.path().join("paired.db");
let mut e = Exchange::open(&path).unwrap();
for account in ["alice", "bob"] {
e.execute(json!({"op":"fund","id":account,"account":account,"cents":1000}))
.unwrap();
}
e.execute(json!({"op":"list","id":"market","market":"e","rules":"official result"}))
.unwrap();
let mut no = order("first", "bob", "buy", 40, 10);
no["outcome"] = json!("NO");
e.execute(no).unwrap();
e.execute(order("second", "alice", "buy", 60, 10)).unwrap();
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
let s = state(&mut e);
assert_eq!(s["paired_fills"].as_array().unwrap().len(), 1);
assert_eq!(s["paired_fills"][0]["kind"], "mint");
assert_eq!(s["markets"][0]["collateral"], 1000);
assert_eq!(s["accounts"][0]["cash"], 400);
assert_eq!(s["accounts"][1]["cash"], 600);
e.execute(order("rest", "alice", "sell", 55, 10)).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
let quote = e
.execute(json!({"op":"quote","market":"e","outcome":"NO"}))
.unwrap();
assert_eq!(quote["best_bid_micros"], 450000);
let mut sell = order("exit", "bob", "sell", 41, 10);
sell["outcome"] = json!("NO");
sell["tif"] = json!("FOK");
let reply = e.execute(sell.clone()).unwrap();
assert_eq!(reply["filled"], 10);
assert_eq!(e.execute(sell).unwrap(), reply);
let s = state(&mut e);
assert_eq!(s["paired_fills"][1]["kind"], "merge");
let trades = e
.execute(json!({"op":"trades","account":"bob","asset_id":"eb:NO:e"}))
.unwrap();
let rows = trades["trades"].as_array().unwrap();
assert_eq!(rows.len(), 2);
assert_eq!(rows[0]["role"], "taker");
assert_eq!(rows[0]["kind"], "merge");
assert_eq!(rows[0]["gross_cents"], 450);
assert_eq!(rows[1]["kind"], "mint");
assert_eq!(rows[1]["role"], "auction");
assert_eq!(rows[1]["gross_cents"], 400);
assert_eq!(s["markets"][0]["collateral"], 0);
assert_eq!(s["accounts"][0]["cash"], 950);
assert_eq!(s["accounts"][1]["cash"], 1050);
assert!(s["positions"]
.as_array()
.unwrap()
.iter()
.all(|p| p["quantity"] == 0));
let history=e.execute(json!({"op":"history","market":"e","outcome":"NO","from_ms":0,"to_ms":i64::MAX,"limit":3})).unwrap();
assert_eq!(history["points"][0]["price_micros"], 400000);
assert_eq!(history["points"][1]["price_micros"], 450000);
}
#[test]
fn direct_and_complementary_liquidity_share_price_time_priority() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
let mut no = order("rest-no", "bob", "buy", 40, 2);
no["outcome"] = json!("NO");
e.execute(no).unwrap(); // projected ask 60, before direct ask at 60
e.execute(order("equal", "alice", "sell", 60, 3)).unwrap();
e.execute(order("better", "alice", "sell", 59, 1)).unwrap();
let mut buy = order("sweep", "alice", "buy", 63, 4);
buy["tif"] = json!("FOK");
assert_eq!(e.execute(buy).unwrap()["filled"], 4);
let s = state(&mut e);
assert_eq!(s["fills"][0]["seq"], 1);
assert_eq!(s["fills"][0]["price"], 59);
assert_eq!(s["paired_fills"][0]["seq"], 2);
assert_eq!(s["paired_fills"][0]["quantity"], 2);
assert_eq!(s["fills"][1]["seq"], 3);
assert_eq!(s["fills"][1]["quantity"], 1);
}
#[test]
fn book_groups_direct_and_complementary_remaining_size() {
let dir = tempdir().unwrap();
let path = dir.path().join("depth.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let yes = json!({"op":"book","market":"e","outcome":"YES"});
let no = json!({"op":"book","market":"e","outcome":"NO"});
assert_eq!(e.execute(yes.clone()).unwrap()["asks"], json!([]));
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
e.execute(order("direct", "alice", "sell", 60, 3)).unwrap();
let mut mirrored = order("mirrored", "bob", "buy", 40, 4);
mirrored["outcome"] = json!("NO");
let seq = e.execute(mirrored).unwrap()["order"].clone();
e.execute(order("dearer", "alice", "sell", 65, 1)).unwrap();
let levels = e.execute(yes.clone()).unwrap();
assert_eq!(
levels["asks"],
json!([{"price_micros":600000,"size":7},{"price_micros":650000,"size":1}])
);
assert_eq!(levels["bids"], json!([]));
let inverse = e.execute(no.clone()).unwrap();
assert_eq!(
inverse["bids"],
json!([{"price_micros":400000,"size":7},{"price_micros":350000,"size":1}])
);
e.execute(order("partial", "bob", "buy", 60, 2)).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(yes.clone()).unwrap()["asks"][0]["size"], 5);
e.execute(json!({"op":"cancel","id":"withdraw","account":"bob","order":seq}))
.unwrap();
assert_eq!(e.execute(yes).unwrap()["asks"][0]["size"], 1);
assert_eq!(e.execute(no).unwrap()["bids"][0]["size"], 1);
assert!(e
.execute(json!({"op":"book","market":"missing","outcome":"YES"}))
.is_err());
assert!(e
.execute(json!({"op":"book","market":"e","outcome":"other"}))
.is_err());
}
#[test]
fn account_order_pages_track_partial_fills_and_terminal_orders() {
let dir = tempdir().unwrap();
let path = dir.path().join("orders.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
let first = e.execute(order("first", "alice", "sell", 60, 5)).unwrap()["order"].clone();
let second = e.execute(order("second", "alice", "sell", 65, 2)).unwrap()["order"].clone();
let buy = e.execute(order("take", "bob", "buy", 60, 2)).unwrap()["order"].clone();
let page = json!({"op":"open_orders","account":"alice","market":"e","outcome":"YES","limit":1});
let result = e.execute(page.clone()).unwrap();
assert_eq!(result["orders"][0]["original_size"], 5);
assert_eq!(result["orders"][0]["size_matched"], 2);
assert_eq!(result["orders"][0]["open_size"], 3);
assert_eq!(result["next_after"], first);
let mut rest = page.clone();
rest["after"] = result["next_after"].clone();
let result = e.execute(rest).unwrap();
assert_eq!(result["orders"][0]["order"], second);
assert!(result["next_after"].is_null());
e.execute(json!({"op":"cancel","id":"remove","account":"alice","order":first}))
.unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
let listed = e.execute(page).unwrap();
assert_eq!(listed["orders"][0]["order"], second);
let lookup = json!({"op":"open_orders","account":"alice","order":first});
let closed = e.execute(lookup.clone()).unwrap();
assert_eq!(closed["orders"][0]["status"], "cancelled");
assert_eq!(closed["orders"][0]["size_matched"], 2);
assert_eq!(closed["orders"][0]["open_size"], 0);
let mut foreign = lookup;
foreign["account"] = json!("bob");
assert_eq!(e.execute(foreign).unwrap()["orders"], json!([]));
let filled = e
.execute(json!({"op":"open_orders","account":"bob","order":buy}))
.unwrap();
assert_eq!(filled["orders"][0]["status"], "filled");
assert_eq!(filled["orders"][0]["size_matched"], 2);
assert_eq!(
e.execute(json!({"op":"open_orders","account":"bob"}))
.unwrap()["orders"],
json!([])
);
}
#[test]
fn portfolio_tracks_reserved_pairs_partial_sale_and_redemption() {
let dir = tempdir().unwrap();
let path = dir.path().join("positions.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
let ask = e.execute(order("ask", "alice", "sell", 60, 10)).unwrap();
let list = json!({"op":"positions","account":"alice","market":"e"});
let find_yes = |page: Value| {
page["positions"]
.as_array()
.unwrap()
.iter()
.find(|p| p["outcome"] == "YES")
.unwrap()
.clone()
};
let held = find_yes(e.execute(list.clone()).unwrap());
assert_eq!(held["size"], 10);
assert_eq!(held["available_size"], 0);
assert_eq!(held["reserved_size"], 10);
assert_eq!(held["mergeable"], true);
assert_eq!(held["available_pairs"], 0);
e.execute(order("take", "bob", "buy", 60, 2)).unwrap();
let held = find_yes(e.execute(list.clone()).unwrap());
assert_eq!(held["size"], 8);
assert_eq!(held["reserved_size"], 8);
e.execute(json!({"op":"cancel","id":"free","account":"alice","order":ask["order"]}))
.unwrap();
assert_eq!(
find_yes(e.execute(list.clone()).unwrap())["available_pairs"],
8
);
e.execute(json!({"op":"close","id":"close","market":"e"}))
.unwrap();
e.execute(json!({"op":"finalize","id":"result","market":"e","winner":"YES"}))
.unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(
find_yes(e.execute(list.clone()).unwrap())["payout_cents"],
800
);
let mut page = json!({"op":"positions","account":"alice","status":"REDEEMABLE","limit":1});
let first = e.execute(page.clone()).unwrap();
assert_eq!(first["positions"][0]["outcome"], "YES");
page["after"] = first["next_after"].clone();
let second = e.execute(page).unwrap();
assert_eq!(second["positions"][0]["outcome"], "NO");
assert!(second["next_after"].is_null());
let lost = e
.execute(json!({"op":"positions","account":"alice","status":"REDEEMABLE_LOST"}))
.unwrap();
assert_eq!(lost["positions"][0]["status"], "REDEEMABLE");
assert_eq!(lost["positions"][0]["payout_cents"], 0);
e.execute(json!({"op":"redeem","id":"collect","account":"alice","market":"e"}))
.unwrap();
assert_eq!(e.execute(list).unwrap()["positions"], json!([]));
let closed = e
.execute(json!({"op":"positions","account":"alice","status":"CLOSED"}))
.unwrap();
assert_eq!(closed["positions"].as_array().unwrap().len(), 2);
let other = e
.execute(json!({"op":"positions","account":"bob"}))
.unwrap();
assert_eq!(other["positions"][0]["payout_cents"], 200);
}
#[test]
fn gtd_expiry_survives_rejection_and_recovery() {
let dir = tempdir().unwrap();
let path = dir.path().join("expiry.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
let db = rusqlite::Connection::open(&path).unwrap();
let now: i64 = db
.query_row("SELECT unixepoch()", [], |r| r.get(0))
.unwrap();
let mut ask = order("dated", "alice", "sell", 60, 5);
ask["tif"] = json!("GTD");
assert!(e.execute(ask.clone()).is_err());
ask["expiration"] = json!(now + 179);
assert!(e.execute(ask.clone()).is_err());
ask["expiration"] = json!(now + 600);
ask["post_only"] = json!(true);
let receipt = e.execute(ask.clone()).unwrap();
let mut bid = order("dated-buy", "bob", "buy", 20, 3);
bid["expiration"] = json!(now + 600);
let bid_id = e.execute(bid).unwrap()["order"].as_i64().unwrap();
e.execute(order("take", "bob", "buy", 60, 2)).unwrap();
let ask_id = receipt["order"].as_i64().unwrap();
db.execute(
"UPDATE order_deadlines SET expiration=unixepoch()+60 WHERE seq=?",
[ask_id],
)
.unwrap();
let mut sweep = order("sweep", "bob", "buy", 65, 1);
sweep["tif"] = json!("FOK");
assert!(e.execute(sweep).is_err());
assert_eq!(e.execute(ask).unwrap(), receipt);
let lookup = e
.execute(json!({"op":"open_orders","account":"alice","order":ask_id}))
.unwrap();
assert_eq!(lookup["orders"][0]["status"], "expired");
assert_eq!(lookup["orders"][0]["size_matched"], 2);
assert_eq!(lookup["orders"][0]["open_size"], 0);
let held = e
.execute(json!({"op":"positions","account":"alice"}))
.unwrap();
let yes = held["positions"]
.as_array()
.unwrap()
.iter()
.find(|r| r["outcome"] == "YES")
.unwrap();
assert_eq!(yes["available_size"], 8);
assert_eq!(yes["reserved_size"], 0);
drop(e);
db.execute(
"UPDATE order_deadlines SET expiration=unixepoch()+59 WHERE seq=?",
[bid_id],
)
.unwrap();
let mut e = Exchange::open(&path).unwrap();
let s = state(&mut e);
assert_eq!(s["accounts"][1]["cash"], 1880);
assert_eq!(s["orders"][1]["status"], "expired");
assert_eq!(
e.execute(json!({"op":"book","market":"e","outcome":"NO"}))
.unwrap()["asks"],
json!([])
);
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(state(&mut e)["accounts"][1]["cash"], 1880);
}
#[test]
fn asset_discovery_and_routing_share_one_orderbook_across_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("assets.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let market = "杯赛:NO:决赛";
e.execute(json!({"op":"list","id":"new","market":market,"rules":"official"}))
.unwrap();
let discovery = json!({"op":"assets","market":market});
let assets = e.execute(discovery.clone()).unwrap()["outcomes"].clone();
let yes = assets[0]["asset_id"].clone();
let no = assets[1]["asset_id"].clone();
assert_ne!(yes, no);
e.execute(json!({"op":"split","id":"pairs","account":"alice","market":market,"qty":3}))
.unwrap();
e.execute(json!({"op":"open","id":"open","market":market}))
.unwrap();
let ask = json!({"op":"order","id":"offer","asset_id":yes,"account":"alice","side":"sell","price":47,"qty":3});
let receipt = e.execute(ask.clone()).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(discovery).unwrap()["outcomes"], assets);
assert_eq!(e.execute(ask).unwrap(), receipt);
let book = e.execute(json!({"op":"book","asset_id":yes})).unwrap();
assert_eq!(
book,
e.execute(json!({"op":"book","market":market,"outcome":"YES"}))
.unwrap()
);
assert_eq!(book["asks"][0]["size"], 3);
let opposite = e.execute(json!({"op":"quote","asset_id":no})).unwrap();
assert_eq!(opposite["best_bid_micros"], 530000);
let mut buy = order("take", "bob", "buy", 47, 2);
buy["market"] = json!(market);
let mut conflicting = buy.clone();
conflicting["asset_id"] = no.clone();
assert!(e.execute(conflicting).is_err());
assert_eq!(e.execute(buy).unwrap()["filled"], 2);
let history = e
.execute(json!({"op":"history","asset_id":yes,"from_ms":0,"to_ms":i64::MAX,"limit":10}))
.unwrap();
assert_eq!(history["points"][0]["quantity"], 2);
assert_eq!(history["asset_id"], yes);
let live = e
.execute(json!({"op":"open_orders","asset_id":yes,"account":"alice"}))
.unwrap();
assert_eq!(live["orders"][0]["open_size"], 1);
assert_eq!(live["orders"][0]["asset_id"], yes);
let held = e
.execute(json!({"op":"positions","market":market,"account":"bob"}))
.unwrap();
assert_eq!(held["positions"][0]["asset_id"], yes);
for asset in ["eb:YES:unlisted", "eb:DRAW:e", "venue:123"] {
assert!(e.execute(json!({"op":"book","asset_id":asset})).is_err());
}
}
#[test]
fn account_fills_page_both_order_legs_and_reconcile_after_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("trades.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"go","market":"e"}))
.unwrap();
let ask = e.execute(order("offer", "alice", "sell", 47, 4)).unwrap()["order"].clone();
let own = e.execute(order("own", "alice", "buy", 50, 2)).unwrap()["order"].clone();
let buy = order("take", "bob", "buy", 49, 1);
let receipt = e.execute(buy.clone()).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(buy).unwrap(), receipt);
let mut q = json!({"op":"trades","account":"alice","limit":2});
let page = e.execute(q.clone()).unwrap();
let legs = page["trades"].as_array().unwrap();
assert_eq!(legs.len(), 2);
assert_eq!(legs[0]["order"], ask);
assert_eq!(legs[0]["role"], "maker");
assert_eq!(legs[0]["price_micros"], 470000);
assert_eq!(legs[1]["order"], own);
assert_eq!(legs[1]["side"], "buy");
q["after"] = page["next_after"].clone();
let page = e.execute(q).unwrap();
assert!(page["next_after"].is_null());
assert_eq!(page["trades"][0]["execution"], legs[1]["execution"]);
assert_eq!(page["trades"][0]["order"], ask);
let matched = e
.execute(json!({"op":"trades","account":"alice","order":ask}))
.unwrap();
assert_eq!(
matched["trades"]
.as_array()
.unwrap()
.iter()
.map(|r| r["size"].as_i64().unwrap())
.sum::<i64>(),
3
);
assert_eq!(
e.execute(json!({"op":"trades","account":"bob","order":ask}))
.unwrap()["trades"],
json!([])
);
}
#[test]
fn contested_resolution_blocks_both_payout_paths_until_a_verdict() {
let dir = tempdir().unwrap();
let path = dir.path().join("oracle.db");
let mut e = Exchange::open(&path).unwrap();
e.execute(json!({"op":"fund","id":"fund","account":"alice","cents":1000}))
.unwrap();
e.execute(
json!({"op":"list","id":"list","market":"m","rules":"official outcome",
"resolution":{"kind":"optimistic","eligible_at":0}}),
)
.unwrap();
e.execute(json!({"op":"split","id":"split","account":"alice","market":"m","qty":2}))
.unwrap();
e.execute(json!({"op":"close","id":"close","market":"m"}))
.unwrap();
let status = json!({"op":"resolution","market":"m"});
let make = |id: &str| json!({"op":"propose","id":id,"market":"m","winner":"YES","proposer":"alice","evidence":"score sheet"});
let challenge = |id: &str, p: &Value| json!({"op":"dispute","id":id,"market":"m","proposal":p,"challenger":"bob","evidence":"corrected score"});
let first = e.execute(make("p1")).unwrap()["proposal"].clone();
for op in ["finalize", "resolve"] {
assert!(e
.execute(json!({"op":op,"id":op,"market":"m","winner":"YES"}))
.is_err());
}
let c = challenge("d1", &first);
let receipt = e.execute(c.clone()).unwrap();
assert_eq!(receipt["status"], "awaiting_second_proposal");
let second = e.execute(make("p2")).unwrap()["proposal"].clone();
assert!(e.execute(challenge("obsolete", &first)).is_err());
assert_eq!(e.execute(c).unwrap(), receipt);
e.execute(challenge("d2", &second)).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(
e.execute(status.clone()).unwrap()["status"],
"awaiting_arbitration"
);
let redeem = json!({"op":"redeem","id":"claim","market":"m","account":"alice"});
assert!(e.execute(redeem.clone()).is_err());
let decision = json!({"op":"adjudicate","id":"verdict","market":"m","proposal":second,"verdict":"NO","evidence":"simulated vote record"});
let finalized = e.execute(decision.clone()).unwrap();
assert_eq!(e.execute(decision).unwrap(), finalized);
let resolved = e.execute(status).unwrap();
assert_eq!(resolved["winner"], "NO");
assert_eq!(resolved["payouts"], json!([0, 1]));
assert!(resolved["resolved_at_ms"].is_i64());
assert_eq!(resolved["proposals"][1]["verdict"], "NO");
assert_eq!(resolved["proposals"][0]["challenger"], "bob");
assert_eq!(e.execute(redeem).unwrap()["paid"], 200);
}
#[test]
fn unchallenged_second_proposal_only_clears_its_own_outcome() {
let dir = tempdir().unwrap();
let path = dir.path().join("unchallenged.db");
let mut e = Exchange::open(&path).unwrap();
e.execute(
json!({"op":"list","id":"list","market":"m","rules":"official",
"resolution":{"kind":"optimistic","eligible_at":0}}),
)
.unwrap();
e.execute(json!({"op":"close","id":"close","market":"m"}))
.unwrap();
let proposal = |id: &str, winner: &str| {
json!({"op":"propose","id":id,"market":"m","winner":winner,
"proposer":"a","evidence":"observed result"})
};
let first = e.execute(proposal("first", "YES")).unwrap();
e.execute(
json!({"op":"dispute","id":"challenge","market":"m","proposal":first["proposal"],
"challenger":"b","evidence":"corrected result"}),
)
.unwrap();
let second = e.execute(proposal("second", "NO")).unwrap();
let finalize =
|winner: &str| json!({"op":"finalize","id":"finish","market":"m","winner":winner});
assert!(e.execute(finalize("NO")).is_err());
let db = rusqlite::Connection::open(&path).unwrap();
db.execute(
"UPDATE resolution_proposals SET proposed_at=unixepoch()-7200 WHERE id=?",
[second["proposal"].as_i64().unwrap()],
)
.unwrap();
assert!(e.execute(finalize("YES")).is_err());
assert_eq!(e.execute(finalize("NO")).unwrap()["winner"], "NO");
}
#[test]
fn twap_market_closes_before_settlement_and_reuses_exact_observations() {
let dir = tempdir().unwrap();
let path = dir.path().join("twap.db");
let mut e = Exchange::open(&path).unwrap();
let db = rusqlite::Connection::open(&path).unwrap();
let now: i64 = db
.query_row("SELECT unixepoch()", [], |r| r.get(0))
.unwrap();
let start = now - 300;
let end = now - 1;
e.execute(json!({"op":"fund","id":"a","account":"alice","cents":1000}))
.unwrap();
e.execute(
json!({"op":"list","id":"l","market":"m","rules":"final >= opening is Up",
"resolution":{"kind":"twap","stream":"test/btc-usd","start_at":start,"end_at":now+600}}),
)
.unwrap();
e.execute(json!({"op":"split","id":"s","market":"m","account":"alice","qty":3}))
.unwrap();
e.execute(json!({"op":"open","id":"o","market":"m"}))
.unwrap();
e.execute(json!({"op":"order","id":"sell","market":"m","account":"alice","side":"sell","outcome":"YES","price":50,"qty":3})).unwrap();
let observe = |id: &str, t: i64, price: &str| {
json!({"op":"observe","id":id,"market":"m","stream":"test/btc-usd",
"price":price,"observed_at":t,"evidence":"simulated-report"})
};
e.execute(observe("initial", start, "0100.0000000000000000010"))
.unwrap();
assert!(e.execute(observe("future", now + 600, "200")).is_err());
db.execute("UPDATE twap_markets SET end_at=? WHERE market='m'", [end])
.unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
let report = json!({"op":"resolution","market":"m"});
assert_eq!(
e.execute(report.clone()).unwrap()["status"],
"awaiting_observations"
);
assert_eq!(state(&mut e)["orders"][0]["status"], "cancelled");
let finish = json!({"op":"finalize","id":"f","market":"m"});
assert!(e.execute(finish.clone()).is_err());
assert!(e
.execute(json!({"op":"resolve","id":"bypass","market":"m","winner":"YES"}))
.is_err());
assert!(e.execute(observe("wrong-time", end - 1, "100")).is_err());
let mut wrong_stream = observe("wrong-stream", end, "100");
wrong_stream["stream"] = json!("test/other");
assert!(e.execute(wrong_stream).is_err());
e.execute(observe("end", end, "100.000000000000000000"))
.unwrap();
e.execute(observe("same", end, "100")).unwrap();
assert!(e.execute(observe("conflict", end, "101")).is_err());
let detail = e.execute(report).unwrap();
assert_eq!(detail["computed_winner"], "NO");
assert_eq!(detail["opening"], "100.000000000000000001");
assert_eq!(e.execute(finish).unwrap()["winner"], "NO");
assert_eq!(
e.execute(json!({"op":"redeem","id":"claim","market":"m","account":"alice"}))
.unwrap()["paid"],
300
);
}
#[test]
fn batch_cancel_releases_only_remaining_owned_orders_and_replays_receipt() {
let dir = tempdir().unwrap();
let path = dir.path().join("cancel.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
let ask = e.execute(order("offer", "alice", "sell", 63, 5)).unwrap()["order"].clone();
let filled = e.execute(order("take", "bob", "buy", 65, 2)).unwrap()["order"].clone();
let foreign = e.execute(order("other", "bob", "buy", 10, 1)).unwrap()["order"].clone();
let mut no = order("no", "alice", "buy", 20, 4);
no["outcome"] = json!("NO");
let bid = e.execute(no).unwrap()["order"].clone();
let batch = json!({"op":"cancel_orders","id":"withdraw","account":"alice",
"orders":[bid,ask,bid,foreign,99999]});
let result = e.execute(batch.clone()).unwrap();
assert_eq!(result["canceled"], json!([bid, ask]));
assert_eq!(
result["not_canceled"][foreign.to_string().as_str()],
"order not found"
);
assert_eq!(result["not_canceled"]["99999"], "order not found");
let again = e
.execute(json!({"op":"cancel_orders","id":"again","account":"bob","orders":[filled]}))
.unwrap();
assert_eq!(
again["not_canceled"][filled.to_string().as_str()],
"order is filled"
);
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(batch).unwrap(), result);
let state = state(&mut e);
assert_eq!(state["accounts"][0]["cash"], 1126);
let yes = state["positions"]
.as_array()
.unwrap()
.iter()
.find(|p| p["account"] == "alice" && p["outcome"] == "YES")
.unwrap();
assert_eq!(yes["quantity"], 8);
let bob = e
.execute(json!({"op":"open_orders","account":"bob"}))
.unwrap();
assert_eq!(bob["orders"][0]["order"], foreign);
}
#[test]
fn market_and_asset_cancels_are_scoped_to_the_original_side() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"op":"list","id":"m2","market":"other","rules":"official"}))
.unwrap();
let yes = e.execute(order("yes", "alice", "sell", 60, 1)).unwrap()["order"].clone();
let mut n = order("no", "alice", "buy", 40, 1);
n["outcome"] = json!("NO");
let no = e.execute(n).unwrap()["order"].clone();
let mut elsewhere = order("other-bid", "alice", "buy", 10, 1);
elsewhere["market"] = json!("other");
let other = e.execute(elsewhere).unwrap()["order"].clone();
let scoped = json!({"op":"cancel_market_orders","id":"yes-only","account":"alice","asset_id":"eb:YES:e"});
assert_eq!(e.execute(scoped.clone()).unwrap()["canceled"], json!([yes]));
let new = e.execute(order("later", "alice", "sell", 60, 1)).unwrap()["order"].clone();
assert_eq!(e.execute(scoped).unwrap()["canceled"], json!([yes]));
assert!(e
.execute(json!({"op":"cancel_market_orders","id":"missing","account":"alice"}))
.is_err());
assert!(e
.execute(json!({"op":"cancel_all","id":"wrong","account":"alice","market":"e"}))
.is_err());
assert!(e
.execute(json!({"op":"cancel_orders","id":"empty","account":"alice","orders":[]}))
.is_err());
assert!(e
.execute(
json!({"op":"cancel_orders","id":"oversize","account":"alice","orders":vec![1;3001]})
)
.is_err());
let market = e
.execute(json!({"op":"cancel_market_orders","id":"m-only","account":"alice","market":"e"}))
.unwrap();
assert_eq!(market["canceled"], json!([no, new]));
let all = e
.execute(json!({"op":"cancel_all","id":"everything","account":"alice"}))
.unwrap();
assert_eq!(all, json!({"canceled":[other],"not_canceled":{}}));
}
#[test]
fn cash_buy_reconciles_direct_and_complementary_depth_with_an_exact_budget() {
let dir = tempdir().unwrap();
let path = dir.path().join("budget.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"fund","id":"c","account":"buyer","cents":170}))
.unwrap();
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
e.execute(order("ask", "alice", "sell", 35, 2)).unwrap();
let mut no = order("other-side", "alice", "buy", 55, 3);
no["outcome"] = json!("NO");
e.execute(no).unwrap();
let request = json!({"op":"market_buy","id":"budget","asset_id":"eb:YES:e","account":"buyer",
"amount_cents":170,"max_price":50});
let before = state(&mut e);
for (field, value) in [
("tif", json!("FOK")),
("amount_cents", json!(171)),
("max_price", json!(34)),
] {
let mut invalid = request.clone();
invalid[field] = value;
assert!(e.execute(invalid).is_err());
assert_eq!(state(&mut e), before);
}
let receipt = e.execute(request.clone()).unwrap();
assert_eq!(receipt["spent_cents"].to_string(), "169.9");
assert_eq!(receipt["unspent_cents"].to_string(), "0.1");
assert_eq!(receipt["filled"].to_string(), "4.22");
assert_eq!(receipt["status"], "cancelled");
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(request).unwrap(), receipt);
let s = state(&mut e);
assert_eq!(s["accounts"][2]["cash"], 0);
assert_eq!(s["paired_fills"][0]["kind"], "mint");
assert_eq!(s["markets"][0]["collateral"], 1222);
let lookup = e
.execute(json!({"op":"open_orders","account":"buyer","order":receipt["order"]}))
.unwrap();
assert_eq!(lookup["orders"][0]["spent_cents"].to_string(), "169.9");
assert_eq!(lookup["orders"][0]["open_size"], 0);
let fok = e
.execute(
json!({"op":"market_buy","id":"exact","market":"e","outcome":"YES",
"account":"bob","amount_cents":27,"max_price":45,"tif":"FOK"}),
)
.unwrap();
assert_eq!(fok["spent_cents"], 27);
assert_eq!(fok["status"], "filled");
}
#[test]
fn market_estimate_uses_latest_committed_depth_without_reserving_it() {
let dir = tempdir().unwrap();
let path = dir.path().join("estimate.db");
let mut client = Exchange::open(&path).unwrap();
setup(&mut client);
let mut maker = Exchange::open(path).unwrap();
maker
.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
maker
.execute(json!({"op":"split","id":"bm","account":"bob","market":"e","qty":2}))
.unwrap();
maker.execute(order("bid", "bob", "buy", 60, 2)).unwrap();
let mut opposite = order("opposite", "bob", "sell", 45, 2);
opposite["outcome"] = json!("NO");
let resting = maker.execute(opposite).unwrap()["order"].clone();
let preview =
json!({"op":"estimate","asset_id":"eb:YES:e","side":"sell","qty":5,"min_price":50});
let before = state(&mut client);
let quote = client.execute(preview.clone()).unwrap();
assert_eq!(quote["filled_shares"], 4);
assert_eq!(quote["gross_cents"], 230);
assert_eq!(quote["worst_fill_price"], 55);
assert_eq!(quote["average_price_micros"], 575000);
assert_eq!(quote["unsold_shares"], 1);
assert_eq!(state(&mut client), before);
let mut all = preview.clone();
all["tif"] = json!("FOK");
assert_eq!(client.execute(all).unwrap()["executable"], false);
maker
.execute(json!({"op":"cancel","id":"withdraw","account":"bob","order":resting}))
.unwrap();
let fresh = client.execute(preview).unwrap();
let sale = json!({"op":"market_sell","id":"sale","asset_id":"eb:YES:e","account":"alice","qty":5,"min_price":50});
let mut guarded = sale.clone();
guarded["min_price"] = json!(61);
assert!(client.execute(guarded).is_err());
let reply = client.execute(sale.clone()).unwrap();
assert_eq!(client.execute(sale).unwrap(), reply);
assert_eq!(reply["filled"], fresh["filled_shares"]);
assert_eq!(reply["proceeds_cents"], fresh["gross_cents"]);
assert_eq!(reply["proceeds_cents"], 120);
assert_eq!(reply["unsold_shares"], 3);
let empty = client
.execute(json!({"op":"estimate","market":"e","outcome":"YES","side":"sell","qty":1}))
.unwrap();
assert!(empty["worst_fill_price"].is_null());
assert!(empty["average_price_micros"].is_null());
assert_eq!(empty["executable"], false);
maker.execute(order("ask", "alice", "sell", 35, 2)).unwrap();
let buy = client
.execute(json!({"op":"estimate","asset_id":"eb:YES:e","side":"buy","amount_cents":81}))
.unwrap();
assert_eq!(buy["worst_fill_price"], 35);
assert_eq!(buy["gross_cents"], 70);
assert_eq!(buy["unspent_cents"], 11);
}
#[test]
fn topics_share_discovery_and_keep_distinct_tradable_assets_on_append() {
let dir = tempdir().unwrap();
let path = dir.path().join("topics.sqlite");
let mut e = Exchange::open(&path).unwrap();
let sport: Value = serde_json::from_str(
include_str!("../../../docs/examples/football.jsonl")
.lines()
.next()
.unwrap(),
)
.unwrap();
e.execute(sport.clone()).unwrap();
let commands: Vec<Value> = include_str!("../../../docs/examples/topic.jsonl")
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
for cmd in &commands[..2] {
e.execute(cmd.clone()).unwrap();
}
let original = e.execute(commands[4].clone()).unwrap()["markets"][0].clone();
e.execute(commands[2].clone()).unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
let detail = e.execute(commands[4].clone()).unwrap();
assert_eq!(
detail,
e.execute(json!({"op":"catalog","event":"nvda-2027"}))
.unwrap()
);
assert_eq!(detail["markets"][1], original);
assert_eq!(detail["markets"][0]["group_order"], 200);
let assets = e
.execute(json!({"op":"assets","market":"nvda-200"}))
.unwrap();
assert_eq!(assets["outcomes"], detail["markets"][0]["outcomes"]);
assert_ne!(
assets["outcomes"][0]["asset_id"],
original["outcomes"][0]["asset_id"]
);
assert_eq!(
e.execute(commands[3].clone()).unwrap()["events"]
.as_array()
.unwrap()
.len(),
1
);
let first = e.execute(json!({"op":"events","limit":1})).unwrap();
assert_eq!(first["next"], "cup-a-b");
let last = e
.execute(json!({"op":"events","after":first["next"],"limit":1}))
.unwrap();
assert_eq!(last["events"][0]["id"], "nvda-2027");
assert!(last["next"].is_null());
let mut collision = sport;
collision["id"] = json!("create-conflict");
collision["event"] = detail["event"]["slug"].clone();
assert!(e.execute(collision).is_err());
let mut invalid = commands[2].clone();
invalid["id"] = json!("invalid");
invalid["market"] = json!("invalid");
invalid["listing"]["event"] = json!("cup-a-b");
assert!(e.execute(invalid).is_err());
assert!(e
.execute(json!({"op":"assets","market":"invalid"}))
.is_err());
}
#[test]
fn negative_risk_conversion_reserves_collateral_for_exactly_one_winner() {
let dir = tempdir().unwrap();
let path = dir.path().join("neg-risk.sqlite");
let mut e = Exchange::open(&path).unwrap();
let cmds: Vec<Value> = include_str!("../../../docs/examples/neg-risk.jsonl")
.lines()
.map(|s| serde_json::from_str(s).unwrap())
.collect();
let (convert, setup) = cmds.split_last().unwrap();
for cmd in setup {
e.execute(cmd.clone()).unwrap();
}
let mut insufficient = convert.clone();
insufficient["id"] = json!("insufficient");
insufficient["no_markets"] = json!(["a", "other"]);
let before = state(&mut e);
assert!(e.execute(insufficient).is_err());
assert_eq!(state(&mut e), before);
let result = e.execute(convert.clone()).unwrap();
assert_eq!(result["released_cents"], 200);
assert_eq!(result["yes_markets"], json!(["other"]));
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(convert.clone()).unwrap(), result);
let state_now = state(&mut e);
assert_eq!(state_now["neg_risk_groups"][0]["reserve_cents"], 200);
assert_eq!(state_now["accounts"][0]["cash"], 2800);
let catalog = e
.execute(json!({"op":"catalog","event":"election"}))
.unwrap();
assert_eq!(catalog["markets"][2]["neg_risk_index"], 2);
for m in ["a", "b", "other"] {
e.execute(json!({"op":"close","id":format!("close-{m}"),"market":m}))
.unwrap();
}
e.execute(json!({"op":"finalize","id":"a-no","market":"a","winner":"NO"}))
.unwrap();
e.execute(json!({"op":"finalize","id":"b-no","market":"b","winner":"NO"}))
.unwrap();
assert!(e
.execute(json!({"op":"resolve","id":"all-no","market":"other","winner":"NO"}))
.is_err());
let paid = e
.execute(json!({"op":"resolve","id":"pay","market":"other","winner":"YES"}))
.unwrap();
assert_eq!(paid["paid"], 200);
let end = state(&mut e);
assert_eq!(end["accounts"][0]["cash"], 3000);
assert_eq!(end["neg_risk_groups"][0]["reserve_cents"], 0);
assert_eq!(end["neg_risk_groups"][0]["winner"], "other");
}
#[test]
fn negative_risk_all_subsets_conserve_cash_for_every_winner_and_reporting_order() {
let fixture: Vec<Value> = include_str!("../../../docs/examples/neg-risk.jsonl")
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
let markets = ["a", "b", "other"];
for mask in 1..8 {
let inputs: Vec<&str> = markets
.iter()
.enumerate()
.filter_map(|(i, &m)| (mask & (1 << i) != 0).then_some(m))
.collect();
for winner in markets {
for first in 0..3 {
for second in (0..3).filter(|i| *i != first) {
let mut e = Exchange::open(":memory:").unwrap();
for command in &fixture[..fixture.len() - 1] {
e.execute(command.clone()).unwrap();
}
e.execute(json!({"op":"split","id":"split-other","market":"other","account":"user","qty":2})).unwrap();
let converted=e.execute(json!({"op":"convert","id":"convert","group":"winner","account":"user","qty":2,"no_markets":inputs})).unwrap();
assert_eq!(converted["released_cents"], json!((inputs.len() - 1) * 200));
for i in [first, second, 3 - first - second] {
let member = markets[i];
e.execute(
json!({"op":"close","id":format!("close-{member}"),"market":member}),
)
.unwrap();
let verdict = if member == winner { "YES" } else { "NO" };
e.execute(json!({"op":"resolve","id":format!("resolve-{member}"),"market":member,"winner":verdict})).unwrap();
if member == winner && i == first {
let other = markets[second];
// Exercise the second-YES guard on a closed member, then keep the reporting order.
e.execute(
json!({"op":"close","id":format!("close-{other}"),"market":other}),
)
.unwrap();
assert!(e.execute(json!({"op":"finalize","id":"second-yes","market":other,"winner":"YES"})).is_err());
}
}
let end = state(&mut e);
assert_eq!(end["accounts"][0]["cash"], 3000);
assert!(end["markets"]
.as_array()
.unwrap()
.iter()
.all(|m| m["collateral"] == 0));
assert_eq!(end["neg_risk_groups"][0]["reserve_cents"], 0);
}
}
}
}
}
#[test]
fn augmented_placeholder_preserves_converted_shares_and_routes_unnamed_winners_to_other() {
let commands: Vec<Value> = include_str!("../../../docs/examples/augmented.jsonl")
.lines()
.map(|s| serde_json::from_str(s).unwrap())
.collect();
for (observed, winner) in [("丙", "b"), ("丁", "other")] {
let dir = tempdir().unwrap();
let path = dir.path().join("augmented.db");
let mut e = Exchange::open(&path).unwrap();
for cmd in &commands[..9] {
e.execute(cmd.clone()).unwrap();
}
let catalog = json!({"op":"catalog","event":"election"});
let before = e.execute(catalog.clone()).unwrap();
assert_eq!(before["markets"].as_array().unwrap().len(), 2);
let asset = json!({"op":"assets","market":"b"});
e.execute(json!({"op":"order","id":"existing","account":"user","market":"a","outcome":"YES","side":"sell","price":42,"qty":1})).unwrap();
let orders = json!({"op":"open_orders","account":"user","market":"a"});
let resting = e.execute(orders.clone()).unwrap();
let unopened = e.execute(asset.clone()).unwrap();
assert_eq!(unopened["augmented_role"], "placeholder");
let holdings = json!({"op":"positions","account":"user","market":"b"});
let stake = e.execute(holdings.clone()).unwrap()["positions"][0].clone();
assert_eq!(stake["size"], 1);
let order = json!({"op":"order","id":"sell-slot","account":"user","asset_id":stake["asset_id"],"side":"sell","qty":1,"price":50});
assert!(e.execute(order.clone()).is_err());
let mut dup = commands[9].clone();
dup["name"] = json!("甲");
assert!(e.execute(dup).is_err());
e.execute(commands[9].clone()).unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(orders).unwrap(), resting);
let updated = e.execute(asset.clone()).unwrap();
assert_eq!(updated["outcomes"], unopened["outcomes"]);
assert_eq!(updated["outcome_name"], "丙");
assert_eq!(
e.execute(holdings).unwrap()["positions"][0]["asset_id"],
stake["asset_id"]
);
let catalog = e.execute(catalog).unwrap();
assert_eq!(catalog["markets"].as_array().unwrap().len(), 3);
assert_eq!(catalog["markets"][1]["group_title"], "丙");
e.execute(order).unwrap();
let result = json!({"op":"finalize_augmented","id":"observed","group":"winner","observed_name":observed,"evidence":"公告 8"});
for market in ["a", "b"] {
e.execute(json!({"op":"close","id":format!("close-{market}"),"market":market}))
.unwrap();
}
assert!(e
.execute(json!({"op":"finalize","id":"child","market":"a","winner":"YES"}))
.is_err());
let before = state(&mut e);
assert!(e.execute(result.clone()).is_err());
assert_eq!(state(&mut e), before);
e.execute(json!({"op":"close","id":"close-other","market":"other"}))
.unwrap();
let receipt = e.execute(result.clone()).unwrap();
assert_eq!(receipt["winner"], winner);
assert_eq!(receipt, e.execute(result).unwrap());
assert_eq!(
e.execute(json!({"op":"redeem","id":"claim","market":winner,"account":"user"}))
.unwrap()["paid"],
100
);
}
}
#[test]
fn wallet_activity_paginates_fills_and_records_each_automatic_redemption_once() {
let dir = tempdir().unwrap();
let path = dir.path().join("activity.sqlite");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
e.execute(order("ask", "alice", "sell", 49, 2)).unwrap();
e.execute(order("buy", "bob", "buy", 49, 2)).unwrap();
e.execute(json!({"op":"merge","id":"merge","market":"e","account":"alice","qty":3}))
.unwrap();
e.execute(json!({"op":"close","id":"close","market":"e"}))
.unwrap();
let resolve = json!({"op":"resolve","id":"pay","market":"e","winner":"YES"});
e.execute(resolve.clone()).unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
e.execute(resolve).unwrap();
let all = e
.execute(json!({"op":"activity","account":"alice","direction":"ASC"}))
.unwrap();
let rows = all["activity"].as_array().unwrap();
assert_eq!(rows.len(), 4);
let find = |kind: &str| rows.iter().find(|row| row["type"] == kind).unwrap();
assert_eq!(find("TRADE")["cash_delta_cents"], 98);
assert_eq!(find("MERGE")["cash_delta_cents"], 300);
assert_eq!(find("SPLIT")["cash_delta_cents"], -1000);
assert_eq!(find("REDEEM")["shares"], 12);
assert_eq!(find("REDEEM")["cash_delta_cents"], 500);
let mut query = json!({"op":"activity","account":"alice","direction":"ASC","limit":1});
let mut seen = Vec::new();
loop {
let page = e.execute(query.clone()).unwrap();
seen.extend(page["activity"].as_array().unwrap().iter().cloned());
if page["next_after"].is_null() {
break;
}
query["after"] = page["next_after"].clone();
}
assert_eq!(&seen, rows);
let bob = e
.execute(json!({"op":"activity","account":"bob","types":["REDEEM"]}))
.unwrap();
assert_eq!(bob["activity"][0]["cash_delta_cents"], 200);
let deposit = e
.execute(
json!({"op":"activity","account":"alice","types":["DEPOSIT"],"include_deposits":true}),
)
.unwrap();
assert_eq!(deposit["activity"][0]["cash_delta_cents"], 2000);
}
#[test]
fn prices_history_keeps_the_terminal_tick_and_pins_pages_before_settlement() {
let dir = tempdir().unwrap();
let path = dir.path().join("prices.sqlite");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
let query = json!({"op":"prices_history","asset_id":"eb:YES:e","start":120,"end":290,"bucket_seconds":60});
assert_eq!(e.execute(query.clone()).unwrap()["data"], json!([]));
for (i, price) in [43, 47, 55].into_iter().enumerate() {
e.execute(order(&format!("sell-{i}"), "alice", "sell", price, 1))
.unwrap();
e.execute(order(&format!("buy-{i}"), "bob", "buy", price, 1))
.unwrap();
}
let db = rusqlite::Connection::open(&path).unwrap();
db.execute("UPDATE trade_prices SET at_ms=CASE fill WHEN 1 THEN 121000 WHEN 2 THEN 149000 ELSE 245000 END",[]).unwrap();
let point = |t: i64, p: f64, r: i64, source: &str| json!({"timestamp":t,"price":p,"resolution_seconds":r,"source":source});
let original = e.execute(query.clone()).unwrap()["data"].clone();
assert_eq!(
original,
json!([
point(120, 0.47, 60, "trade"),
point(240, 0.55, 60, "trade"),
point(245, 0.55, 0, "trade")
])
);
let wire = |engine: &Exchange, params: Value| {
engine.public_price_history(serde_json::from_value(params).unwrap())
};
let clob = |engine: &Exchange, start: f64, end: f64, minutes: i64| {
engine
.clob_price_history(
serde_json::from_value(json!({
"market":"eb:YES:e","startTs":start,"endTs":end,"fidelity":minutes
}))
.unwrap(),
)
.unwrap()
};
assert_eq!(
clob(&e, 120.0, 245.0, 1),
json!({"history":[{"t":149,"p":0.47},{"t":245,"p":0.55}]})
);
assert_eq!(clob(&e, 149.001, 244.999, 1), json!({"history":[]}));
assert_eq!(
clob(&e, 120.0, 245.0, 10),
json!({"history":[{"t":245,"p":0.55}]})
);
let first_wire = wire(
&e,
json!({"tokenId":"eb:YES:e","start":120,"end":290,"bucketSeconds":60,"limit":1}),
)
.unwrap();
assert_eq!(
first_wire["data"],
json!([{"timestamp":120,"price":0.47,"resolution_seconds":60}])
);
let saved = first_wire["pagination"]["next_cursor"].as_str().unwrap();
assert!(wire(&e, json!({"token_id":"eb:NO:e","cursor":saved})).is_err());
assert!(wire(
&e,
json!({"token_id":"eb:YES:e","start":121,"cursor":saved})
)
.is_err());
assert!(wire(&e, json!({"token_id":"eb:YES:e","cursor":"broken!"})).is_err());
let mut first = query.clone();
first["limit"] = json!(1);
let page = e.execute(first).unwrap();
e.execute(json!({"op":"close","id":"close","market":"e"}))
.unwrap();
e.execute(json!({"op":"finalize","id":"void","market":"e","winner":"VOID"}))
.unwrap();
db.execute(
"UPDATE price_settlements SET at_ms=273000 WHERE market='e'",
[],
)
.unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(
clob(&e, 120.0, 290.0, 1),
json!({"history":[{"t":149,"p":0.47},{"t":273,"p":0.5}]})
);
let second_wire = wire(
&e,
json!({"token_id":"eb:YES:e","start":120,"end":290,"cursor":saved,"limit":99}),
)
.unwrap();
assert_eq!(second_wire["pagination"]["limit"], 1);
assert_eq!(second_wire["pagination"]["offset"], 1);
assert_eq!(
second_wire["data"],
json!([{"timestamp":240,"price":0.55,"resolution_seconds":60}])
);
let final_wire = wire(
&e,
json!({"token_id":"eb:YES:e","cursor":second_wire["pagination"]["next_cursor"]}),
)
.unwrap();
assert_eq!(
final_wire["data"],
json!([{"timestamp":245,"price":0.55,"resolution_seconds":0}])
);
assert_eq!(
final_wire["pagination"],
json!({"limit":1,"offset":2,"has_more":false,"next_cursor":null})
);
let at_resolution = wire(&e, json!({"token_id":"eb:YES:e","asOf":273})).unwrap();
assert_eq!(
at_resolution["data"],
json!([{"timestamp":273,"price":0.5,"resolution_seconds":0}])
);
let mut seen = page["data"].as_array().unwrap().clone();
let mut cursor = page["pagination"]["next_cursor"].clone();
while !cursor.is_null() {
let p = e
.execute(json!({"op":"prices_history","asset_id":"eb:YES:e","cursor":cursor}))
.unwrap();
seen.extend(p["data"].as_array().unwrap().iter().cloned());
cursor = p["pagination"]["next_cursor"].clone();
}
assert_eq!(json!(seen), original);
let resolved = e.execute(query).unwrap();
assert_eq!(resolved["data"][3], point(290, 0.5, 0, "local_settlement"));
for (t, price) in [
(120, None),
(121, Some(0.43)),
(272, Some(0.55)),
(273, Some(0.5)),
] {
let data = e
.execute(json!({"op":"prices_history","asset_id":"eb:YES:e","as_of":t}))
.unwrap()["data"]
.clone();
assert_eq!(data[0]["price"], json!(price));
}
assert!(e
.execute(
json!({"op":"prices_history","asset_id":"eb:YES:e","as_of":121,"bucket_seconds":60})
)
.is_err());
assert!(e
.execute(json!({"op":"prices_history","asset_id":"eb:YES:e","start":0,"end":1296001}))
.is_err());
}
#[test]
fn quote_cursor_replays_only_committed_changes_to_best_prices() {
let dir = tempdir().unwrap();
let path = dir.path().join("quotes.sqlite");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"start","market":"e"}))
.unwrap();
let snapshot = json!({"op":"quote","asset_id":"eb:YES:e"});
assert_eq!(e.execute(snapshot.clone()).unwrap()["quote_seq"], 0);
let bid = order("best", "bob", "buy", 8, 1);
e.execute(bid.clone()).unwrap();
let first = e.execute(snapshot.clone()).unwrap()["quote_seq"].clone();
e.execute(bid).unwrap();
let mut mirrored = order("no-buy", "bob", "buy", 91, 1);
mirrored["outcome"] = json!("NO");
let maker = e.execute(mirrored).unwrap();
e.execute(order("behind", "bob", "buy", 7, 1)).unwrap();
let page = |asset: &str, seq: &Value| json!({"op":"quote_history","asset_id":asset,"after":seq,"limit":1});
let change = e.execute(page("eb:YES:e", &first)).unwrap();
let q = &change["points"][0];
assert_eq!(q["best_bid_micros"], 80000);
assert_eq!(q["best_ask_micros"], 90000);
assert_eq!(q["midpoint_micros"], 85000);
assert_eq!(q["spread_micros"], 10000);
assert_eq!(change["has_more"], false);
let reflected = e.execute(page("eb:NO:e", &first)).unwrap();
assert_eq!(reflected["points"][0]["best_ask_micros"], 920000);
assert_eq!(reflected["points"][0]["best_bid_micros"], 910000);
assert_eq!(reflected["cursor"], change["cursor"]);
assert_eq!(state(&mut e)["fills"], json!([]));
let db = rusqlite::Connection::open(&path).unwrap();
let now: i64 = db
.query_row("SELECT unixepoch()", [], |r| r.get(0))
.unwrap();
let mut dated = order("gtd", "alice", "sell", 9, 1);
dated["expiration"] = json!(now + 900);
let dated_id = e.execute(dated).unwrap()["order"].clone();
e.execute(json!({"op":"cancel","id":"cancel-no","order":maker["order"],"account":"bob"}))
.unwrap();
assert_eq!(
e.execute(snapshot.clone()).unwrap()["quote_seq"],
change["cursor"]
);
db.execute(
"UPDATE order_deadlines SET expiration=unixepoch()+60 WHERE seq=?",
[dated_id.as_i64().unwrap()],
)
.unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
e.execute(json!({"op":"cancel_all","id":"cancel-bids","account":"bob"}))
.unwrap();
let one = e.execute(page("eb:YES:e", &change["cursor"])).unwrap();
assert_eq!(one["has_more"], true);
assert_eq!(one["points"][0]["best_bid_micros"], 80000);
assert!(one["points"][0]["best_ask_micros"].is_null());
let two = e.execute(page("eb:YES:e", &one["cursor"])).unwrap();
assert!(two["points"][0]["best_bid_micros"].is_null());
assert!(two["points"][0]["midpoint_micros"].is_null());
assert_eq!(two["has_more"], false);
let empty = e.execute(page("eb:YES:e", &two["cursor"])).unwrap();
assert_eq!(empty["points"], json!([]));
assert_eq!(empty["cursor"], two["cursor"]);
}
#[test]
fn catalog_and_ranked_volume_count_executions_once_across_conditions() {
let mut e = Exchange::open(":memory:").unwrap();
let mut result = Value::Null;
for line in include_str!("../../../docs/examples/football.jsonl")
.lines()
.chain(include_str!("../../../docs/examples/volume.jsonl").lines())
{
result = e.execute(serde_json::from_str(line).unwrap()).unwrap();
}
assert_eq!(
result["volume"]["all_time"],
json!({"matched_shares":5,"taker_shares":5,"taker_notional_cents":180,"unknown_role_shares":0})
);
assert_eq!(result["volume"]["all_time"], result["volume"]["last_24h"]);
assert_eq!(result["conditions"][0]["market"], "full-2-1");
assert_eq!(result["conditions"][1]["market"], "half-1-0");
let catalog = e
.execute(json!({"op":"catalog","event":"cup-a-b"}))
.unwrap();
assert_eq!(catalog["event"]["volume"], result["volume"]);
for condition in result["conditions"].as_array().unwrap() {
let listing = catalog["markets"]
.as_array()
.unwrap()
.iter()
.find(|m| m["market"] == condition["market"])
.unwrap();
assert_eq!(listing["volume"], condition["volume"]);
}
}
#[test]
fn valuation_counts_reserved_shares_and_distinguishes_unpriced_from_zero() {
let dir = tempdir().unwrap();
let path = dir.path().join("valuation.db");
let mut e = Exchange::open(&path).unwrap();
let mut snapshots = Vec::new();
for line in include_str!("../../../docs/examples/valuation.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
let response = e.execute(cmd.clone()).unwrap();
match cmd["op"].as_str().unwrap() {
"portfolio_value" => snapshots.push(response),
"positions" => {
let yes = response["positions"]
.as_array()
.unwrap()
.iter()
.find(|p| p["outcome"] == "YES")
.unwrap();
assert_eq!(yes["reserved_size"], 8);
assert_eq!(yes["current_price_micros"], 565000);
assert_eq!(yes["price_source"], "midpoint");
assert_eq!(yes["current_value_micros"], 4520000);
drop(e);
e = Exchange::open(&path).unwrap();
}
_ => {}
}
}
assert_eq!(snapshots.len(), 4);
assert!(snapshots[0]["value_micros"].is_null());
assert_eq!(snapshots[0]["unpriced_positions"], 1);
assert_eq!(snapshots[0]["priced_value_micros"], 4800000);
assert_eq!(snapshots[1]["value_micros"], 8870000);
assert_eq!(snapshots[2]["value_micros"], 8000000);
assert_eq!(snapshots[3]["value_micros"], 0);
}
#[test]
fn holders_net_reserved_and_hedged_balances_and_page_each_token() {
let mut e = Exchange::open(":memory:").unwrap();
let mut first = Value::Null;
let mut gross = Value::Null;
for line in include_str!("../../../docs/examples/holders.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
let response = e.execute(cmd.clone()).unwrap();
if cmd["op"] == "holders" {
if cmd["basis"] == "gross" {
gross = response;
} else {
first = response;
}
}
}
assert_eq!(first["data"].as_array().unwrap().len(), 2);
assert_eq!(
first["data"][0]["holders"][0],
json!({"account":"alice","amount":3,"rank":1})
);
assert_eq!(
first["data"][1]["holders"][0],
json!({"account":"bob","amount":3,"rank":1})
);
let next = e
.execute(json!({"op":"holders","cursor":first["next_cursor"]}))
.unwrap();
assert_eq!(next["data"].as_array().unwrap().len(), 1);
assert_eq!(
next["data"][0]["holders"][0],
json!({"account":"carol","amount":0,"rank":2})
);
assert!(next["next_cursor"].is_null());
assert!(e
.execute(json!({"op":"holders","cursor":first["next_cursor"],"market":"different"}))
.is_err());
assert_eq!(gross["data"][0]["holders"][0]["amount"], 10);
assert_eq!(gross["data"][1]["holders"][0]["amount"], 7);
assert_eq!(
gross["data"][1]["holders"][0]["current_value_micros"],
2800000
);
assert_eq!(gross["data"][1]["holders"][1]["account"], "bob");
assert_eq!(
e.execute(json!({"op":"holders","markets":["missing","cup","cup"],"min_balance":3.5}))
.unwrap()["data"],
json!([])
);
e.execute(json!({"op":"close","id":"end","market":"cup"}))
.unwrap();
e.execute(json!({"op":"finalize","id":"result","market":"cup","winner":"YES"}))
.unwrap();
e.execute(json!({"op":"redeem","id":"collect","account":"alice","market":"cup"}))
.unwrap();
let after = e
.execute(json!({"op":"holders","market":"cup","min_balance":1}))
.unwrap();
assert_eq!(after["data"].as_array().unwrap().len(), 1);
assert_eq!(after["data"][0]["holders"][0]["account"], "bob");
}
#[test]
fn public_trades_reconcile_event_volume_and_resume_between_legs() {
let mut e = Exchange::open(":memory:").unwrap();
for line in include_str!("../../../docs/examples/football.jsonl")
.lines()
.chain(include_str!("../../../docs/examples/volume.jsonl").lines())
{
e.execute(serde_json::from_str(line).unwrap()).unwrap();
}
let event = e
.execute(json!({"op":"public_trades","event":"cup-a-b"}))
.unwrap();
let data = event["data"].as_array().unwrap();
assert_eq!(data.len(), 2);
assert_eq!(data[0]["kind"], "transfer");
assert_eq!(data[1]["kind"], "mint");
assert_eq!(data[1]["outcome"], "NO");
assert_eq!(data[1]["price_micros"], 400000);
assert_eq!(
data.iter()
.map(|r| r["gross_cents"].as_i64().unwrap())
.sum::<i64>(),
180
);
let first = e
.execute(json!({"op":"public_trades","market":"full-2-1","taker_only":false,"limit":1}))
.unwrap();
let next = e
.execute(json!({"op":"public_trades","cursor":first["next_cursor"]}))
.unwrap();
assert_eq!(first["data"][0]["role"], "taker");
assert_eq!(next["data"][0]["role"], "maker");
assert_eq!(next["data"][0]["gross_cents"], 180);
assert!(next["next_cursor"].is_null());
assert!(e
.execute(json!({"op":"public_trades","event":"elsewhere","cursor":first["next_cursor"]}))
.is_err());
assert_eq!(
e.execute(
json!({"op":"public_trades","filter_type":"CASH","filter_amount":1,"side":"BUY"})
)
.unwrap()["data"]
.as_array()
.unwrap()
.len(),
1
);
assert_eq!(
e.execute(json!({"op":"public_trades","market":"unlisted"}))
.unwrap()["data"],
json!([])
);
}
#[test]
fn priced_interest_follows_outstanding_tokens_through_transfer_merge_and_redemption() {
let mut exchange = Exchange::open(":memory:").unwrap();
let mut snapshots = Vec::new();
for line in include_str!("../../../docs/examples/open-interest.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
let response = exchange.execute(cmd.clone()).unwrap();
if cmd["op"] == "open_interest" {
assert_eq!(response["data"].as_array().unwrap().len(), 1);
snapshots.push(response["data"][0].clone());
}
}
assert_eq!(snapshots.len(), 6);
assert_eq!(snapshots[0]["condition_id"], "cup");
assert_eq!(snapshots[0]["value_micros"], 0);
assert_eq!(snapshots[1]["gross_shares"], 20);
assert_eq!(snapshots[1]["unpriced_shares"], 10);
assert_eq!(snapshots[1]["priced_value_micros"], 6000000);
assert!(snapshots[1]["value"].is_null());
assert_eq!(snapshots[2]["value"].as_f64(), Some(10.0));
assert_eq!(snapshots[2]["gross_shares"], 20);
assert_eq!(snapshots[3]["condition_id"], "GLOBAL");
assert_eq!(snapshots[3]["value_micros"], 7000000);
assert_eq!(snapshots[3]["gross_shares"], 14);
assert_eq!(snapshots[4]["value_micros"], 2000000);
assert_eq!(snapshots[5]["value_micros"], 0);
assert_eq!(
exchange
.execute(json!({"op":"open_interest","market":"missing"}))
.unwrap()["data"],
json!([])
);
}
#[test]
fn fees_follow_taker_cash_budget_and_net_sale_proceeds() {
let dir = tempdir().unwrap();
let path = dir.path().join("fees.db");
let mut e = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/fees.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
if cmd["op"] == "market_buy" {
e.execute(json!({"op":"fund","id":"poor","account":"poor","cents":5000}))
.unwrap();
let before = state(&mut e);
assert!(e.execute(json!({"op":"order","id":"unfunded-fee","market":"cup","outcome":"YES","side":"buy","price":50,"qty":100,"account":"poor"})).is_err());
assert_eq!(state(&mut e), before);
}
let reply = e.execute(cmd.clone()).unwrap();
match cmd["op"].as_str().unwrap() {
"estimate" if cmd["amount_cents"] == 5000 => {
assert_eq!(reply["filled_shares"].to_string(), "97.56")
}
"estimate" => assert_eq!(reply["fee_micros"], 1250000),
"market_buy" => {
assert_eq!(reply["total_spent_micros"], 51250000);
assert_eq!(reply["fee_micros"], 1250000);
drop(e);
e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(cmd).unwrap(), reply);
}
"market_sell" => {
assert_eq!(reply["fee_micros"], 10500);
assert_eq!(reply["net_proceeds_micros"], 289500);
}
_ => {}
}
}
let s = state(&mut e);
assert_eq!(s["accounts"][1]["cash"], 903);
assert_eq!(s["cash_remainders"][0]["micros"], 9500);
assert_eq!(s["execution_fees"].as_array().unwrap().len(), 2);
let leg = e
.execute(json!({"op":"trades","account":"alice","market":"cup"}))
.unwrap();
assert!(leg["trades"]
.as_array()
.unwrap()
.iter()
.all(|r| r["fee_micros"] == 0));
}
#[test]
fn heartbeat_rotates_and_recovers_only_orders_owned_by_the_expired_key() {
let dir = tempdir().unwrap();
let path = dir.path().join("heartbeats.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
e.execute(json!({"op":"list","id":"second","market":"other","rules":"r"}))
.unwrap();
let mut a = order("ask", "alice", "sell", 60, 4);
a["key_id"] = json!("bot");
e.execute(a).unwrap();
let mut b = order("bid", "alice", "buy", 30, 2);
b["market"] = json!("other");
b["key_id"] = json!("bot");
e.execute(b).unwrap();
let base = order("default", "alice", "buy", 10, 1);
e.execute(base).unwrap();
let mut manual = order("manual", "alice", "buy", 11, 1);
manual["key_id"] = json!("manual");
e.execute(manual).unwrap();
let mut bob = order("bob-bid", "bob", "buy", 12, 1);
bob["key_id"] = json!("bot");
e.execute(bob).unwrap();
let beat = |account: &str, id: &str| json!({"op":"heartbeat","account":account,"key_id":"bot","heartbeat_id":id});
let first = e.execute(beat("alice", "")).unwrap();
let first_id = first["heartbeat_id"].as_str().unwrap();
let second = e.execute(beat("alice", first_id)).unwrap();
let second_id = second["heartbeat_id"].as_str().unwrap();
assert_ne!(first_id, second_id);
assert_eq!(
e.execute(beat("alice", first_id)).unwrap(),
json!({"error_msg":"Invalid Heartbeat ID","heartbeat_id":second_id})
);
let observer = rusqlite::Connection::open(&path).unwrap();
let deadline: i64 = observer
.query_row(
"SELECT deadline_ms FROM order_heartbeats WHERE account='alice'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(second["deadline_ms"], deadline);
e.execute(beat("bob", "")).unwrap();
observer
.execute(
"UPDATE order_heartbeats SET deadline_ms=0 WHERE account='alice'",
[],
)
.unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
let s = state(&mut e);
let statuses: Vec<_> = s["orders"]
.as_array()
.unwrap()
.iter()
.map(|o| o["status"].as_str().unwrap())
.collect();
assert_eq!(statuses, ["cancelled", "cancelled", "live", "live", "live"]);
assert_eq!(s["accounts"][0]["cash"], 979);
assert_eq!(
s["positions"]
.as_array()
.unwrap()
.iter()
.find(|p| p["outcome"] == "YES")
.unwrap()["quantity"],
10
);
assert_eq!(
e.execute(beat("alice", second_id)).unwrap()["heartbeat_id"],
""
);
let mut later = order("later", "alice", "buy", 10, 1);
later["key_id"] = json!("bot");
e.execute(later).unwrap();
e.maintain().unwrap();
assert_eq!(state(&mut e)["orders"][5]["status"], "live");
e.execute(json!({"op":"heartbeat","account":"alice","heartbeat_id":""}))
.unwrap();
observer
.execute(
"UPDATE order_heartbeats SET deadline_ms=0 WHERE account='alice' AND key_id=''",
[],
)
.unwrap();
e.maintain().unwrap();
let s = state(&mut e);
assert_eq!(s["orders"][2]["status"], "cancelled");
assert_eq!(s["orders"][3]["status"], "live");
assert_eq!(s["orders"][5]["status"], "live");
}
#[test]
fn minimum_size_checks_submitted_orders_and_preserves_partial_fills() {
let dir = tempdir().unwrap();
let path = dir.path().join("minimum.db");
let mut e = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/minimum-size.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
let result = e.execute(cmd.clone()).unwrap();
if cmd["id"] == "first" {
assert_eq!(result["filled"], 5);
}
if cmd["op"] == "book" {
assert_eq!(result["asks"][0]["size"], 3);
assert_eq!(result["min_order_size"], "5");
}
if cmd["id"] == "second" {
assert_eq!(result["filled"], 3);
}
}
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(
e.execute(json!({"op":"assets","market":"e"})).unwrap()["min_order_size"],
"5"
);
let before = state(&mut e);
for cmd in [
order("small", "bob", "buy", 55, 4),
json!({"op":"market_sell","id":"small-sell","market":"e","account":"alice","outcome":"YES","qty":4,"min_price":1}),
json!({"op":"market_buy","id":"small-buy","market":"e","account":"bob","outcome":"YES","amount_cents":259,"max_price":52}),
json!({"op":"estimate","asset_id":"eb:YES:e","side":"buy","amount_cents":259,"max_price":52}),
json!({"op":"estimate","asset_id":"eb:NO:e","side":"sell","qty":4}),
] {
assert!(e
.execute(cmd)
.unwrap_err()
.to_string()
.contains("min_order_size"));
}
assert_eq!(state(&mut e), before);
let empty=e.execute(json!({"op":"estimate","asset_id":"eb:YES:e","side":"buy","amount_cents":260,"max_price":52})).unwrap();
assert_eq!(empty["filled_shares"], 0);
e.execute(json!({"op":"list","id":"fractional","market":"f","rules":"r","min_order_size":"5.125000","taker_fee_rate_ppm":50000})).unwrap();
assert_eq!(
e.execute(json!({"op":"assets","market":"f"})).unwrap()["min_order_size"],
"5.125"
);
e.execute(json!({"op":"open","id":"open-f","market":"f"}))
.unwrap();
for (budget, ok) in [(262, false), (263, true)] {
let quote=e.execute(json!({"op":"estimate","market":"f","outcome":"YES","side":"buy","max_price":50,"amount_cents":budget}));
assert_eq!(quote.is_ok(), ok);
}
let invalid = json!({"op":"list","id":"retry","market":"invalid","rules":"r","min_order_size":"0.0000001"});
assert!(e.execute(invalid).is_err());
e.execute(json!({"op":"list","id":"retry","market":"invalid","rules":"r"}))
.unwrap();
assert!(e
.execute(json!({"op":"assets","market":"invalid"}))
.unwrap()["min_order_size"]
.is_null());
}
#[test]
fn single_and_batch_execution_prices_follow_opposing_liquidity() {
let dir = tempdir().unwrap();
let path = dir.path().join("execution-prices.db");
let mut e = Exchange::open(&path).unwrap();
let mut batch = Value::Null;
let mut single = Vec::new();
for line in include_str!("../../../docs/examples/execution-prices.jsonl").lines() {
let request: Value = serde_json::from_str(line).unwrap();
let response = e.execute(request.clone()).unwrap();
match request["op"].as_str().unwrap() {
"price" => single.push(response["price"].clone()),
"prices" => {
for (asset, buy, sell) in [
("eb:YES:cup:final", 0.11, 0.09),
("eb:NO:cup:final", 0.91, 0.89),
] {
assert_eq!(response[asset]["BUY"].as_f64(), Some(buy));
assert_eq!(response[asset]["SELL"].as_f64(), Some(sell));
}
batch = request;
}
_ => {}
}
}
assert_eq!(single, vec![Value::Null, json!("0.11")]);
let mut reader = Exchange::open(&path).unwrap();
assert_eq!(
reader.execute(batch.clone()).unwrap(),
e.execute(batch.clone()).unwrap()
);
e.execute(json!({"op":"cancel_all","id":"cancel","account":"alice"}))
.unwrap();
let empty = reader.execute(batch.clone()).unwrap();
assert_eq!(empty["eb:NO:cup:final"], json!({"BUY":null,"SELL":null}));
let item = batch["requests"][0].clone();
let limit = json!({"op":"prices","requests":vec![item.clone();500]});
assert_eq!(
reader.execute(limit).unwrap(),
json!({"eb:YES:cup:final":{"BUY":null}})
);
for invalid in [
json!({"op":"prices","requests":[]}),
json!({"op":"prices","requests":vec![item.clone();501]}),
json!({"op":"prices","requests":[item,{"token_id":"eb:YES:unknown","side":"BUY"}]}),
json!({"op":"price","token_id":"eb:other:cup:final","side":"SELL"}),
json!({"op":"price","token_id":"eb:YES:cup:final","side":"other"}),
] {
assert!(reader.execute(invalid).is_err());
}
}
#[test]
fn collateral_query_reconciles_subcent_funding_reservations_and_trade() {
let dir = tempdir().unwrap();
let path = dir.path().join("subcent.db");
let mut exchange = Exchange::open(&path).unwrap();
let balance = json!({"op":"balance","account":"buyer"});
for line in include_str!("../../../docs/examples/cash-balance.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
if cmd["id"] == "trade" {
exchange
.execute(json!({"op":"fund","id":"short","account":"short","micros":512499}))
.unwrap();
let mut short = cmd.clone();
short["id"] = json!("failed");
short["account"] = json!("short");
let before = state(&mut exchange);
assert!(exchange.execute(short).is_err());
assert_eq!(state(&mut exchange), before);
}
let response = exchange.execute(cmd.clone()).unwrap();
match cmd["id"].as_str() {
Some("seller") => assert_eq!(response, json!({"funded":100})),
Some("buyer") => assert_eq!(response, json!({"funded":51,"funded_micros":512500})),
Some("rest") => assert_eq!(
exchange.execute(balance.clone()).unwrap(),
json!({"account":"buyer","available_micros":22500,"reserved_micros":490000,"total_cash_micros":512500})
),
Some("withdraw") => assert_eq!(
exchange.execute(balance.clone()).unwrap()["available_micros"],
512500
),
Some("trade") => assert_eq!(response["fee_micros"], 12500),
_ => {}
}
if cmd["op"] == "activity" {
assert_eq!(response["activity"][0]["net_cash_delta_micros"], -512500);
assert_eq!(response["activity"][1]["net_cash_delta_micros"], 512500);
}
}
drop(exchange);
let mut exchange = Exchange::open(&path).unwrap();
assert_eq!(exchange.execute(balance).unwrap()["total_cash_micros"], 0);
assert_eq!(
exchange
.execute(json!({"op":"balance","account":"seller"}))
.unwrap()["total_cash_micros"],
500000
);
let repeat = json!({"op":"fund","id":"buyer","account":"buyer","micros":512500});
assert_eq!(exchange.execute(repeat).unwrap()["funded_micros"], 512500);
for invalid in [
json!({"micros":0}),
json!({"cents":1,"micros":1}),
json!({"micros":10000000000001_i64}),
json!({}),
] {
let mut request = invalid;
request["op"] = json!("fund");
request["account"] = json!("invalid");
request["id"] = json!("invalid");
assert!(exchange.execute(request).is_err());
}
assert!(exchange
.execute(json!({"op":"balance","account":"invalid"}))
.is_err());
}
#[test]
fn configured_ticks_bind_order_amounts_execution_and_opening_price() {
let dir = tempdir().unwrap();
let path = dir.path().join("ticks.db");
let mut exchange = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/tick-size.jsonl").lines() {
let request: Value = serde_json::from_str(line).unwrap();
let result = exchange.execute(request.clone()).unwrap();
if request["op"] == "limit_amounts" {
assert_eq!(result["size_micros"], 5120000);
assert_eq!(result["collateral_micros"], 66560);
assert_eq!(result["local_precision_supported"], true);
let (maker, taker) = if request["side"] == "buy" {
("66560", "5120000")
} else {
("5120000", "66560")
};
assert_eq!(result["makerAmount"], maker);
assert_eq!(result["takerAmount"], taker);
}
if request["op"] == "book" {
assert_eq!(result["tick_size"], "0.001");
}
if request["op"] == "state" {
assert_eq!(result["fills"][0]["price"], 60);
}
}
drop(exchange);
let mut e = Exchange::open(path).unwrap();
let before = state(&mut e);
for bad in [
json!({"op":"order","id":"bad","market":"coarse","outcome":"NO","account":"bob","price":51,"qty":1,"side":"buy"}),
json!({"op":"market_sell","id":"bad","market":"coarse","outcome":"YES","account":"bob","min_price":51,"qty":1}),
json!({"op":"market_buy","id":"bad","market":"coarse","outcome":"YES","account":"bob","max_price":51,"amount_cents":90}),
json!({"op":"estimate","market":"coarse","outcome":"YES","side":"buy","max_price":51,"amount_cents":90}),
json!({"op":"limit_amounts","asset_id":"eb:YES:sample-559651","side":"buy","price_micros":13100,"size_micros":5000000}),
json!({"op":"limit_amounts","asset_id":"eb:YES:sample-559651","side":"buy","price_micros":13000,"size_micros":4999999}),
json!({"op":"list","id":"invalid","market":"legacy","rules":"r","tick_size":"0.03"}),
] {
assert!(e.execute(bad).is_err());
}
assert_eq!(state(&mut e), before);
assert_eq!(
e.execute(json!({"op":"assets","market":"coarse"})).unwrap()["tick_size"],
"0.1"
);
e.execute(json!({"op":"list","id":"invalid","market":"legacy","rules":"r"}))
.unwrap();
assert!(e.execute(json!({"op":"assets","market":"legacy"})).unwrap()["tick_size"].is_null());
assert_eq!(
json!(e.minimum_tick_size("eb:NO:legacy").unwrap()),
json!(0.01)
);
assert!(e
.minimum_tick_size("eb:YES:no-such-market")
.unwrap()
.is_none());
e.execute(json!({"op":"order","id":"old","market":"legacy","outcome":"YES","account":"bob","side":"buy","price":0,"qty":1})).unwrap();
}
#[test]
fn replayed_tick_changes_preserve_valid_orders_and_release_only_residuals() {
let dir = tempdir().unwrap();
let path = dir.path().join("tick-changes.db");
let mut e = Exchange::open(&path).unwrap();
let reader = Exchange::open(&path).unwrap();
let mut original = Value::Null;
let mut cursor = Value::Null;
for line in include_str!("../../../docs/examples/tick-changes.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
let response = e.execute(cmd.clone()).unwrap();
if let Some(step) = cmd.get("new_tick_size").or(cmd.get("tick_size")) {
for token in ["eb:YES:cup", "eb:NO:cup"] {
let current = reader.minimum_tick_size(token).unwrap().unwrap();
assert_eq!(current.to_string(), step.as_str().unwrap());
}
}
match cmd["op"].as_str().unwrap() {
"tick_size_change" if cmd["id"] == "finer" => {
assert_eq!(response["canceled"], json!([]))
}
"tick_size_change" => {
assert_eq!(response["canceled"], json!([1, 3]));
original = response;
}
"limit_amounts" => assert_eq!(response["collateral_micros"], 65000),
"book" => {
assert_eq!(response["tick_seq"], original["tick_seq"]);
assert_eq!(response["tick_size"], "0.1");
assert_eq!(response["bids"], json!([{"price_micros":400000,"size":1}]));
}
"balance" => {
assert_eq!(response["available_micros"], 18970000);
assert_eq!(response["reserved_micros"], 400000);
}
"tick_history" => {
assert_eq!(response["has_more"], true);
cursor = response["cursor"].clone();
}
_ => {}
}
}
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(
json!(e.minimum_tick_size("eb:YES:cup").unwrap()),
json!(0.1)
);
let before = state(&mut e);
let position = before["positions"]
.as_array()
.unwrap()
.iter()
.find(|p| p["account"] == "alice" && p["outcome"] == "NO")
.unwrap();
assert_eq!(position["quantity"], 4);
let event = json!({"op":"tick_size_change","asset_id":"eb:YES:cup","id":"mirror","new_tick_size":"0.1000","timestamp":"1757908892400"});
assert_eq!(e.execute(event.clone()).unwrap(), original);
let mut stale = event.clone();
stale["id"] = json!("stale");
stale["timestamp"] = json!("1757908892375");
let mut conflict = event.clone();
conflict["id"] = json!("conflict");
conflict["new_tick_size"] = json!("0.01");
let mut mismatch = event;
mismatch["id"] = json!("wrong-old");
mismatch["timestamp"] = json!("1757908892410");
mismatch["old_tick_size"] = json!("0.005");
mismatch["new_tick_size"] = json!("0.001");
for bad in [
stale,
conflict,
mismatch,
json!({"op":"order","id":"offgrid","market":"cup","outcome":"YES","side":"buy","account":"bob","price":51,"qty":1}),
] {
assert!(e.execute(bad).is_err());
}
assert_eq!(before, state(&mut e));
let page = e
.execute(json!({"op":"tick_history","asset_id":"eb:NO:cup","after":cursor}))
.unwrap();
assert_eq!(page["events"].as_array().unwrap().len(), 1);
assert_eq!(page["events"][0]["asset_id"], "eb:NO:cup");
assert_eq!(page["events"][0]["seq"], original["tick_seq"]);
assert_eq!(page["has_more"], false);
}
#[test]
fn kickoff_clears_three_books_once_and_returns_only_remaining_reserves() {
let dir = tempdir().unwrap();
let path = dir.path().join("football.db");
let mut exchange = Exchange::open(&path).unwrap();
setup(&mut exchange);
for line in include_str!("../../../docs/examples/football.jsonl").lines() {
let mut command: Value = serde_json::from_str(line).unwrap();
if command["op"] == "event" {
command["scheduled_at_ms"] = json!(i64::MAX);
}
exchange.execute(command).unwrap();
}
let mut other = Exchange::open(&path).unwrap();
exchange
.execute(json!({"op":"open","id":"full-open","market":"full-2-1"}))
.unwrap();
exchange
.execute(
json!({"op":"split","id":"full-split","market":"full-2-1","account":"alice","qty":4}),
)
.unwrap();
let mut place = |id, account, side, price, qty, market: &str| {
let mut cmd = order(id, account, side, price, qty);
cmd["market"] = json!(market);
exchange.execute(cmd).unwrap()
};
place("ask-full", "alice", "sell", 60, 4, "full-2-1");
place("fill-one", "bob", "buy", 60, 1, "full-2-1");
place("bid-half", "bob", "buy", 40, 2, "half-1-0");
place("bid-goals", "bob", "buy", 30, 3, "over-25");
place("unrelated", "bob", "buy", 20, 1, "e");
let book = json!({"op":"book","market":"full-2-1","outcome":"YES"});
assert_eq!(
other.execute(book.clone()).unwrap()["asks"]
.as_array()
.unwrap()
.len(),
1
);
let reschedule = json!({"op":"reschedule_sports","id":"early","event":"cup-a-b",
"previous_ms":i64::MAX,"scheduled_at_ms":1});
let receipt = exchange.execute(reschedule.clone()).unwrap();
assert_eq!(other.execute(book.clone()).unwrap()["asks"], json!([]));
let s = state(&mut other);
assert_eq!(s["accounts"][1]["cash"], 1920);
let positions = s["positions"].as_array().unwrap();
assert!(positions.iter().any(|p| p["account"] == "alice"
&& p["market"] == "full-2-1"
&& p["outcome"] == "YES"
&& p["quantity"] == 3));
assert_eq!(s["orders"][4]["status"], "live");
let catalog = json!({"op":"catalog","event":"cup-a-b"});
let meta = other.execute(catalog.clone()).unwrap()["event"]["kickoff"].clone();
assert_eq!(meta["cancelled_orders"], 3);
assert!(meta["cleared_at_ms"].as_i64().unwrap() >= 1);
let mut live = order("in-play", "alice", "sell", 60, 3);
live["market"] = json!("full-2-1");
other.execute(live).unwrap();
drop(exchange);
drop(other);
let mut recovered = Exchange::open(path).unwrap();
assert_eq!(recovered.execute(reschedule.clone()).unwrap(), receipt);
let mut stale = reschedule;
stale["id"] = json!("late-retry");
assert!(recovered.execute(stale).is_err());
assert_eq!(
recovered.execute(catalog).unwrap()["event"]["kickoff"],
meta
);
assert_eq!(
recovered.execute(book).unwrap()["asks"]
.as_array()
.unwrap()
.len(),
1
);
}
#[test]
fn fractional_pairs_share_reservations_and_redeem_after_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("sets.db");
let mut e = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/fractional-inventory.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
if cmd["id"] == "merge-free" {
let mut too_many = cmd.clone();
too_many["qty_micros"] = json!(500002);
let before = state(&mut e);
assert!(e.execute(too_many).is_err());
assert_eq!(state(&mut e), before);
}
if cmd["id"] == "payout" {
drop(e);
e = Exchange::open(&path).unwrap();
}
let r = e.execute(cmd.clone()).unwrap();
match cmd["op"].as_str().unwrap() {
"positions" => {
let yes = r["positions"]
.as_array()
.unwrap()
.iter()
.find(|p| p["outcome"] == "YES")
.unwrap();
for (threshold, expected) in
[("1.500001", 2), ("1.500001000000001", 0), ("1500001e-6", 2)]
{
let minimum: serde_json::Number = threshold.parse().unwrap();
let holders=e.execute(json!({"op":"holders","market":"match","basis":"gross","min_balance":minimum})).unwrap();
assert_eq!(holders["data"].as_array().unwrap().len(), expected);
}
assert_eq!(yes["size"].to_string(), "1.500001");
assert_eq!(yes["available_pairs"].to_string(), "0.500001");
assert_eq!(yes["reserved_size"], 1);
}
"redeem" => {
assert_eq!(r["paid"].to_string(), "100.0001");
assert_eq!(e.execute(cmd).unwrap(), r);
}
"balance" => assert_eq!(r["available_micros"], 3_000_000),
"activity" => {
let rows = r["activity"].as_array().unwrap();
assert_eq!(rows[0]["shares"].to_string(), "1.500001");
assert_eq!(rows[1]["net_cash_delta_micros"], 500001);
assert_eq!(rows.last().unwrap()["shares"].to_string(), "2.000002");
}
_ => {}
}
}
assert!(state(&mut e)["position_remainders"]
.as_array()
.unwrap()
.is_empty());
}
#[test]
fn half_payout_keeps_unpayable_base_unit_in_market_backing() {
let mut e = Exchange::open(":memory:").unwrap();
for cmd in [
json!({"op":"fund","id":"a","account":"alice","micros":3}),
json!({"op":"list","id":"m","market":"e","rules":"void"}),
json!({"op":"split","id":"s","account":"alice","market":"e","qty_micros":3}),
json!({"op":"close","id":"c","market":"e"}),
json!({"op":"resolve","id":"r","market":"e","winner":"VOID"}),
] {
e.execute(cmd).unwrap();
}
assert_eq!(
e.execute(json!({"op":"balance","account":"alice"}))
.unwrap()["available_micros"],
2
);
let s = state(&mut e);
assert_eq!(s["settlement_dust"][0]["micros"], 1);
assert_eq!(s["collateral_remainders"][0]["micros"], 1);
}
#[test]
fn auction_fraction_survives_restart_then_trades_at_maker_price() {
let dir = tempdir().unwrap();
let path = dir.path().join("lots.db");
let mut engine = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/fractional-orders.jsonl").lines() {
let request: Value = serde_json::from_str(line).unwrap();
if request["op"] == "book" {
drop(engine);
engine = Exchange::open(&path).unwrap();
}
let reply = engine.execute(request.clone()).unwrap();
match request["op"].as_str().unwrap() {
"book" => assert_eq!(reply["asks"][0]["size"].to_string(), "0.73"),
"cancel" => assert_eq!(reply["cancelled"].to_string(), "0.44"),
"balance" => assert_eq!(reply["available_micros"], 1_565_500),
"history" => {
assert_eq!(reply["points"][0]["quantity"].to_string(), "0.5");
assert_eq!(reply["points"][1]["quantity"].to_string(), "0.29");
assert_eq!(reply["points"][1]["price_micros"], 550000);
}
_ => {}
}
}
let lookup = engine
.execute(json!({"op":"open_orders","account":"maker","order":1}))
.unwrap();
assert_eq!(lookup["orders"][0]["size_matched"].to_string(), "0.79");
assert_eq!(lookup["orders"][0]["original_size"].to_string(), "1.23");
let pos = engine
.execute(json!({"op":"positions","account":"maker","market":"e"}))
.unwrap();
let yes = pos["positions"]
.as_array()
.unwrap()
.iter()
.find(|p| p["outcome"] == "YES")
.unwrap();
assert_eq!(yes["available_size"].to_string(), "1.21");
assert_eq!(yes["reserved_size"], 0);
}
#[test]
fn old_resting_order_is_scaled_once_and_keeps_fifo_after_partial_fill() {
let dir = tempdir().unwrap();
let path = dir.path().join("old.db");
let db = rusqlite::Connection::open(&path).unwrap();
db.execute_batch(include_str!("../src/schema.sql")).unwrap();
db.execute_batch(
"INSERT INTO accounts VALUES('a',0),('b',100);
INSERT INTO markets(id,rules,phase,collateral) VALUES('old','r','continuous',100);
INSERT INTO positions VALUES('a','old','YES',0),('a','old','NO',1);
INSERT INTO orders VALUES(17,'a','old','YES','sell',40,1,1,'live');",
)
.unwrap();
drop(db);
for _ in 0..2 {
let mut e = Exchange::open(&path).unwrap();
assert_eq!(
e.execute(json!({"op":"book","market":"old","outcome":"YES"}))
.unwrap()["asks"][0]["size"],
1
);
}
let mut e = Exchange::open(&path).unwrap();
e.execute(json!({"op":"order","id":"hit","account":"b","market":"old","outcome":"YES","side":"buy","price":50,"size_micros":10000})).unwrap();
let r = e
.execute(json!({"op":"cancel","id":"release","account":"a","order":17}))
.unwrap();
assert_eq!(r["cancelled"].to_string(), "0.99");
}
#[test]
fn subcent_fills_reconcile_across_restart_budget_and_complement() {
let dir = tempdir().unwrap();
let path = dir.path().join("fine.db");
let mut e = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/fine-price-execution.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
if cmd["op"] == "price" {
drop(e);
e = Exchange::open(&path).unwrap();
}
if cmd["id"] == "buy" {
for invalid in [
json!({"price_micros":13500}),
json!({"price":1,"price_micros":13000}),
] {
let mut broken = cmd.clone();
broken
.as_object_mut()
.unwrap()
.extend(invalid.as_object().unwrap().clone());
assert!(e.execute(broken).is_err());
}
}
let r = e.execute(cmd.clone()).unwrap();
match cmd["op"].as_str().unwrap() {
"price" => assert_eq!(r["price"], "0.013"),
"balance" => assert_eq!(r["available_micros"], 1_933_440),
"estimate" => {
assert_eq!(r["total_spent_micros"], 9880);
assert_eq!(r["worst_fill_price"].to_string(), "1.3");
}
"market_buy" => {
assert_eq!(r["unspent_micros"], 120);
assert_eq!(r["total_spent_micros"], 9880);
}
"cancel" => assert_eq!(r["cancelled"].to_string(), "0.12"),
"history" => {
assert_eq!(r["points"][0]["price_micros"], 987000);
assert_eq!(r["points"][0]["quantity"].to_string(), "1.01");
}
_ => {}
}
}
let state = state(&mut e);
assert_eq!(state["fills"][0]["price"].to_string(), "1.3");
assert_eq!(state["paired_fills"][0]["yes_price"].to_string(), "1.3");
assert_eq!(state["markets"][0]["collateral"], 801);
let replay = e.execute(json!({"op":"volume","market":"e"})).unwrap();
assert_eq!(
replay["volume"]["all_time"]["taker_notional_cents"].to_string(),
"8.957"
);
}
#[test]
fn auction_uses_fine_grid_and_coarsening_releases_exact_bid_reserve() {
let mut e = Exchange::open(":memory:").unwrap();
e.execute(json!({"op":"list","id":"l","market":"e","rules":"r","tick_size":"0.001"}))
.unwrap();
for (who, cents) in [("maker", 200), ("buyer", 100)] {
e.execute(json!({"op":"fund","id":who,"account":who,"cents":cents}))
.unwrap();
}
e.execute(json!({"op":"split","id":"s","market":"e","account":"maker","qty":2}))
.unwrap();
for (id, account, side, p, qty) in [
("a", "maker", "sell", 12000, 2),
("b", "buyer", "buy", 12000, 3),
("c", "buyer", "buy", 17000, 2),
] {
e.execute(json!({"op":"order","id":id,"market":"e","outcome":"YES","account":account,"side":side,"price_micros":p,"qty":qty})).unwrap();
}
e.execute(json!({"op":"open","id":"o","market":"e"}))
.unwrap();
assert_eq!(state(&mut e)["fills"][0]["price"].to_string(), "1.3");
let balance = json!({"op":"balance","account":"buyer"});
let before = e.execute(balance.clone()).unwrap();
assert_eq!(before["reserved_micros"], 36000);
assert_eq!(before["available_micros"], 938000);
e.execute(json!({"op":"tick_size_change","id":"wider","asset_id":"eb:YES:e","old_tick_size":"0.001","new_tick_size":"0.01","timestamp":"1"})).unwrap();
let after = e.execute(balance).unwrap();
assert_eq!(after["available_micros"], 974000);
assert_eq!(after["reserved_micros"], 0);
}
#[test]
fn market_amounts_preview_and_execution_share_the_same_protection() {
let mut exchange = Exchange::open(":memory:").unwrap();
let buy = json!({"makerAmount":"10000000","takerAmount":"19230700"});
let sell = json!({"makerAmount":"5010000","takerAmount":"2404800"});
for line in include_str!("../../../docs/examples/market-amounts.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
let result = exchange.execute(cmd.clone()).unwrap();
match cmd["op"].as_str().unwrap() {
"market_amounts" => {
let expected = if cmd["side"] == "buy" { &buy } else { &sell };
for key in ["makerAmount", "takerAmount"] {
assert_eq!(result[key], expected[key]);
}
}
"estimate" => {
assert_eq!(result["order_amounts"], buy);
assert_eq!(result["filled_shares"], 20);
}
"market_buy" => {
assert_eq!(result["order_amounts"], buy);
assert_eq!(result["filled"], 20);
assert_eq!(result["spent_cents"], 1000);
}
"market_sell" => {
assert_eq!(result["order_amounts"], sell);
assert_eq!(result["proceeds_cents"].to_string(), "250.5");
}
_ => {}
}
}
}
#[test]
fn unsafe_encoded_buy_is_rejected_by_preview_estimate_and_submission() {
let mut e = Exchange::open(":memory:").unwrap();
e.execute(json!({"op":"list","id":"l","market":"tiny","rules":"r","tick_size":"0.1"}))
.unwrap();
e.execute(json!({"op":"open","id":"o","market":"tiny"}))
.unwrap();
let before = state(&mut e);
for request in [
json!({"op":"market_amounts","side":"buy","price_micros":300000,"amount_cents":1}),
json!({"op":"estimate","side":"buy","max_price":30,"amount_cents":1}),
json!({"op":"market_buy","id":"b","account":"buyer","max_price":30,"amount_cents":1}),
] {
let mut request = request;
request["asset_id"] = json!("eb:YES:tiny");
assert!(format!("{:#}", e.execute(request).unwrap_err())
.contains("rounded market buy exceeds price protection"));
}
assert_eq!(state(&mut e), before);
}
#[test]
fn derives_protection_from_current_depth_and_replays_the_original_receipt() {
let dir = tempdir().unwrap();
let path = dir.path().join("book.db");
let mut writer = Exchange::open(&path).unwrap();
let mut client = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/depth-protection.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
match cmd["op"].as_str().unwrap() {
"estimate" => {
let result = client.execute(cmd.clone()).unwrap();
assert_eq!(result["filled_shares"], 5);
if cmd["tif"] == "FOK" {
assert!(result["protection_price_micros"].is_null());
assert_eq!(result["executable"], false);
let before = state(&mut client);
assert!(client.execute(json!({"op":"market_buy","id":"short","asset_id":"eb:YES:fixture","account":"taker","amount_cents":231,"tif":"FOK"})).is_err());
assert_eq!(state(&mut client), before);
} else {
assert_eq!(result["protection_price_micros"], 500000);
assert_eq!(result["executable"], true);
}
}
"market_buy" => {
let r = client.execute(cmd.clone()).unwrap();
assert_eq!(r["protection_price_micros"], 500000);
assert_eq!(r["filled"], 4);
assert_eq!(r["spent_cents"], 180);
drop(client);
client = Exchange::open(&path).unwrap();
assert_eq!(client.execute(cmd).unwrap(), r);
}
"market_sell" => {
let r = client.execute(cmd).unwrap();
assert_eq!(r["protection_price_micros"], 200000);
assert_eq!(r["proceeds_cents"], 80);
}
_ => {
writer.execute(cmd).unwrap();
}
}
}
}
#[test]
fn automatic_price_uses_sdk_level_precision_while_cash_execution_is_exact() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"op":"open","id":"open","market":"e"}))
.unwrap();
for (id, price) in [("a10", 10), ("a70", 70), ("a90", 90)] {
e.execute(order(id, "alice", "sell", price, 1)).unwrap();
}
let r = e.execute(json!({"op":"market_buy","id":"depth","market":"e","outcome":"YES","account":"bob","amount_cents":80,"tif":"FOK"})).unwrap();
assert_eq!(r["protection_price_micros"], 900000);
assert_eq!(r["spent_cents"], 80);
assert_eq!(r["filled"], 2);
}
#[test]
fn sdk_book_groups_opposite_outcomes_and_preserves_snapshot_through_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("snapshot.db");
let mut writer = Exchange::open(&path).unwrap();
let mut reader = Exchange::open(&path).unwrap();
let mut snapshots = Vec::new();
for line in include_str!("../../../docs/examples/clob-book.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
if cmd["op"] == "clob_book" {
snapshots.push(reader.execute(cmd).unwrap());
} else {
writer.execute(cmd).unwrap();
}
}
let snapshot = &snapshots[1];
assert_eq!(snapshots[0]["bids"], json!([]));
assert_ne!(snapshots[0]["hash"], snapshot["hash"]);
assert_eq!(snapshot["last_trade_price"], "");
assert_eq!(snapshot["min_order_size"], "1");
assert_eq!(snapshot["tick_size"], "0.01");
assert_eq!(snapshot["neg_risk"], false);
assert_eq!(
snapshot["bids"],
json!([{"price":"0.2","size":"1"},{"price":"0.3","size":"3.5"}])
);
assert_eq!(
snapshot["asks"],
json!([{"price":"0.8","size":"2"},{"price":"0.6","size":"1"}])
);
drop(reader);
let mut reader = Exchange::open(&path).unwrap();
let request = json!({"op":"clob_book","token_id":"eb:YES:demo"});
assert_eq!(&reader.execute(request.clone()).unwrap(), snapshot);
let local = reader
.execute(json!({"op":"book","asset_id":"eb:YES:demo"}))
.unwrap();
assert_eq!(local["bids"][0], json!({"price_micros":300000,"size":3.5}));
writer
.execute(json!({"op":"fund","id":"buyer","account":"buyer","cents":100}))
.unwrap();
writer.execute(json!({"op":"market_buy","id":"take","account":"buyer","asset_id":"eb:YES:demo","amount_cents":60})).unwrap();
let changed = reader.execute(request).unwrap();
assert_ne!(changed["hash"], snapshot["hash"]);
assert_eq!(changed["last_trade_price"], "0.6");
assert_eq!(changed["asks"], json!([{"price":"0.8","size":"2"}]));
}
#[test]
fn feed_replays_unchanged_best_price_depth_partial_fills_and_removals() {
let dir = tempdir().unwrap();
let db = dir.path().join("depth.db");
let mut writer = Exchange::open(&db).unwrap();
let mut reader = Exchange::open(&db).unwrap();
for line in include_str!("../../../docs/examples/depth-feed.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
if cmd["op"] != "book_feed" {
let receipt = writer.execute(cmd.clone()).unwrap();
assert_eq!(writer.execute(cmd).unwrap(), receipt);
continue;
}
let data = reader.execute(cmd.clone()).unwrap();
let events = data["events"].as_array().unwrap();
match cmd["after"].as_i64() {
None => {
assert_eq!(data["cursor"], 1);
assert_eq!(events.len(), 2);
assert_eq!(events[0]["type"], "book");
assert_eq!(
events[0]["payload"]["bids"][0],
json!({"price":"0.3","size":"2"})
);
assert_eq!(
events[1]["payload"]["asks"][0],
json!({"price":"0.7","size":"2"})
);
assert!(events[0]["payload"]["last_trade_price"].is_null());
drop(reader);
reader = Exchange::open(&db).unwrap();
}
Some(1) => {
assert_eq!(data["has_more"], true);
assert_eq!(data["cursor"], 3);
assert_eq!(events.len(), 2);
for (event, size) in events.iter().zip(["3", "1"]) {
assert_eq!(event["type"], "price_change");
let levels = event["payload"]["price_changes"].as_array().unwrap();
assert_eq!(levels.len(), 2);
assert_eq!(levels[0]["asset_id"], "eb:YES:demo");
assert_eq!(levels[0]["side"], "BUY");
assert_eq!(levels[0]["best_bid"], "0.3");
assert_eq!(levels[0]["size"], size);
assert_eq!(levels[1]["asset_id"], "eb:NO:demo");
assert_eq!(levels[1]["side"], "SELL");
assert_eq!(levels[1]["best_ask"], "0.7");
assert_eq!(levels[1]["size"], size);
}
}
Some(3) => {
let cleared = &events[0]["payload"]["price_changes"][0];
assert_eq!(cleared["size"], "0");
assert!(cleared["best_bid"].is_null());
assert_eq!(data["has_more"], false);
}
Some(4) => assert!(events.is_empty()),
_ => panic!("unexpected sample cursor"),
}
}
}
#[test]
fn market_stream_preserves_trades_and_empty_book_tick_across_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("stream.db");
let mut writer = Exchange::open(&path).unwrap();
let yes = "eb:YES:demo".to_owned();
let no = "eb:NO:demo".to_owned();
let tokens = [no.clone(), yes.clone(), no.clone()];
for line in include_str!("../../../docs/examples/market-stream-trades.jsonl").lines() {
let cmd: Value = serde_json::from_str(line).unwrap();
let result = writer.execute(cmd.clone()).unwrap();
if cmd["id"] == "maker-ask" {
let prices = writer.last_trade_prices(&tokens).unwrap();
assert!(prices.is_empty());
} else if cmd["id"] == "buy" || cmd["id"] == "no" {
let prices = writer.last_trade_prices(&tokens).unwrap();
assert_eq!(
prices,
vec![json!({"token_id":yes,"price":"0.4","side":"BUY"})]
);
}
assert_eq!(writer.execute(cmd).unwrap(), result);
}
drop(writer);
let mut reader = Exchange::open(&path).unwrap();
let prices = reader.last_trade_prices(&tokens).unwrap();
assert_eq!(
prices[0],
json!({"token_id":no,"price":"0.65","side":"SELL"})
);
assert_eq!(
prices[1],
json!({"token_id":yes,"price":"0.35","side":"BUY"})
);
assert_eq!(prices[0], prices[2]);
let page = reader.market_stream_page("demo", Some(0)).unwrap();
let kinds: Vec<_> = page
.frames
.iter()
.map(|(_, f)| f["event_type"].as_str().unwrap())
.collect();
assert_eq!(
kinds,
[
"tick_size_change",
"tick_size_change",
"price_change",
"last_trade_price",
"price_change",
"price_change",
"last_trade_price",
"last_trade_price",
"price_change"
]
);
let tick = &page.frames[1].1;
assert_eq!(tick["asset_id"], "eb:NO:demo");
assert_eq!(tick["timestamp"], "1782753357257");
assert_eq!(tick["old_tick_size"], "0.01");
assert_eq!(tick["new_tick_size"], "0.001");
let direct = &page.frames[3].1;
assert_eq!(direct["asset_id"], "eb:YES:demo");
assert_eq!(direct["price"], "0.4");
assert_eq!(direct["size"], "2");
assert_eq!(direct["side"], "BUY");
assert_eq!(direct["fee_rate_bps"], "250");
assert!(direct["transaction_hash"].is_null());
let (yes, no) = (&page.frames[6], &page.frames[7]);
assert_eq!(yes.0, no.0);
assert_eq!(yes.1["side"], "BUY");
assert_eq!(yes.1["price"], "0.35");
assert_eq!(no.1["side"], "SELL");
assert_eq!(no.1["price"], "0.65");
assert!(reader
.market_stream_page("demo", Some(page.cursor))
.unwrap()
.frames
.is_empty());
assert_eq!(
reader.market_stream_page("demo", None).unwrap().cursor,
page.cursor
);
}
#[test]
fn batch_book_reads_keep_complementary_depth_on_one_revision() {
let dir = tempdir().unwrap();
let path = dir.path().join("batch.db");
let mut writer = Exchange::open(&path).unwrap();
let mut reader = Exchange::open(&path).unwrap();
for cmd in [
json!({"op":"list","id":"list","market":"demo","rules":"Local binary outcome","tick_size":"0.01"}),
json!({"op":"fund","id":"fund","account":"maker","cents":3000}),
json!({"op":"open","id":"open","market":"demo"}),
] {
writer.execute(cmd).unwrap();
}
let tokens = ["eb:YES:demo", "eb:NO:demo", "eb:YES:demo"].map(String::from);
let start = std::sync::Barrier::new(2);
std::thread::scope(|scope| {
scope.spawn(|| {
start.wait();
for index in 0..24 {
let order = writer
.execute(json!({"op":"order","id":format!("bid-{index}"),
"account":"maker","asset_id":"eb:YES:demo","side":"buy","price":30,"qty":1}))
.unwrap();
writer
.execute(json!({"op":"cancel","id":format!("cancel-{index}"),
"account":"maker","order":order["order"]}))
.unwrap();
}
});
start.wait();
for _ in 0..48 {
let books = reader.public_books(&tokens).unwrap();
assert_eq!(books.len(), 3);
assert_eq!(books[0], books[2]);
assert_eq!(books[0]["timestamp"], books[1]["timestamp"]);
let bids = books[0]["bids"].as_array().unwrap();
let asks = books[1]["asks"].as_array().unwrap();
assert_eq!(bids.len(), asks.len());
if !bids.is_empty() {
assert_eq!(bids, &[json!({"price":"0.3","size":"1"})]);
assert_eq!(asks, &[json!({"price":"0.7","size":"1"})]);
}
}
});
let books = reader.public_books(&tokens).unwrap();
assert_eq!(books[0]["bids"], json!([]));
assert_eq!(books[1]["asks"], json!([]));
}
#[test]
fn clob_parameters_follow_the_market_across_both_tokens_and_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("market-info.db");
let mut writer = Exchange::open(&path).unwrap();
let reader = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/football.jsonl")
.lines()
.take(2)
{
let mut cmd: Value = serde_json::from_str(line).unwrap();
if cmd["op"] == "list" {
cmd["tick_size"] = json!("0.005");
cmd["min_order_size"] = json!("2.5");
cmd["taker_fee_rate_ppm"] = json!(25000);
}
writer.execute(cmd).unwrap();
}
let market = "full-2-1";
let pair = reader.market_by_token("eb:NO:full-2-1").unwrap().unwrap();
assert_eq!(
pair,
reader.market_by_token("eb:YES:full-2-1").unwrap().unwrap()
);
assert_eq!(pair["condition_id"], market);
let info = reader.clob_market_info(market).unwrap().unwrap();
assert_eq!(
info["t"],
json!([{"t":pair["primary_token_id"],"o":"2:1"},{"t":pair["secondary_token_id"],"o":"其他比分"}])
);
assert_eq!(info["mts"], json!(0.005));
assert_eq!(info["mos"], json!(2.5));
assert_eq!(info["fd"], json!({"r":0.025,"e":1,"to":true}));
assert_eq!(info["gst"], "2027-01-15T08:00:00.000Z");
writer
.execute(
json!({"op":"tick_size_change","id":"change","asset_id":"eb:NO:full-2-1",
"old_tick_size":"0.005","new_tick_size":"0.001","timestamp":"1"}),
)
.unwrap();
assert_eq!(
reader.clob_market_info(market).unwrap().unwrap()["mts"],
json!(0.001)
);
for line in include_str!("../../../docs/examples/neg-risk.jsonl")
.lines()
.take(5)
{
writer.execute(serde_json::from_str(line).unwrap()).unwrap();
}
drop(reader);
let reopened = Exchange::open(&path).unwrap();
let topic = reopened.clob_market_info("a").unwrap().unwrap();
assert_eq!(topic["nr"], true);
assert_eq!(topic["t"][0]["o"], "是");
assert!(topic["gst"].is_null());
assert!(topic.get("fd").is_none());
}
#[test]
fn midpoint_keeps_half_a_tick_after_reopening_the_book() {
let dir = tempdir().unwrap();
let path = dir.path().join("midpoint.db");
let mut exchange = Exchange::open(&path).unwrap();
for line in include_str!("../../../docs/examples/midpoint.jsonl").lines() {
exchange
.execute(serde_json::from_str(line).unwrap())
.unwrap();
}
let tokens = [
"eb:YES:mid-example".to_owned(),
"eb:NO:mid-example".to_owned(),
];
exchange
.execute(json!({"op":"order","id":"fine-bid","asset_id":tokens[0],
"account":"mid-yes","side":"buy","price_micros":80100,"qty":1}))
.unwrap();
drop(exchange);
let reopened = Exchange::open(&path).unwrap();
let prices = reopened.midpoints(&tokens).unwrap();
assert_eq!(prices[&tokens[0]].as_deref(), Some("0.08505"));
assert_eq!(prices[&tokens[1]].as_deref(), Some("0.91495"));
}
#[test]
fn published_clarification_clears_only_its_market_and_replays_after_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("clarifications.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
for cmd in [
json!({"op":"list","id":"other-list","market":"other","rules":"other result"}),
json!({"op":"open","id":"start","market":"e"}),
order("rest-ask", "alice", "sell", 60, 2),
order("rest-bid", "bob", "buy", 40, 1),
json!({"op":"order","id":"other-bid","market":"other","outcome":"NO","account":"bob","side":"buy","price":10,"qty":1}),
] {
e.execute(cmd).unwrap();
}
let book = json!({"op":"clob_book","token_id":"eb:YES:e"});
let original = e.execute(book.clone()).unwrap();
let first = json!({"op":"publish_clarification","id":"n1","market":"e","content":"Use the official result sheet.","clear_book":false});
assert_eq!(e.execute(first).unwrap()["canceled_count"], 0);
assert_eq!(e.execute(book.clone()).unwrap()["asks"], original["asks"]);
let next = json!({"op":"publish_clarification","id":"n2","market":"e","content":"The result includes overtime.","clear_book":true});
let state = json!({"op":"resolution","market":"e"});
let connection = rusqlite::Connection::open(&path).unwrap();
connection.execute_batch("CREATE TRIGGER reject_clear BEFORE UPDATE OF status ON orders WHEN OLD.market='e' BEGIN SELECT RAISE(ABORT,'simulated release failure'); END;").unwrap();
assert!(e.execute(next.clone()).is_err());
assert_eq!(
e.execute(state.clone()).unwrap()["clarifications"]
.as_array()
.unwrap()
.len(),
1
);
assert_eq!(e.execute(book.clone()).unwrap()["bids"], original["bids"]);
connection
.execute_batch("DROP TRIGGER reject_clear")
.unwrap();
let receipt = e.execute(next.clone()).unwrap();
assert_eq!(receipt["canceled_count"], 2);
assert_eq!(e.execute(book.clone()).unwrap()["asks"], json!([]));
assert_eq!(e.execute(book.clone()).unwrap()["bids"], json!([]));
assert_eq!(
e.execute(json!({"op":"balance","account":"bob"})).unwrap()["available_micros"],
19_900_000
);
let other = e
.execute(json!({"op":"clob_book","token_id":"eb:NO:other"}))
.unwrap();
assert_eq!(other["bids"].as_array().unwrap().len(), 1);
e.execute(order("new-bid", "bob", "buy", 39, 1)).unwrap();
drop(e);
let mut e = Exchange::open(&path).unwrap();
assert_eq!(e.execute(next).unwrap(), receipt);
assert_eq!(
e.execute(book).unwrap()["bids"].as_array().unwrap().len(),
1
);
let resolution = e.execute(state).unwrap();
assert_eq!(resolution["rules"], "official result");
assert!(resolution["payouts"].is_null());
assert!(resolution["resolved_at_ms"].is_null());
assert_eq!(resolution["clarifications"][1]["clearBook"], true);
assert!(resolution["clarifications"][1]["txTimestamp"].is_null());
e.execute(json!({"op":"close","id":"end","market":"e"}))
.unwrap();
e.execute(json!({"op":"finalize","id":"void","market":"e","winner":"VOID"}))
.unwrap();
let settled = e.execute(json!({"op":"resolution","market":"e"})).unwrap();
assert_eq!(settled["payouts"], json!([1, 1]));
assert_eq!(settled["clarifications"], resolution["clarifications"]);
assert!(e.execute(json!({"op":"publish_clarification","id":"late","market":"e","content":"late note","clear_book":false})).is_err());
}
#[test]
fn event_clarifications_span_sibling_markets_across_restart() {
let dir = tempdir().unwrap();
let path = dir.path().join("event-notes.sqlite");
let mut db = Exchange::open(&path).unwrap();
let mut event_ids = Vec::new();
for example in [
include_str!("../../../docs/examples/football.jsonl"),
include_str!("../../../docs/examples/topic.jsonl"),
] {
let mut commands = example
.lines()
.map(|line| serde_json::from_str::<Value>(line).unwrap());
let event = db.execute(commands.next().unwrap()).unwrap();
let event_id = event["event_id"].as_i64().unwrap();
assert!(event_id > 0);
event_ids.push(event_id);
for listing in commands.take(2) {
db.execute(listing).unwrap();
}
}
assert_ne!(event_ids[0], event_ids[1]);
db.execute(json!({"op":"list","id":"solo-list","market":"solo","rules":"Example."}))
.unwrap();
for market in ["full-2-1", "nvda-300", "solo", "half-1-0"] {
db.execute(json!({"op":"publish_clarification","id":format!("note-{market}"),"market":market,"content":market,"clear_book":false})).unwrap();
}
drop(db);
let mut db = Exchange::open(&path).unwrap();
let catalog = db
.execute(json!({"op":"catalog","slug":"nvda-closing-price-2027"}))
.unwrap();
assert_eq!(catalog["event"]["event_id"], event_ids[1]);
let events = db
.execute(json!({"op":"events","category":"sports","limit":10}))
.unwrap();
assert_eq!(events["events"][0]["event_id"], event_ids[0]);
let rows = db
.filtered_market_clarifications(&[], &event_ids, 10, 0, true)
.unwrap();
assert_eq!(
rows.iter()
.map(|r| r["content"].as_str().unwrap())
.collect::<Vec<_>>(),
["full-2-1", "nvda-300", "half-1-0"]
);
let sports = [event_ids[0], event_ids[0]];
assert_eq!(
db.filtered_market_clarifications(&[], &sports, 1, 1, true)
.unwrap(),
vec![rows[2].clone()]
);
let market = rows[2]["marketId"].as_i64().unwrap();
assert_eq!(
db.filtered_market_clarifications(&[market], &sports, 10, 0, false)
.unwrap(),
vec![rows[2].clone()]
);
assert!(db
.filtered_market_clarifications(&[market], &event_ids[1..], 10, 0, true)
.unwrap()
.is_empty());
let all = db.market_clarifications(&[], 10, 0, true).unwrap();
assert_eq!(all.len(), 4);
assert_eq!(all[2]["content"], "solo");
}
#[test]
fn gamma_directory_reads_numeric_slugs_separately_and_keeps_settled_markets() {
use exchange::DirectoryKey;
let dir = tempdir().unwrap();
let path = dir.path().join("gamma.sqlite");
let mut db = Exchange::open(&path).unwrap();
db.execute(json!({"op":"list","id":"first","market":"one","slug":"2","rules":"First."}))
.unwrap();
db.execute(json!({"op":"list","id":"second","market":"two","slug":"1","rules":"Second."}))
.unwrap();
let first = db.gamma_market(DirectoryKey::Id(1)).unwrap().unwrap();
assert_eq!(first["conditionId"], "one");
assert_eq!(first["slug"], "2");
assert_eq!(first["outcomePrices"], Value::Null);
assert_eq!(
db.gamma_market(DirectoryKey::Slug("1")).unwrap().unwrap()["conditionId"],
"two"
);
db.execute(json!({"op":"close","id":"seal","market":"one"}))
.unwrap();
db.execute(json!({"op":"finalize","id":"void","market":"one","winner":"VOID"}))
.unwrap();
drop(db);
let db = Exchange::open(&path).unwrap();
let final_state = db.gamma_market(DirectoryKey::Slug("2")).unwrap().unwrap();
assert_eq!(final_state["id"], first["id"]);
assert_eq!(final_state["closed"], true);
assert_eq!(final_state["acceptingOrders"], false);
assert_eq!(final_state["outcomePrices"], r#"["0.5","0.5"]"#);
}
#[test]
fn directory_pages_filter_parents_without_truncating_siblings() {
use exchange::{
DirectoryKey,
DirectoryResource::{Events, Markets},
};
let mut db = Exchange::open(":memory:").unwrap();
for sample in [
include_str!("../../../docs/examples/topic.jsonl"),
include_str!("../../../docs/examples/football.jsonl"),
] {
for line in sample.lines().take(3) {
db.execute(serde_json::from_str(line).unwrap()).unwrap();
}
}
db.execute(json!({"op":"close","id":"seal-high","market":"nvda-300"}))
.unwrap();
let query = |pairs: &[(&str, &str)]| {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect::<Vec<_>>()
};
let page = db
.gamma_list(
Events,
&query(&[("order", "title,id"), ("limit", "1"), ("ascending", "true")]),
)
.unwrap();
let next = db
.gamma_list(
Events,
&query(&[
("order", "title,id"),
("limit", "1"),
("offset", "1"),
("ascending", "true"),
]),
)
.unwrap();
assert_eq!(page.len(), 1);
assert_eq!(next.len(), 1);
assert_ne!(page[0]["id"], next[0]["id"]);
assert_eq!(page[0]["markets"].as_array().unwrap().len(), 2);
assert_eq!(next[0]["markets"].as_array().unwrap().len(), 2);
let topic = db
.gamma_event(DirectoryKey::Slug("nvda-closing-price-2027"))
.unwrap()
.unwrap();
assert_eq!(topic["closed"], false);
let filters = query(&[
("slug", "nvda-200"),
("slug", "nvda-300"),
("slug", "nvda-300"),
]);
let open = db.gamma_list(Markets, &filters).unwrap();
assert_eq!(open.len(), 1);
assert_eq!(open[0]["conditionId"], "nvda-200");
let mut filters = filters;
filters.extend(query(&[
("closed", "any"),
("ascending", "true"),
("offset", "1"),
("limit", "1"),
]));
assert_eq!(db.gamma_list(Markets, &filters).unwrap(), open);
db.execute(json!({"op":"close","id":"seal-low","market":"nvda-200"}))
.unwrap();
let closed = db
.gamma_list(Events, &query(&[("closed", "true")]))
.unwrap();
assert_eq!(closed.len(), 1);
assert_eq!(closed[0]["id"], topic["id"]);
assert_eq!(closed[0]["closed"], true);
assert_eq!(closed[0]["markets"].as_array().unwrap().len(), 2);
assert_eq!(db.gamma_list(Events, &[]).unwrap().len(), 2);
let many = vec![("id".to_owned(), "1".to_owned()); 101];
assert!(db.gamma_list(Markets, &many).is_err());
}
#[test]
fn trade_feed_replays_both_wallet_legs_and_keeps_the_cursor_after_restart() {
fn feed(db: &Exchange, query: Value) -> Value {
db.public_trade_feed(serde_json::from_value(query).unwrap())
.unwrap()
}
let dir = tempdir().unwrap();
let path = dir.path().join("public-fills.db");
let mut db = Exchange::open(&path).unwrap();
for sample in [
include_str!("../../../docs/examples/football.jsonl"),
include_str!("../../../docs/examples/volume.jsonl"),
] {
for line in sample.lines() {
db.execute(serde_json::from_str(line).unwrap()).unwrap();
}
}
let event = db
.gamma_event(exchange::DirectoryKey::Slug("cup-a-b"))
.unwrap()
.unwrap();
let event_id = event["id"].as_str().unwrap();
let first = feed(&db, json!({"eventId":event_id,"user":"bob","limit":1}));
assert_eq!(first["data"][0]["price"], json!(0.3));
assert_eq!(first["data"][0]["size"], 2);
assert_eq!(first["data"][0]["side"], "BUY");
assert_eq!(first["data"][0]["event_slug"], "cup-a-b");
assert_eq!(first["pagination"]["has_more"], true);
let cursor = first["pagination"]["next_cursor"].as_str().unwrap();
drop(db);
let db = Exchange::open(&path).unwrap();
let next = feed(
&db,
json!({"user":"bob","event_id":event_id,"cursor":cursor,"limit":999}),
);
assert_eq!(
next["pagination"],
json!({"offset":1,"limit":1,"has_more":false,"next_cursor":null})
);
let leg = &next["data"][0];
assert_eq!(leg["token_id"], "eb:NO:full-2-1");
assert_eq!(leg["price"], json!(0.4));
assert_eq!(leg["size"], 3);
assert_eq!(leg["outcome"], "其他比分");
assert_eq!(leg["outcome_index"], 1);
let changed = feed(
&db,
json!({"cursor":cursor,"user":"alice","side":"SELL","takerOnly":false}),
);
assert_eq!(changed["data"][0]["proxy_wallet"], "alice");
assert_eq!(changed["data"][0]["token_id"], "eb:YES:half-1-0");
let timestamp = first["data"][0]["timestamp"].as_i64().unwrap();
let sale = feed(
&db,
json!({"condition":"half-1-0","user":"alice","side":"SELL","taker_only":false,"start":timestamp,"end":timestamp,"filterType":"CASH","filterAmount":0.6}),
);
assert_eq!(sale["data"].as_array().unwrap().len(), 1);
assert!(feed(&db,json!({"user":"alice","end":timestamp-1,"start":timestamp-1,"side":"SELL","taker_only":false}))["data"].as_array().unwrap().is_empty());
assert!(feed(&db, json!({"eventId":"99999"}))["data"]
.as_array()
.unwrap()
.is_empty());
assert!(db
.public_trade_feed(serde_json::from_value(json!({"cursor":format!("{}A",cursor)})).unwrap())
.is_err());
let other = Exchange::open(":memory:").unwrap();
assert!(other
.public_trade_feed(serde_json::from_value(json!({"cursor":cursor})).unwrap())
.is_err());
}
#[test]
fn resolution_feed_tracks_a_reset_and_final_split_after_reopening() {
let dir = tempdir().unwrap();
let path = dir.path().join("resolutions.db");
let mut e = Exchange::open(&path).unwrap();
let question = format!("0x{}", "ab".repeat(32));
let listing = |market: &str, id: &str| {
json!({
"op":"list","id":market,"market":market,"rules":"Official result",
"resolution":{"kind":"optimistic","eligible_at":0,"question_id":id}
})
};
let lookup = |db: &Exchange, selector: Value| {
db.public_resolutions(serde_json::from_value(selector).unwrap())
.unwrap()["data"]
.clone()
};
let view = |db: &Exchange| lookup(db, json!({"questionId":question}))[0].clone();
e.execute(listing("m", &question)).unwrap();
assert!(e.execute(listing("duplicate", &question)).is_err());
assert!(e.execute(listing("bad", "0xabc")).is_err());
assert_eq!(lookup(&e, json!({"condition":"duplicate,bad"})), json!([]));
assert_eq!(view(&e)["status"], "posed");
assert_eq!(view(&e)["price"], "69");
e.execute(json!({"op":"close","id":"close","market":"m"}))
.unwrap();
for (i, result, expected) in [
(1, "YES", "proposed"),
(2, "NO", "reproposed"),
(3, "VOID", "reproposed"),
] {
let p = e.execute(json!({"op":"propose","id":format!("p{i}"),"market":"m","winner":result,"proposer":"alice","evidence":"score"})).unwrap()["proposal"].clone();
let live = view(&e);
assert_eq!(live["status"], expected);
assert_eq!(live["settlement_time_basis"], "proposal_expiration");
e.execute(json!({"op":"dispute","id":format!("d{i}"),"market":"m","proposal":p,"challenger":"bob","evidence":"correction"})).unwrap();
let challenged = view(&e);
assert_eq!(
challenged["status"],
if i == 1 { "challenged" } else { "disputed" }
);
assert!(challenged.get("expected_settlement_time").is_none());
if i >= 2 {
e.execute(json!({"op":"adjudicate","id":format!("v{i}"),"market":"m","proposal":p,"verdict":if i==2 {"TOO_EARLY"} else {"VOID"},"evidence":"decision"})).unwrap();
}
if i == 2 {
let reset = view(&e);
assert_eq!(reset["status"], "challenged");
assert_eq!(reset["proposed_price"], "0");
assert_eq!(reset["reproposed_price"], "69");
}
}
drop(e);
let db = Exchange::open(path).unwrap();
let final_question = view(&db);
assert!(final_question.get("condition_id").is_none());
assert_eq!(final_question["price"], "500000000000000000");
assert_eq!(final_question["was_arbitrated"], true);
let final_market = lookup(&db, json!({"conditionId":"m,m"}));
assert_eq!(final_market.as_array().unwrap().len(), 1);
assert_eq!(final_market[0]["question_id"], question);
assert_eq!(final_market[0]["status"], "resolved");
assert_eq!(final_market[0]["payouts"], json!([500000, 500000]));
assert_eq!(
final_market[0]["last_update_timestamp"],
final_market[0]["resolved_at"]
);
assert!(final_market[0].get("resolved_block").is_none());
}