Expose negative-risk membership and convert fractional outcome balances
This commit is contained in:
@@ -1362,3 +1362,29 @@ sequenceDiagram
|
||||
E->>D: 读取成交曲线系数
|
||||
E-->>C: 按成交数量与各档价格计算费用
|
||||
```
|
||||
|
||||
### 互斥资产标识和小数份额转换
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
C["command.rs"] --> M["market.rs"] --> N["neg_risk.rs · 成员、转换、赢家准备金"]
|
||||
N --> I["inventory.rs · 百万分之一份的数量和抵押"]
|
||||
N --> L["ledger.rs · 现金与份额"]
|
||||
N --> S["schema.sql · 分组、准备金与小数余数"]
|
||||
X["lib.rs · Exchange"] --> N
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>E: token_neg_risk(资产 ID)
|
||||
E->>D: 检查市场和分组成员记录
|
||||
E-->>C: 成员返回 true,普通市场返回 false
|
||||
C->>E: convert,两种 NO 各 250001 微份
|
||||
E->>D: 同一事务扣除 NO 和抵押,增加其余 YES、准备金、现金和活动记录
|
||||
E-->>C: 本次释放 250001 微单位现金
|
||||
C->>E: 裁决赢家
|
||||
E->>D: 将完整准备金含小数余数划入赢家抵押
|
||||
```
|
||||
|
||||
@@ -65,7 +65,8 @@ pub(crate) enum Command {
|
||||
group: String,
|
||||
account: String,
|
||||
no_markets: Vec<String>,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
},
|
||||
Split {
|
||||
market: String,
|
||||
|
||||
@@ -72,15 +72,20 @@ pub(crate) fn movement(
|
||||
tx: &Transaction,
|
||||
request: &str,
|
||||
account: &str,
|
||||
market: &str,
|
||||
target: &str,
|
||||
kind: &str,
|
||||
shares: i64,
|
||||
cash: i64,
|
||||
) -> Result<()> {
|
||||
let (market, group_id) = if kind == "CONVERSION" {
|
||||
(None, Some(target))
|
||||
} else {
|
||||
(Some(target), None)
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO wallet_movements(request_id,account,kind,market,shares,cash_delta,at_ms)
|
||||
VALUES(?,?,?,?,?,?,CAST(unixepoch('subsec')*1000 AS INTEGER))",
|
||||
params![request, account, kind, market, shares / UNIT, cash / 10000],
|
||||
"INSERT INTO wallet_movements(request_id,account,kind,market,group_id,shares,cash_delta,at_ms)
|
||||
VALUES(?,?,?,?,?,?,?,CAST(unixepoch('subsec')*1000 AS INTEGER))",
|
||||
params![request, account, kind, market, group_id, shares / UNIT, cash / 10000],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO precise_movements VALUES(?,?,?,?)",
|
||||
@@ -89,6 +94,19 @@ pub(crate) fn movement(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn quantity_units(qty: Option<i64>, qty_micros: Option<i64>) -> Result<i64> {
|
||||
Ok(match (qty, qty_micros) {
|
||||
(Some(q), None) => {
|
||||
crate::validation::amount(q)?;
|
||||
q * UNIT
|
||||
}
|
||||
(None, Some(u)) if (1..=1_000_000_000 * UNIT).contains(&u) => u,
|
||||
_ => anyhow::bail!(
|
||||
"provide exactly one positive qty or qty_micros within the quantity limit"
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn pairs(
|
||||
tx: &Transaction,
|
||||
request: &str,
|
||||
@@ -108,16 +126,7 @@ pub(crate) fn pairs(
|
||||
&["preopen", "continuous", "closed"][..]
|
||||
},
|
||||
)?;
|
||||
let units = match (qty, qty_micros) {
|
||||
(Some(q), None) => {
|
||||
crate::validation::amount(q)?;
|
||||
q * UNIT
|
||||
}
|
||||
(None, Some(u)) if (1..=1_000_000_000 * UNIT).contains(&u) => u,
|
||||
_ => anyhow::bail!(
|
||||
"provide exactly one positive qty or qty_micros within the quantity limit"
|
||||
),
|
||||
};
|
||||
let units = quantity_units(qty, qty_micros)?;
|
||||
let delta = if split { units } else { -units };
|
||||
ledger::cash_micros(tx, account, -delta)?;
|
||||
for outcome in ["YES", "NO"] {
|
||||
|
||||
@@ -245,6 +245,7 @@ impl Exchange {
|
||||
"fills",
|
||||
"paired_fills",
|
||||
"neg_risk_groups",
|
||||
"neg_risk_reserve_remainders",
|
||||
"augmented_results",
|
||||
] {
|
||||
let mut stmt = tx.prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))?;
|
||||
|
||||
@@ -147,7 +147,16 @@ pub(crate) fn apply(
|
||||
account,
|
||||
no_markets,
|
||||
qty,
|
||||
} => crate::neg_risk::convert(tx, &group, &account, &no_markets, qty),
|
||||
qty_micros,
|
||||
} => crate::neg_risk::convert(
|
||||
tx,
|
||||
request_id,
|
||||
&group,
|
||||
&account,
|
||||
&no_markets,
|
||||
qty,
|
||||
qty_micros,
|
||||
),
|
||||
Command::Split {
|
||||
market,
|
||||
account,
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
use crate::{
|
||||
ledger,
|
||||
validation::{amount, identifier},
|
||||
};
|
||||
use crate::{assets, inventory, ledger, validation::identifier, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
impl Exchange {
|
||||
pub fn token_neg_risk(&self, token: &str) -> Result<Option<bool>, MarketDataError> {
|
||||
let (_, market) = assets::parse_id(token)
|
||||
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
||||
let mut stmt=self.db.prepare_cached(
|
||||
"SELECT EXISTS(SELECT 1 FROM neg_risk_members WHERE market=m.id) FROM markets m WHERE m.id=?1"
|
||||
)?;
|
||||
Ok(stmt.query_row([market], |row| row.get(0)).optional()?)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn define(
|
||||
tx: &Transaction,
|
||||
group: &str,
|
||||
@@ -41,14 +49,16 @@ pub(crate) fn define(
|
||||
|
||||
pub(crate) fn convert(
|
||||
tx: &Transaction,
|
||||
request: &str,
|
||||
group: &str,
|
||||
account: &str,
|
||||
no_markets: &[String],
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
) -> Result<Value> {
|
||||
identifier(group)?;
|
||||
identifier(account)?;
|
||||
amount(qty)?;
|
||||
let units = inventory::quantity_units(qty, qty_micros)?;
|
||||
let selected: BTreeSet<&str> = no_markets.iter().map(String::as_str).collect();
|
||||
ensure!(
|
||||
!selected.is_empty() && selected.len() == no_markets.len(),
|
||||
@@ -73,39 +83,46 @@ pub(crate) fn convert(
|
||||
members.iter().all(|(_, phase)| phase != "resolved"),
|
||||
"group already resolving"
|
||||
);
|
||||
let cents = qty * 100;
|
||||
let mut yes_markets = Vec::new();
|
||||
for (market, _) in &members {
|
||||
if selected.contains(market.as_str()) {
|
||||
ledger::position(tx, account, market, "NO", -qty)?;
|
||||
ensure!(
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral-?1 WHERE id=?2 AND collateral>=?1",
|
||||
params![cents, market]
|
||||
)? == 1,
|
||||
"insufficient market backing"
|
||||
);
|
||||
inventory::position(tx, account, market, "NO", -units)?;
|
||||
inventory::backing(tx, market, -units)?;
|
||||
} else {
|
||||
ledger::position(tx, account, market, "YES", qty)?;
|
||||
inventory::position(tx, account, market, "YES", units)?;
|
||||
yes_markets.push(market);
|
||||
}
|
||||
}
|
||||
let released = (selected.len() as i64 - 1) * cents;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET reserve_cents=reserve_cents+?1 WHERE id=?2",
|
||||
params![cents, group],
|
||||
let released = (selected.len() as i64 - 1) * units;
|
||||
let reserve: i64 = tx.query_row(
|
||||
"SELECT micros FROM neg_risk_reserves WHERE id=?",
|
||||
[group],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ledger::cash(tx, account, released)?;
|
||||
Ok(
|
||||
json!({"group":group,"qty":qty,"no_markets":no_markets,"yes_markets":yes_markets,"released_cents":released}),
|
||||
)
|
||||
let reserve = reserve
|
||||
.checked_add(units)
|
||||
.ok_or_else(|| anyhow::anyhow!("group reserve overflow"))?;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET reserve_cents=? WHERE id=?",
|
||||
params![reserve / 10000, group],
|
||||
)?;
|
||||
tx.execute("INSERT INTO neg_risk_reserve_remainders(group_id,micros) VALUES(?,?) ON CONFLICT(group_id) DO UPDATE SET micros=excluded.micros",params![group,reserve%10000])?;
|
||||
ledger::cash_micros(tx, account, released)?;
|
||||
let mut receipt = json!({"group":group,"qty":inventory::decimal(units.into(),inventory::UNIT),
|
||||
"no_markets":no_markets,"yes_markets":yes_markets,"released_cents":inventory::decimal(released.into(),10000)});
|
||||
if qty_micros.is_some() {
|
||||
inventory::movement(tx, request, account, group, "CONVERSION", units, released)?;
|
||||
receipt["qty_micros"] = json!(units);
|
||||
receipt["released_micros"] = json!(released);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
// Run in the same transaction as the binary payout check. A failing verdict
|
||||
// rolls back the transfer as well as any optimistic-resolution state change.
|
||||
pub(crate) fn allocate_payout(tx: &Transaction, market: &str, outcome: &str) -> Result<()> {
|
||||
let group: Option<(String, Option<String>, i64)> = tx.query_row(
|
||||
"SELECT g.id,g.winner,g.reserve_cents FROM neg_risk_members n JOIN neg_risk_groups g ON g.id=n.group_id WHERE n.market=?",
|
||||
"SELECT g.id,g.winner,g.micros FROM neg_risk_members n JOIN neg_risk_reserves g ON g.id=n.group_id WHERE n.market=?",
|
||||
[market], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
).optional()?;
|
||||
let Some((group, winner, reserve)) = group else {
|
||||
@@ -120,9 +137,10 @@ pub(crate) fn allocate_payout(tx: &Transaction, market: &str, outcome: &str) ->
|
||||
match outcome {
|
||||
"YES" => {
|
||||
ensure!(winner.is_none(), "group already has a winner");
|
||||
inventory::backing(tx, market, reserve)?;
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral+?1 WHERE id=?2",
|
||||
params![reserve, market],
|
||||
"DELETE FROM neg_risk_reserve_remainders WHERE group_id=?",
|
||||
[&group],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET winner=?1,reserve_cents=0 WHERE id=?2",
|
||||
|
||||
@@ -196,6 +196,12 @@ CREATE TABLE IF NOT EXISTS neg_risk_groups (
|
||||
id TEXT PRIMARY KEY, reserve_cents INTEGER NOT NULL DEFAULT 0 CHECK(reserve_cents>=0),
|
||||
winner TEXT REFERENCES markets
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_reserve_remainders (
|
||||
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS neg_risk_reserves AS
|
||||
SELECT g.id,g.winner,g.reserve_cents*10000+COALESCE(r.micros,0) AS micros
|
||||
FROM neg_risk_groups g LEFT JOIN neg_risk_reserve_remainders r ON r.group_id=g.id;
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_members (
|
||||
market TEXT PRIMARY KEY REFERENCES markets, group_id TEXT NOT NULL REFERENCES neg_risk_groups,
|
||||
ordinal INTEGER NOT NULL, UNIQUE(group_id,ordinal)
|
||||
|
||||
@@ -3725,3 +3725,72 @@ fn fractional_basis_point_curve_keeps_its_precision_without_inventing_a_base_fee
|
||||
assert!(e.execute(bad).is_err());
|
||||
assert!(e.clob_market_info("invalid").unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fractional_conversions_carry_reserve_and_activity_through_restart() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("fractional-negative-risk.sqlite");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
for line in include_str!("../../../docs/examples/neg-risk.jsonl").lines() {
|
||||
let cmd: Value = serde_json::from_str(line).unwrap();
|
||||
if cmd["op"] == "define_neg_risk" {
|
||||
assert_eq!(e.token_neg_risk("eb:NO:a").unwrap(), Some(false));
|
||||
}
|
||||
e.execute(cmd).unwrap();
|
||||
}
|
||||
let commands: Vec<Value> = include_str!("../../../docs/examples/neg-risk-fractional.jsonl")
|
||||
.lines()
|
||||
.map(|l| serde_json::from_str(l).unwrap())
|
||||
.collect();
|
||||
for cmd in &commands[..2] {
|
||||
e.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let mut invalid = commands[2].clone();
|
||||
invalid["id"] = json!("missing-no");
|
||||
invalid["no_markets"] = json!(["a", "other"]);
|
||||
let before = state(&mut e);
|
||||
assert!(e.execute(invalid).is_err());
|
||||
assert_eq!(state(&mut e), before);
|
||||
let r = e.execute(commands[2].clone()).unwrap();
|
||||
assert_eq!(r["released_micros"], 250001);
|
||||
assert_eq!(r["released_cents"], json!(25.0001));
|
||||
let during = state(&mut e);
|
||||
assert_eq!(during["neg_risk_groups"][0]["reserve_cents"], 225);
|
||||
assert_eq!(during["neg_risk_reserve_remainders"][0]["micros"], 1);
|
||||
drop(e);
|
||||
let mut e = Exchange::open(path).unwrap();
|
||||
assert_eq!(e.execute(commands[2].clone()).unwrap(), r);
|
||||
assert_eq!(e.token_neg_risk("eb:YES:a").unwrap(), Some(true));
|
||||
assert_eq!(e.token_neg_risk("eb:NO:other").unwrap(), Some(true));
|
||||
assert_eq!(e.token_neg_risk("eb:NO:missing").unwrap(), None);
|
||||
e.execute(commands[3].clone()).unwrap();
|
||||
let after = state(&mut e);
|
||||
assert_eq!(after["neg_risk_groups"][0]["reserve_cents"], 226);
|
||||
assert_eq!(after["neg_risk_reserve_remainders"][0]["micros"], 0);
|
||||
let activity = e.execute(commands[4].clone()).unwrap();
|
||||
let rows = activity["activity"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert_eq!(rows[1]["shares"], json!(0.250001));
|
||||
assert_eq!(rows[1]["net_cash_delta_micros"], 250001);
|
||||
assert_eq!(rows[1]["group"], "winner");
|
||||
assert_eq!(rows[2]["net_cash_delta_micros"], 9999);
|
||||
for (market, winner) in [("a", "NO"), ("b", "NO"), ("other", "YES")] {
|
||||
e.execute(json!({"op":"close","id":format!("close-{market}"),"market":market}))
|
||||
.unwrap();
|
||||
e.execute(
|
||||
json!({"op":"finalize","id":format!("final-{market}"),"market":market,"winner":winner}),
|
||||
)
|
||||
.unwrap();
|
||||
e.execute(
|
||||
json!({"op":"redeem","id":format!("claim-{market}"),"account":"user","market":market}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
e.execute(json!({"op":"balance","account":"user"})).unwrap()["available_micros"],
|
||||
30000000
|
||||
);
|
||||
let end = state(&mut e);
|
||||
assert_eq!(end["neg_risk_groups"][0]["reserve_cents"], 0);
|
||||
assert_eq!(end["neg_risk_reserve_remainders"], json!([]));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user