Polytraders Dev Guide
internal
v3 spine Phase 1 · Shared contracts 9 demo-wired · 0 shadow-ready · 0 production-live · 100 pending · 109 total 15/33 infra tasks the plan status board
HomeBy LayerExecution2.5 GasOracle

2.5 GasOracle

Execution Execution Utility Reshape LIVE General live capital · Direct P5 · Execution rails pending stub

GasOracle continuously monitors the Polygon network gas-price environment and advises the execution layer on whether on-chain operations (order submission, cancel-and-replace, neg-risk conversions) are economically viable at the current gas price. It defers non-urgent operations when gas is above the rolling percentile threshold, and never defers risk-critical operations such as emergency cancellations.

v3 readiness

Docs27/27
donehow scored
Impl0/15
pendinghow scored
Backtest0/4
pendinghow scored
Runtime0/8
pendinghow scored

A bot is done when all four scores are. What does done mean?

1. Bot Identity

LayerExecution  Execution
Bot classExecution Utility
AuthorityReshape
StatusLIVE
ReadinessGeneral live
Runs beforeOrder signing and on-chain submission
Runs afterExecutionPlan assembly (SmartRouter)
Applies toEvery on-chain operation that can be deferred without breaching a risk constraint
Default modegeneral_live
User-visibleAdvanced details only
Developer ownerPolytraders core

Operational profile

Modes supportedquarantine

2. Purpose

GasOracle continuously monitors the Polygon network gas-price environment and advises the execution layer on whether on-chain operations (order submission, cancel-and-replace, neg-risk conversions) are economically viable at the current gas price. It defers non-urgent operations when gas is above the rolling percentile threshold, and never defers risk-critical operations such as emergency cancellations.

3. Why This Bot Matters

  • Submitting during a gas spike

    Transaction costs erode trade profitability; maker rebates (paid in pUSD) can be wiped out by gas fees on low-edge positions.

  • Deferring a risk-critical cancellation

    A resting order that should be pulled stays live during adverse market movement, accumulating unintended exposure.

  • Using a stale 24h gas baseline

    The percentile thresholds are miscalibrated, causing GasOracle to defer operations during normal conditions or approve during actual spikes.

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

Legacy signals migrated from the v1 catalogue. Re-classify into the four-column form before this bot ships.

InputSourceRequired?Use
Pending neg-risk conversion EV vs. expected gas costlegacy

5. Required Internal Inputs

InputSourceRequired?Use
Polygon mempool gas-price snapshot (gwei)onchain RPC (eth_gasPrice / fee history)YesCurrent gas price evaluated against the rolling 24h percentile baseline.
Rolling 24h gas-price baselineinternal time-series storeYesCompute the max_gas_percentile_for_ops threshold from historical distribution.
Pending operation queue with urgency flagsinternal execution schedulerYesIdentify whether each pending op is risk-critical (never_defer) or deferrable.

6. Parameter Guide

ParameterDefaultWarningHardWhat it controls
max_gas_percentile_for_ops758595Maximum historical gas-price percentile (0–100) at which non-urgent on-chain operations are approved. Operations are deferred when the current gas price exceeds this percentile of the rolling 24h distribution.
conversion_min_ev_usd0.10.050.0Minimum expected value (pUSD) that a neg-risk conversion must generate after gas costs before GasOracle approves the on-chain conversion call.
defer_non_urgentTrueWhen true, non-urgent on-chain operations (routine cancel-replace, post-fill bookkeeping) are deferred when gas exceeds max_gas_percentile_for_ops.
never_defer_riskTrueLocked true. Risk-critical on-chain operations (emergency order cancellations, kill-switch triggered burns) always bypass gas deferral logic.

7. Detailed Parameter Instructions

max_gas_percentile_for_ops

What it means

Maximum historical gas-price percentile (0–100) at which non-urgent on-chain operations are approved. Operations are deferred when the current gas price exceeds this percentile of the rolling 24h distribution.

Default

{ "max_gas_percentile_for_ops": 75 }

Why this default matters

