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); }