1.3 OracleRiskMonitor
OracleRiskMonitor watches the UMA Optimistic Oracle queue for proposals and active disputes on markets where open positions exist. When a market enters a resolution proposal or a dispute window, the bot can block new orders on that market, require reduced size, or flag a position for review. It protects against the scenario where a trade is submitted into a market moments before a contested resolution flips the outcome. It never overrides the strategy intent or changes the direction of an order — it only controls whether and how much the order is permitted to proceed.
v3 readiness
A bot is done when all four scores are. What does done mean?
1. Bot Identity
| Layer | Risk Risk |
|---|---|
| Bot class | Guardrail |
| Authority | RejectReshape |
| Status | LIVE |
| Readiness | General live |
| Runs before | ExecutionPlan emit |
| Runs after | Strategy OrderIntent |
| Applies to | Every OrderIntent on markets that use the UMA Optimistic Oracle for resolution |
| Default mode | general_live |
| User-visible | Advanced details only |
| Developer owner | Polytraders core — Risk pod |
Operational profile
| Modes supported | quarantine |
|---|
2. Purpose
OracleRiskMonitor watches the UMA Optimistic Oracle queue for proposals and active disputes on markets where open positions exist. When a market enters a resolution proposal or a dispute window, the bot can block new orders on that market, require reduced size, or flag a position for review. It protects against the scenario where a trade is submitted into a market moments before a contested resolution flips the outcome. It never overrides the strategy intent or changes the direction of an order — it only controls whether and how much the order is permitted to proceed.
3. Why This Bot Matters
Trading into an active oracle dispute
A position opened after a dispute was filed may be immediately underwater if the dispute resolves against the expected outcome; the resolution risk was not priced in.
Holding a full position through the proposal window
Markets entering their proposal phase have uncertain resolution timing. Holding full size through this window increases exposure to a binary outcome that cannot be hedged once the proposal is live.
Stale oracle status
If the oracle queue feed is unavailable, a strategy could open or increase a position without knowing a dispute is already active. The safe behaviour is to block, not to approve on missing data.
Neg-risk market definition shift during proposal
On neg-risk markets, the 'Other' outcome definition can shift if a proposal is disputed, potentially invalidating the expected payout structure.
No worked examples on this bot yet. Worked examples are optional but strongly recommended — they turn an abstract failure mode into something a developer can verify in a fixture.
4. Required Polymarket Inputs
| Input | Source | Required? | Use |
|---|---|---|---|
| Market resolution-source flag and dispute window metadata | Gamma API | Yes | Identify whether the market uses the UMA oracle and retrieve the resolution window start and end times. |
| UMA Optimistic Oracle on-chain proposal and dispute events | UMA Optimistic Oracle | Yes | Detect when a proposal has been submitted or a dispute has been filed for a market relevant to open positions or pending orders. |
| Open position list with market identifiers | Data API | Yes | Cross-reference oracle events against markets where the account currently holds a position, to determine which events require action. |
| Neg-risk flag per market | Gamma API | No | Apply stricter reduce_at_proposal_pct on neg-risk markets, as definition shifts can affect multiple related markets simultaneously. |
5. Required Internal Inputs
| Input | Source | Required? | Use |
|---|---|---|---|
| Current position size per market | PortfolioGuard | Yes | Calculate the maximum allowed position size after applying reduce_at_proposal_pct during the proposal window. |
| KillSwitch active flag | KillSwitch | Yes | If KillSwitch is active, reject all orders without checking oracle status. |
6. Parameter Guide
| Parameter | Default | Warning | Hard | What it controls |
|---|---|---|---|---|
| reduce_at_proposal_pct | 50 | 70 | 100 | Maximum allowed position size, expressed as a percentage of the configured per-market limit, when a market has an active UMA proposal but no dispute yet. |
| block_disputed | True | None | None | When true, reject all new orders on any market where a UMA dispute is currently active. |
| max_dispute_window_h | 48 | 72 | 168 | Maximum duration in hours that a dispute window is considered 'recent' for monitoring purposes. Disputes older than this limit are treated as stale and require a manual review flag. |
| downgrade_size_by_confidence | True | None | None | When true, apply an additional proportional reduction to the allowed order size based on the elapsed fraction of the proposal window. As the window progresses, less new size is permitted. |
7. Detailed Parameter Instructions
reduce_at_proposal_pct
What it means
Maximum allowed position size, expressed as a percentage of the configured per-market limit, when a market has an active UMA proposal but no dispute yet.
Default
{ "reduce_at_proposal_pct": 50 }
Why this default matters
Cutting position size to 50% during a proposal window limits exposure to a binary outcome while still allowing strategies to maintain partial coverage.
Threshold logic
| Condition | Action |
|---|---|
| No proposal active | APPROVE at full size |
| Proposal active, size ≤ 50% of limit | APPROVE |
| Proposal active, size > 50% of limit | RESHAPE_REQUIRED — cap to 50% of per-market limit |
| reduce_at_proposal_pct = 100 (locked) | REJECT all new orders on that market during proposal window |
Developer check
if (proposalActive && orderSize > limit * (p.default / 100)) return reshape({ max_size_usd: limit * (p.default / 100) });
User-facing English
This market is currently in its resolution proposal window. We limited your order size to reduce exposure while the outcome is being confirmed.
block_disputed
What it means
When true, reject all new orders on any market where a UMA dispute is currently active.
Default
{ "block_disputed": true }
Why this default matters
An active dispute means the resolution outcome is genuinely uncertain and contested on-chain. Adding exposure during a live dispute is inconsistent with sound risk management.
Threshold logic
| Condition | Action |
|---|---|
| block_disputed=true AND dispute active | REJECT — ORACLE_DISPUTE_ACTIVE |
| block_disputed=false AND dispute active | WARN only — allow with annotation |
Developer check
if (p.block_disputed && disputeActive) return reject('ORACLE_DISPUTE_ACTIVE');
User-facing English
This market has an active resolution dispute. We blocked this order while the dispute is ongoing.
max_dispute_window_h
What it means
Maximum duration in hours that a dispute window is considered 'recent' for monitoring purposes. Disputes older than this limit are treated as stale and require a manual review flag.
Default
{ "max_dispute_window_h": 48 }
Why this default matters
UMA disputes typically resolve within 48 hours. Tracking disputes beyond 168 hours (one week) adds noise without meaningful risk signal.
Threshold logic
| Condition | Action |
|---|---|
| Dispute age ≤ 48 h | Block (block_disputed applies) |
| Dispute age 48–168 h | WARN — flag for manual review |
| Dispute age > 168 h | Treat as resolved; escalate to incident commander |
Developer check
const ageH = (Date.now() - disputeStartMs) / 3600000; if (ageH > p.hard) escalate('DISPUTE_OVERDUE');
User-facing English
This market has had an unresolved dispute for an unusually long time. New orders are paused until the situation is reviewed.
downgrade_size_by_confidence
What it means
When true, apply an additional proportional reduction to the allowed order size based on the elapsed fraction of the proposal window. As the window progresses, less new size is permitted.
Default
{ "downgrade_size_by_confidence": true }
Why this default matters
Risk increases as a market moves deeper into its resolution window. Tapering size over time reflects rising uncertainty without requiring a hard binary block.
Threshold logic
| Condition | Action |
|---|---|
| downgrade_size_by_confidence=true, proposal fraction < 0.5 | Use reduce_at_proposal_pct as-is |
| downgrade_size_by_confidence=true, proposal fraction ≥ 0.5 | Halve the allowed size cap proportionally to elapsed window fraction |
| downgrade_size_by_confidence=false | Use reduce_at_proposal_pct flat regardless of elapsed time |
Developer check
if (p.downgrade_size_by_confidence) cap = cap * (1 - proposalFraction * 0.5);
User-facing English
The resolution window for this market is well underway. We reduced the maximum order size further to account for the increased uncertainty.
8. Default Configuration
{
"bot_id": "risk.oracle_risk_monitor",
"version": "1.0.0",
"mode": "hard_guard",
"defaults": {
"reduce_at_proposal_pct": 50,
"block_disputed": true,
"max_dispute_window_h": 48,
"downgrade_size_by_confidence": true
},
"locked": {
"block_disputed": {
"immutable": true
},
"max_dispute_window_h": {
"max": 168
}
}
}9. Implementation Flow
- Receive OrderIntent from Strategy layer including market_id, side, and size_usd.
- Check KillSwitch active flag; if active, return REJECT with KILL_SWITCH_ACTIVE immediately.
- Fetch market resolution-source metadata from Gamma API for the target market_id to confirm UMA oracle is used.
- Subscribe to or poll UMA Optimistic Oracle on-chain events to detect any active proposal or dispute for this market.
- If a dispute is active and block_disputed=true, return REJECT with reason_code=ORACLE_DISPUTE_ACTIVE.
- If a proposal is active (but no dispute), retrieve the current position size for this market from PortfolioGuard.
- Apply reduce_at_proposal_pct to compute the maximum allowed size. If downgrade_size_by_confidence=true, further reduce the cap based on elapsed fraction of the proposal window.
- If order.size_usd > computed cap, return RESHAPE_REQUIRED with constraints.max_size_usd set to the computed cap.
- If the market is neg-risk, apply a 20% additional reduction to the cap due to potential definition-shift risk.
- Return APPROVE if all checks pass, with inputs_used and checked_at timestamp.
10. Reference Implementation
Polls the UMA Optimistic Oracle for active proposals and disputes on the target market, then applies proposal-window size caps or hard rejects, depending on dispute status and the elapsed fraction of the proposal window.
Pseudocode is language-agnostic. FETCH = read input. EMIT = produce output. Translate to TS/Python/Go/Rust.
FUNCTION evaluateOracleRisk(intent):
// --- 0. KillSwitch gate ---
ks = FETCH internal.killswitch.status
IF ks.active:
EMIT RiskVote(decision=HARD_REJECT, reason=KILL_SWITCH_ACTIVE)
RETURN
// --- 1. Fetch market resolution metadata ---
marketMeta = fetchClobPublic('/markets/' + intent.market_id)
IF marketMeta IS NULL OR isStale(marketMeta, params.stale_top_seconds):
EMIT RiskVote(decision=HARD_REJECT, reason=STALE_MARKET_DATA)
RETURN
IF marketMeta.resolution_source != 'UMA':
// Non-UMA markets pass through without oracle checks
EMIT RiskVote(decision=APPROVE)
RETURN
// --- 2. Fetch UMA oracle state ---
oracleState = FETCH onchain.uma.proposal_status(intent.market_id)
// oracleState: { proposalActive, disputeActive, proposalStartMs, challengeWindowMs }
// $750 pUSD proposer bond; 2h challenge window; disputed → DVM 24-48h
// --- 3. Hard reject on active dispute ---
IF oracleState.disputeActive AND params.block_disputed:
EMIT RiskVote(decision=HARD_REJECT, reason=ORACLE_DISPUTE_ACTIVE)
RETURN
// --- 4. Proposal window size cap ---
IF oracleState.proposalActive:
position = FETCH internal.portfolio_guard.market_position(intent.market_id)
proposalFraction = (now_ms() - oracleState.proposalStartMs)
/ oracleState.challengeWindowMs
cap = position.per_market_limit * (params.reduce_at_proposal_pct / 100)
IF params.downgrade_size_by_confidence AND proposalFraction >= 0.5:
cap = cap * (1 - proposalFraction * 0.5)
// NegRisk: apply extra 20% reduction
IF marketMeta.neg_risk:
cap = cap * 0.80
cap = toUsdcUnits(cap)
IF intent.size_usd > cap:
EMIT RiskVote(decision=RESHAPE_REQUIRED,
reason=ORACLE_RESOLUTION_PENDING,
constraints={ max_size_usd: cap })
RETURN
// --- 5. Bond check ---
IF oracleState.proposerBondPUsd < 750:
EMIT RiskVote(decision=HARD_REJECT, reason=ORACLE_PROPOSER_BOND_BELOW_MIN)
RETURN
// --- 6. Happy path ---
EMIT RiskVote(decision=APPROVE, checked_at=now_iso())
Helpers used
| Helper | Signature | Purpose |
|---|---|---|
| fetchClobPublic | fetchClobPublic(path: str) -> JSON | Unauthenticated GET against https://clob.polymarket.com; returns parsed JSON or null on error. |
| isStale | isStale(snapshot: any, maxAgeS: int) -> bool | Returns true if snapshot._fetched_at_ms is older than maxAgeS seconds. |
| toUsdcUnits | toUsdcUnits(rawUsd: float) -> int | Rounds a raw pUSD float to the integer unit used by CTFExchangeV2 (6 decimals). |
| platformFee | platformFee(notional: float, prob: float, feeRate: float) -> float | Computes platform fee C * feeRate * p * (1-p); used for cost estimation during proposal window. |
SDK calls used
fetchClobPublic('/markets/0xabc123...')fetchClobPublic('/book?market=0xabc123...')onchain.uma.proposal_status('0xabc123...')internal.killswitch.status()internal.portfolio_guard.market_position('0xabc123...')
Complexity: O(1) per intent — single market oracle state lookup
11. Wire Examples
Input — what arrives on the wire
OrderIntent on UMA-resolved market in active dispute — internal
{
"intent_id": "int_9c2e4d6f8a0b1c3e",
"market_id": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b",
"side": "BUY",
"outcome": "YES",
"size_usd": 600,
"neg_risk": false,
"generated_at": "2026-05-09T07:00:00Z"
}
UMA oracle state (on-chain) — clob_public
{
"market_id": "0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b",
"resolution_source": "UMA",
"proposal_active": true,
"dispute_active": true,
"proposal_start_ms": 1746770400000,
"challenge_window_ms": 7200000,
"proposer_bond_pusd": 750,
"dispute_filed_at": "2026-05-09T07:00:00Z",
"neg_risk": false
}
Output — what the bot emits
RiskVote — HARD_REJECT (active dispute)
{
"guard_id": "risk.oracle_risk_monitor",
"decision": "HARD_REJECT",
"severity": "HARD",
"reason_code": "ORACLE_DISPUTE_ACTIVE",
"message": "Market 0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b has an active UMA resolution dispute filed at 2026-05-09T07:00:00Z. New orders are blocked until the dispute resolves.",
"constraints": {},
"inputs_used": [
"gamma_api.market.resolution_source",
"onchain.uma.dispute_events",
"internal.killswitch.status"
],
"checked_at": "2026-05-09T07:02:00Z"
}
RiskVote — RESHAPE_REQUIRED (proposal window, no dispute)
{
"guard_id": "risk.oracle_risk_monitor",
"decision": "RESHAPE_REQUIRED",
"severity": "WARN",
"reason_code": "ORACLE_RESOLUTION_PENDING",
"message": "Market is in UMA proposal window (fraction=0.40). Max size capped to 1000 pUSD.",
"constraints": {
"max_size_usd": 1000,
"passive_only": false,
"close_only": false
},
"inputs_used": [
"gamma_api.market.resolution_source",
"onchain.uma.proposal_events",
"internal.portfolio_guard.position"
],
"checked_at": "2026-05-09T08:00:00Z"
}
Reproduce locally
curl 'https://clob.polymarket.com/markets/0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b'12. Decision Logic
APPROVE
No active proposal and no active dispute for the target market, or proposal is active and order size is within the reduce_at_proposal_pct cap after downgrade adjustment.
RESHAPE_REQUIRED
Market is in proposal window and order size exceeds the reduce_at_proposal_pct cap — emit constraints.max_size_usd at the computed safe level.
REJECT
Active UMA dispute and block_disputed=true (ORACLE_DISPUTE_ACTIVE), oracle feed is unavailable or stale (STALE_MARKET_DATA), or KillSwitch is active (KILL_SWITCH_ACTIVE).
WARNING_ONLY
Not used as primary path — OracleRiskMonitor has reject authority. Spread-style anomalies and overdue disputes emit log annotations but the hard guard path is always reject or reshape.
13. Standard Decision Output
This bot returns a RiskVote object. See RiskVote schema.
{
"guard_id": "risk.oracle_risk_monitor",
"decision": "REJECT",
"severity": "HARD",
"reason_code": "ORACLE_DISPUTE_ACTIVE",
"message": "Market CLOB:0xabc123 has an active UMA resolution dispute filed at 2026-05-08T14:00:00Z. New orders are blocked until the dispute resolves.",
"constraints": {},
"inputs_used": [
"gamma_api.market.resolution_source",
"uma.oracle.dispute_events",
"internal.killswitch.status"
],
"checked_at": "2026-05-09T07:00:00Z"
}14. Reason Codes
| Code | Severity | Meaning | Action | User-facing message |
|---|---|---|---|---|
KILL_SWITCH_ACTIVE | HARD_REJECT | Global kill switch is active. | Immediately return HARD_REJECT without oracle lookup. | Trading is currently paused. Please try again later. |
STALE_MARKET_DATA | HARD_REJECT | Oracle feed or market metadata is older than the staleness threshold. | Return HARD_REJECT; retry on next fresh fetch. | Oracle status could not be verified. The order was blocked until a fresh status is available. |
ORACLE_DISPUTE_ACTIVE | HARD_REJECT | An active UMA dispute is filed for this market; outcome is contested on-chain. | Return HARD_REJECT if block_disputed=true. | This market has an active resolution dispute. Orders are blocked while the dispute is ongoing. |
ORACLE_RESOLUTION_PENDING | RESHAPE | Market is in the 2-hour UMA proposal window but no dispute has been filed yet. | Return RESHAPE_REQUIRED with cap = reduce_at_proposal_pct * per_market_limit. | This market is in its resolution window. Your order size was reduced to limit exposure while the outcome is being confirmed. |
ORACLE_PROPOSER_BOND_BELOW_MIN | HARD_REJECT | The UMA proposer bond for this market is below the required 750 pUSD minimum, indicating a misconfigured or suspicious market. | Return HARD_REJECT; log market_id and observed bond amount. | This market could not be verified for safe trading. The order was blocked. |
ORACLE_RESOLUTION_CONFIDENCE_DOWNGRADE | RESHAPE | Market is more than 50% through its proposal window; size cap is further reduced proportionally. | Apply downgrade formula: cap = cap * (1 - proposal_fraction * 0.5). | This market is well into its resolution window. The maximum order size was reduced further due to the increased uncertainty. |
ORACLE_NEGRISK_PROPOSAL_REDUCTION | RESHAPE | NegRisk market in proposal window; extra 20% size reduction applied due to definition-shift risk. | Apply 0.8 multiplier to cap before emitting RESHAPE_REQUIRED. | This is a neg-risk market in its resolution phase. An additional size reduction was applied. |
ORACLE_DISPUTE_OVERDUE | WARN | Dispute age exceeds max_dispute_window_h; escalation required. | Emit WARN annotation and escalate to incident commander; continue blocking per block_disputed. |
15. Metrics & Logs
Metrics emitted
| Metric | Type | Unit | Labels | Meaning |
|---|---|---|---|---|
polytraders_risk_oracleriskmonitor_decisions_total | counter | count | decision, reason_code, market_id | Total RiskVote decisions broken down by decision type and reason. |
polytraders_risk_oracleriskmonitor_dispute_age_hours | gauge | seconds | market_id | Age of the active dispute for markets currently in dispute; triggers alert when approaching max_dispute_window_h. |
polytraders_risk_oracleriskmonitor_proposal_fraction | gauge | ratio | market_id | Elapsed fraction of the UMA 2-hour proposal window; drives confidence-downgrade logic. |
polytraders_risk_oracleriskmonitor_oracle_fetch_latency_ms | histogram | seconds | Latency of UMA on-chain oracle state fetch. | |
polytraders_risk_oracleriskmonitor_markets_in_proposal | gauge | count | Number of markets currently in an active UMA proposal window. | |
polytraders_risk_oracleriskmonitor_markets_in_dispute | gauge | count | Number of markets currently in an active UMA dispute. |
Alerts
| Alert | Condition | Severity | Runbook |
|---|---|---|---|
OracleRiskMonitorDisputeActive | polytraders_risk_oracleriskmonitor_markets_in_dispute > 0 | P1 | #runbook-oracle-dispute-active |
OracleRiskMonitorDisputeOverdue | polytraders_risk_oracleriskmonitor_dispute_age_hours > 48 | P0 | #runbook-oracle-dispute-overdue |
OracleRiskMonitorStaleFeed | rate(polytraders_risk_oracleriskmonitor_decisions_total{reason_code='STALE_MARKET_DATA'}[5m]) > 0.1 | P1 | #runbook-oracle-stale-feed |
OracleRiskMonitorHighRejectRate | rate(polytraders_risk_oracleriskmonitor_decisions_total{decision='HARD_REJECT'}[5m]) / rate(polytraders_risk_oracleriskmonitor_decisions_total[5m]) > 0.3 | P2 | #runbook-oracle-reject-rate |
Dashboards
- Grafana — Risk overview / OracleRiskMonitor
- Grafana — UMA oracle status / proposal and dispute tracker
Log levels
| Level | What gets logged |
|---|---|
| DEBUG | proposalFraction value, cap computation, and bond amount on every evaluation. |
| INFO | RiskVote decision emitted (decision, reason_code, market_id). |
| WARN | Dispute age approaching max_dispute_window_h; oracle feed latency elevated. |
| ERROR | UMA on-chain feed unreachable; market metadata fetch returned null. |
16. Developer Reporting
{
"bot_id": "risk.oracle_risk_monitor",
"decision": "REJECT",
"reason_code": "ORACLE_DISPUTE_ACTIVE",
"inputs_used": [
"gamma_api.market.resolution_source",
"uma.oracle.dispute_events"
],
"metrics": {
"market_id": "CLOB:0xabc123",
"dispute_filed_at": "2026-05-08T14:00:00Z",
"dispute_age_h": 17.0,
"block_disputed": true,
"proposal_active": true,
"proposal_fraction_elapsed": 0.63
},
"checked_at": "2026-05-09T07:00:00Z"
}17. Plain-English Reporting
| Situation | User-facing explanation |
|---|---|
| Order blocked — oracle dispute active | This market currently has a contested resolution. Someone has challenged the proposed outcome on-chain. We blocked your order while this dispute is active because the final result is genuinely uncertain. |
| Order downsized — market in proposal window | This market has entered its resolution phase. We reduced your order size to limit your exposure while the outcome is being confirmed. |
| Order further reduced — late in proposal window | This market is well into its resolution window. We reduced the maximum allowed order size further because the uncertainty increases as the resolution deadline approaches. |
| Order blocked — oracle feed unavailable | We could not verify the current oracle status for this market. Rather than proceed without this information, we blocked the order until a fresh oracle status is available. |
| Neg-risk market — order reduced for definition-shift risk | This is a neg-risk market currently in proposal. We applied an additional size reduction because the outcome definition for related markets can shift during the proposal period. |
18. Failure-Mode Block
| main_failure_mode | Approving a trade into a market with an active dispute, resulting in a position that is exposed to a binary resolution outcome the strategy did not price in. |
|---|---|
| false_positive_risk | Blocking or downsizing orders on a market where a proposal has been filed but is very likely to pass uncontested, causing unnecessary missed exposure. |
| false_negative_risk | Approving an order against stale oracle data that was up-to-date at fetch time but has since entered a dispute, if the polling interval is too wide. |
| safe_fallback | If the UMA oracle event feed is unavailable or the last event fetch is older than stale_top_seconds, reject all orders on affected markets with STALE_MARKET_DATA. Never approve on missing oracle status. |
| required_dependencies | UMA Optimistic Oracle on-chain event feed, Gamma API market metadata, PortfolioGuard per-market position ledger, KillSwitch active flag |
19. Failure-Injection Recipes
| Scenario | How to inject | Expected behaviour | Recovery |
|---|---|---|---|
DISPUTE_ACTIVE | Set mock oracle state disputeActive=true for a target market | All evaluations on that market return HARD_REJECT(ORACLE_DISPUTE_ACTIVE) | Returns to APPROVE when disputeActive=false in oracle state. |
STALE_ORACLE_FEED | Freeze oracle state cache for 90s (TTL=30s) | HARD_REJECT(STALE_MARKET_DATA) on every evaluation | Returns to normal within one evaluation after fresh oracle fetch. |
LOW_PROPOSER_BOND | Set mock proposerBondPUsd=500 (below 750 floor) | HARD_REJECT(ORACLE_PROPOSER_BOND_BELOW_MIN) | Returns to APPROVE once bond is at or above 750 pUSD. |
PROPOSAL_WINDOW_LATE | Set proposalFraction=0.85 and downgrade_size_by_confidence=true | RESHAPE_REQUIRED with cap significantly below reduce_at_proposal_pct baseline | Cap returns to baseline once proposal resolves. |
KILL_SWITCH_ON | Set internal.killswitch.status.active=true | HARD_REJECT(KILL_SWITCH_ACTIVE) on every intent without oracle fetch | Returns to normal pipeline on manual KillSwitch reset. |
20. State & Persistence
Maintains a short-lived in-memory cache of oracle state per market_id to avoid redundant on-chain calls within the same evaluation window.
State stores
| Name | Kind | Key | Value shape | TTL | Durability |
|---|---|---|---|---|---|
oracle_state_cache | in-memory | market_id | { proposalActive: bool, disputeActive: bool, proposalStartMs: int, challengeWindowMs: int, proposerBondPUsd: float } | 30s | best-effort |
Cold-start recovery
On cold start, the cache is empty. The first evaluation for each market triggers a fresh on-chain fetch.
On restart
Oracle state is re-fetched on first evaluation; no durable state is loaded.
21. Concurrency & Idempotency
| Aspect | Specification |
|---|---|
| Execution model | single-threaded event loop |
| Max in-flight | 100 |
| Idempotency key | intent_id |
| Replay-safe | True |
| Deduplication | by intent_id within a 24h window |
| Ordering guarantees | FIFO per market_id |
| Per-call timeout (ms) | 250 |
| Backpressure strategy | drop newest |
| Locking / mutual exclusion | per-market_id mutex |
22. Dependencies
Depends on (must run first)
| Bot | Why | Contract |
|---|---|---|
| risk.kill_switch | Global brake — checked first before any oracle fetch. | RiskVote.HARD_REJECT(KILL_SWITCH_ACTIVE) short-circuits. |
| risk.portfolio_guard | Per-market position limit is needed to compute the proposal-window size cap. | cap = portfolio_guard.per_market_limit * reduce_at_proposal_pct. |
Emits to (downstream consumers)
| Bot | Why | Contract |
|---|---|---|
| exec.smart_router | Approved or reshaped RiskVote passes to SmartRouter. | HARD_REJECT on ORACLE_DISPUTE_ACTIVE causes SmartRouter to discard the intent. |
Used by (auto-aggregated)
External services
| Service | Endpoint | SLA assumed | On failure |
|---|---|---|---|
| UMA Optimistic Oracle (on-chain) | Polygon RPC / UMA oracle contract | best-effort / chain-dependent | HARD_REJECT(STALE_MARKET_DATA) until oracle state is readable. |
| Gamma API | https://gamma-api.polymarket.com | 99.9% / 500ms p99 | HARD_REJECT(STALE_MARKET_DATA) if market metadata is unavailable. |
| CLOB API (read) | https://clob.polymarket.com | 99.95% / 200ms p99 | Falls back to Gamma API for market metadata. |
23. Security Surfaces
OracleRiskMonitor is read-only. It never signs orders or holds private keys.
Signing surface
This bot does NOT sign anything.
Abuse vectors considered
- Feeding a stale or forged oracle state to bypass dispute detection
- Manipulating proposalFraction to reduce the size cap during a proposal window
Mitigations
- Oracle state has a 30s TTL; stale data triggers HARD_REJECT rather than pass-through
- proposalFraction is computed from on-chain timestamps, not from any mutable local state
24. Polymarket V2 Compatibility
| Aspect | Value |
|---|---|
| CLOB version | v2 |
| Collateral asset | pUSD |
| EIP-712 Exchange domain version | 2 |
| Aware of builderCode field | no |
| Aware of negative-risk markets | yes |
| Multi-chain ready | no |
| SDK used | @polymarket/clob-client-v2 ^2.x |
| Settlement contract | CTFExchangeV2 on Polygon |
| Notes | UMA proposer bond is 750 pUSD (replaces 750 USDC.e from v1). Dispute challenge window is 2 hours; escalated disputes go to DVM voting (24-48h debate + ~48h voting). NegRisk markets carry extra size reduction during proposal window due to potential definition shifts. |
API surfaces declared
Networks supported
25. Versioning & Migration
| Field | Value |
|---|---|
| spec | 2.0.0 |
| implementation | 2.1.3 |
| schema | 2 |
| released | 2026-04-28 |
Migration history
| Date | From | To | Reason | Action taken |
|---|---|---|---|---|
| 2026-04-28 | v1 (USDC.e + HMAC builder) | v2 (pUSD + builderCode field) | Polymarket V2 cutover | Migrated SDK. Proposer bond check now validates 750 pUSD instead of 750 USDC.e. No structural change to oracle dispute logic; removed feeRateBps references. |
26. Acceptance Tests
Unit Tests
| Test | Setup | Expected result |
|---|---|---|
| Approve when no proposal and no dispute | proposalActive=false, disputeActive=false | APPROVE with no constraints |
| Reshape when proposal active and size exceeds cap | proposalActive=true, reduce_at_proposal_pct=50, per_market_limit=2000, size_usd=1200 | RESHAPE_REQUIRED with constraints.max_size_usd=1000 |
| Reject when dispute active and block_disputed=true | disputeActive=true, block_disputed=true | REJECT with reason_code=ORACLE_DISPUTE_ACTIVE |
| Allow when dispute active and block_disputed=false | disputeActive=true, block_disputed=false | APPROVE with warning annotation ORACLE_DISPUTE_ACTIVE |
| Downgrade cap further when proposal fraction > 0.5 | proposalActive=true, proposal_fraction=0.8, reduce_at_proposal_pct=50, downgrade_size_by_confidence=true | RESHAPE_REQUIRED with cap reduced below standard 50% level |
| Reject when oracle feed is stale | oracle_feed_age_s=200, stale_top_seconds=60 | REJECT with reason_code=STALE_MARKET_DATA |
| Neg-risk market applies additional 20% reduction | proposalActive=true, neg_risk=true, reduce_at_proposal_pct=50, per_market_limit=2000 | RESHAPE_REQUIRED with constraints.max_size_usd=800 (50% × 0.8) |
Integration Tests
| Test | Expected result |
|---|---|
| Live UMA oracle event triggers block on in-flight OrderIntent | REJECT(ORACLE_DISPUTE_ACTIVE) emitted within one polling cycle after dispute filed on-chain |
| Position size from PortfolioGuard correctly caps reshape size end-to-end | Reshape constraint is consistent with PortfolioGuard ledger values |
| Oracle feed outage causes reject-safe fallback across all affected markets | All orders on UMA-resolved markets return REJECT(STALE_MARKET_DATA) when feed is down |
Property Tests
| Property | Required behaviour |
|---|---|
| Missing oracle feed data never results in APPROVE | Always true — null or stale oracle status produces REJECT(STALE_MARKET_DATA) |
| Reshape size is always ≤ requested order size | Always true — downgrade adjustments only reduce the cap, never increase it |
| block_disputed=true always results in REJECT when disputeActive=true | Always true regardless of order size or market state |
27. Operational Runbook
OracleRiskMonitor incidents are driven by active UMA disputes or stale oracle feed. Disputes are expected events; on-call must validate the dispute is legitimate before considering any override.
On-call actions
| Alert | First step | Diagnosis | Mitigation | Escalate to |
|---|---|---|---|---|
OracleRiskMonitorDisputeActive | Identify which market_id is in dispute from the Grafana panel. | Check UMA oracle on-chain for dispute details. Verify the dispute was filed legitimately (not a griefing attempt with insufficient bond). | If legitimate, the guard is working correctly — do not override. If suspicious, escalate to Risk pod lead. | Risk pod lead immediately for any P1 dispute event. |
OracleRiskMonitorDisputeOverdue | Check dispute age on the Grafana panel. Escalate immediately if > 48h. | DVM vote may be stalled. Check UMA DVM governance interface for vote status. | Maintain HARD_REJECT on affected market until DVM resolves. Do not reduce block_disputed. | Incident commander + Risk pod lead within 15 minutes of alert. |
OracleRiskMonitorStaleFeed | Check Polygon RPC connectivity and oracle contract read latency. | If RPC is degraded, oracle state fetch is timing out and falling back to reject-safe. | Switch to backup RPC endpoint. The guard's reject-safe default protects positions. | Infra on-call if RPC is down > 5 minutes. |
OracleRiskMonitorHighRejectRate | Check reason_code breakdown. If dominated by ORACLE_DISPUTE_ACTIVE, normal guard behaviour. | If STALE_MARKET_DATA is dominant, follow stale-feed runbook. | Pause affected strategies if the rejection is blocking all orders unnecessarily. | Risk pod lead after 15 minutes of sustained high reject rate. |
Manual overrides
polytraders bot pause risk.oracle_risk_monitor— Stops emitting RiskVotes. Use only during a known feed outage with explicit Risk pod lead sign-off.polytraders bot flush-cache risk.oracle_risk_monitor --market <market_id>— Evicts the oracle state cache for a specific market, forcing a fresh on-chain fetch.
Healthcheck
GET /health → 200 if on-chain oracle state fetch latency < 500ms and no market has been in dispute for > max_dispute_window_h.28. Promotion Gates
A bot does not advance to the next readiness state until every gate below is green. Gates are observable from production data — no subjective sign-off.
Promote to Shadow
| Gate | How measured | Threshold |
|---|---|---|
| Unit tests pass including all acceptance_tests.unit cases | CI test run | 100% pass |
| Integration test: active dispute → HARD_REJECT verified end-to-end | Integration test suite with mock oracle | Pass |
Promote to Limited live
| Gate | How measured | Threshold |
|---|---|---|
| Oracle feed latency p99 < 250ms over 48h | polytraders_risk_oracleriskmonitor_oracle_fetch_latency_ms histogram | p99 < 250ms |
| No false-positive HARD_REJECT during normal (no-dispute) operation | Shadow vs live comparison | 0 false positives |
Promote to General live
| Gate | How measured | Threshold |
|---|---|---|
| Successfully blocked at least one synthetic dispute injection in staging | Failure injection test log | Pass |
| Proposal-window reshape correctly reduces size in E2E flow | E2E test + fill log audit | 100% compliance |
29. Developer Checklist
Ready-to-ship score: 27/27 sections complete · 100%
| Requirement | Status |
|---|---|
| Purpose defined | ✓ done |
| Required inputs listed | ✓ done |
| Parameters defined | ✓ done |
| Defaults defined | ✓ done |
| Warning thresholds defined | ✓ done |
| Hard thresholds defined | ✓ done |
| Safe fallback defined | ✓ done |
| Structured output defined | ✓ done |
| Developer log defined | ✓ done |
| Plain-English explanation | ✓ done |
| Unit tests defined | ✓ done |
| Integration tests defined | ✓ done |
| Property tests defined | ✓ done |
| Failure-mode block complete | ✓ done |
| Reference implementation pseudocode | ✓ done |
| Wire examples (input + output) | ✓ done |
| Reason codes listed | ✓ done |
| Metrics & logs defined | ✓ done |
| State & persistence defined | ✓ done |
| Concurrency & idempotency defined | ✓ done |
| Dependencies declared | ✓ done |
| Security surfaces declared | ✓ done |
| Polymarket V2 compatibility declared | ✓ done |
| Version & migration history declared | ✓ done |
| Operational runbook defined | ✓ done |
| Promotion gates defined | ✓ done |
| Failure-injection recipes defined | ✓ done |