feat(integrations): Polymarket trading + market data (#1398, venue 1/3)
Summary
- Adds the Polymarket integration (read + trading) — the first of three venues called out in #1398 (Kalshi + Hyperliquid follow as separate PRs on the same
#1398umbrella). - Read surface: market / event / orderbook / price discovery via Gamma + CLOB public APIs, plus authenticated reads (positions, balance, open orders, USDC.e allowance) once an EOA is configured.
- Trading surface:
place_order+cancel_orderagainst the Polymarket CLOB with EIP-712 typed-data signing on Polygon (chain_id 137). - Approval gate: every write action requires
arguments.approved == true. Stopgap until #1339's formal approval gate lands —TODO(#1339)recorded inline. - Capability catalog split:
skills.polymarket_readonly(browse) +skills.polymarket_trading(Beta, Action, destination = "Polymarket CLOB API").
Problem
Per #1398, Polymarket, Kalshi, and Hyperliquid each need explicit tool surfaces rather than being folded into vague "exchange support". Today the repo has no exchange / prediction-market domain in the core, no venue-specific auth or signing primitives, and no tool surface for balances, positions, market discovery, or order flow. Without that, the agent can hold a wallet but cannot reason over a real trading venue.
Solution
New tool module src/openhuman/tools/impl/network/polymarket.rs — single PolymarketTool exposing 11 actions tagged by action enum:
| Surface | Actions |
|---|---|
| Public reads | list_markets, get_market, list_events, get_orderbook, get_price |
| Authenticated reads | get_positions, get_balance, get_open_orders, get_usdc_allowance |
| Writes | place_order, cancel_order |
Signing primitives:
src/openhuman/tools/impl/network/clob_auth.rs— L1 handshake (POST/auth/api-keyw/ fallback/auth/derive-api-key) + L2 HMAC-SHA256 header signer overtimestamp + method + path + body. Timestamp in unix seconds.src/openhuman/tools/impl/network/polymarket_orders.rs— EIP-712 typed-dataOrderstruct +domain_separator(chain_id = 137, Polymarket CLOB Exchange contract) +sign_orderreturning hex signature.
Polygon RPC wiring kept narrow: polygon_rpc_url lives in PolymarketConfig (no new WalletChain::Polygon variant) so the blast radius stays inside the tool module. USDC.e allowance reads go through eth_call over that RPC.
Config (src/openhuman/config/schema/tools.rs) — additive fields:
eoa_address: Option<String>polygon_rpc_url: String(defaulthttps://polygon-rpc.com)usdc_contract: String(default0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174— USDC.e bridged on Polygon, not native USDC)clob_exchange_contract: String(default0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E)derived_clob_credentials: Option<PolymarketClobCredentials>(persisted across runs; will migrate to SecretStore once #1900 lands)
Approval gate: require_write_approval(approved: Option<bool>) runs before any write action issues HTTP. If approved != true, returns Polymarket write requires explicit user approval. Re-invoke with arguments.approved = true after confirming with the user. — no HTTP touched. Approval-gate tests verify the no-HTTP property.
Retry / timeout: 3 × 500ms backoff on 429 / 5xx, no retry on 4xx, explicit deadline error on user-configured timeout_secs (default 15s). Same shape as siblings to be added by the Kalshi + Hyperliquid PRs.
Submission Checklist
- [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
- [x] Diff coverage ≥ 80% — 22 polymarket lib tests cover: 11-action schema deserialization; happy paths for
list_markets,get_market(id + slug),list_events,get_orderbook,get_price,get_positions,get_balance(USDC.e default),get_open_orders,get_usdc_allowance(Polygoneth_call),place_order(signed POST); approval gate (place_orderandcancel_orderno-HTTP on missing approval); HMAC signing fixture (clob_auth); EIP-712 fixture (polymarket_orders, chain_id 137); side normalisation; 4xx / 5xx / timeout. Perfeedback_cargo_test_lib_full_run.mdthe full-lib run OOMs locally; CI gates the full matrix. - [x] N/A: coverage matrix —
docs/TEST-COVERAGE-MATRIX.mddoes not have a Polymarket / trading-venue row yet; the matrix entry will land in the venue-3 PR alongside Hyperliquid + Kalshi rows so the row covers the whole#1398umbrella in one edit. - [x] All affected feature IDs from the matrix are listed in the PR description under
## Related - [x] No new external network dependencies introduced —
polymarket_tests.rsuses an in-processTcpListenermock; Gamma + CLOB endpoints are configurable so smoke can target a local mock per Testing Strategy. - [x] N/A: release manual smoke — Polymarket trading is feature-flagged via
integrations.polymarket.enabledand not part of the release-cut surface yet. - [x] N/A:
Closes #1398— #1398 covers three venues; this PR ships venue 1/3. Closing reference will land on the venue-3 PR. See## Related.
Impact
- Runtime: desktop, opt-in via
integrations.polymarket.enabledconfig flag. Off-by-default. No behavioural change for users who don't touch the flag. - Network: Gamma (
gamma-api.polymarket.com), CLOB (clob.polymarket.com), and a Polygon RPC (defaultpolygon-rpc.com). All configurable. - Security: writes are gated by the
approved=truestopgap and an EIP-712 typed-data signature over the order on chain_id 137. L1 handshake derives a per-EOA L2 API key + secret which lives in config (will move to SecretStore after #1900). No raw wallet privkey leaves the wallet module. - Performance: cold-path retry adds 3 × 500ms on
5xx/429; hot path one HTTP per action. Nonce fetched per submission via CLOB/nonce?user=— extra round-trip on eachplace_order(documented; caching deferred). - Compatibility: additive — new RPC actions on the existing
tools_polymarket_executecontroller. No public RPC surface change beyond the action enum widening.
Related
- Refs #1398 (Polymarket — venue 1/3). The umbrella issue stays open until Kalshi + Hyperliquid PRs land.
- Closes #1398: NO — partial scope. Follow-up PRs will close it.
- Follow-up PR(s)/TODOs:
- Kalshi (venue 2/3) — same approval-flag stopgap; queued.
- Hyperliquid (venue 3/3) — closes
#1398on merge; queued. - Migrate
derived_clob_credentialsstorage to SecretStore once #1900 lands. - Replace
approved=truestopgap with formal approval gate once #1339 lands.
AI Authored PR Metadata (required for Codex/Linear PRs)
Linear Issue
- Key: N/A (GitHub-only issue)
- URL: https://github.com/tinyhumansai/openhuman/issues/1398
Commit & Branch
- Branch:
feat/1398-polymarket - Commit SHA: top =
23176452(test/docs), 12 commits ahead of base + merge of upstream/main
Validation Run
- [x]
cargo check - [x]
cargo test --lib polymarket— 22 passed - [x] Manual smoke: local TcpListener mock on :8901 with
[integrations.polymarket] gamma_base_url + clob_base_urloverridden in user config —list_markets+get_marketaction returned mock fixtures viaopenhuman.tools_polymarket_execute. - [x]
pnpm typecheck— N/A (no frontend changes in this PR)
Validation Blocked
command:cargo test --lib(full lib run)error:SIGKILL'd locally perfeedback_cargo_test_lib_full_run.mdimpact:CI gates the full matrix; scope-filtered run passes 22/22
Behavior Changes
- Intended: add 11-action Polymarket tool gated behind
integrations.polymarket.enabled; trading writes gated byapproved=true - User-visible: agent can browse Polymarket markets / events / orderbooks / prices, read EOA-owned positions / balance / open orders, and (with explicit approval) place / cancel limit orders
Parity Contract
- Legacy behavior preserved: integrations disabled by default; existing read-only landing from earlier on this branch unchanged for callers that only use the public-data surface
- Guard/fallback/dispatch parity checks:
tools_polymarket_executealready routes byactionfield; new actions auto-reachable without schema regen. Approval gate is a function-local check, not a separate middleware — migration toApprovalGate(#1339) will replacerequire_write_approvalcall sites.
Summary by CodeRabbit
-
New Features
- Polymarket integration: market discovery, orderbook/price viewing, authenticated balance/position queries, and order placement/cancellation (writes gated by explicit approval)
- Configurable integration toggle with optional credential persistence and network timeout settings; capabilities marked Beta
-
Documentation
- New Polymarket integration guide covering setup, authentication/signing flows, headers/nonce rules, error/retry behavior, and required permissions
-
Tests
- Comprehensive unit/integration tests and fixtures covering discovery, CLOB reads, signed requests, write flows, and error handling
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] ▶️ Resume reviews
- [ ] 🔍 Trigger review
📝 Walkthrough
Walkthrough
Adds a Polymarket integration: docs, configuration schema, CLOB credential derivation and signing, EIP-712 order signing, a PolymarketTool implementing read/write actions (Gamma/CLOB/Polygon flows), RPC/controller wiring, capability catalog entries, and comprehensive tests and fixtures.
Changes
Polymarket Integration v1
| Layer / File(s) | Summary |
|---|---|
Documentation and capability declaration gitbooks/SUMMARY.md, gitbooks/developing/integrations/polymarket.md, src/openhuman/about_app/catalog.rs |
Docs entry and two new capability catalog entries for Polymarket read-only and trading. |
Configuration schema and defaults src/openhuman/config/..., src/openhuman/config/schema/tools.rs |
Adds PolymarketClobCredentials, PolymarketConfig, defaults (endpoints, RPC, contracts, timeout), and wires integrations.polymarket into IntegrationsConfig. |
Network module wiring src/openhuman/tools/impl/network/mod.rs |
Adds clob_auth, polymarket, polymarket_orders modules and re-exports PolymarketTool. |
CLOB authentication infrastructure src/openhuman/tools/impl/network/clob_auth.rs |
Implements credential derivation (POST /auth/api-key with derive fallback), L1 EIP-712 header signing, secret decoding, HMAC-SHA256 CLOB request signing, response parsing, and tests. |
EIP-712 order signing src/openhuman/tools/impl/network/polymarket_orders.rs |
Defines Order model, EIP-712 domain builder, sign_order, side normalization, and unit tests. |
PolymarketTool implementation src/openhuman/tools/impl/network/polymarket.rs |
Implements PolymarketTool (constructor, request enum), dispatch for Gamma/CLOB/Polygon reads/writes, credential caching/persistence, signer resolution, nonce parsing, signed order build/submit/cancel, HTTP helpers with bounded retries/backoff, Tool trait wiring, and helpers. |
RPC/controller registration and wallet access src/openhuman/tools/ops.rs, src/openhuman/tools/schemas.rs, src/openhuman/wallet/mod.rs |
Conditionally registers the tool, adds tools_polymarket_execute controller/schema and handler, updates test counts, and exposes ops::secret_material crate-visible. |
Comprehensive test suite and fixtures src/openhuman/tools/impl/network/polymarket_tests.rs, tests/fixtures/polymarket/* |
Adds Tokio mock server, extensive end-to-end action tests (discovery, orderbook/price, authenticated reads, allowance), write approval/security gating tests, retry/timeout semantics tests, utility unit tests, and JSON fixtures. |
Sequence Diagram(s)
sequenceDiagram
participant Client
participant PolymarketTool
participant GammaAPI
participant CLOBAPI
participant PolygonRPC
participant LocalWallet
Client->>PolymarketTool: request(action, arguments, approved?, user?)
PolymarketTool->>GammaAPI: GET /markets or /events (discovery)
PolymarketTool->>CLOBAPI: GET signed endpoints (positions/balance/open_orders) with signed headers
PolymarketTool->>PolygonRPC: POST eth_call (allowance) -> returns hex U256
Client->>PolymarketTool: place_order (approved=true)
PolymarketTool->>LocalWallet: derive Polymarket signer & sign EIP-712 order
PolymarketTool->>CLOBAPI: POST /order with signed order and signed headers
CLOBAPI-->>PolymarketTool: order response / nonce
PolymarketTool-->>Client: ToolResult (data or error)
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
"A rabbit in a patch, with ledger and quill,
I hop through docs and code with a thrill.
Signed orders nibble, tests jump like leaves,
Credentials tucked safe beneath tiny sleeves.
Hooray—Polymarket blooms; the rabbit believes!"
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 23.14% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | Title 'feat(integrations): Polymarket trading + market data (#1398, venue 1/3)' clearly and concisely summarizes the main change—adding Polymarket trading and market data integration functionality. |
| Linked Issues check | ✅ Passed | All core coding requirements from #1398 are met: venue-specific tool architecture defined, 11 actions exposed (reads/authenticated reads/writes), EIP-712 signing implemented, auth/retry semantics with ~22 tests, and diff includes comprehensive test coverage. |
| Out of Scope Changes check | ✅ Passed | All changes directly support Polymarket integration: config schemas, CLOB auth, order signing, tool implementation, tests, and fixtures are in-scope per #1398; no unrelated wallet/swap/generic exchange abstractions or autonomous trading loops were introduced. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
Comment @coderabbitai help to get the list of available commands and usage tips.
@coderabbitai review
Review triggered. Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.✅ Actions performed
[!TIP] For best results, initiate chat on the files or code changes.
@ozpool Thanks for the follow-up. The fix in f3ca1901 looks correct — dropping derive(Debug) and replacing it with a custom redacting impl that prints all three fields as <redacted> brings ClobAuthResponse in line with the ClobCredentials / PolymarketClobCredentials treatment already in place. Consistent redaction across all three credential-bearing types is the right call.
@coderabbitai — addressing the duplicate finding on clob_auth.rs:341-349 (ClobAuthResponse Debug leak): Addressed in f3ca1901. Dropped the derive(Debug) and replaced with a custom redacting impl that matches the ClobCredentials / PolymarketClobCredentials treatment from earlier commits — all three fields print as <redacted>.
[!TIP] For best results, initiate chat on the files or code changes.
@oxoxDev Thanks for the confirmation. The fix in f3ca1901 looks correct — dropping derive(Debug) and replacing it with a custom redacting impl that prints all three fields as <redacted> brings ClobAuthResponse in line with the ClobCredentials / PolymarketClobCredentials treatment already in place. Consistent redaction across all credential-bearing types is the right call.
@M3gA-Mind — thank you for the thorough pass. Going through item by item. Eight commits landed on the branch addressing your review, plus an explicit deferral list for the items that need wider architectural alignment.
Must-fix (3/3) ✅
| # | Item | Commit |
|---|---|---|
| 1 | is_concurrency_safe → false for write actions (nonce collision) |
012c6397 |
| 2 | CSPRNG salt via OsRng (no more rand::random) |
a88af32c |
| 3 | ensure_https guard on polygon_rpc_url in allowance read |
e2e54833 |
Should-fix (3/3) ✅
| # | Item | Commit |
|---|---|---|
| 4 | Re-derive timestamp before fallback in derive_credentials |
b440dc72 |
| 5 | Extract send_with_retry helper — dedupes ~180 LOC across get_json / post_json_raw / delete_json |
36034502 |
| 6 | get_market with neither market_id nor slug test |
cf3604c3 (POST→GET fallback + persist-failure tests deferred — see below) |
Architectural cleanup (in this PR) ✅
| # | Item | Commit |
|---|---|---|
| 7 | Unify ClobCredentials + PolymarketClobCredentials (delete the dual struct + From-impl glue) |
2b098ee4 |
| 8 | ensure_clob_credentials now holds the cache lock across derive_credentials — single-flight derivation, no more concurrent-caller race |
2b098ee4 |
| 9 | Inline doc comments for non-obvious decisions: approval-gate stopgap (with security note), round_down/round_normal asymmetry, raw ERC-20 ABI encoding, persist_clob_credentials best-effort guarantee, derived_clob_credentials plaintext threat model |
2b4ce323 |
Deferred to follow-up (explicit rationale)
| Item | Why deferred |
|---|---|
f64 → rust_decimal::Decimal for price/size |
Crate addition sets precedent for the Kalshi + Hyperliquid PRs (venues 2/3 + 3/3 on this umbrella). Want architectural buy-in on Decimal vs string-passthrough before paying the dep cost on all three venues. Filing as follow-up after the umbrella merges. |
File-size split of polymarket.rs (1419 LOC, >2.8× the project guideline) |
Genuine refactor that needs module-boundary discussion — likely polymarket/{tool.rs, request.rs, signing.rs, allowance.rs}. Will land in a dedicated PR after the venue-3 PR opens (so Kalshi/Hyperliquid can adopt the same shape). |
Replace unsafe { std::env::set_var } with serial_test crate |
The existing TEST_ENV_LOCK static std::sync::Mutex<()> already serializes env-var tests project-wide; the unsafe blocks are an artefact of Rust 2024 edition's tightened std API and exist throughout the codebase. Migrating just polymarket tests to serial_test adds a new dev-dep + breaks the project's existing serialization convention. Worth a project-wide RFC. |
| Credential-derivation POST→GET fallback test + persist-failure path test | Requires a multi-response mock fixture (the existing route helper takes a single VecDeque per path). Cleanest landed alongside the test-helper refactor I'm planning for Kalshi/Hyperliquid (whose RSA-PSS + EIP-712 signing paths need similar multi-response tests). |
SecretStore migration for derived_clob_credentials |
Explicitly blocked on #1900. Threat-model is now documented inline so the gap is visible until that lands. |
What you might also want to look at
- The HTTPS guard carves out
127.0.0.1/localhost/[::1]for the in-processTcpListenermock harness — explicitly documented as a test affordance. Real Polymarket CLOB hosts don't resolve to loopback. If you'd prefer#[cfg(test)]-gated allowance instead, happy to refactor. is_concurrency_safereturnsfalseonly forplace_order/cancel_order— reads stay concurrency-safe. Want it tighter (e.g. include credentialed reads likeget_positions)? They don't have the nonce-collision pattern but do share the cache-warm-up window.- The
require_write_approvaldoc comment now spells out the framework gate (SecurityPolicy::enforce_tool_operation) + stopgap layering so reviewers know both must remain until #1339.
Re-pushed all 9 commits to oxoxDev:feat/1398-polymarket. CR is re-running on the latest tip.