Route orders and market data by stable outcome asset IDs
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
use crate::validation::identifier;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::Connection;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
// The outcome precedes the market so every valid market string, including
|
||||
// those containing colons, round-trips without escaping or a database migration.
|
||||
pub(crate) fn id(market: &str, outcome: &str) -> String {
|
||||
format!("eb:{outcome}:{market}")
|
||||
}
|
||||
|
||||
pub(crate) fn outcomes(market: &str, yes: &str, no: &str) -> Value {
|
||||
json!([
|
||||
{"outcome":"YES","label":yes,"asset_id":id(market,"YES")},
|
||||
{"outcome":"NO","label":no,"asset_id":id(market,"NO")}
|
||||
])
|
||||
}
|
||||
|
||||
pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
|
||||
identifier(market)?;
|
||||
let (yes, no, phase): (String, String, String) = db.query_row(
|
||||
"SELECT COALESCE(s.yes_label,'YES'),COALESCE(s.no_label,'NO'),m.phase
|
||||
FROM markets m LEFT JOIN sports_markets s ON s.market=m.id WHERE m.id=?1",
|
||||
[market],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
Ok(json!({"market":market,"phase":phase,"outcomes":outcomes(market,&yes,&no)}))
|
||||
}
|
||||
|
||||
// Resolve only commands that address one outcome. Keep the original request
|
||||
// untouched in the idempotency ledger so historic receipts still replay exactly.
|
||||
pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
if !matches!(
|
||||
request["op"].as_str(),
|
||||
Some("order" | "book" | "quote" | "history" | "open_orders")
|
||||
) {
|
||||
return Ok(());
|
||||
}
|
||||
let fields = request.as_object_mut().context("expected object")?;
|
||||
let Some(asset) = fields.remove("asset_id") else {
|
||||
return Ok(());
|
||||
};
|
||||
let (outcome, market) = asset
|
||||
.as_str()
|
||||
.and_then(|s| s.strip_prefix("eb:"))
|
||||
.and_then(|s| s.split_once(':'))
|
||||
.context("invalid Eventbook asset_id")?;
|
||||
ensure!(matches!(outcome, "YES" | "NO"), "invalid asset outcome");
|
||||
identifier(market)?;
|
||||
for (field, value) in [("market", market), ("outcome", outcome)] {
|
||||
if let Some(existing) = fields.get(field) {
|
||||
ensure!(
|
||||
existing.as_str() == Some(value),
|
||||
"asset_id conflicts with {field}"
|
||||
);
|
||||
}
|
||||
fields.insert(field.to_owned(), json!(value));
|
||||
}
|
||||
let listed: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "unknown Eventbook asset_id");
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user