199 lines
7.0 KiB
Rust
199 lines
7.0 KiB
Rust
use anyhow::{ensure, Context, Result};
|
|
use serde_json::{json, Value};
|
|
|
|
fn pair(value: &Value) -> Result<[String; 2]> {
|
|
Ok(match value.as_str() {
|
|
Some(s) => serde_json::from_str(s)?,
|
|
None => serde_json::from_value(value.clone())?,
|
|
})
|
|
}
|
|
|
|
// Polymarket serializes token IDs as decimal strings. Decode without f64 or u128 truncation.
|
|
fn uint256(raw: &str) -> Result<[u8; 32]> {
|
|
ensure!(
|
|
!raw.is_empty() && raw.len() <= 78 && raw.bytes().all(|b| b.is_ascii_digit()),
|
|
"invalid decimal token ID"
|
|
);
|
|
let mut bytes = [0u8; 32];
|
|
for digit in raw.bytes() {
|
|
let mut carry = u16::from(digit - b'0');
|
|
for byte in bytes.iter_mut().rev() {
|
|
let n = u16::from(*byte) * 10 + carry;
|
|
*byte = n as u8;
|
|
carry = n >> 8;
|
|
}
|
|
ensure!(carry == 0, "token ID exceeds uint256");
|
|
}
|
|
Ok(bytes)
|
|
}
|
|
|
|
fn tokens(value: &Value) -> Result<[String; 2]> {
|
|
let ids = pair(value)?;
|
|
ensure!(
|
|
uint256(&ids[0])? != uint256(&ids[1])?,
|
|
"duplicate outcome identifiers"
|
|
);
|
|
Ok(ids)
|
|
}
|
|
|
|
fn position_condition(ids: &[String; 2]) -> Result<String> {
|
|
let yes = uint256(&ids[0])?;
|
|
let no = uint256(&ids[1])?;
|
|
ensure!(
|
|
yes[..31] == no[..31] && yes[31] == 0 && no[31] == 1,
|
|
"position IDs must encode the same condition and YES/NO outcome indexes"
|
|
);
|
|
use std::fmt::Write;
|
|
let mut condition = String::from("0x");
|
|
for byte in &yes[..31] {
|
|
write!(condition, "{byte:02x}")?;
|
|
}
|
|
Ok(condition)
|
|
}
|
|
|
|
pub(crate) struct Market {
|
|
pub assets: [String; 2],
|
|
pub report: Value,
|
|
}
|
|
|
|
impl Market {
|
|
pub fn parse(m: &Value) -> Result<Self> {
|
|
let version = m
|
|
.get("version")
|
|
.filter(|v| !v.is_null())
|
|
.map(|v| v.as_str().context("invalid market version"))
|
|
.transpose()?;
|
|
let v2 = match version {
|
|
Some("v2") => true,
|
|
Some("v1") | None => false,
|
|
_ => anyhow::bail!("unknown Polymarket market version"),
|
|
};
|
|
let (key, aux) = if v2 {
|
|
("positionIds", "clobTokenIds")
|
|
} else {
|
|
("clobTokenIds", "positionIds")
|
|
};
|
|
let assets = tokens(&m[key]).with_context(|| format!("invalid {key}"))?;
|
|
let condition = m["conditionId"]
|
|
.as_str()
|
|
.filter(|s| !s.is_empty())
|
|
.context("missing condition ID")?;
|
|
let labels = (!m["outcomes"].is_null())
|
|
.then(|| pair(&m["outcomes"]))
|
|
.transpose()?;
|
|
let neg_risk = m["negRisk"].as_bool();
|
|
let target = match (version, neg_risk) {
|
|
(Some("v2"), _) => Some("Router"),
|
|
(Some("v1"), Some(true)) => Some("NegRiskCtfCollateralAdapter"),
|
|
(Some("v1"), Some(false)) => Some("CtfCollateralAdapter"),
|
|
_ => None,
|
|
};
|
|
let position_condition_id = match version {
|
|
Some("v2") => Some(position_condition(&assets)?),
|
|
Some("v1") => Some(condition.to_owned()),
|
|
_ => None,
|
|
};
|
|
let mut report = json!({"venue":"polymarket","market":m["id"],"condition_id":condition,
|
|
"version":version,"neg_risk":neg_risk,"book_id_field":key,
|
|
"position_ledger":version.map(|_| if v2 {"PositionManager"} else {"ConditionalTokens"}),
|
|
"position_target":target,"position_condition_id":position_condition_id});
|
|
// An optional identifier family never prevents sampling valid books in the active family.
|
|
let alternate = if m[aux].is_null() {
|
|
None
|
|
} else {
|
|
match tokens(&m[aux]) {
|
|
Ok(ids) => Some(ids),
|
|
Err(e) => {
|
|
report["catalog_warning"] = json!(format!("invalid {aux}: {e}"));
|
|
None
|
|
}
|
|
}
|
|
};
|
|
let (clob, positions) = if v2 {
|
|
(alternate.as_ref(), Some(&assets))
|
|
} else {
|
|
(Some(&assets), alternate.as_ref())
|
|
};
|
|
report["outcomes"] = json!((0..2)
|
|
.map(|i| json!({"outcome_index":i,"asset_id":assets[i],
|
|
"label":labels.as_ref().map(|p| &p[i]),"clob_token_id":clob.map(|p| &p[i]),
|
|
"position_id":positions.map(|p| &p[i])}))
|
|
.collect::<Vec<_>>());
|
|
Ok(Self { assets, report })
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn sample(raw: &str) -> Value {
|
|
serde_json::from_str(raw).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn live_ctf_catalog_keeps_both_id_families_and_selects_the_adapter() {
|
|
let mut m = sample(include_str!("../fixtures/gamma-559651.json"));
|
|
let parsed = Market::parse(&m).unwrap();
|
|
let r = parsed.report;
|
|
assert_eq!(r["position_target"], "CtfCollateralAdapter");
|
|
assert_eq!(r["position_condition_id"], m["conditionId"]);
|
|
assert_eq!(r["outcomes"][0]["position_id"], m["positionIds"][0]);
|
|
assert_eq!(r["outcomes"][0]["clob_token_id"], parsed.assets[0]);
|
|
assert_ne!(
|
|
r["outcomes"][0]["position_id"],
|
|
r["outcomes"][0]["asset_id"]
|
|
);
|
|
m["negRisk"] = json!(true);
|
|
assert_eq!(
|
|
Market::parse(&m).unwrap().report["position_target"],
|
|
"NegRiskCtfCollateralAdapter"
|
|
);
|
|
m["negRisk"] = Value::Null;
|
|
assert!(Market::parse(&m).unwrap().report["position_target"].is_null());
|
|
m["positionIds"] = json!(["bad", "1"]);
|
|
let r = Market::parse(&m).unwrap().report;
|
|
assert!(r["catalog_warning"].is_string());
|
|
assert!(r["outcomes"][0]["position_id"].is_null());
|
|
m["version"] = Value::Null;
|
|
assert_eq!(
|
|
Market::parse(&m).unwrap().report["book_id_field"],
|
|
"clobTokenIds"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn documented_v2_pair_decodes_without_loss_and_selects_the_router() {
|
|
let mut m = sample(include_str!("../fixtures/gamma-v2-docs.json"));
|
|
let r = Market::parse(&m).unwrap().report;
|
|
assert_eq!(r["position_target"], "Router");
|
|
assert_eq!(
|
|
r["position_condition_id"],
|
|
"0x017089ce3ba22aaa0a4cba8250b8c8e1eb0000000000000000000000000000"
|
|
);
|
|
assert_eq!(r["outcomes"][1]["asset_id"], m["positionIds"][1]);
|
|
assert!(r["outcomes"][1]["clob_token_id"].is_null());
|
|
m["positionIds"][1] = json!("257");
|
|
assert!(Market::parse(&m).is_err());
|
|
m["positionIds"] = json!(["257", "256"]);
|
|
assert!(Market::parse(&m).is_err());
|
|
m["positionIds"] = Value::Null;
|
|
m["clobTokenIds"] = json!(["12", "13"]);
|
|
assert!(Market::parse(&m).is_err());
|
|
m["version"] = json!("future");
|
|
assert!(Market::parse(&m).is_err());
|
|
assert_eq!(
|
|
uint256(
|
|
"115792089237316195423570985008687907853269984665640564039457584007913129639935"
|
|
)
|
|
.unwrap(),
|
|
[255; 32]
|
|
);
|
|
assert!(uint256(
|
|
"115792089237316195423570985008687907853269984665640564039457584007913129639936"
|
|
)
|
|
.is_err());
|
|
assert!(tokens(&json!(["1", "01"])).is_err());
|
|
}
|
|
}
|