Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33b3991c69 |
No files matched your search
+15
-16
@@ -41,22 +41,6 @@ sequenceDiagram
|
||||
end
|
||||
```
|
||||
|
||||
## 模拟裁决保证金
|
||||
|
||||
可信 JSONL 可在 `list` 的乐观裁决配置中设置 `bond_micros`。首轮争议单独使用 `settle_first_dispute_bond`,提交市场、提案、裁定和证据。`resolution` 返回每笔提案尚锁定、转付和销毁的金额。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor O as 操作员
|
||||
participant C as JSONL CLI
|
||||
participant E as Exchange
|
||||
O->>C: 提交首轮争议的保证金裁定
|
||||
C->>E: 写入首轮裁定证据并按提案去重
|
||||
E-->>C: 返回收款人和金额
|
||||
O->>C: 查询 resolution
|
||||
C->>E: 读取市场裁决状态与保证金账本
|
||||
```
|
||||
|
||||
## 市场 WebSocket
|
||||
|
||||
已有可执行文件可用 `cli DATABASE --market-ws 127.0.0.1:9001` 启动行情监听,客户端连接 `ws://127.0.0.1:9001/ws/market`。同一数据库可以由另一条 JSON 行命令会话写入。监听模式只接收市场订阅与心跳。每个连接独立维护订阅,所有连接共享一个 Exchange。当前服务提供明文 WebSocket,接入 TLS 需要相应的服务入口。
|
||||
@@ -441,3 +425,18 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
### 钱包成交量
|
||||
|
||||
`GET /v2/user-volume?user=alice&start=1785542400&end=1785628800` 返回 `data.volume`(份数)、`data.volume_usdc` 和 `data.trade_count`。省略边界或填 0 表示该侧不限。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/user-volume
|
||||
H->>E: 钱包、起止时间
|
||||
E-->>H: UTC 整日成交汇总
|
||||
H-->>C: data 对象
|
||||
```
|
||||
@@ -335,6 +335,13 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
if path == "/v2/user-volume" {
|
||||
if req.method() != &Method::Get {
|
||||
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
|
||||
}
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let route = path.strip_prefix('/').unwrap_or(path);
|
||||
let (name, segment) = route
|
||||
.split_once('/')
|
||||
@@ -515,6 +522,7 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
let page = match path {
|
||||
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
|
||||
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/user-volume" => read_page(params, engine, Exchange::public_user_volume),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
|
||||
_ => read_page(params, engine, Exchange::public_price_history),
|
||||
@@ -533,6 +541,10 @@ fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value)
|
||||
503,
|
||||
json!({"code":"unavailable","error":"portfolio valuation unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/user-volume" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"user volume unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/resolutions" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
|
||||
@@ -703,6 +715,10 @@ mod tests {
|
||||
("GET","/v2/value?user=a&condition=",String::new(),400,None),
|
||||
("GET","/v2/value?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
|
||||
("POST","/v2/value",String::new(),405,None),
|
||||
("GET","/v2/user-volume?user=unknown",String::new(),200,Some(json!({"data":{"volume":0,"volume_usdc":0,"trade_count":0}}))),
|
||||
("GET","/v2/user-volume?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
|
||||
("GET","/v2/user-volume",String::new(),400,None),
|
||||
("POST","/v2/user-volume",String::new(),405,None),
|
||||
("GET","/v2/trades?user=unknown&conditionId=unknown&takerOnly=false",String::new(),200,Some(empty_trades)),
|
||||
("GET","/v2/trades?offset=2",String::new(),400,None),
|
||||
("GET","/v2/trades?cursor=invalid",String::new(),400,None),
|
||||
|
||||
+16
-19
@@ -2,6 +2,19 @@
|
||||
|
||||
维护一个 SQLite 模拟市场。每条写命令在同一事务内完成资金或份额预留、订单更新和幂等回执。成交明细由 matching 计算。只读 state 使用一个一致快照。
|
||||
|
||||
## 钱包成交量
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant H as HTTP
|
||||
participant E as portfolio/user_volume.rs
|
||||
participant D as SQLite
|
||||
H->>E: 钱包与 Unix 秒起止参数
|
||||
E->>E: 校验钱包,把有效边界转换为 UTC 日
|
||||
E->>D: 读取该钱包的买卖成交,汇总窗口内份数、成交额和笔数
|
||||
E-->>H: 单个数据对象
|
||||
```
|
||||
|
||||
## 文件依赖
|
||||
|
||||
箭头从使用方指向提供类型或功能的文件。虚线连到 workspace 内的另一个 crate。图中省略标准库及第三方 crate。
|
||||
@@ -25,8 +38,6 @@ flowchart LR
|
||||
publicsql -->|预定窗口内的成交及订单| schema
|
||||
publictrades -->|标识结果资产| assets
|
||||
publictrades -->|校验事件及盘口选择| valid
|
||||
api -->|保存裁决保证金和资金去向| oracle_bonds["src/resolution/bonds.rs"]
|
||||
oracle_bonds -->|扣款或退款| collateral["src/ledger.rs"]
|
||||
queries -->|市场持有人榜单| holders["src/holders.rs"]
|
||||
holders -->|按余额及结果分页| holderrows["src/holders.sql"]
|
||||
holderrows -->|读取含挂单预留的持仓| markschema
|
||||
@@ -43,6 +54,9 @@ flowchart LR
|
||||
api -->|事务内派发| market["src/market.rs"]
|
||||
api -->|解析只读查询| queries["src/catalog.rs"]
|
||||
queries -->|查询各盘及赛事成交量| volume["src/volume.rs"]
|
||||
api -->|查询钱包成交量| user_volume["src/portfolio/user_volume.rs"]
|
||||
user_volume -->|按 UTC 日期汇总钱包成交| user_volume_sql["src/portfolio/user_volume.sql"]
|
||||
user_volume_sql -->|读取按账户拆开的成交| wallet_legs["src/price_migration.sql"]
|
||||
volume -->|按市场汇总普通及互补成交| volumesql["src/volume.sql"]
|
||||
volumesql -->|成交、时间及吃单方| schema
|
||||
queries -->|市价预估| estimate["src/estimate.rs"]
|
||||
@@ -460,23 +474,6 @@ sequenceDiagram
|
||||
E-->>C: 一个观测或空数组
|
||||
```
|
||||
|
||||
## 乐观裁决保证金
|
||||
|
||||
上架时可在 `resolution` 中配置 `bond_micros`。提案与挑战各扣一份模拟保证金。无争议终裁将保证金返还提案人。争议裁定将赢家本金和败方约一半保证金入账,余下金额记录为销毁。首轮重新提案后,可通过 `settle_first_dispute_bond` 单独登记首轮裁定及证据。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor P as 提案人
|
||||
actor C as 挑战者
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
P->>E: 提交提案和证据
|
||||
E->>D: 同事务记录提案并锁定现金
|
||||
C->>E: 提交挑战和证据
|
||||
E->>D: 同事务扣挑战保证金并登记争议
|
||||
E->>D: 按裁定退还赢家本金并记录败方保证金去向
|
||||
```
|
||||
|
||||
## 最优报价变化与断线续读
|
||||
|
||||
`lib.rs` 安装 `quote_schema.sql`,按市场保存事务提交时的买一和卖一。常规交易随请求回执写入,`expiry.rs` 在订单到期或定时封盘的事务内用 `quotes.rs` 写入变化。`assets.rs` 和 `catalog.rs` 将资产路由至当前报价或历史查询。
|
||||
|
||||
@@ -158,13 +158,6 @@ pub(crate) enum Command {
|
||||
challenger: String,
|
||||
evidence: String,
|
||||
},
|
||||
#[serde(rename = "settle_first_dispute_bond")]
|
||||
SettleFirstDisputeBond {
|
||||
market: String,
|
||||
proposal: i64,
|
||||
verdict: String,
|
||||
evidence: String,
|
||||
},
|
||||
Adjudicate {
|
||||
market: String,
|
||||
proposal: i64,
|
||||
|
||||
@@ -54,6 +54,7 @@ pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use portfolio::UserVolumeQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
|
||||
@@ -341,12 +341,6 @@ pub(crate) fn apply(
|
||||
challenger,
|
||||
evidence,
|
||||
} => resolution::dispute(tx, &market, proposal, &challenger, &evidence),
|
||||
Command::SettleFirstDisputeBond {
|
||||
market,
|
||||
proposal,
|
||||
verdict,
|
||||
evidence,
|
||||
} => resolution::settle_first_dispute_bond(tx, &market, proposal, &verdict, &evidence),
|
||||
Command::Adjudicate {
|
||||
market,
|
||||
proposal,
|
||||
@@ -449,7 +443,6 @@ pub(crate) fn finalize(tx: &Transaction, market: &str, winner: &str) -> Result<i
|
||||
phase(tx, market, &["closed"])?;
|
||||
ensure!(matches!(winner, "YES" | "NO" | "VOID"), "invalid winner");
|
||||
resolution::authorize_finalization(tx, market, winner)?;
|
||||
resolution::settle_undisputed_bond(tx, market, winner)?;
|
||||
crate::neg_risk::allocate_payout(tx, market, winner)?;
|
||||
// Each outcome redeems in whole collateral base units. Half-payout rounding
|
||||
// is per outcome balance, including when both balances belong to one wallet.
|
||||
|
||||
@@ -10,6 +10,9 @@ use rusqlite::{params, Connection};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
mod user_volume;
|
||||
pub use user_volume::UserVolumeQuery;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
use super::protocol::CONTRACTS;
|
||||
use crate::{
|
||||
inventory::decimal,
|
||||
lots::PER_SHARE,
|
||||
tick_size::PAR,
|
||||
validation::{hex_id, identifier},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::params;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct UserVolumeQuery {
|
||||
user: String,
|
||||
start: Option<i64>,
|
||||
end: Option<i64>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_user_volume(&self, query: UserVolumeQuery) -> Result<Value, MarketDataError> {
|
||||
let user = &query.user;
|
||||
identifier(user).map_err(|_| MarketDataError::Invalid("invalid user".into()))?;
|
||||
if CONTRACTS.iter().any(|c| c.eq_ignore_ascii_case(user)) {
|
||||
return Err(MarketDataError::Invalid(
|
||||
"protocol contract is not a user".into(),
|
||||
));
|
||||
}
|
||||
let start = query.start.filter(|&at| at != 0);
|
||||
let end = query.end.filter(|&at| at != 0);
|
||||
if matches!(start.zip(end), Some((start, end)) if start > end) {
|
||||
return Ok(json!({"data":{"volume":0,"volume_usdc":0,"trade_count":0}}));
|
||||
}
|
||||
let day = |at: i64| at.div_euclid(86_400);
|
||||
let (shares, notional, count): (i64, i64, i64) = self
|
||||
.db
|
||||
.prepare_cached(include_str!("user_volume.sql"))?
|
||||
.query_row(
|
||||
params![user, hex_id(user, 40), start.map(day), end.map(day)],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
Ok(json!({"data":{
|
||||
"volume":decimal(shares.into(), PER_SHARE),
|
||||
"volume_usdc":decimal(notional.into(), PER_SHARE * PAR),
|
||||
"trade_count":count
|
||||
}}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
WITH owners AS (
|
||||
SELECT ?1 AS id WHERE NOT ?2
|
||||
UNION ALL
|
||||
SELECT id FROM accounts WHERE ?2 AND id=?1 COLLATE NOCASE
|
||||
), legs AS (
|
||||
SELECT execution, quantity, price,
|
||||
at_ms/86400000 - (at_ms%86400000<0) AS utc_day
|
||||
FROM wallet_trade_legs
|
||||
WHERE account IN (SELECT id FROM owners)
|
||||
)
|
||||
SELECT COALESCE(SUM(quantity),0), COALESCE(SUM(quantity*price),0), COUNT(DISTINCT execution)
|
||||
FROM legs
|
||||
WHERE (?3 IS NULL OR utc_day>=?3) AND (?4 IS NULL OR utc_day<=?4)
|
||||
@@ -1,6 +1,4 @@
|
||||
mod bonds;
|
||||
pub(crate) mod http;
|
||||
pub(crate) use bonds::{settle_first_dispute_bond, settle_undisputed_bond};
|
||||
|
||||
use crate::validation::identifier;
|
||||
use anyhow::{ensure, Result};
|
||||
@@ -14,7 +12,6 @@ pub(crate) enum Policy {
|
||||
Optimistic {
|
||||
eligible_at: i64,
|
||||
question_id: Option<String>,
|
||||
bond_micros: Option<i64>,
|
||||
},
|
||||
Twap {
|
||||
stream: String,
|
||||
@@ -25,12 +22,11 @@ pub(crate) enum Policy {
|
||||
|
||||
impl Policy {
|
||||
pub fn save(self, tx: &Transaction, market: &str) -> Result<()> {
|
||||
let (eligible_at, question_id, bond) = match self {
|
||||
let (eligible_at, question_id) = match self {
|
||||
Self::Optimistic {
|
||||
eligible_at,
|
||||
question_id,
|
||||
bond_micros,
|
||||
} => (eligible_at, question_id, bond_micros),
|
||||
} => (eligible_at, question_id),
|
||||
Self::Twap {
|
||||
stream,
|
||||
start_at,
|
||||
@@ -42,9 +38,6 @@ impl Policy {
|
||||
"INSERT INTO optimistic_markets(market,eligible_at) VALUES(?,?)",
|
||||
params![market, eligible_at],
|
||||
)?;
|
||||
if let Some(bond) = bond {
|
||||
bonds::configure(tx, market, bond)?;
|
||||
}
|
||||
if let Some(id) = question_id {
|
||||
tx.execute(
|
||||
"INSERT INTO resolution_questions(market,question_id) VALUES(?,?)",
|
||||
@@ -78,9 +71,7 @@ pub(crate) fn propose(
|
||||
FROM market_resolution WHERE market=?1 AND status IN ('awaiting_proposal','awaiting_second_proposal')",
|
||||
params![market,winner,proposer,evidence])?;
|
||||
ensure!(changed == 1, "market is not accepting proposals");
|
||||
let proposal = tx.last_insert_rowid();
|
||||
bonds::lock(tx, market, proposer, None)?;
|
||||
Ok(json!({"proposal":proposal,"status":"challenge_window"}))
|
||||
Ok(json!({"proposal":tx.last_insert_rowid(),"status":"challenge_window"}))
|
||||
}
|
||||
|
||||
pub(crate) fn dispute(
|
||||
@@ -97,7 +88,6 @@ pub(crate) fn dispute(
|
||||
WHERE market=?1 AND id=?2 AND id=(SELECT proposal FROM market_resolution WHERE market=?1 AND status='challenge_window')",
|
||||
params![market,proposal,challenger,evidence])?;
|
||||
ensure!(changed == 1, "proposal is outside its challenge window");
|
||||
bonds::lock(tx, market, challenger, Some(proposal))?;
|
||||
let status: String = tx.query_row(
|
||||
"SELECT status FROM market_resolution WHERE market=?",
|
||||
[market],
|
||||
@@ -122,7 +112,6 @@ pub(crate) fn record_verdict(
|
||||
WHERE market=?1 AND id=?2 AND id=(SELECT proposal FROM market_resolution WHERE market=?1 AND status='awaiting_arbitration')",
|
||||
params![market,proposal,verdict,evidence])?;
|
||||
ensure!(changed == 1, "proposal is not awaiting arbitration");
|
||||
bonds::settle(tx, market, proposal, verdict, Some(evidence))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -153,7 +142,6 @@ pub(crate) fn read(db: &Connection, market: &str) -> Result<Value> {
|
||||
_ => Value::Null,
|
||||
};
|
||||
state["clarifications"] = json!(crate::clarifications::for_resolution(db, market)?);
|
||||
bonds::add_state(db, market, &mut state)?;
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,299 +0,0 @@
|
||||
use crate::ledger;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(super) fn configure(tx: &Transaction, market: &str, micros: i64) -> Result<()> {
|
||||
ensure!(
|
||||
(0..=10_000_000_000_000).contains(µs),
|
||||
"invalid resolution bond"
|
||||
);
|
||||
if micros > 0 {
|
||||
tx.execute(
|
||||
"INSERT INTO resolution_bond_terms VALUES(?1,?2)",
|
||||
params![market, micros],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bond(db: &Connection, market: &str) -> rusqlite::Result<Option<i64>> {
|
||||
db.query_row(
|
||||
"SELECT micros FROM resolution_bond_terms WHERE market=?1",
|
||||
[market],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()
|
||||
}
|
||||
|
||||
pub(super) fn lock(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
account: &str,
|
||||
challenged: Option<i64>,
|
||||
) -> Result<()> {
|
||||
if let Some(micros) = bond(tx, market)? {
|
||||
if let Some(id) = challenged {
|
||||
let distinct: bool = tx.query_row(
|
||||
"SELECT proposer<>?2 FROM resolution_proposals WHERE id=?1",
|
||||
params![id, account],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(distinct, "cannot bond both sides of a dispute");
|
||||
}
|
||||
ledger::cash_micros(tx, account, -micros)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn settle(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
id: i64,
|
||||
verdict: &str,
|
||||
evidence: Option<&str>,
|
||||
) -> Result<Option<Value>> {
|
||||
let Some(micros) = bond(tx, market)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let (proposed, proposer, challenger): (String, String, Option<String>) = tx.query_row(
|
||||
"SELECT result,proposer,challenger FROM resolution_proposals WHERE id=?1 AND market=?2",
|
||||
params![id, market],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
let (recipient, paid, burned) = match challenger {
|
||||
Some(challenger) => {
|
||||
// UMA burns floor(loser's bond / 2) and pays the rest to the winner.
|
||||
let burned = micros / 2;
|
||||
(
|
||||
if proposed == verdict {
|
||||
proposer
|
||||
} else {
|
||||
challenger
|
||||
},
|
||||
2 * micros - burned,
|
||||
burned,
|
||||
)
|
||||
}
|
||||
None => {
|
||||
ensure!(
|
||||
proposed == verdict,
|
||||
"undisputed proposal must match verdict"
|
||||
);
|
||||
(proposer, micros, 0)
|
||||
}
|
||||
};
|
||||
let inserted = tx.execute(
|
||||
"INSERT INTO resolution_bond_settlements VALUES(?1,?2,?3,?4,?5,?6)
|
||||
ON CONFLICT(proposal) DO NOTHING",
|
||||
params![id, verdict, evidence, recipient, paid, burned],
|
||||
)?;
|
||||
if inserted == 1 {
|
||||
ledger::cash_micros(tx, &recipient, paid)?;
|
||||
} else {
|
||||
let prior: String = tx.query_row(
|
||||
"SELECT verdict FROM resolution_bond_settlements WHERE proposal=?1",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
prior == verdict,
|
||||
"resolution bond already settled with another verdict"
|
||||
);
|
||||
}
|
||||
Ok(Some(json!({
|
||||
"proposal":id,"verdict":verdict,"recipient":recipient,"paid_micros":paid,"burned_micros":burned
|
||||
})))
|
||||
}
|
||||
|
||||
pub(crate) fn settle_first_dispute_bond(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
id: i64,
|
||||
verdict: &str,
|
||||
evidence: &str,
|
||||
) -> Result<Value> {
|
||||
ensure!(
|
||||
matches!(verdict, "YES" | "NO" | "VOID" | "TOO_EARLY"),
|
||||
"invalid bond verdict"
|
||||
);
|
||||
ensure!(
|
||||
!evidence.trim().is_empty(),
|
||||
"bond verdict requires evidence"
|
||||
);
|
||||
let allowed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM resolution_proposals
|
||||
WHERE id=?1 AND market=?2 AND round=1 AND challenged_at IS NOT NULL)",
|
||||
params![id, market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(allowed, "bond verdict requires a contested first proposal");
|
||||
settle(tx, market, id, verdict, Some(evidence))?
|
||||
.context("market has no configured resolution bond")
|
||||
}
|
||||
|
||||
pub(crate) fn settle_undisputed_bond(tx: &Transaction, market: &str, winner: &str) -> Result<()> {
|
||||
if bond(tx, market)?.is_some() {
|
||||
let id:Option<i64> = tx.query_row(
|
||||
"SELECT proposal FROM market_resolution WHERE market=?1 AND status='ready_to_finalize'",
|
||||
[market],|r|r.get(0),
|
||||
).optional()?;
|
||||
if let Some(id) = id {
|
||||
settle(tx, market, id, winner, None)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn add_state(db: &Connection, market: &str, state: &mut Value) -> Result<()> {
|
||||
let Some(micros) = bond(db, market)? else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT p.id,p.challenger IS NOT NULL,s.verdict,s.recipient,s.paid_micros,s.burned_micros,s.evidence
|
||||
FROM resolution_proposals p LEFT JOIN resolution_bond_settlements s ON s.proposal=p.id
|
||||
WHERE p.market=?1 ORDER BY p.id",
|
||||
)?;
|
||||
let history = stmt
|
||||
.query_map([market], |r| {
|
||||
let contested: bool = r.get(1)?;
|
||||
let paid: Option<i64> = r.get(4)?;
|
||||
Ok(json!({"proposal":r.get::<_,i64>(0)?,
|
||||
"locked_micros":if paid.is_some(){0}else if contested{2*micros}else{micros},
|
||||
"verdict":r.get::<_,Option<String>>(2)?,"recipient":r.get::<_,Option<String>>(3)?,
|
||||
"paid_micros":paid,"burned_micros":r.get::<_,Option<i64>>(5)?,"evidence":r.get::<_,Option<String>>(6)?
|
||||
}))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
state["bond_micros"] = json!(micros);
|
||||
state["bonds"] = json!(history);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Exchange;
|
||||
|
||||
#[test]
|
||||
fn locks_both_sides_and_settles_each_oracle_round_once() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("oracle-bonds.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
for request in [
|
||||
json!({"op":"fund","id":"alice","account":"alice","micros":20000000}),
|
||||
json!({"op":"fund","id":"bob","account":"bob","micros":20000000}),
|
||||
json!({"op":"fund","id":"poor","account":"poor","micros":1}),
|
||||
json!({"op":"list","id":"cup","market":"cup","rules":"winner","resolution":{
|
||||
"kind":"optimistic","eligible_at":0,"bond_micros":5000001
|
||||
}}),
|
||||
json!({"op":"open","id":"open","market":"cup"}),
|
||||
json!({"op":"close","id":"close","market":"cup"}),
|
||||
] {
|
||||
db.execute(request).unwrap();
|
||||
}
|
||||
assert!(db
|
||||
.execute(json!({"op":"propose","id":"poor-proposal","market":"cup",
|
||||
"winner":"NO","proposer":"poor","evidence":"sample"}))
|
||||
.is_err());
|
||||
let first = db
|
||||
.execute(json!({"op":"propose","id":"first","market":"cup",
|
||||
"winner":"NO","proposer":"alice","evidence":"sample"}))
|
||||
.unwrap()["proposal"]
|
||||
.as_i64()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ledger::balance(&db.db, "alice").unwrap()["available_micros"],
|
||||
14999999
|
||||
);
|
||||
for account in ["alice", "poor"] {
|
||||
assert!(db
|
||||
.execute(
|
||||
json!({"op":"dispute","id":format!("wrong-{account}"),"market":"cup",
|
||||
"proposal":first,"challenger":account,"evidence":"sample"})
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
db.execute(json!({"op":"dispute","id":"first-challenge","market":"cup",
|
||||
"proposal":first,"challenger":"bob","evidence":"sample"}))
|
||||
.unwrap();
|
||||
let second = db
|
||||
.execute(json!({"op":"propose","id":"second","market":"cup",
|
||||
"winner":"YES","proposer":"alice","evidence":"alternate"}))
|
||||
.unwrap()["proposal"]
|
||||
.as_i64()
|
||||
.unwrap();
|
||||
db.execute(
|
||||
json!({"op":"dispute","id":"second-challenge","market":"cup",
|
||||
"proposal":second,"challenger":"bob","evidence":"sample"}),
|
||||
)
|
||||
.unwrap();
|
||||
db.execute(
|
||||
json!({"op":"adjudicate","id":"second-result","market":"cup",
|
||||
"proposal":second,"verdict":"YES","evidence":"market verdict"}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let state = db
|
||||
.execute(json!({"op":"resolution","market":"cup"}))
|
||||
.unwrap();
|
||||
assert_eq!(state["winner"], "YES");
|
||||
assert_eq!(state["bonds"][0]["locked_micros"], 10000002);
|
||||
assert_eq!(state["bonds"][1]["recipient"], "alice");
|
||||
assert_eq!(state["bonds"][1]["burned_micros"], 2500000);
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let pay = |id, verdict| {
|
||||
json!({"op":"settle_first_dispute_bond","id":id,"market":"cup",
|
||||
"proposal":first,"verdict":verdict,"evidence":"separate first oracle request"})
|
||||
};
|
||||
let result = db.execute(pay("settle-first", "YES")).unwrap();
|
||||
assert_eq!(result["recipient"], "bob");
|
||||
assert_eq!(result["paid_micros"], 7500002);
|
||||
assert_eq!(db.execute(pay("settle-retry", "YES")).unwrap(), result);
|
||||
assert!(db.execute(pay("conflicting-verdict", "NO")).is_err());
|
||||
assert_eq!(
|
||||
ledger::balance(&db.db, "alice").unwrap()["available_micros"],
|
||||
17500000
|
||||
);
|
||||
assert_eq!(
|
||||
ledger::balance(&db.db, "bob").unwrap()["available_micros"],
|
||||
17500000
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(json!({"op":"resolution","market":"cup"}))
|
||||
.unwrap()["winner"],
|
||||
"YES"
|
||||
);
|
||||
|
||||
for request in [
|
||||
json!({"op":"list","id":"cup-2","market":"cup-2","rules":"winner","resolution":{
|
||||
"kind":"optimistic","eligible_at":0,"bond_micros":5000001
|
||||
}}),
|
||||
json!({"op":"open","id":"open-2","market":"cup-2"}),
|
||||
json!({"op":"close","id":"close-2","market":"cup-2"}),
|
||||
json!({"op":"propose","id":"uncontested","market":"cup-2","winner":"YES",
|
||||
"proposer":"alice","evidence":"sample"}),
|
||||
] {
|
||||
db.execute(request).unwrap();
|
||||
}
|
||||
db.db
|
||||
.execute(
|
||||
"UPDATE resolution_proposals SET proposed_at=0 WHERE market='cup-2'",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
db.execute(json!({"op":"finalize","id":"final","market":"cup-2","winner":"YES"}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ledger::balance(&db.db, "alice").unwrap()["available_micros"],
|
||||
17500000
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(json!({"op":"resolution","market":"cup-2"}))
|
||||
.unwrap()["bonds"][0]["locked_micros"],
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -160,19 +160,6 @@ CREATE VIEW IF NOT EXISTS market_resolution AS
|
||||
LEFT JOIN resolution_proposals r ON r.id=(
|
||||
SELECT id FROM resolution_proposals WHERE market=m.id ORDER BY id DESC LIMIT 1);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS resolution_bond_terms (
|
||||
market TEXT PRIMARY KEY REFERENCES optimistic_markets(market),
|
||||
micros INTEGER NOT NULL CHECK(micros BETWEEN 1 AND 10000000000000)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS resolution_bond_settlements (
|
||||
proposal INTEGER PRIMARY KEY REFERENCES resolution_proposals(id),
|
||||
verdict TEXT NOT NULL CHECK(verdict IN ('YES','NO','VOID','TOO_EARLY')),
|
||||
evidence TEXT,
|
||||
recipient TEXT NOT NULL REFERENCES accounts(id),
|
||||
paid_micros INTEGER NOT NULL CHECK(paid_micros>0),
|
||||
burned_micros INTEGER NOT NULL CHECK(burned_micros>=0)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS twap_markets (
|
||||
market TEXT PRIMARY KEY REFERENCES markets, stream TEXT NOT NULL,
|
||||
start_at INTEGER NOT NULL CHECK(start_at>=0), end_at INTEGER NOT NULL CHECK(end_at>start_at),
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn volume(db: &Exchange, query: Value) -> Value {
|
||||
db.public_user_volume(serde_json::from_value(query).unwrap())
|
||||
.unwrap()["data"]
|
||||
.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallet_volume_counts_both_roles_and_rounds_bounds_to_utc_days() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("wallet-volume.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
for line in include_str!("../../../docs/examples/valuation.jsonl")
|
||||
.lines()
|
||||
.take(7)
|
||||
{
|
||||
db.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"list-pair","market":"pair","rules":"赛果"}),
|
||||
json!({"op":"open","id":"open-pair","market":"pair"}),
|
||||
json!({"op":"order","id":"buy-no","market":"pair","account":"alice","outcome":"NO","side":"buy","price":40,"qty":3}),
|
||||
json!({"op":"order","id":"buy-yes","market":"pair","account":"bob","outcome":"YES","side":"buy","price":60,"qty":3}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
// Put the executions on opposite sides of UTC midnight.
|
||||
let sqlite = rusqlite::Connection::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
sqlite
|
||||
.execute("UPDATE trade_prices SET at_ms=86399999", [])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
sqlite
|
||||
.execute("UPDATE paired_fills SET at_ms=86400000", [])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
drop(sqlite);
|
||||
|
||||
let zero = json!({"volume":0,"volume_usdc":0,"trade_count":0});
|
||||
assert_eq!(volume(&db, json!({"user":"unknown"})), zero);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":86500,"end":86400})),
|
||||
zero
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":1,"end":1})),
|
||||
json!({"volume":2,"volume_usdc":1.2,"trade_count":1})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":86500,"end":86500})),
|
||||
json!({"volume":3,"volume_usdc":1.2,"trade_count":1})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"alice","start":0,"end":0})),
|
||||
json!({"volume":5,"volume_usdc":2.4,"trade_count":2})
|
||||
);
|
||||
assert_eq!(
|
||||
volume(&db, json!({"user":"bob"})),
|
||||
json!({"volume":5,"volume_usdc":3,"trade_count":2})
|
||||
);
|
||||
}
|
||||
@@ -87,11 +87,7 @@ Polymarket 的 CTF 市场使用结果 token ID,Protocol V2 市场使用结果
|
||||
|
||||
首次挑战开放第二轮,两次挑战转入模拟仲裁。adjudicate 接收 market、第二次被挑战的 proposal、verdict 和 evidence。YES、NO 或 VOID 会在同一事务内核对抵押并最终裁决;TOO_EARLY 保留整段历史并开放替代提案,再次挑战将直接进入仲裁。resolution 查询返回每轮结果、参考证据、提案与挑战时间、仲裁结论和最终结果。状态恢复和兑付隔离的集成用例为 contested_resolution_blocks_both_payout_paths_until_a_verdict。
|
||||
|
||||
两小时窗口及两轮升级顺序依据公开规则。当前采用可信 CLI 操作员录入仲裁结果,证据以原文保存。提案奖励、真实预言机验证以及链上开始和最终确认时间仍待实现。结束无人争议的轮次需要提交 finalize 或 resolve。[Polymarket 裁决规则](https://docs.polymarket.com/concepts/resolution.md)
|
||||
|
||||
### 乐观裁决保证金
|
||||
|
||||
配置 `bond_micros` 后,提案和挑战从已存在的模拟账户扣等额保证金。资金不足会回滚提案或挑战。无争议的合法终裁返还本金。争议裁定时返还赢家本金,败方保证金向下取整的一半记为销毁,其余归赢家。首轮争议重发问题后保留原保证金,操作员可用独立命令登记其裁定、证据和付款,其结果不更改市场裁决。真实链上请求奖励、最终仲裁费用和链上对账尚未实现。[Polymarket 裁决规则](https://docs.polymarket.com/concepts/resolution) · [UMA 结算合约](https://github.com/UMAprotocol/protocol/blob/master/packages/core/contracts/optimistic-oracle-v2/implementation/OptimisticOracleV2.sol)
|
||||
两小时窗口及两轮升级顺序依据公开规则。当前采用可信 CLI 操作员录入仲裁结果,证据以原文保存。提案与反提案的保证金、奖励、真实预言机验证以及链上开始和最终确认时间仍待实现。结束无人争议的轮次需要提交 finalize 或 resolve。[Polymarket 裁决规则](https://docs.polymarket.com/concepts/resolution.md)
|
||||
|
||||
## 涨跌市场与 TWAP 报告
|
||||
|
||||
@@ -227,6 +223,12 @@ JSONL 下单面板的 `price` 接受 token_id 和方向,BUY 读取最低卖价
|
||||
|
||||
[可重放样例](examples/execution-prices.jsonl)开始时只有 YES 买单,买入 YES 的报价为 null。随后有人以 0.89 挂买 NO,YES 买入价变成 0.11,卖出价为 0.09。NO 买入价为 0.91,卖出价为 0.89。这四个报价均来自挂单,无需先发生交易。单侧没有对手时保留该键并返回 null。重复项合并,未知资产使整批失败。空批次拒绝,盘前返回待集合竞价的挂单报价。上述边界属于本地约定。本地 token_id 使用 Eventbook 的结果资产 ID,公开接口的生产响应、原生资产编号与无流动性时的处理仍待对照。
|
||||
|
||||
### 钱包成交量 Data API
|
||||
|
||||
官方 `GET /v2/user-volume` 按 UTC 整日统计钱包的买卖成交,返回份数、USDC 金额和成交笔数。起止参数以 Unix 秒表示,省略或填 0 关闭该侧边界。倒置窗口及无成交钱包返回零。[官方接口](https://docs.polymarket.com/api-reference/wallet/get-a-users-trading-volume)
|
||||
|
||||
在空数据库重放 [估值样例](examples/valuation.jsonl) 的前七条命令。Alice 和 Bob 分别查询 `/v2/user-volume`,均应得到 2 份、1.2 USDC 和 1 笔。互补成交使用各自的结果资产价格。金额为成交价乘份数,费用与抵押拆并不计。盘口关闭后历史成交仍可查询。本地按成交编号去重计笔数,无可信时间的旧成交只进入不限日期的汇总。独立的组合 RFQ 账本及生产端点的持续对账仍待接入。
|
||||
|
||||
## 精确抵押币现金余额
|
||||
|
||||
`balance` 返回账户可用现金、有效买单预留现金及二者之和,单位均为百万分之一模拟美元。拆分完整结果集所用的抵押和已买入的份额另由仓位账本记录。模拟 fund 可以用整数 micros 建立账户,也可以沿用 cents。入金回执和 activity 的 net_cash_delta_micros 可用于精确对账,原 funded 和 cash_delta_cents 字段保留整分部分。一个账户只接受首次 fund;相同请求可幂等重放。
|
||||
|
||||
Reference in new issue
Block a user