Setting the gate at the 75th percentile ensures operations are deferred during the top quarter of daily gas-price spikes, keeping transaction costs within budget without causing excessive deferrals.

Threshold logic

ConditionAction
current_gas <= p75APPROVE — submit operation
p75 < current_gas <= p85WARN — elevated gas; proceed for non-urgent ops
p85 < current_gas <= p95RESHAPE — defer all non-urgent ops
current_gas > p95Hard block — defer unless never_defer_risk=true

Developer check

if pct > params.hard and not op.never_defer: return defer('GAS_ORACLE_SPIKE_BLOCK')

User-facing English

On-chain operations are paused temporarily because network fees are unusually high right now.

conversion_min_ev_usd

What it means

Minimum expected value (pUSD) that a neg-risk conversion must generate after gas costs before GasOracle approves the on-chain conversion call.

Default

{ "conversion_min_ev_usd": 0.1 }

Why this default matters

Requiring at least $0.10 net EV prevents marginal conversions from being triggered when gas costs consume the arb spread.

Threshold logic

ConditionAction
ev_after_gas >= 0.10APPROVE conversion
0.05 <= ev_after_gas < 0.10WARN — margin thin
ev_after_gas < 0.05RESHAPE — defer conversion

Developer check

ev_net = ev_gross - gas_cost_pusd; if ev_net < params.hard: return defer('GAS_ORACLE_EV_BELOW_FLOOR')

User-facing English

— not yet authored —

defer_non_urgent

What it means

When true, non-urgent on-chain operations (routine cancel-replace, post-fill bookkeeping) are deferred when gas exceeds max_gas_percentile_for_ops.

Default

{ "defer_non_urgent": true }

Why this default matters

Deferring non-urgent operations by default limits gas spend during spikes without impacting trading outcomes.

Threshold logic

ConditionAction
defer_non_urgent=true AND gas > thresholdQueue op for retry in next evaluation cycle
defer_non_urgent=falseSubmit regardless of gas price (not recommended except for testing)

Developer check

if not params.defer_non_urgent: skip_gas_check()

User-facing English

— not yet authored —

never_defer_risk

What it means

Locked true. Risk-critical on-chain operations (emergency order cancellations, kill-switch triggered burns) always bypass gas deferral logic.

Default

{ "never_defer_risk": true }

Why this default matters

A gas spike must never prevent the system from executing an emergency cancellation. Risk safety is unconditional.

Threshold logic

ConditionAction
op.risk_critical=true AND never_defer_risk=trueAPPROVE unconditionally — bypass gas check

Developer check

assert params.never_defer_risk == True  # locked; config change requires approval

User-facing English

— not yet authored —

8. Default Configuration

{
  "bot_id": "exec.gas_oracle",
  "version": "2.1.0",
  "mode": "general_live",
  "defaults": {
    "max_gas_percentile_for_ops": 75,
    "conversion_min_ev_usd": 0.1,
    "defer_non_urgent": true,
    "never_defer_risk": true
  },
  "locked": {
    "never_defer_risk": {
      "value": true
    }
  }
}

9. Implementation Flow

  1. Fetch current Polygon gas price (gwei) via onchain RPC (eth_feeHistory or eth_gasPrice).
  2. Retrieve the rolling 24h gas-price baseline from the internal time-series store; compute percentile rank of current gas price.
  3. For each pending on-chain operation in the execution scheduler queue, read its urgency flag (risk_critical vs. non_urgent).
  4. If op.risk_critical=true (never_defer_risk=true locked): approve unconditionally — emit GasDecision.PASS.
  5. If current gas percentile <= max_gas_percentile_for_ops: approve non-urgent op — emit GasDecision.PASS.
  6. If percentile is in the WARN band (max_gas_percentile..+10): approve with a WARN annotation on the GasDecision.
  7. If percentile exceeds max_gas_percentile_for_ops and defer_non_urgent=true: emit GasDecision.DEFER with retry_after_s set to next expected dip (estimated from baseline).
  8. For neg-risk conversion ops: additionally compute ev_after_gas = ev_gross - gas_cost_pusd; if below conversion_min_ev_usd, emit GasDecision.DEFER with GAS_ORACLE_EV_BELOW_FLOOR.
  9. Emit GasDecision record to internal execution scheduler with verdict, reason_code, gas_gwei_current, gas_percentile, and retry_after_s.
  10. Append data point to rolling 24h baseline.

