Support amount-specific negative-risk redemptions and wallet receipts

This commit is contained in:
2026-12-03 13:17:04 +08:00
parent 98eece1c50
commit 3bec895a0a
9 changed files with 199 additions and 22 deletions
+6 -2
View File
@@ -117,11 +117,15 @@ impl Filter {
} else {
crate::inventory::decimal(gross, 10000)
};
items.push(json!({"type":r.get::<_,String>(5)?,"account":self.account,"at_ms":r.get::<_,Option<i64>>(4)?,
let mut item = json!({"type":r.get::<_,String>(5)?,"account":self.account,"at_ms":r.get::<_,Option<i64>>(4)?,
"market":market,"group":r.get::<_,Option<String>>(7)?,"asset_id":asset,"outcome":outcome,
"shares":shares,"cash_delta_cents":cash_cents,"fee_micros":fee,"net_cash_delta_micros":gross-i128::from(fee),
"side":r.get::<_,Option<String>>(12)?,"price_micros":r.get::<_,Option<i64>>(13)?.map(|p|p*100),
"request_id":r.get::<_,Option<String>>(10)?,"execution":(source==1).then_some(seq),"order":(source==1).then_some(leg)}));
"request_id":r.get::<_,Option<String>>(10)?,"execution":(source==1).then_some(seq),"order":(source==1).then_some(leg)});
if let Some(raw) = r.get::<_, Option<String>>(17)? {
item["amounts_micros"] = serde_json::from_str(&raw)?;
}
items.push(item);
last = Some(Cursor {
asc,
key: (r.get(0)?, source, seq, leg),
+3 -1
View File
@@ -11,7 +11,9 @@ SELECT COALESCE(at_ms,-1) AS ts,source,seq,leg,at_ms,kind,market,group_id,shares
CASE WHEN source=1 THEN cash_delta WHEN kind='DEPOSIT' THEN (SELECT json_extract(response,'$.funded_micros')
FROM requests WHERE id=activity.request_id) ELSE
(SELECT cash_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END,
CASE WHEN source=1 THEN shares*10000 ELSE (SELECT shares_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END
CASE WHEN source=1 THEN shares*10000 ELSE (SELECT shares_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END,
CASE WHEN kind='REDEEM' THEN (SELECT json_extract(response,'$.amounts_micros')
FROM requests WHERE id=activity.request_id) END
FROM activity
WHERE (?2 IS NULL OR market=?2)
AND (?3 IS NULL OR kind IN (SELECT value FROM json_each(?3)))
+9
View File
@@ -178,6 +178,8 @@ pub(crate) enum Command {
Redeem {
market: String,
account: String,
#[serde(default, deserialize_with = "redeem_amounts")]
amounts_micros: Option<[i64; 2]>,
},
Resolve {
market: String,
@@ -194,3 +196,10 @@ pub(crate) enum TimeInForce {
Fak,
Fok,
}
// Only an omitted field selects full redemption. An explicit null must not spend a balance.
fn redeem_amounts<'de, D: serde::Deserializer<'de>>(
input: D,
) -> Result<Option<[i64; 2]>, D::Error> {
<[i64; 2]>::deserialize(input).map(Some)
}
+34 -19
View File
@@ -380,13 +380,20 @@ pub(crate) fn apply(
json!({"phase":"resolved","winner":winner,"outstanding_cents":crate::inventory::decimal(i128::from(backing),10000)}),
)
}
Command::Redeem { market, account } => {
Command::Redeem {
market,
account,
amounts_micros,
} => {
identifier(&account)?;
phase(tx, &market, &["resolved"])?;
let paid = redeem(tx, &market, &account, request_id)?;
Ok(
json!({"market":market,"account":account,"paid":crate::inventory::decimal(i128::from(paid),10000)}),
)
let paid = redeem(tx, &market, &account, request_id, amounts_micros)?;
let mut receipt = json!({"market":market,"account":account,"paid":crate::inventory::decimal(i128::from(paid),10000)});
if let Some(amounts) = amounts_micros {
receipt["amounts_micros"] = json!(amounts);
receipt["paid_micros"] = json!(paid);
}
Ok(receipt)
}
Command::Resolve { market, winner } => {
let backing = finalize(tx, &market, &winner)?;
@@ -398,7 +405,7 @@ pub(crate) fn apply(
.collect::<rusqlite::Result<Vec<_>>>()?;
let mut paid = 0;
for account in accounts {
paid += redeem(tx, &market, &account, request_id)?;
paid += redeem(tx, &market, &account, request_id, None)?;
}
let dust: i64 = tx.query_row(
"SELECT COALESCE((SELECT micros FROM settlement_dust WHERE market=?),0)",
@@ -465,20 +472,30 @@ pub(crate) fn finalize(tx: &Transaction, market: &str, winner: &str) -> Result<i
Ok(backing)
}
fn redeem(tx: &Transaction, market: &str, account: &str, request_id: &str) -> Result<i64> {
fn redeem(
tx: &Transaction,
market: &str,
account: &str,
request_id: &str,
amounts: Option<[i64; 2]>,
) -> Result<i64> {
let (shares, paid) = match amounts {
Some(amounts) => crate::neg_risk::burn_for_redemption(tx, market, account, amounts)?,
None => burn_full_balance(tx, market, account)?,
};
crate::inventory::movement(tx, request_id, account, market, "REDEEM", shares, paid)?;
if paid > 0 {
crate::inventory::backing(tx, market, -paid)?;
ledger::cash_micros(tx, account, paid)?;
}
Ok(paid)
}
fn burn_full_balance(tx: &Transaction, market: &str, account: &str) -> Result<(i64, i64)> {
let (shares,paid):(Option<i64>,Option<i64>)=tx.query_row(
"SELECT SUM(available),SUM(CASE payout_per_share WHEN 50 THEN available/2 WHEN 100 THEN available ELSE 0 END)
FROM position_units WHERE market=? AND account=? AND available>0",params![market,account],|r|Ok((r.get(0)?,r.get(1)?)))?;
let paid = paid.ok_or_else(|| anyhow::anyhow!("no positions to redeem"))?;
crate::inventory::movement(
tx,
request_id,
account,
market,
"REDEEM",
shares.unwrap_or(0),
paid,
)?;
tx.execute(
"DELETE FROM position_remainders WHERE market=? AND account=?",
params![market, account],
@@ -487,7 +504,5 @@ fn redeem(tx: &Transaction, market: &str, account: &str, request_id: &str) -> Re
"UPDATE positions SET quantity=0 WHERE market=? AND account=? AND quantity>0",
params![market, account],
)?;
crate::inventory::backing(tx, market, -paid)?;
ledger::cash_micros(tx, account, paid)?;
Ok(paid)
Ok((shares.unwrap_or(0), paid))
}
+30
View File
@@ -183,6 +183,36 @@ pub(crate) fn convert(
Ok(receipt)
}
/// Burn the YES/NO amounts transferred by a negative-risk adapter caller.
/// The caller settles the returned (burned shares, collateral payout) in this transaction.
pub(crate) fn burn_for_redemption(
tx: &Transaction,
market: &str,
account: &str,
amounts: [i64; 2],
) -> Result<(i64, i64)> {
let winner: Option<String> = tx.query_row(
"SELECT m.winner FROM neg_risk_members n JOIN markets m ON m.id=n.market WHERE n.market=? AND m.phase='resolved'",
[market], |row| row.get(0),
).optional()?;
let [yes, no] = amounts;
let paid = match winner.as_deref() {
Some("YES") => yes,
Some("NO") => no,
_ => anyhow::bail!("explicit redemption amounts require a resolved negative-risk market"),
};
ensure!(yes >= 0 && no >= 0, "negative redemption amount");
let burned = yes
.checked_add(no)
.ok_or_else(|| anyhow::anyhow!("redemption share total overflow"))?;
for (outcome, units) in [("YES", yes), ("NO", no)] {
if units > 0 {
inventory::position(tx, account, market, outcome, -units)?;
}
}
Ok((burned, paid))
}
// 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<()> {