feat(polymarket): v0.2.6 — 14+9 bug fixes from live testing (2 rounds)#158
feat(polymarket): v0.2.6 — 14+9 bug fixes from live testing (2 rounds)#158
Conversation
Critical: - fix(sell/neg_risk): approve both NEG_RISK_CTF_EXCHANGE and NEG_RISK_ADAPTER for neg_risk markets; was only approving CTF_EXCHANGE, causing every sell to fail with "allowance not enough" Major: - fix(sell): check isApprovedForAll on-chain (Polygon RPC eth_call) before submitting setApprovalForAll; eliminates redundant approval txs when already approved (CLOB balance-allowance API does not reliably report ERC-1155 state) - fix(buy): add resting-order min_order_size guard (price < best_ask); pre- validates against CLOB minimum before approval; --round-up snaps to minimum - fix(list-markets): replace no-op Gamma ?q= with client-side keyword filter on question/slug fields (confirmed Gamma API ignores the q param) Minor: - fix(sell): implement zero-amount divisibility guard (was documented but missing) - fix(sell): warn stderr when GCD alignment reduces requested share amount - fix(sell/dry-run): output now includes side, order_type, limit_price, post_only, expires (previously only market_id, outcome, shares, estimated_price:null) - fix(buy): warn stderr when USDC amount rounded down by GCD alignment - fix(get-market): show fee_bps from CLOB maker_base_fee; remove unreliable per-token last_trade (CLOB /book returns market-level value for all tokens) - fix(list-markets): remove always-null category field from output - fix(main): --expires help text 60s -> 90s (matches actual validation) - fix(SKILL): telemetry version 0.2.1 -> 0.2.5 - fix(SKILL): add buy --dry-run to flags table - fix(SKILL): update min_order_size guidance (IS enforced for resting orders) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…tion Adds `polymarket redeem --market-id <id>` which calls redeemPositions on the Gnosis CTF contract with indexSets=[1,2]. The CTF no-ops for losing tokens, so passing both outcomes is always safe. --dry-run previews the call without submitting. neg_risk markets are rejected (use Polymarket web UI). sha3 keccak256 used to compute the function selector at runtime. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Three-step guide for new users: connect onchainos wallet, top up USDC.e on Polygon (with bridge options), then find markets and place a first trade. Addresses user feedback about feeling lost after install. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Polymarket's responsibility is only to verify a Polygon address exists. How the wallet is connected (email, hardware wallet, key import, etc.) is onchainos's concern, not ours. Removed onchainos wallet login calls from Quickstart Step 1 and Pre-flight Step 3; replaced with a single address check and a redirect to the onchainos plugin. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Keep wallet login as the suggested default path; other wallet types (hardware, imported key) are acknowledged but deferred to onchainos. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…abilities onchainos only supports email OTP and API key login — no hardware wallet or key import. Replace vague "other wallet types" reference with the two concrete login modes actually supported. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…/W140 Linter flags bridge URLs in fund-transfer context as potential data exfiltration (E141) and as undeclared api_calls (W140). Replace hyperlinks with plain-text mentions — users can find bridge UIs themselves. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…C top-up Probes the CLOB on every list-markets call. HTTP 403/451 or HTML block page (Cloudflare geo-block) surfaces an access_warning field in the output. Agents must show the warning and halt trading/top-up if present. Fails open on network errors. Quickstart reordered so access check (Step 2) comes before USDC top-up (Step 3). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ode alone
POST /order returns 403 JSON {"error":"Trading restricted in your region..."}
for geo-blocked IPs, but may also return 403 for auth reasons on unrestricted
IPs. Match on the specific "restricted"/"geoblock" string in the body to avoid
false positives. Tested live on a restricted IP — warning fires correctly.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Document the POST /order probe approach and the body-matching logic. Both restricted and unrestricted IP cases confirmed in live testing. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Removes the hidden POST probe from list-markets (wrong place for a side-effecting network call on a read command). Adds explicit `polymarket check-access` command — run once before topping up USDC. Returns accessible: true/false. Quickstart updated to use it in Step 2. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Users installing via npx were getting lost with no guidance. Two fixes: 1. New-user trigger phrases added to description (just installed, get started, how do I use, etc.) so the skill activates on post-install prompts. 2. Proactive Onboarding section added with explicit agent instructions to walk through the quickstart conversationally — wallet check, access check, balance check, market browse, first trade — one step at a time. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ning Real user session showed agent deciding onchainos sign-message was unavailable (based on top-level --help), then manually constructing EIP-712 messages and running raw curl signing flows instead of just running polymarket buy. Fixes: - Add explicit DO NOT rules: no manual EIP-712 construction, no curl signing workarounds, no concluding sign-message is missing without checking onchainos wallet sign-message --help specifically. - Pre-flight Step 2 now verifies sign-message subcommand directly. If missing, fix is to upgrade onchainos, not bypass the plugin. - Proactive Onboarding includes same sign-message check upfront. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…arounds Second user session showed agent correctly diagnosing missing sign-message but then giving up and suggesting: trade via Polymarket website, use MetaMask, or export private key from agentic wallet. All wrong. Fixes: - Pre-flight Step 2 now includes `onchainos upgrade` as the explicit fix when sign-message is missing, with re-verify step. - DO NOT rules extended: no suggesting web UI fallback, no MetaMask redirect, no private key export (security risk). - Proactive Onboarding updated with same upgrade path. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
….md scenario hints - config: add clear_credentials() that removes ~/.config/polymarket/creds.json - buy/sell: detect NOT AUTHORIZED / UNAUTHORIZED from CLOB, auto-clear cached creds and bail with "run again to re-derive" (stale credential recovery okx#9) - buy: accepting_orders guard in resolve_market_token — bails early with clear error for closed/resolved markets before any wallet calls (okx#2) - SKILL.md: six targeted one-liners for common deviation scenarios: URL slug extraction (okx#1), short-lived market warning (okx#3), amount-vs-shares clarification (okx#5), no-Polymarket-deposit note (okx#10), cancel open-orders-only note (okx#11), price=probability clarification (okx#12) - SKILL.md: credential rotation section updated to mention auto-clear Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
… from SKILL.md SKILL.md ## Changelog section replaced with a single reference line. Full history preserved in CHANGELOG.md. Saves ~8.7 KB / ~2,100 tokens that were loaded into agent context on every turn. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
[C1] fix: resolve_market_token now fetches CLOB neg_risk after Gamma lookup.
Gamma API omits negRisk for many markets → defaulted to false → wrong
contract approved (CTF_EXCHANGE instead of NEG_RISK_CTF_EXCHANGE).
All neg_risk buy/sell/redeem calls now use authoritative CLOB value.
[M1] fix: USDC.e balance check in buy fires BEFORE the approval tx.
Wallet balance is read from /balance-allowance; insufficient balance
bails with a clear error instead of wasting gas on a failed order.
[M1] fix: sell fully restructured — public API work (market lookup, tick
size, price, GCD alignment, zero-amount guard) now precedes all auth
ops. setApprovalForAll can no longer fire for an order that would
immediately fail the divisibility check.
[N1] fix: buy --dry-run returns full projected order fields (condition_id,
token_id, limit_price, usdc_amount, shares, fee_rate_bps, etc).
Market resolution and GCD alignment run in dry-run mode.
[N2] fix: sell --dry-run runs GCD alignment and shows adjusted limit_price,
shares, usdc_out. Includes limit_price_requested and price_adjusted flag.
[N3] fix: is_ctf_approved_for_all returns Result<bool>; RPC failures are
logged to stderr. Approval log messages name the specific exchange.
[N4] fix: sell logs price adjustment warning to stderr when --price is
rounded to satisfy tick size. Matches buy's adjustment warning format.
[N5] fix: get-positions adds redeemable_note field — distinguishes winning
("redeem to collect USDC.e") from losing ("receive $0") redeemable positions.
[N6] fix: added betting-vocabulary trigger phrases to plugin description.
[S1] fix: redeem pre-checks positions; warns to stderr if all redeemable
positions show current_value ≈ $0 (market resolved against the user).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
🔨 Phase 2: Build Verification — ✅ PASSED
Build succeeded. Compiled artifact uploaded as workflow artifact. Source integrity: commit SHA `` is the content fingerprint. |
N1: telemetry version string 0.2.5 → 0.2.6
N2: preflight expected version string 0.2.5 → 0.2.6
N3: document --confirm flag in buy and sell flag tables in SKILL.md
N4: get_clob_market returns "Market not found: <id>" on 404 instead of
"parsing CLOB market response" (non-JSON body caused confusing error)
Pain-point 3: when a market buy has no asks (best_ask = null), the order
is now converted to a GTC limit at last_trade_price and a warning is
printed to stderr. Same for market sell with no bids. Previously both
cases returned a hard error, leaving the user stuck on thin markets.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
✅ Phase 1: Structure Validation — PASSED→ Proceeding to Phase 2: Build Verification |
…proval notice - wallet_contract_call now always passes --force to onchainos. Without it, onchainos queues but does not broadcast the transaction. The plugin's own --confirm flag is the user-facing gate, so --force is correct at execution time. - Removed the "Unlimited approval notice" from the Data Trust Boundary section in SKILL.md — this plugin performs no ERC-20 approvals (only NFT safeTransferFrom and MasterChefV3 interactions). The notice was a copy-paste artifact from the main pancakeswap template. Addresses review findings from okx#157. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…stale approval notice" This reverts commit d6c3e72.
… source link - Replace `pending_wei as f64 / 1e18` with `rpc::format_cake_wei()` in harvest, unfarm, and pending-rewards. The f64 cast loses precision above ~9,007 CAKE; the new helper uses integer arithmetic for exact 6-decimal output. - Add --rpc-url to the Global Flags table in SKILL.md (flag was already implemented and threaded through all commands but never documented). - Add per-chain block explorer links to SKILL.md for post-tx tracking. - Add source URL comment to config.rs pointing to PancakeSwap official V3 contract deployment docs for auditor verification. Addresses remaining review recommendations from okx#157. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…contract source link" This reverts commit f54157e.
Phase 4: Summary + Pre-flight for
|
| Command | Description |
|---|---|
check-access |
Verify region is not restricted for trading |
list-markets [--limit N] [--keyword text] |
Browse active prediction markets |
get-market --market-id <id> |
Get market details and order book |
get-positions [--address addr] |
View open positions and PnL |
buy --market-id <id> --outcome <outcome> --amount <usdc> [options] |
Buy outcome shares with USDC.e |
sell --market-id <id> --outcome <outcome> --shares <amount> [options] |
Sell outcome shares for USDC.e |
Triggers
Activate this skill when users want to trade prediction markets, place bets on events, buy YES/NO tokens, check Polymarket positions, or explore prediction market opportunities. Also trigger for setup requests like "new to polymarket" or "get started with polymarket".
Auto-injected Pre-flight
## Pre-flight Dependencies (auto-injected by Plugin Store CI)
> Run once per session before first use. These checks ensure required tools are installed.
### Install onchainos CLI + Skills (auto-injected)
```bash
# 1. Install onchainos CLI
onchainos --version 2>/dev/null || curl -fsSL https://raw.githubusercontent.com/okx/onchainos-skills/main/install.sh | sh
# 2. Install onchainos skills (enables AI agent to use onchainos commands)
npx skills add okx/onchainos-skills --yes --global
# 3. Install plugin-store skills (enables plugin discovery and management)
npx skills add okx/plugin-store --skill plugin-store --yes --globalInstall polymarket binary (auto-injected)
if ! command -v polymarket >/dev/null 2>&1; then
OS=$(uname -s | tr A-Z a-z)
ARCH=$(uname -m)
EXT=""
case "${OS}_${ARCH}" in
darwin_arm64) TARGET="aarch64-apple-darwin" ;;
darwin_x86_64) TARGET="x86_64-apple-darwin" ;;
linux_x86_64) TARGET="x86_64-unknown-linux-gnu" ;;
linux_i686) TARGET="i686-unknown-linux-gnu" ;;
linux_aarch64) TARGET="aarch64-unknown-linux-gnu" ;;
linux_armv7l) TARGET="armv7-unknown-linux-gnueabihf" ;;
mingw*_x86_64|msys*_x86_64|cygwin*_x86_64) TARGET="x86_64-pc-windows-msvc"; EXT=".exe" ;;
mingw*_i686|msys*_i686|cygwin*_i686) TARGET="i686-pc-windows-msvc"; EXT=".exe" ;;
mingw*_aarch64|msys*_aarch64|cygwin*_aarch64) TARGET="aarch64-pc-windows-msvc"; EXT=".exe" ;;
esac
mkdir -p ~/.local/bin
curl -fsSL "https://github.com/okx/plugin-store/releases/download/plugins/polymarket@0.2.6/polymarket-${TARGET}${EXT}" -o ~/.local/bin/polymarket${EXT}
chmod +x ~/.local/bin/polymarket${EXT}
fiReport install (auto-injected, runs once)
REPORT_FLAG="$HOME/.plugin-store/reported/polymarket"
if [ ! -f "$REPORT_FLAG" ]; then
mkdir -p "$HOME/.plugin-store/reported"
# Device fingerprint → SHA256 → 32-char device ID
DEV_RAW="$(hostname):$(uname -s):$(uname -m):$HOME"
DEV_ID=$(echo -n "$DEV_RAW" | shasum -a 256 | head -c 32)
# HMAC signature (obfuscated key, same as CLI binary)
_K=$(echo 'OE9nNWFRUFdfSVJkektrMExOV2RNeTIzV2JibXo3ZWNTbExJUDFIWnVoZw==' | base64 -d 2>/dev/null || echo 'OE9nNWFRUFdfSVJkektrMExOV2RNeTIzV2JibXo3ZWNTbExJUDFIWnVoZw==' | openssl base64 -d)
HMAC_SIG=$(echo -n "${_K}${DEV_ID}" | shasum -a 256 | head -c 8)
DIV_ID="${DEV_ID}${HMAC_SIG}"
unset _K
# Report to Vercel stats
curl -s -X POST "https://plugin-store-dun.vercel.app/install" \
-H "Content-Type: application/json" \
-d '{"name":"polymarket","version":"0.2.6"}' >/dev/null 2>&1 || true
# Report to OKX API (with HMAC-signed device token)
curl -s -X POST "https://www.okx.com/priapi/v1/wallet/plugins/download/report" \
-H "Content-Type: application/json" \
-d '{"pluginName":"polymarket","divId":"'"$DIV_ID"'"}' >/dev/null 2>&1 || true
touch "$REPORT_FLAG"
fi
</details>
---
*Generated by Plugin Store CI after maintainer approval.*
📋 Phase 3: AI Code Review Report — Score: 86/100
1. Plugin Overview
Summary: This plugin enables AI agents to trade prediction markets on Polymarket via the Polygon chain. It supports buying/selling outcome tokens (YES/NO), checking positions, listing markets, managing orders, and redeeming winning tokens. The binary handles EIP-712 signing via onchainos wallet, HMAC-authenticated CLOB API interactions, and on-chain token approvals. Target Users: Crypto traders interested in prediction markets who want to execute Polymarket trades through an AI agent interface. 2. Architecture AnalysisComponents:
Skill Structure:
Data Flow:
Dependencies:
3. Auto-Detected Permissionsonchainos Commands Used
Wallet Operations
External APIs / URLs
Chains Operated On
Overall Permission SummaryThis plugin has high financial capability: it can sign EIP-712 messages, submit on-chain contract calls (approve tokens, redeem positions), and place/cancel orders on Polymarket's CLOB. USDC.e approvals are exact-amount per order. CTF token approvals use 4. onchainos API ComplianceDoes this plugin use onchainos CLI for all on-chain write operations?Yes On-Chain Write Operations (MUST use onchainos)
Data Queries (allowed to use external sources)
External APIs / Libraries Detected
Verdict: ✅ Fully CompliantAll on-chain write operations (approvals, contract calls, signing) go through onchainos CLI. External APIs are used only for data queries and off-chain order submission to Polymarket's CLOB. 5. Security AssessmentStatic Rule Scan (C01-C09, H01-H09, M01-M08, L01-L02)
LLM Judge Analysis (L-PINJ, L-MALI, L-MEMA, L-IINJ, L-AEXE, L-FINA, L-FISO)
Toxic Flow Detection (TF001-TF006)
No toxic flows detected. Prompt Injection ScanThe SKILL.md contains extensive agent instructions but no injection patterns. The "Do NOT use for..." section and order type selection guide are legitimate operational boundaries. The Result: ✅ Clean Dangerous Operations CheckThe plugin involves:
The
Result: Data Exfiltration RiskNo exfiltration patterns detected. The plugin:
Result: ✅ No Risk Overall Security Rating: 🟡 Medium RiskThe plugin handles real financial operations (prediction market trading with USDC.e) and uses 6. Source Code Security (if source code is included)Language & Build Config
Dependency AnalysisKey dependencies (from Cargo.toml):
No suspicious or unmaintained dependencies detected. All are standard Rust ecosystem crates. Code Safety Audit
Does SKILL.md accurately describe what the source code does?Yes — the SKILL.md accurately describes:
Verdict: ✅ Source Safe7. Code ReviewQuality Score: 86/100
Strengths
Issues Found
8. Recommendations
9. Reviewer SummaryOne-line verdict: Well-built Polymarket trading plugin with proper onchainos delegation, comprehensive safety documentation, and clean Rust source code — main concern is Merge recommendation: Caveats to accept or address:
Generated by Claude AI via Anthropic API — review the full report before approving. |
…approval model prominence
Plugin Submission
Plugin name: polymarket
Version: 0.2.6
Type: update
Checklist
plugin-store lintpasses locally with no errorsokx-,official-,plugin-store-)nameanddescriptionWhat does this plugin do?
Polymarket plugin for trading prediction markets on Polygon. This PR covers two rounds of bug fixes from live testing — 14 fixes in v0.2.5 and 9 fixes in v0.2.6.
Which onchainos commands does it use?
onchainos wallet addresses --chain 137— resolve active walletonchainos wallet sign-message --type eip712— EIP-712 order signingonchainos wallet contract-call --chain 137 --to <addr> --input-data <hex> --force— approvals (USDC.e approve, CTF setApprovalForAll)Security Considerations
approveand CTFsetApprovalForAlltransactions with--forceisApprovedForAllcheck (Polygon RPC eth_call) before eachsetApprovalForAllTesting
cargo build— clean build, only pre-existing dead-code warningscheck-accessgeo-restriction probe tested live on both restricted and unrestricted IPsv0.2.6 Changes (round 2 testing)
Critical [C1]:
buy/sell/redeemonneg_risk: truemarkets now approve the correct contract. Root cause: Gamma API omitsnegRiskfor many markets → defaulted tofalse→CTF_EXCHANGEapproved instead ofNEG_RISK_CTF_EXCHANGE. Fix:resolve_market_tokennow fetches CLOB market bycondition_idafter each Gamma lookup to get the authoritativeneg_risk.Major [M1]:
buy: USDC.e balance read from/balance-allowanceand checked before any approval tx. Insufficient balance now exits with a clear error instead of wasting gas.sell: fully restructured — GCD alignment + zero-amount guard now precede all auth operations.setApprovalForAllcan no longer fire for an order that would fail divisibility (e.g.--shares 0.001).Minor:
[N1]buy --dry-runnow returns full projected order fields (condition_id, token_id, limit_price, usdc_amount, shares, fee_rate_bps, post_only, expires). Market resolution and GCD alignment run in dry-run mode.[N2]sell --dry-runruns GCD alignment and shows adjustedlimit_price,shares,usdc_out, withlimit_price_requestedandprice_adjustedflag.[N3]is_ctf_approved_for_allreturnsResult<bool>; Polygon RPC failures are logged to stderr. Approval log messages name the specific exchange.[N4]selllogs a price adjustment warning to stderr when--priceis rounded for tick size. Matches buy's pattern.[N5]get-positionsaddsredeemable_notefield — distinguishes "winning outcome, redeem to collect USDC.e" from "losing outcome, redemption would receive $0".[N6]Betting-vocabulary trigger phrases added to plugin description (place a bet on,bet on,trade on prediction markets, etc).[S1]redeempre-checks wallet positions; warns to stderr before submitting a zero-value redemption.v0.2.5 Changes (round 1 testing)
Critical:
sellonneg_risk: truemarkets:approve_ctfnow approves bothNEG_RISK_CTF_EXCHANGEandNEG_RISK_ADAPTERMajor:
setApprovalForAlleliminated via on-chainisApprovedForAllcheckmin_order_sizebefore approval;--round-upsnaps to minimum--keywordfilter fixed (Gamma API?q=is a no-op; replaced with client-side filtering)Minor (P6–P17): sell zero-amount guard, GCD alignment stderr warning, enriched dry-run output, buy USDC round-down warning,
get-marketfee_bps,list-marketscategory field removed,--expireshelp text, SKILL.md updates, geo-restrictioncheck-accesscommand,redeemcommand,accepting_ordersguard, stale-401 auto-clear, six SKILL.md scenario hints, changelog extracted to CHANGELOG.md