Expose negative-risk membership and convert fractional outcome balances
This commit is contained in:
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user