10. Reference Implementation

Fetches the current Polygon gas price, computes its percentile rank against the rolling 24h baseline, and emits a GasDecision (PASS/DEFER) for each pending on-chain operation. Risk-critical operations always bypass the gas gate.

Pseudocode is language-agnostic. FETCH = read input. EMIT = produce output. Translate to TS/Python/Go/Rust.

FUNCTION evaluateGas(pending_ops):
  // --- 1. Fetch current gas price ---
  gas_gwei = FETCH onchain_rpc.eth_gasPrice()  // gwei
  IF gas_gwei IS NULL:
    FOR op IN pending_ops:
      IF NOT op.risk_critical:
        EMIT GasDecision(op, DEFER, GAS_ORACLE_RPC_FAILURE)
    RETURN

  // --- 2. Compute percentile rank from 24h baseline ---
  baseline = FETCH internal.gas_baseline_24h()  // sorted list of gwei samples
  IF baseline IS NULL OR isStale(baseline, 300):
    cap_gwei = 100  // static fallback cap
    pct = 99 IF gas_gwei > cap_gwei ELSE 50
    EMIT WARN GAS_ORACLE_BASELINE_UNAVAILABLE
  ELSE:
    pct = percentile_rank(gas_gwei, baseline)  // 0..100

  // --- 3. For each pending operation ---
  FOR op IN pending_ops:
    // --- 3a. Risk-critical bypass ---
    IF op.risk_critical AND params.never_defer_risk:
      EMIT GasDecision(op, PASS, GAS_ORACLE_RISK_BYPASS,
                       gas_gwei=gas_gwei, pct=pct)
      CONTINUE

    // --- 3b. Neg-risk conversion EV check ---
    IF op.kind == 'negrisk_conversion':
      gas_cost_pusd = estimate_gas_cost_pusd(gas_gwei, op.gas_limit)
      ev_net = op.ev_gross_pusd - gas_cost_pusd
      IF ev_net < params.conversion_min_ev_usd:
        EMIT GasDecision(op, DEFER, GAS_ORACLE_EV_BELOW_FLOOR,
                         ev_net=ev_net, gas_cost_pusd=gas_cost_pusd)
        CONTINUE

    // --- 3c. Gas percentile gate ---
    IF pct > params.max_gas_percentile_for_ops:
      IF NOT params.defer_non_urgent:
        EMIT GasDecision(op, PASS, GAS_ORACLE_ELEVATED)
      ELSE:
        retry_after_s = estimate_gas_dip_s(baseline, params.max_gas_percentile_for_ops)
        EMIT GasDecision(op, DEFER, GAS_ORACLE_SPIKE_BLOCK,
                          retry_after_s=retry_after_s, gas_percentile=pct)
    ELSE IF pct > params.max_gas_percentile_for_ops - 10:
      EMIT GasDecision(op, PASS, GAS_ORACLE_ELEVATED, warn=true, gas_percentile=pct)
    ELSE:
      EMIT GasDecision(op, PASS, GAS_ORACLE_OK, gas_percentile=pct)

  // --- 4. Append current sample to baseline ---
  internal.gas_baseline_24h.append(gas_gwei, now_ms())

SDK calls used

  • onchain_rpc.eth_gasPrice()
  • onchain_rpc.eth_feeHistory(blockCount=20, newestBlock='latest')
  • internal.gas_baseline_24h.fetch()
  • internal.gas_baseline_24h.append(sample)
  • estimate_gas_cost_pusd(gas_gwei, gas_limit)

Complexity: O(P) where P = number of pending on-chain operations per evaluation cycle

11. Wire Examples

Input — what arrives on the wire

