Refresh recorded venue asset state with monotonic observations
This commit is contained in:
@@ -1459,3 +1459,5 @@ sequenceDiagram
|
||||
```
|
||||
|
||||
`bind_polymarket_assets` 将完整协议配对绑定到已创建的本地市场。操作员用 zero_outcome 声明外场结果索引 0 对应本地 YES 或 NO。绑定和请求回执在同一事务提交。数字资产、外场条件和已绑定的结构条件可通过 GET /v2/tokens 反查;响应附带 local_asset_id。成交流程继续通过本地资产提交委托。
|
||||
|
||||
同一配对可携带 observed_at_ms 刷新外场状态。旧快照不会覆盖新状态,最终兑付冲突会回滚。
|
||||
|
||||
@@ -347,3 +347,9 @@ CREATE UNIQUE INDEX IF NOT EXISTS pm_alias_structure_slots
|
||||
ON polymarket_token_aliases(structure,slot) WHERE structure IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS pm_alias_question_slots
|
||||
ON polymarket_token_aliases(group_id,question,module,slot) WHERE group_id IS NOT NULL;
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS polymarket_token_observation_times (
|
||||
token_id TEXT PRIMARY KEY REFERENCES polymarket_token_aliases(token_id),
|
||||
observed_at_ms INTEGER NOT NULL CHECK(observed_at_ms>0)
|
||||
);
|
||||
|
||||
@@ -14,6 +14,7 @@ pub(crate) struct Bind {
|
||||
market: String,
|
||||
external_condition: String,
|
||||
zero_outcome: String,
|
||||
observed_at_ms: Option<i64>,
|
||||
data: Vec<Value>,
|
||||
}
|
||||
|
||||
@@ -118,6 +119,10 @@ impl<'a> Row<'a> {
|
||||
impl Bind {
|
||||
pub(crate) fn register(self, tx: &Transaction<'_>) -> Result<Value> {
|
||||
identifier(&self.market)?;
|
||||
ensure!(
|
||||
self.observed_at_ms.is_none_or(|ms| ms > 0),
|
||||
"invalid observation time"
|
||||
);
|
||||
ensure!(
|
||||
matches!(self.zero_outcome.as_str(), "YES" | "NO"),
|
||||
"zero_outcome must be YES or NO"
|
||||
@@ -140,6 +145,27 @@ impl Bind {
|
||||
"repeated protocol outcome"
|
||||
);
|
||||
}
|
||||
if self.observed_at_ms.is_some() {
|
||||
let mut states = BTreeMap::new();
|
||||
for value in &self.data {
|
||||
let row = Row::read(value, &self.external_condition)?;
|
||||
let state = SnapshotState::read(value)?;
|
||||
let pair = states.entry(row.module).or_insert_with(|| [None, None]);
|
||||
pair[row.slot] = Some(state);
|
||||
}
|
||||
for pair in states.values() {
|
||||
let [Some(a), Some(b)] = pair else {
|
||||
anyhow::bail!("incomplete protocol pair");
|
||||
};
|
||||
ensure!(
|
||||
a.closed == b.closed && a.resolved == b.resolved,
|
||||
"protocol pair has inconsistent lifecycle"
|
||||
);
|
||||
if let (Some(a), Some(b)) = (a.price, b.price) {
|
||||
ensure!((a + b - 1.0).abs() <= 1e-9, "final payouts must sum to one");
|
||||
}
|
||||
}
|
||||
}
|
||||
let v2_count = families.keys().filter(|m| **m != "v1_ctf").count();
|
||||
ensure!(v2_count <= 1, "multiple V2 protocols for the same market");
|
||||
let mut group_ref = None;
|
||||
@@ -218,6 +244,7 @@ impl Bind {
|
||||
.into_iter()
|
||||
.map(|key| (key.to_owned(), value[key].clone()))
|
||||
.collect();
|
||||
let observation = Value::Object(observation);
|
||||
tx.execute(
|
||||
"INSERT INTO polymarket_token_aliases VALUES(?1,?2,?3,?4,?5,?6,?7,?8)
|
||||
ON CONFLICT(token_id) DO NOTHING",
|
||||
@@ -229,7 +256,7 @@ impl Bind {
|
||||
row.group,
|
||||
row.question,
|
||||
row.slot as i64,
|
||||
Value::Object(observation).to_string()
|
||||
observation.to_string()
|
||||
],
|
||||
)?;
|
||||
let observed: Option<String> = tx
|
||||
@@ -240,16 +267,19 @@ impl Bind {
|
||||
)
|
||||
.optional()?;
|
||||
let prior: Value = serde_json::from_str(&observed.context("missing stored token")?)?;
|
||||
let prior = Row::read(&prior, &self.external_condition)?;
|
||||
let prior_identity = Row::read(&prior, &self.external_condition)?;
|
||||
ensure!(
|
||||
prior.module == row.module
|
||||
&& prior.structure == row.structure
|
||||
&& prior.slot == row.slot
|
||||
&& prior.group == row.group
|
||||
&& prior.question == row.question
|
||||
&& prior.opposite == row.opposite,
|
||||
prior_identity.module == row.module
|
||||
&& prior_identity.structure == row.structure
|
||||
&& prior_identity.slot == row.slot
|
||||
&& prior_identity.group == row.group
|
||||
&& prior_identity.question == row.question
|
||||
&& prior_identity.opposite == row.opposite,
|
||||
"token already bound with different identity"
|
||||
);
|
||||
if let Some(observed_at_ms) = self.observed_at_ms {
|
||||
refresh(tx, row.token, prior, &observation, observed_at_ms)?;
|
||||
}
|
||||
}
|
||||
Ok(
|
||||
json!({"market":self.market,"external_condition":self.external_condition,
|
||||
@@ -257,3 +287,87 @@ impl Bind {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct SnapshotState {
|
||||
closed: bool,
|
||||
resolved: bool,
|
||||
price: Option<f64>,
|
||||
}
|
||||
|
||||
impl SnapshotState {
|
||||
fn read(data: &Value) -> Result<Self> {
|
||||
let closed = data["closed"]
|
||||
.as_bool()
|
||||
.context("closed must be a boolean")?;
|
||||
let resolved = data["resolved"]
|
||||
.as_bool()
|
||||
.context("resolved must be a boolean")?;
|
||||
let price = data["final_price"].as_f64();
|
||||
if resolved {
|
||||
ensure!(
|
||||
closed && price.is_some_and(|p| (0.0..=1.0).contains(&p)),
|
||||
"invalid final payout"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
data["final_price"].is_null(),
|
||||
"unresolved asset has a final payout"
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
closed,
|
||||
resolved,
|
||||
price,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const LIVE_FIELDS: &[&str] = &["closed", "resolved", "final_price", "outcome"];
|
||||
|
||||
fn refresh(
|
||||
tx: &Transaction<'_>,
|
||||
token: &str,
|
||||
mut prior: Value,
|
||||
incoming: &Value,
|
||||
observed_at_ms: i64,
|
||||
) -> Result<()> {
|
||||
let last: Option<i64> = tx
|
||||
.query_row(
|
||||
"SELECT observed_at_ms FROM polymarket_token_observation_times WHERE token_id=?1",
|
||||
[token],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some(last) = last {
|
||||
if observed_at_ms < last {
|
||||
return Ok(());
|
||||
}
|
||||
if observed_at_ms == last {
|
||||
ensure!(
|
||||
LIVE_FIELDS.iter().all(|&key| prior[key] == incoming[key]),
|
||||
"conflicting observations at the same time"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if prior["resolved"] == true {
|
||||
ensure!(
|
||||
incoming["resolved"] == true
|
||||
&& prior["final_price"].as_f64() == incoming["final_price"].as_f64(),
|
||||
"observation contradicts a recorded final payout"
|
||||
);
|
||||
}
|
||||
for &key in LIVE_FIELDS {
|
||||
prior[key] = incoming[key].clone();
|
||||
}
|
||||
tx.execute(
|
||||
"UPDATE polymarket_token_aliases SET observation=?1 WHERE token_id=?2",
|
||||
params![prior.to_string(), token],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO polymarket_token_observation_times VALUES(?1,?2)
|
||||
ON CONFLICT(token_id) DO UPDATE SET observed_at_ms=excluded.observed_at_ms",
|
||||
params![token, observed_at_ms],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5,11 +5,12 @@ WITH selectors AS (
|
||||
)
|
||||
SELECT s.ordinal,t.observation,m.market,
|
||||
CASE WHEN t.slot=0 THEN m.zero_outcome
|
||||
WHEN m.zero_outcome='YES' THEN 'NO' ELSE 'YES' END AS outcome
|
||||
WHEN m.zero_outcome='YES' THEN 'NO' ELSE 'YES' END AS outcome,o.observed_at_ms
|
||||
FROM selectors s
|
||||
JOIN polymarket_token_aliases t ON
|
||||
(s.kind='external_token' AND t.token_id=s.id)
|
||||
OR (s.kind='condition' AND
|
||||
(t.condition_id=s.id OR t.group_id=s.id OR t.structure=s.id OR t.structure=s.id||'00'))
|
||||
JOIN polymarket_market_aliases m ON m.condition_id=t.condition_id
|
||||
LEFT JOIN polymarket_token_observation_times o ON o.token_id=t.token_id
|
||||
ORDER BY s.ordinal,t.question,t.condition_id,(t.module<>'v1_ctf'),t.slot
|
||||
|
||||
@@ -118,17 +118,19 @@ impl Exchange {
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, String>(3)?,
|
||||
r.get::<_, Option<i64>>(4)?,
|
||||
))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
let external_ordinals: HashSet<_> = externals.iter().map(|r| r.0).collect();
|
||||
data.retain(|(ordinal, _)| !external_ordinals.contains(ordinal));
|
||||
for (ordinal, raw, market, outcome) in externals {
|
||||
for (ordinal, raw, market, outcome, observed_at_ms) in externals {
|
||||
let mut row: Value =
|
||||
serde_json::from_str(&raw).map_err(|_| MarketDataError::Unavailable)?;
|
||||
row["local_condition_id"] = json!(market);
|
||||
row["local_asset_id"] = json!(assets::id(&market, &outcome));
|
||||
row["observed_at_ms"] = json!(observed_at_ms);
|
||||
data.push((ordinal, row));
|
||||
}
|
||||
data.sort_by_key(|row| row.0);
|
||||
|
||||
@@ -4262,3 +4262,55 @@ fn polymarket_asset_bindings_preserve_protocols_and_explicit_outcome_direction()
|
||||
rows[3]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polymarket_observations_refresh_without_reverting_a_final_payout() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("refresh.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
setup(&mut engine);
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-asset-refresh.json"
|
||||
))
|
||||
.unwrap();
|
||||
let resolved = fixture["directory"]["body"]["data"].clone();
|
||||
let mut open = resolved.clone();
|
||||
for item in open.as_array_mut().unwrap() {
|
||||
item["closed"] = json!(false);
|
||||
item["resolved"] = json!(false);
|
||||
item["final_price"] = Value::Null;
|
||||
}
|
||||
let late = fixture["directory"]["observed_at_ms"].as_i64().unwrap();
|
||||
let early = fixture["prior_book"]["observed_at_ms"].as_i64().unwrap();
|
||||
let condition = &resolved[0]["condition_id"];
|
||||
let obs = |id, stamp, rows: &Value| {
|
||||
json!({
|
||||
"op":"bind_polymarket_assets", "id":id,"market":"e","zero_outcome":"YES",
|
||||
"external_condition":condition,"observed_at_ms":stamp,"data":rows
|
||||
})
|
||||
};
|
||||
engine.execute(obs("before", early, &open)).unwrap();
|
||||
engine.execute(obs("final", late, &resolved)).unwrap();
|
||||
engine.execute(obs("old", early, &open)).unwrap();
|
||||
assert!(engine
|
||||
.execute(obs("same-time-conflict", late, &open))
|
||||
.is_err());
|
||||
assert!(engine
|
||||
.execute(obs("new-conflict", late + 1, &open))
|
||||
.is_err());
|
||||
drop(engine);
|
||||
let engine = Exchange::open(path).unwrap();
|
||||
let lookup = engine
|
||||
.public_tokens(serde_json::from_value(json!({"condition":condition})).unwrap())
|
||||
.unwrap();
|
||||
let rows = lookup["data"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
for row in rows {
|
||||
assert_eq!(row["resolved"], true);
|
||||
assert_eq!(row["observed_at_ms"], late);
|
||||
}
|
||||
let local = engine
|
||||
.public_tokens(serde_json::from_value(json!({"condition":"e"})).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(local["data"][0]["resolved"], false);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user