Bind verified Polymarket token families to local outcomes
This commit is contained in:
@@ -1457,3 +1457,5 @@ sequenceDiagram
|
||||
D-->>E: 结果标签、互补资产、事件及兑付
|
||||
E-->>H: 按请求顺序返回 data
|
||||
```
|
||||
|
||||
`bind_polymarket_assets` 将完整协议配对绑定到已创建的本地市场。操作员用 zero_outcome 声明外场结果索引 0 对应本地 YES 或 NO。绑定和请求回执在同一事务提交。数字资产、外场条件和已绑定的结构条件可通过 GET /v2/tokens 反查;响应附带 local_asset_id。成交流程继续通过本地资产提交委托。
|
||||
|
||||
@@ -9,6 +9,8 @@ pub(crate) enum Command {
|
||||
micros: Option<i64>,
|
||||
},
|
||||
Event(crate::catalog::Event),
|
||||
#[serde(rename = "bind_polymarket_assets")]
|
||||
BindPolymarketAssets(crate::token_aliases::Bind),
|
||||
#[serde(rename = "reschedule_sports")]
|
||||
RescheduleSports {
|
||||
event: String,
|
||||
|
||||
@@ -41,6 +41,7 @@ mod resident;
|
||||
mod resolution;
|
||||
mod tick_changes;
|
||||
mod tick_size;
|
||||
mod token_aliases;
|
||||
mod token_directory;
|
||||
use resident::Books;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ pub(crate) fn apply(
|
||||
request_id: &str,
|
||||
) -> Result<Value> {
|
||||
match command {
|
||||
Command::BindPolymarketAssets(binding) => binding.register(tx),
|
||||
Command::Fund {
|
||||
account,
|
||||
cents,
|
||||
|
||||
@@ -327,3 +327,23 @@ CREATE TABLE IF NOT EXISTS trade_cursor_key (
|
||||
);
|
||||
INSERT INTO trade_cursor_key(singleton,secret)
|
||||
SELECT 1,randomblob(32) WHERE NOT EXISTS(SELECT 1 FROM trade_cursor_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS polymarket_market_aliases (
|
||||
condition_id TEXT PRIMARY KEY,
|
||||
market TEXT NOT NULL UNIQUE REFERENCES markets(id),
|
||||
zero_outcome TEXT NOT NULL CHECK(zero_outcome IN ('YES','NO'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS polymarket_token_aliases (
|
||||
token_id TEXT PRIMARY KEY,
|
||||
condition_id TEXT NOT NULL REFERENCES polymarket_market_aliases(condition_id),
|
||||
module TEXT NOT NULL, structure TEXT, group_id TEXT, question INTEGER,
|
||||
slot INTEGER NOT NULL CHECK(slot IN (0,1)),
|
||||
observation TEXT NOT NULL CHECK(json_valid(observation)),
|
||||
UNIQUE(condition_id,module,slot)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS pm_alias_structures ON polymarket_token_aliases(structure);
|
||||
CREATE INDEX IF NOT EXISTS pm_alias_groups ON polymarket_token_aliases(group_id,question);
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
use crate::{
|
||||
assets,
|
||||
token_directory::{condition_hex, decimal_token},
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct Bind {
|
||||
market: String,
|
||||
external_condition: String,
|
||||
zero_outcome: String,
|
||||
data: Vec<Value>,
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
token: &'a str,
|
||||
opposite: &'a str,
|
||||
module: &'a str,
|
||||
structure: Option<&'a str>,
|
||||
group: Option<&'a str>,
|
||||
slot: usize,
|
||||
question: Option<i64>,
|
||||
}
|
||||
|
||||
fn full_condition(id: &str) -> bool {
|
||||
id.len() == 66 && condition_hex(id).as_deref() == Some(id)
|
||||
}
|
||||
|
||||
fn position_id(raw: &str) -> [u8; 32] {
|
||||
// The decimal string has already been checked against uint256::MAX.
|
||||
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 next = u16::from(*byte) * 10 + carry;
|
||||
*byte = next as u8;
|
||||
carry = next >> 8;
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
impl<'a> Row<'a> {
|
||||
fn read(row: &'a Value, condition: &str) -> Result<Self> {
|
||||
let token = row["token_id"].as_str().context("token_id is required")?;
|
||||
let opposite = row["opposite_token_id"]
|
||||
.as_str()
|
||||
.context("opposite_token_id is required")?;
|
||||
ensure!(
|
||||
decimal_token(token) == Some(token)
|
||||
&& decimal_token(opposite) == Some(opposite)
|
||||
&& token != opposite,
|
||||
"invalid external outcome identifiers"
|
||||
);
|
||||
ensure!(
|
||||
row["condition_id"] == condition,
|
||||
"external condition mismatch"
|
||||
);
|
||||
let module = row["module"].as_str().context("module is required")?;
|
||||
let slot = row["outcome_index"]
|
||||
.as_u64()
|
||||
.filter(|i| *i < 2)
|
||||
.context("invalid outcome index")? as usize;
|
||||
let structure = row["structural_condition_id"].as_str();
|
||||
let group = row["neg_risk_market_id"].as_str();
|
||||
let question = row["question_index"].as_i64();
|
||||
ensure!(
|
||||
group.is_some() == question.is_some()
|
||||
&& group.is_none_or(full_condition)
|
||||
&& question.is_none_or(|q| q >= 0),
|
||||
"invalid negative-risk question reference"
|
||||
);
|
||||
match module {
|
||||
"v1_ctf" => ensure!(
|
||||
row["structural_condition_id"].is_null(),
|
||||
"CTF has no structure ID"
|
||||
),
|
||||
"binary" | "neg_risk" => {
|
||||
ensure!(
|
||||
(module == "neg_risk") == group.is_some(),
|
||||
"V2 module mismatch"
|
||||
);
|
||||
let bytes = position_id(token);
|
||||
let other = position_id(opposite);
|
||||
let mut expected = String::from("0x");
|
||||
use std::fmt::Write;
|
||||
for byte in &bytes[..31] {
|
||||
write!(expected, "{byte:02x}")?;
|
||||
}
|
||||
expected.push_str("00");
|
||||
ensure!(
|
||||
structure == Some(expected.as_str())
|
||||
&& usize::from(bytes[31]) == slot
|
||||
&& bytes[..31] == other[..31]
|
||||
&& usize::from(other[31]) == 1 - slot,
|
||||
"V2 token does not encode the supplied condition and outcome"
|
||||
);
|
||||
}
|
||||
_ => anyhow::bail!("unsupported external token module"),
|
||||
}
|
||||
Ok(Self {
|
||||
token,
|
||||
opposite,
|
||||
module,
|
||||
structure,
|
||||
group,
|
||||
slot,
|
||||
question,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Bind {
|
||||
pub(crate) fn register(self, tx: &Transaction<'_>) -> Result<Value> {
|
||||
identifier(&self.market)?;
|
||||
ensure!(
|
||||
matches!(self.zero_outcome.as_str(), "YES" | "NO"),
|
||||
"zero_outcome must be YES or NO"
|
||||
);
|
||||
ensure!(
|
||||
full_condition(&self.external_condition),
|
||||
"expected a canonical external market condition"
|
||||
);
|
||||
ensure!(
|
||||
(2..=4).contains(&self.data.len()),
|
||||
"provide a complete outcome pair for each protocol"
|
||||
);
|
||||
let mut families = BTreeMap::new();
|
||||
for value in &self.data {
|
||||
let token = Row::read(value, &self.external_condition)?;
|
||||
let slot = token.slot;
|
||||
let pair = families.entry(token.module).or_insert_with(|| [None, None]);
|
||||
ensure!(
|
||||
pair[slot].replace(token).is_none(),
|
||||
"repeated protocol outcome"
|
||||
);
|
||||
}
|
||||
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;
|
||||
for pair in families.values() {
|
||||
let [Some(a), Some(b)] = pair else {
|
||||
anyhow::bail!("incomplete protocol pair");
|
||||
};
|
||||
ensure!(
|
||||
a.opposite == b.token
|
||||
&& b.opposite == a.token
|
||||
&& a.structure == b.structure
|
||||
&& a.group == b.group
|
||||
&& a.question == b.question,
|
||||
"outcomes do not form one pair"
|
||||
);
|
||||
if let Some((group, question)) = group_ref {
|
||||
ensure!(
|
||||
(a.group, a.question) == (group, question),
|
||||
"protocols identify different questions"
|
||||
);
|
||||
}
|
||||
group_ref = Some((a.group, a.question));
|
||||
}
|
||||
let listed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[&self.market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "unknown local market");
|
||||
tx.execute("INSERT INTO polymarket_market_aliases VALUES(?1,?2,?3) ON CONFLICT(condition_id) DO NOTHING",
|
||||
params![self.external_condition,self.market,self.zero_outcome])?;
|
||||
let bound: (String, String) = tx.query_row(
|
||||
"SELECT market,zero_outcome FROM polymarket_market_aliases WHERE condition_id=?1",
|
||||
[&self.external_condition],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
bound == (self.market.clone(), self.zero_outcome.clone()),
|
||||
"market condition already bound with different identity"
|
||||
);
|
||||
let current_group: Option<(Option<String>, Option<i64>)> = tx.query_row(
|
||||
"SELECT group_id,question FROM polymarket_token_aliases WHERE condition_id=?1 LIMIT 1",
|
||||
[&self.external_condition], |row| Ok((row.get(0)?,row.get(1)?)),
|
||||
).optional()?;
|
||||
if let (Some((stored_group, stored_question)), Some((group, question))) =
|
||||
(current_group, group_ref)
|
||||
{
|
||||
ensure!(
|
||||
(stored_group.as_deref(), stored_question) == (group, question),
|
||||
"market already bound to a different question"
|
||||
);
|
||||
}
|
||||
for value in &self.data {
|
||||
let row = Row::read(value, &self.external_condition)?;
|
||||
// Only retain fields exposed by the external directory.
|
||||
let observation: serde_json::Map<_, _> = [
|
||||
"token_id",
|
||||
"condition_id",
|
||||
"structural_condition_id",
|
||||
"module",
|
||||
"outcome_index",
|
||||
"clob_index",
|
||||
"outcome",
|
||||
"opposite_token_id",
|
||||
"resolved",
|
||||
"final_price",
|
||||
"title",
|
||||
"market_slug",
|
||||
"closed",
|
||||
"neg_risk",
|
||||
"neg_risk_market_id",
|
||||
"question_index",
|
||||
"event_id",
|
||||
"event_slug",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|key| (key.to_owned(), value[key].clone()))
|
||||
.collect();
|
||||
tx.execute(
|
||||
"INSERT INTO polymarket_token_aliases VALUES(?1,?2,?3,?4,?5,?6,?7,?8)
|
||||
ON CONFLICT(token_id) DO NOTHING",
|
||||
params![
|
||||
row.token,
|
||||
self.external_condition,
|
||||
row.module,
|
||||
row.structure,
|
||||
row.group,
|
||||
row.question,
|
||||
row.slot as i64,
|
||||
Value::Object(observation).to_string()
|
||||
],
|
||||
)?;
|
||||
let observed: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT observation FROM polymarket_token_aliases WHERE token_id=?1",
|
||||
[row.token],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
let prior: Value = serde_json::from_str(&observed.context("missing stored token")?)?;
|
||||
let prior = 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,
|
||||
"token already bound with different identity"
|
||||
);
|
||||
}
|
||||
Ok(
|
||||
json!({"market":self.market,"external_condition":self.external_condition,
|
||||
"zero_asset_id":assets::id(&self.market,&self.zero_outcome),"tokens":self.data.len()}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
WITH selectors AS (
|
||||
SELECT key AS ordinal, json_extract(value,'$[0]') AS id,
|
||||
json_extract(value,'$[2]') AS kind
|
||||
FROM json_each(?1)
|
||||
)
|
||||
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
|
||||
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
|
||||
ORDER BY s.ordinal,t.question,t.condition_id,(t.module<>'v1_ctf'),t.slot
|
||||
@@ -18,7 +18,7 @@ fn invalid(message: impl Into<String>) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.into())
|
||||
}
|
||||
|
||||
fn condition_hex(value: &str) -> Option<String> {
|
||||
pub(crate) fn condition_hex(value: &str) -> Option<String> {
|
||||
let hex = value
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| value.strip_prefix("0X"))?;
|
||||
@@ -28,6 +28,18 @@ fn condition_hex(value: &str) -> Option<String> {
|
||||
Some(format!("0x{}", hex.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
pub(crate) fn decimal_token(value: &str) -> Option<&str> {
|
||||
let digits = value.trim_start_matches('0');
|
||||
if value.is_empty()
|
||||
|| !value.bytes().all(|b| b.is_ascii_digit())
|
||||
|| digits.len() > MAX_TOKEN.len()
|
||||
|| (digits.len() == MAX_TOKEN.len() && digits > MAX_TOKEN)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(if digits.is_empty() { "0" } else { digits })
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_tokens(&self, query: TokenDirectoryQuery) -> Result<Value, MarketDataError> {
|
||||
let token = query.token_id.as_deref().filter(|s| !s.trim().is_empty());
|
||||
@@ -41,24 +53,16 @@ impl Exchange {
|
||||
let mut seen = HashSet::new();
|
||||
let mut keys = Vec::new();
|
||||
for value in raw.split(',').map(str::trim) {
|
||||
let (key, market, outcome) = if is_token {
|
||||
let (key, outcome, kind) = if is_token {
|
||||
if let Ok((outcome, market)) = assets::parse_id(value) {
|
||||
(value.to_owned(), Some(market.to_owned()), Some(outcome))
|
||||
(market.to_owned(), Some(outcome), "local_token")
|
||||
} else {
|
||||
let digits = value.trim_start_matches('0');
|
||||
if value.is_empty()
|
||||
|| !value.bytes().all(|b| b.is_ascii_digit())
|
||||
|| digits.len() > MAX_TOKEN.len()
|
||||
|| (digits.len() == MAX_TOKEN.len() && digits > MAX_TOKEN)
|
||||
{
|
||||
return Err(invalid(format!("invalid token id: {value}")));
|
||||
}
|
||||
// Numeric IDs are external. They count towards the cap but
|
||||
// have no corresponding local token without a venue mapping.
|
||||
(digits.to_owned(), None, None)
|
||||
let token = decimal_token(value)
|
||||
.ok_or_else(|| invalid(format!("invalid token id: {value}")))?;
|
||||
(token.to_owned(), None, "external_token")
|
||||
}
|
||||
} else if let Some(hex) = condition_hex(value) {
|
||||
(hex.clone(), Some(hex), None)
|
||||
(hex, None, "condition")
|
||||
} else {
|
||||
let listed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)
|
||||
@@ -69,23 +73,21 @@ impl Exchange {
|
||||
if !listed {
|
||||
return Err(invalid(format!("invalid condition id: {value}")));
|
||||
}
|
||||
(value.to_owned(), Some(value.to_owned()), None)
|
||||
(value.to_owned(), None, "condition")
|
||||
};
|
||||
if seen.insert(key) {
|
||||
if seen.insert((key.clone(), outcome)) {
|
||||
if seen.len() > limit {
|
||||
return Err(invalid(format!(
|
||||
"'{selector}' accepts at most {limit} distinct values"
|
||||
)));
|
||||
}
|
||||
if let Some(market) = market {
|
||||
keys.push((market, outcome));
|
||||
}
|
||||
keys.push((key, outcome, kind));
|
||||
}
|
||||
}
|
||||
let data = {
|
||||
let input = serde_json::to_string(&keys).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut data = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("token_directory.sql"))?;
|
||||
let input = serde_json::to_string(&keys).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let rows = stmt.query_map([input], |r| {
|
||||
let rows = stmt.query_map([&input], |r| {
|
||||
let market: String = r.get(0)?;
|
||||
let phase: String = r.get(5)?;
|
||||
let winner: Option<String> = r.get(6)?;
|
||||
@@ -95,7 +97,7 @@ impl Exchange {
|
||||
let price = winner.as_deref().filter(|_| phase=="resolved").map(|winner| {
|
||||
if winner == "VOID" { decimal(5,10) } else { decimal(i128::from(winner == outcome),1) }
|
||||
});
|
||||
Ok(json!({
|
||||
Ok((r.get::<_, i64>(12)?, json!({
|
||||
"token_id":assets::id(&market,outcome),"condition_id":market,
|
||||
"structural_condition_id":null,"module":if group.is_some() { "local_neg_risk" } else { "local_binary" },
|
||||
"outcome_index":index,"clob_index":null,"outcome":r.get::<_,String>(if index==0 {3} else {4})?,
|
||||
@@ -104,10 +106,33 @@ impl Exchange {
|
||||
"final_price":price,"title":r.get::<_,String>(1)?,"market_slug":r.get::<_,String>(2)?,
|
||||
"neg_risk":group.is_some(),"neg_risk_market_id":group,"question_index":r.get::<_,Option<i64>>(9)?,
|
||||
"event_id":r.get::<_,Option<i64>>(10)?,"event_slug":r.get::<_,Option<String>>(11)?
|
||||
}))
|
||||
})))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
let externals = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("token_aliases.sql"))?;
|
||||
let rows = stmt.query_map([&input], |r| {
|
||||
Ok((
|
||||
r.get::<_, i64>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, String>(3)?,
|
||||
))
|
||||
})?;
|
||||
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 {
|
||||
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));
|
||||
data.push((ordinal, row));
|
||||
}
|
||||
data.sort_by_key(|row| row.0);
|
||||
let data: Vec<_> = data.into_iter().map(|(_, row)| row).collect();
|
||||
tx.commit()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
WITH selectors AS (
|
||||
SELECT key AS ordinal, json_extract(value,'$[0]') AS market,
|
||||
json_extract(value,'$[1]') AS outcome
|
||||
json_extract(value,'$[1]') AS outcome, json_extract(value,'$[2]') AS kind
|
||||
FROM json_each(?1)
|
||||
), markets_selected AS (
|
||||
SELECT s.ordinal,m.id AS market,s.outcome
|
||||
FROM selectors s JOIN markets m ON m.id=s.market
|
||||
WHERE s.kind<>'external_token'
|
||||
UNION ALL
|
||||
SELECT s.ordinal,n.market,NULL
|
||||
FROM selectors s JOIN neg_risk_members n ON n.group_id=s.market
|
||||
WHERE s.outcome IS NULL AND NOT EXISTS (SELECT 1 FROM markets m WHERE m.id=s.market)
|
||||
WHERE s.kind='condition' AND s.outcome IS NULL AND NOT EXISTS (SELECT 1 FROM markets m WHERE m.id=s.market)
|
||||
), slots(outcome, outcome_index) AS (VALUES ('YES',0),('NO',1))
|
||||
SELECT m.id,w.question,w.slug,w.yes_label,w.no_label,m.phase,m.winner,s.outcome_index,
|
||||
n.group_id,n.ordinal,e.event_id,e.slug
|
||||
n.group_id,n.ordinal,e.event_id,e.slug,x.ordinal
|
||||
FROM markets_selected x JOIN markets m ON m.id=x.market
|
||||
JOIN market_wire_metadata w ON w.market=x.market
|
||||
JOIN slots s ON x.outcome IS NULL OR s.outcome=x.outcome
|
||||
|
||||
@@ -4219,3 +4219,46 @@ fn public_token_directory_routes_results_and_expands_negative_risk_groups() {
|
||||
assert_eq!(voided[0]["final_price"], 0.5);
|
||||
assert_eq!(voided[1]["final_price"], 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polymarket_asset_bindings_preserve_protocols_and_explicit_outcome_direction() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("venue-ids.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
setup(&mut e);
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../docs/examples/polymarket-asset-binding.json"
|
||||
))
|
||||
.unwrap();
|
||||
let mut command = json!({"op":"bind_polymarket_assets","id":"bind","market":"e","zero_outcome":"NO",
|
||||
"external_condition":fixture["external_condition"], "data":fixture["data"]});
|
||||
let receipt = e.execute(command.clone()).unwrap();
|
||||
assert_eq!(receipt["tokens"], 4);
|
||||
assert_eq!(e.execute(command.clone()).unwrap(), receipt);
|
||||
command["id"] = json!("flipped");
|
||||
command["zero_outcome"] = json!("YES");
|
||||
assert!(e.execute(command).is_err());
|
||||
drop(e);
|
||||
let e = Exchange::open(path).unwrap();
|
||||
let lookup = |query| {
|
||||
e.public_tokens(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
let condition = lookup(json!({"condition":fixture["external_condition"]}));
|
||||
let rows = condition["data"].as_array().unwrap();
|
||||
assert_eq!(rows.len(), 4);
|
||||
assert_eq!(rows[0]["module"], "v1_ctf");
|
||||
assert_eq!(rows[2]["module"], "neg_risk");
|
||||
assert_eq!(rows[2]["local_asset_id"], "eb:NO:e");
|
||||
assert_eq!(rows[3]["local_asset_id"], "eb:YES:e");
|
||||
let structural = rows[2]["structural_condition_id"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
lookup(json!({"condition":&structural[..64]}))["data"],
|
||||
json!([rows[2], rows[3]])
|
||||
);
|
||||
let token = rows[3]["token_id"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
lookup(json!({"token_id":format!("00{token},00123,eb:NO:e")}))["data"][0],
|
||||
rows[3]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"source": "https://data-api.polymarket.com/v2/tokens?condition=0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"date": "Fri, 04 Dec 2026 21:03:26 GMT",
|
||||
"external_condition": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"data": [
|
||||
{
|
||||
"token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 0,
|
||||
"clob_index": 0,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "33748178601941852783056114873418965902944929138778460252404676407918318867810",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": null,
|
||||
"module": "v1_ctf",
|
||||
"outcome_index": 1,
|
||||
"clob_index": 1,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "56766704504589537417119461476407464198158915644205212964421261364010493123785",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 0,
|
||||
"clob_index": null,
|
||||
"outcome": "Yes",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
},
|
||||
{
|
||||
"token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179073",
|
||||
"condition_id": "0xdfb674d9eb1ca2f4b1c38d36562b725d6dca8364b3b1eea2dafc773608959c80",
|
||||
"structural_condition_id": "0x02bf5052dd0f75c60464fe2f290bc93000000300000000000000000000000200",
|
||||
"module": "neg_risk",
|
||||
"outcome_index": 1,
|
||||
"clob_index": null,
|
||||
"outcome": "No",
|
||||
"opposite_token_id": "1242647860242950490718683690862688823036949349322148957738072940768458179072",
|
||||
"resolved": false,
|
||||
"final_price": null,
|
||||
"title": "Will Paris Saint-Germain FC win on 2026-12-04?",
|
||||
"market_slug": "fl1-tou-psg-2026-12-04-psg",
|
||||
"closed": false,
|
||||
"neg_risk": true,
|
||||
"neg_risk_market_id": "0xbac6a2a3e5faf30fdabab133b0258ed9bf5052dd0f75c60464fe2f290bc93000",
|
||||
"question_index": 2,
|
||||
"event_id": 1465085,
|
||||
"event_slug": "fl1-tou-psg-2026-12-04"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -471,3 +471,7 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
### Data API 资产反查
|
||||
|
||||
GET /v2/tokens 接受 token_id / token_ids 或 condition / condition_id / conditionId,二选一。生产样本中,资产查询保持请求顺序并合并重复项,数字标识的前导零会被归一。合法的未知资产返回空数组。用本地市场 ID 返回 YES、NO 两侧,用本地互斥组 ID 按题目序号展开成员。已裁决市场可返回最终兑付值,VOID 有两项 0.5。回执保留稳定的本地 eb 标识并自描述本地模块。对照样本覆盖原生 V2、CTF 和短条件 ID,外场同一市场的多协议资产映射仍待接入本地目录。[生产请求和响应](examples/public-token-directory.json) · [官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
### 本地登记 Polymarket 资产对照
|
||||
|
||||
可信 JSONL 命令 bind_polymarket_assets 接受本地市场、external_condition、zero_outcome 及官方 data 数组。每种协议必须提供互补一对。登记时核对 V2 编码、互斥组与题目归属,禁止冲突重绑。登记后用外场数字资产或条件查询 /v2/tokens 可得到原协议观察字段及 local_asset_id。互斥组查询仅返回已登记成员。保留的结果状态与兑付值来自登记时的外场快照,尚未自动刷新,也未接入真实下单路由。[生产登记样本](examples/polymarket-asset-binding.json)
|
||||
|
||||
Reference in New Issue
Block a user