{
  "label": "Pending non-urgent cancel-replace operation",
  "source": "internal execution scheduler",
  "payload": {
    "op_id": "op_3c4d5e6f7a8b9c0d",
    "kind": "cancel_replace",
    "risk_critical": false,
    "gas_limit": 80000,
    "ev_gross_pusd": null,
    "enqueued_at_ms": 1746768840000
  }
}

Output — what the bot emits

{
  "label": "GasDecision — deferred due to gas spike",
  "payload": {
    "oracle_id": "exec.gas_oracle",
    "op_id": "op_3c4d5e6f7a8b9c0d",
    "verdict": "DEFER",
    "reason_code": "GAS_ORACLE_SPIKE_BLOCK",
    "gas_gwei_current": 142.7,
    "gas_percentile": 88,
    "threshold_percentile": 75,
    "retry_after_s": 180,
    "never_defer_risk": true,
    "evaluated_at_ms": 1746768900000
  }
}

12. Decision Logic

APPROVE

Current gas price falls at or below max_gas_percentile_for_ops of the rolling 24h baseline, or the operation is marked risk_critical.

RESHAPE_REQUIRED

Non-urgent operation deferred to a lower-gas window. The operation is queued with a retry_after_s estimate derived from the baseline distribution.

REJECT

Conversion op net EV falls below conversion_min_ev_usd hard floor (0.0); GasOracle cancels the conversion entirely.

WARNING_ONLY

Gas is in the 75th–85th percentile band; GasDecision.PASS is emitted with a WARN annotation for monitoring.

13. Standard Decision Output

This bot returns a GasDecision object. See GasDecision schema.

{
  "oracle_id": "exec.gas_oracle",
  "op_id": "op_3c4d5e6f7a8b9c0d",
  "verdict": "DEFER",
  "reason_code": "GAS_ORACLE_SPIKE_BLOCK",
  "gas_gwei_current": 142.7,
  "gas_percentile": 88,
  "threshold_percentile": 75,
  "retry_after_s": 180,
  "never_defer_risk": true,
  "evaluated_at_ms": 1746768900000
}

14. Reason Codes

CodeSeverityMeaningActionUser-facing message
GAS_ORACLE_OKINFOCurrent gas price is below max_gas_percentile_for_ops; operation approved.Emit GasDecision.PASS. Operation proceeds normally.
GAS_ORACLE_ELEVATEDWARNGas price is in the warning band (within 10 percentile points above threshold). Operation approved with annotation.Emit GasDecision.PASS with warn=true; monitor for further elevation.Network fees are slightly elevated. Operations are continuing but costs may be higher than usual.
GAS_ORACLE_SPIKE_BLOCKRESHAPEGas price exceeds max_gas_percentile_for_ops; non-urgent operation deferred.Emit GasDecision.DEFER with retry_after_s. Operation queued for next lower-gas window.An on-chain operation was postponed temporarily because network fees are unusually high.
GAS_ORACLE_EV_BELOW_FLOORRESHAPENeg-risk conversion net EV (after gas cost) is below conversion_min_ev_usd threshold.Emit GasDecision.DEFER. Conversion not submitted.
GAS_ORACLE_RISK_BYPASSINFORisk-critical operation approved unconditionally despite elevated gas (never_defer_risk=true locked).Emit GasDecision.PASS. Gas check bypassed. Log gas_gwei for audit.
GAS_ORACLE_RPC_FAILUREHARD_REJECTPolygon RPC gas feed is unreachable; current gas price cannot be determined.Defer all non-urgent ops. Emit GAS_ORACLE_RPC_FAILURE. Risk-critical ops still approved.On-chain operations are paused briefly due to a network connectivity issue.
GAS_ORACLE_BASELINE_UNAVAILABLEWARNRolling 24h gas baseline store is unreachable or stale; falling back to hard static cap.Use static 100 gwei cap. Emit WARN annotation on all GasDecision records this cycle.
KILL_SWITCH_ACTIVEHARD_REJECTGlobal kill switch is active; all on-chain operations except emergency cancellations are halted.Defer all non-risk-critical ops. No GasDecision.PASS emitted.Trading is currently paused.

15. Metrics & Logs

Metrics emitted

MetricTypeUnitLabelsMeaning
polytraders_exec_gasoracle_decisions_totalcountercountverdict, reason_codeTotal GasDecision records emitted per verdict/reason_code.
polytraders_exec_gasoracle_gas_gweigaugegweiCurrent Polygon gas price at the last evaluation cycle.
polytraders_exec_gasoracle_gas_percentilegaugepercentilePercentile rank of current gas price against 24h baseline; >75 triggers deferral.
polytraders_exec_gasoracle_defer_queue_depthgaugecountop_kindNumber of non-urgent operations currently queued awaiting a lower-gas window.
polytraders_exec_gasoracle_rpc_errors_totalcountercountConsecutive RPC fetch failures; sustained > 3 triggers a page alert.
polytraders_exec_gasoracle_eval_latency_mshistogrammsWall-clock time to complete one full evaluation cycle.

Alerts

AlertConditionSeverityRunbook
GasOracleSpikeBlockrate(polytraders_exec_gasoracle_decisions_total{verdict='DEFER',reason_code='GAS_ORACLE_SPIKE_BLOCK'}[10m]) > 0.5warn#runbook-gasoracle-spike-block
GasOracleRpcDownpolytraders_exec_gasoracle_rpc_errors_total > 3page#runbook-gasoracle-rpc-failure
GasOracleDeferQueueDeeppolytraders_exec_gasoracle_defer_queue_depth > 50warn#runbook-gasoracle-defer-queue
GasOracleBaselineStaletime() - polytraders_exec_gasoracle_baseline_updated_at > 600warn#runbook-gasoracle-baseline-stale

Dashboards

  • Grafana — Execution / GasOracle
  • Grafana — Polygon Gas / 24h baseline and current percentile

16. Developer Reporting

{
  "oracle_id": "exec.gas_oracle",
  "op_id": "op_3c4d5e6f7a8b9c0d",
  "op_kind": "cancel_replace",
  "risk_critical": false,
  "gas_gwei_current": 142.7,
  "gas_percentile": 88,
  "max_gas_percentile_for_ops": 75,
  "defer_non_urgent": true,
  "verdict": "DEFER",
  "reason_code": "GAS_ORACLE_SPIKE_BLOCK",
  "retry_after_s": 180,
  "baseline_window_h": 24,
  "evaluated_at_ms": 1746768900000
}

17. Plain-English Reporting

SituationUser-facing explanation
On-chain operation deferred due to gas spikeA routine order update was postponed briefly because network fees are currently elevated. It will be retried automatically when fees return to normal levels.
Neg-risk conversion blocked — margin too thin after gasA conversion operation was not submitted because the expected gain after network fees did not meet the minimum threshold.
Risk-critical cancellation approved despite high gasAn emergency order cancellation was submitted immediately despite elevated network fees because risk safety overrides gas cost constraints.

18. Failure-Mode Block

main_failure_modeStale 24h baseline causing the percentile rank to be computed incorrectly — GasOracle may approve operations during genuine spikes or block during normal conditions.
false_positive_riskDeferring a non-urgent operation unnecessarily during a brief transient spike, causing minor latency in order management.
false_negative_riskApproving an operation at a gas price that turns out to be a spike because the baseline has not yet captured recent price history.
safe_fallbackIf the rolling baseline store is unreachable, fall back to a hard static cap of 100 gwei. If the RPC gas feed is unreachable, defer all non-urgent ops and surface GAS_ORACLE_RPC_FAILURE.
required_dependenciesPolygon onchain RPC (gas price feed), Internal time-series store (24h baseline), Execution scheduler (pending operation queue)

19. Failure-Injection Recipes

ScenarioHow to injectExpected behaviourRecovery
RPC_DOWNBlock outbound TCP to the Polygon RPC endpointReconnects on next evaluation cycle when RPC is restored
BASELINE_STALESet Redis baseline last-updated timestamp to now()-600s without updating samplesBaseline self-heals as samples accumulate after Redis reconnect
GAS_SPIKE_SUSTAINEDInject synthetic gas samples at p98 into the baseline for 30 minutesOps re-evaluated and flushed once gas normalises below threshold
NEVER_DEFER_RISK_TAMPERAttempt to set never_defer_risk=false via config APINo action needed; lock enforced at config validation layer
KILL_SWITCH_ONActivate global KillSwitchResumes on manual KillSwitch reset

20. State & Persistence

Cold-start recovery

On restart, baseline is re-hydrated from Redis. First evaluation cycle uses stored baseline immediately. Deferred ops resume from queue.

21. Concurrency & Idempotency

AspectSpecification
Execution modelsingle-threaded event loop
Max in-flight1
Idempotency keyop_id
Per-call timeout (ms)500
Backpressure strategyEvaluation deferred until current cycle completes; ops queue in Redis
Locking / mutual exclusionnone — single event loop; Redis SETNX for deferred-op deduplication

22. Dependencies

Depends on (must run first)

BotWhyContract
risk.kill_switchKillSwitch active flag overrides all GasOracle approvals for non-risk-critical ops.GasDecision.PASS not emitted for any non-risk-critical op when KillSwitch is active.

Emits to (downstream consumers)

BotWhyContract
exec.smart_routerSmartRouter must receive GasDecision.PASS before submitting a signed order on-chain.
exec.nonce_shepherdNonceShepherd holds nonce reservation when GasOracle emits DEFER.

Used by (auto-aggregated)

2.4

External services

ServiceEndpointSLA assumedOn failure
Polygon RPC (gas feed)https://polygon-rpc.com (or internal RPC node)best-effort / internal node target 99.9%

23. Security Surfaces

Abuse vectors considered

  • Manipulating the rolling baseline store to artificially lower the perceived percentile, causing GasOracle to approve submissions during genuine gas spikes
  • Injecting false risk_critical=true flags on non-risk ops to bypass the gas gate

Mitigations

  • Baseline store (Redis) access restricted to GasOracle service account only
  • risk_critical flag validated against the KillSwitch and Risk pipeline authority — cannot be set by external callers
  • GasDecision records signed with internal HMAC; tampering detected by consumer bots

24. Polymarket V2 Compatibility

AspectValue
CLOB versionv2
Collateral assetpUSD
EIP-712 Exchange domain version2
Aware of builderCode fieldno
Aware of negative-risk marketsno
Multi-chain readyno
SDK usedpy-clob-client-v2 (no direct CLOB calls; only onchain RPC)
Settlement contractCTFExchangeV2
NotesGasOracle is internal-only and does not call Polymarket V2 APIs directly. It monitors the Polygon gas environment and gates on-chain operations. Gas costs are expressed in pUSD (USDC-backed ERC-20) for consistency with V2 fee accounting.

API surfaces declared

onchaininternal

Networks supported

polygon

25. Versioning & Migration

FieldValue
spec2.0.0
implementation2.1.0
schema2
released2026-04-28

Migration history

DateFromToReasonAction taken
2026-04-28v1v2CLOB V2 cutover; collateral renamed from USDC.e to pUSDRemoved all USDC.e references from gas-cost calculation helpers; gas-cost estimates now expressed in pUSD. No CLOB order fields touched by this bot — GasOracle is purely internal/onchain and has no EIP-712 surface.

26. Acceptance Tests

Unit Tests

TestSetupExpected result
Approve operation when gas is at 60th percentile (below 75th threshold)current_gas=p60, max_gas_percentile_for_ops=75, op.risk_critical=falseGasDecision.verdict=PASS
Defer non-urgent operation when gas is at 88th percentilecurrent_gas=p88, max_gas_percentile_for_ops=75, defer_non_urgent=trueGasDecision.verdict=DEFER, reason_code=GAS_ORACLE_SPIKE_BLOCK
Approve risk-critical op unconditionally at 98th percentilecurrent_gas=p98, op.risk_critical=true, never_defer_risk=true (locked)GasDecision.verdict=PASS — gas check bypassed
Block conversion when ev_after_gas < 0.0 (hard floor)ev_gross=0.08, gas_cost_pusd=0.12, conversion_min_ev_usd=0.10GasDecision.verdict=DEFER, reason_code=GAS_ORACLE_EV_BELOW_FLOOR
Emit WARN annotation when gas is in 75th–85th percentile bandcurrent_gas=p80, max_gas_percentile_for_ops=75GasDecision.verdict=PASS with warn_annotation=GAS_ORACLE_ELEVATED

Integration Tests

TestExpected result
End-to-end: deferred op is retried after gas normalisesOp queued with retry_after_s; re-evaluated next cycle; approved once gas drops below threshold
Baseline store outage causes static-cap fallbackGasOracle falls back to 100 gwei hard cap; emits GAS_ORACLE_BASELINE_UNAVAILABLE

Property Tests

PropertyRequired behaviour
never_defer_risk=true (locked) — risk-critical ops always receive PASS regardless of gasAlways true
GasDecision always includes gas_gwei_current, gas_percentile, and evaluated_at_msAlways true

27. Operational Runbook

GasOracle incidents are typically elevated gas causing large defer-queue buildup, or RPC connectivity failures. Neither condition directly causes trading losses — risk-critical ops are always approved — but sustained deferral may cause order management lag.

On-call actions

AlertFirst stepDiagnosisMitigationEscalate to
GasOracleRpcDownVerify Polygon RPC endpoint is reachable from service host. Check internal RPC node health.If RPC is unreachable, all non-urgent ops are deferred and static cap fallback is active.Switch to fallback RPC node if primary is down.Infra on-call if RPC down > 5 minutes
GasOracleDeferQueueDeepCheck current gas percentile in Grafana. If gas has normalised but queue is not draining, check Redis connectivity.Sustained high gas or Redis connectivity issue preventing queue drain.If Redis is down, restart Redis. If gas is genuinely high, notify strategy team.Exec pod lead if queue depth > 200
GasOracleBaselineStaleCheck Redis connectivity and GasOracle process health. Baseline should update every 10s.GasOracle process may be down or Redis write is failing.Restart GasOracle process. Verify Redis write permissions.Exec pod lead after 10 minutes of staleness
GasOracleSpikeBlockMonitor gas in Grafana. If spike is genuine and prolonged, notify strategy team of order management latency.Market gas spike causing all non-urgent ops to defer.No immediate action needed; ops auto-resume when gas normalises.Strategy pod lead if non-urgent ops deferred > 30 minutes

Manual overrides

  • polytraders bot config exec.gas_oracle defer_non_urgent=false --ttl 60 — Disables non-urgent op deferral for 60 seconds. Use only during pre-approved maintenance windows.
  • polytraders bot flush-queue exec.gas_oracle — Force-drains the rate-deferred operation queue after a gas spike resolves.

Healthcheck

GET /internal/health/gasoracle → 200 if RPC reachable, baseline updated within 60s, no consecutive RPC errors. RED if RPC unreachable > 3 polls or baseline stale > 300s.

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

GateHow measuredThreshold
Unit tests pass: all 5 acceptance_tests.unit casesCI test run100% pass
never_defer_risk lock enforced by config validatorUnit test: attempt to set never_defer_risk=false → ConfigErrorPass

Promote to Limited live

GateHow measuredThreshold
p99 eval latency < 500ms over 24hpolytraders_exec_gasoracle_eval_latency_ms histogramp99 < 500ms
Defer-queue drains within 5 minutes of gas normalising in integration testIntegration testPass

Promote to General live

GateHow measuredThreshold
Baseline store failover to static cap tested in stagingFailure injection: BASELINE_STALE scenarioPass — static cap applied correctly
7-day production shadow confirms no false deferral of risk-critical opsAudit log reviewZero risk-critical ops deferred

29. Developer Checklist

Ready-to-ship score: 27/27 sections complete · 100%

RequirementStatus
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