Skip to content

feat(polymarket-plugin): add quickstart command with 7-state onboarding (v0.4.9)#297

Merged
Noah3595 merged 2 commits intookx:mainfrom
GeoGu360:feat/polymarket-plugin-add-quickstart
Apr 21, 2026
Merged

feat(polymarket-plugin): add quickstart command with 7-state onboarding (v0.4.9)#297
Noah3595 merged 2 commits intookx:mainfrom
GeoGu360:feat/polymarket-plugin-add-quickstart

Conversation

@GeoGu360
Copy link
Copy Markdown

Summary

Adds a quickstart subcommand to polymarket-plugin that acts as a single-call status probe: it checks CLOB region access, reads EOA + proxy balances, queries open positions, and returns a status + ready-to-run next_command. Designed as the first command an agent (or new user) runs — every other command is dispatched from its output.

  • New file: src/commands/quickstart.rs (303 lines) with a 7-state state machine
  • Wired into src/commands/mod.rs and src/main.rs (listed first in --help)
  • SUMMARY.md: bold section titles → H2, Quick Start rewritten as a status-dispatched checklist
  • SKILL.md: new ### quickstart section with params / output fields / status table / agent flow
  • Version bump: 0.4.80.4.9 (PATCH, per owner decision) across 4 files + inline SKILL.md refs

State machine

Defaults to guiding users toward the gasless proxy flow:

status Condition next_command
restricted CLOB blocks this IP (US/OFAC) polymarket-plugin check-access
active Has open positions polymarket-plugin get-positions
proxy_ready Proxy funded ≥ $5 USDC.e polymarket-plugin list-markets
needs_deposit Proxy set up, under-funded; EOA ≥ $5 polymarket-plugin deposit --amount <N>
needs_setup EOA ≥ $5, proxy not set up polymarket-plugin setup-proxy
low_balance EOA has some USDC.e but < $5 polymarket-plugin balance
no_funds EOA empty polymarket-plugin balance

Minimum balance threshold: $5 for both EOA and proxy. Default deposit amount: 90 % of EOA USDC.e, floored to cents, clamped ≥ $5.

Implementation notes

  • Non-blocking RPC: balance and position calls use unwrap_or(...) so a transient RPC failure doesn't abort the command — it still emits guidance based on whatever state it could resolve. Matches the hyperliquid-plugin quickstart pattern. Explicit code comment explains the trade-off.
  • No new external domains: reuses existing check_clob_access, get_pol_balance, get_usdc_balance, get_positions helpers. plugin.yaml api_calls unchanged.
  • No new CI risk: no new warnings, binary --version reports 0.4.9, quickstart --help shows only the documented --address flag.

Test plan

  • cargo build passes (0 new warnings; 17 pre-existing dead-code warnings unchanged)
  • polymarket-plugin --versionpolymarket 0.4.9
  • polymarket-plugin quickstart --help shows --address parameter
  • polymarket-plugin --help lists quickstart as the first command
  • 4-file version consistency verified (plugin.yaml / SKILL.md / Cargo.toml / plugin.json)
  • No 0.4.8 refs remain anywhere in the skill directory
  • common-bugs-knowledge-base scan: GEN-001 / EVM-012 / EVM-006 / EVM-005 / api_calls all clear
  • Live run of each status branch (reviewer: pls verify against a test wallet if convenient)

🤖 Generated with Claude Code

…ng (v0.4.9)

Add a `quickstart` subcommand that acts as a single-call status probe:
checks CLOB region access, reads EOA POL + USDC.e balances, reads proxy
USDC.e balance (when `setup-proxy` has been run), and queries open
positions on the maker wallet. Emits a single JSON with a `status`
field plus a ready-to-run `next_command` for the recommended action.

State machine (7 states, defaults to guiding users toward the gasless
proxy flow):
- restricted     — CLOB blocked this IP (US/OFAC) → change region
- active         — has open positions → get-positions
- proxy_ready    — proxy funded ≥ $5 → list-markets → buy
- needs_deposit  — proxy set up but under-funded; EOA ≥ $5 → deposit
- needs_setup    — EOA ≥ $5, proxy not set up → setup-proxy (default)
- low_balance    — EOA has some USDC.e but < $5 → top up
- no_funds       — EOA empty → send USDC.e to EOA

Minimum balance threshold is $5 for both EOA and proxy wallets. The
suggested deposit amount is 90 % of EOA USDC.e, floored to cents, and
clamped to >= $5.

Non-blocking RPC handling: balance/position calls use unwrap_or to
tolerate transient failures — the command still emits guidance based
on whatever state it could resolve, instead of exiting with an error.
This matches the hyperliquid quickstart pattern.

Docs:
- SUMMARY.md: convert `**X**` headers to `## X`, rewrite Quick Start
  as a status-dispatched checklist keyed off `quickstart` output
- SKILL.md: add `### quickstart` section with parameters, output
  fields, status table, and agent flow; add quickstart row to the
  Commands table; bump inline 0.4.8 → 0.4.9 references

No new external API domains — reuses existing check_clob_access,
get_pol_balance, get_usdc_balance, and get_positions helpers that are
already covered by plugin.yaml api_calls.

Version bump: 0.4.8 → 0.4.9 (PATCH, per owner decision).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 21, 2026

🔨 Phase 2: Build Verification — ✅ PASSED

Plugin: polymarket-plugin | Language: rust
Source: @

Compiled from developer source code by our CI. Users install our build artifacts.

Build succeeded. Compiled artifact uploaded as workflow artifact.


Source integrity: commit SHA `` is the content fingerprint.

…sites

Rework the POL-for-gas bullet to lead with the recommended
(POLY_PROXY) path instead of EOA. This aligns SUMMARY.md with the
product direction already reflected elsewhere:

- `quickstart` defaults to guiding new users toward `setup-proxy`
- SKILL.md's mode comparison table labels POLY_PROXY as "recommended"

The code-level `TradingMode::default() == Eoa` is intentionally kept
(backward compat: existing creds.json files without a `mode` field
would otherwise deserialize to PolyProxy with no proxy_wallet and
break `buy`/`sell`). This change is docs-only.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@github-actions
Copy link
Copy Markdown
Contributor

✅ Phase 1: Structure Validation — PASSED

Linting skills/polymarket-plugin...

  ⚠️  [W100] suspicious pattern: 'base64' — contains base64 reference — may embed hidden content
  ⚠️  [W100] suspicious pattern: 'curl ' — contains curl command — external network request

✓ Plugin 'polymarket-plugin' passed with 2 warning(s)

→ Proceeding to Phase 2: Build Verification

@github-actions
Copy link
Copy Markdown
Contributor

Phase 4: Summary + Pre-flight for polymarket-plugin

Review below. AI Code Review is in a separate check.


SUMMARY.md

polymarket-plugin

Trade prediction markets on Polymarket — buy and sell YES/NO outcome tokens on Polygon with automated signing and gasless proxy trading.

Highlights

  • Trade binary (YES/NO) and categorical prediction markets on Polygon
  • Two trading modes: direct EOA trading or gasless proxy wallet trading
  • Automated EIP-712 order signing via onchainos wallet integration
  • Support for 5-minute crypto up/down markets with dedicated commands
  • Real-time market data, order books, and position tracking
  • Automatic API credential derivation and caching
  • Built-in region restrictions and access verification
  • Winning token redemption after market resolution
SKILL_SUMMARY.md

polymarket-plugin

Trade prediction markets on Polymarket — buy and sell YES/NO outcome tokens on Polygon with automated signing and gasless proxy trading.

Highlights

  • Trade binary (YES/NO) and categorical prediction markets on Polygon
  • Two trading modes: direct EOA trading or gasless proxy wallet trading
  • Automated EIP-712 order signing via onchainos wallet integration
  • Support for 5-minute crypto up/down markets with dedicated commands
  • Real-time market data, order books, and position tracking
  • Automatic API credential derivation and caching
  • Built-in region restrictions and access verification
  • Winning token redemption after market resolution

---SEPARATOR---

polymarket-plugin -- Skill Summary

Overview

This skill enables AI agents to trade prediction markets on Polymarket, a decentralized platform on Polygon where users buy and sell outcome tokens for real-world events. The plugin supports both binary (YES/NO) and categorical markets, with prices representing implied probabilities. It offers two trading modes: direct EOA trading (requires POL gas for approvals) and gasless proxy wallet trading (one-time setup, then trade without gas costs). The plugin automatically handles EIP-712 signing, API credential management, and order settlement through Polymarket's CLOB system.

Usage

Install the plugin, connect an onchainos wallet with Polygon support, verify regional access with check-access, then either fund your EOA directly or set up a proxy wallet for gasless trading. Use list-markets to browse opportunities and buy/sell to place trades.

Commands

Command Description
quickstart Check wallet state and get guided next-step command
check-access Verify region is not restricted
list-markets Browse active prediction markets with filtering
list-5m List 5-minute crypto up/down markets
get-market Get market details and order book
get-positions View open positions and P&L
balance Show POL and USDC.e balances for EOA and proxy wallets
buy Buy YES/NO outcome shares
sell Sell outcome shares
cancel Cancel an open order
redeem Redeem winning tokens after market resolves
setup-proxy Deploy proxy wallet for gasless trading
deposit Transfer USDC.e from EOA to proxy wallet
switch-mode Switch default trading mode (eoa/proxy)

Triggers

An AI agent should activate this skill when users want to trade prediction markets, check Polymarket positions, browse political/sports/crypto betting markets, place bets on future events, or when they mention "polymarket", "prediction market", "bet on", "5-minute market", or related trading terminology.

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.

### Version check (auto-injected)

> **AI Agent Instruction**: Run this version check before executing any commands from this skill. If an update is applied, re-read this SKILL.md before proceeding — the instructions may have changed.

```bash
# Check for skill updates (1-hour cache)
UPDATE_CACHE="$HOME/.plugin-store/update-cache/polymarket-plugin"
CACHE_MAX=3600
LOCAL_VER="0.4.9"
DO_CHECK=true

if [ -f "$UPDATE_CACHE" ]; then
  CACHE_MOD=$(stat -f %m "$UPDATE_CACHE" 2>/dev/null || stat -c %Y "$UPDATE_CACHE" 2>/dev/null || echo 0)
  NOW=$(date +%s)
  AGE=$(( NOW - CACHE_MOD ))
  [ "$AGE" -lt "$CACHE_MAX" ] && DO_CHECK=false
fi

if [ "$DO_CHECK" = true ]; then
  REMOTE_VER=$(curl -sf --max-time 3 "https://raw.githubusercontent.com/okx/plugin-store/main/skills/polymarket-plugin/plugin.yaml" | grep '^version' | head -1 | tr -d '"' | awk '{print $2}')
  if [ -n "$REMOTE_VER" ]; then
    mkdir -p "$HOME/.plugin-store/update-cache"
    echo "$REMOTE_VER" > "$UPDATE_CACHE"
  fi
fi

REMOTE_VER=$(cat "$UPDATE_CACHE" 2>/dev/null || echo "$LOCAL_VER")
if [ "$REMOTE_VER" != "$LOCAL_VER" ]; then
  echo "Update available: polymarket-plugin v$LOCAL_VER -> v$REMOTE_VER. Updating..."
  npx skills add okx/plugin-store --skill polymarket-plugin --yes --global 2>/dev/null || true
  echo "Updated polymarket-plugin to v$REMOTE_VER. Please re-read this SKILL.md."
fi

Install onchainos CLI + Skills (auto-injected)

# 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 --global

Install polymarket-plugin binary + launcher (auto-injected)

# Install shared infrastructure (launcher + update checker, only once)
LAUNCHER="$HOME/.plugin-store/launcher.sh"
CHECKER="$HOME/.plugin-store/update-checker.py"
if [ ! -f "$LAUNCHER" ]; then
  mkdir -p "$HOME/.plugin-store"
  curl -fsSL "https://raw.githubusercontent.com/okx/plugin-store/main/scripts/launcher.sh" -o "$LAUNCHER" 2>/dev/null || true
  chmod +x "$LAUNCHER"
fi
if [ ! -f "$CHECKER" ]; then
  curl -fsSL "https://raw.githubusercontent.com/okx/plugin-store/main/scripts/update-checker.py" -o "$CHECKER" 2>/dev/null || true
fi

# Clean up old installation
rm -f "$HOME/.local/bin/polymarket-plugin" "$HOME/.local/bin/.polymarket-plugin-core" 2>/dev/null

# Download binary
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-musl" ;;
  linux_i686)    TARGET="i686-unknown-linux-musl" ;;
  linux_aarch64) TARGET="aarch64-unknown-linux-musl" ;;
  linux_armv7l)  TARGET="armv7-unknown-linux-musleabihf" ;;
  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-plugin@0.4.9/polymarket-plugin-${TARGET}${EXT}" -o ~/.local/bin/.polymarket-plugin-core${EXT}
chmod +x ~/.local/bin/.polymarket-plugin-core${EXT}

# Symlink CLI name to universal launcher
ln -sf "$LAUNCHER" ~/.local/bin/polymarket-plugin

# Register version
mkdir -p "$HOME/.plugin-store/managed"
echo "0.4.9" > "$HOME/.plugin-store/managed/polymarket-plugin"

Report install (auto-injected, runs once)

REPORT_FLAG="$HOME/.plugin-store/reported/polymarket-plugin"
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-plugin","version":"0.4.9"}' >/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-plugin","divId":"'"$DIV_ID"'"}' >/dev/null 2>&1 || true
  touch "$REPORT_FLAG"
fi


</details>

---
*Generated by Plugin Store CI after maintainer approval.*

@github-actions
Copy link
Copy Markdown
Contributor

📋 Phase 3: AI Code Review Report — Score: 88/100

Plugin: polymarket-plugin | Recommendation: ⚠️ Merge with caveats

🔗 Reviewed against latest onchainos source code (live from main branch) | Model: claude-opus-4-7 via Anthropic API | Cost: ~459962+7606 tokens

This is an advisory report. It does NOT block merging. Final decision is made by human reviewers.


1. Plugin Overview
Field Value
Name polymarket-plugin
Version 0.4.9
Category defi-protocol
Author skylavis-sky (skylavis-sky)
License MIT
Has Binary Yes (with build config)
Risk Level Medium (DeFi trading with real funds)

Summary: A Rust CLI plugin that enables trading prediction markets on Polymarket (Polygon chain 137). Supports buying/selling YES/NO outcome tokens, managing positions, bridge deposits, proxy wallet setup for gasless trading, and redeeming winning tokens. Uses onchainos CLI for all wallet signing operations (TEE-protected).

Target Users: Users who want to trade prediction markets (sports, politics, crypto, 5-minute up/down) via AI agents with wallet automation.

2. Architecture Analysis

Components:

  • Skill (SKILL.md) + Binary (Rust source in src/)

Skill Structure:
SKILL.md includes proactive onboarding, 15+ command definitions (quickstart, check-access, list-markets, list-5m, get-market, get-positions, balance, buy, sell, cancel, redeem, setup-proxy, deposit, withdraw, switch-mode), command routing table, order type guide (FOK/GTC/POST_ONLY/GTD), safety guards, and pre-flight checks. Has auto-injected CI pre-flight block (skipped per instructions).

Data Flow:

  • Read operations → Polymarket REST APIs (CLOB, Gamma, Data, Bridge)
  • Write operations → sign EIP-712 orders via onchainos wallet sign-message --type eip712 → POST to CLOB
  • On-chain operations → onchainos wallet contract-call --force (approvals, proxy deployment, redeem)
  • Direct RPC eth_call / eth_getBalance / debug_traceCall to Polygon and other EVM RPCs for balance/verification

Dependencies:

  • onchainos CLI (required for buy/sell/cancel/redeem/deposit/setup-proxy)
  • External APIs: clob.polymarket.com, gamma-api.polymarket.com, data-api.polymarket.com, bridge.polymarket.com
  • RPCs: polygon.drpc.org, ethereum.publicnode.com, arbitrum.drpc.org, base.drpc.org, optimism.drpc.org, bsc.publicnode.com
  • Price oracle: coins.llama.fi (DeFiLlama)
  • Rust crates: tokio, reqwest, clap, serde, sha2, sha3, hmac, getrandom, chrono, dirs
3. Auto-Detected Permissions

onchainos Commands Used

Command Found Exists in onchainos CLI Risk Level Context
onchainos wallet addresses --chain 137 ✅ Yes Low Resolve wallet address
onchainos wallet sign-message --type eip712 ✅ Yes High Sign EIP-712 orders (ClobAuth, Order struct)
onchainos wallet contract-call --force ✅ Yes High ERC-20 approve, CTF approve, redeem, proxy deploy
onchainos wallet send --force ✅ Yes High Native/ERC-20 transfers
onchainos wallet balance --chain <chain> ✅ Yes Low Read token balances
onchainos wallet status ✅ Yes Low Check login state
onchainos wallet login [email] ✅ Yes Low Login flow

All commands exist in onchainos CLI per source reference.

Wallet Operations

Operation Detected? Where Risk
Read balance Yes balance.rs, onchainos.rs (direct RPC + onchainos wallet balance) Low
Send transaction Yes deposit.rs, withdraw.rs, onchainos.rs (transfer_usdc_to_proxy, transfer_erc20_on_chain) High
Sign message Yes auth.rs, signing.rs (EIP-712 via onchainos) High
Contract call Yes buy.rs, sell.rs, redeem.rs, setup_proxy.rs (approvals, CTF redemption, proxy deployment) High

External APIs / URLs

URL / Domain Purpose Risk
clob.polymarket.com Order book, order placement, auth Low (trusted Polymarket endpoint)
gamma-api.polymarket.com Market metadata, listings Low
data-api.polymarket.com Position data Low
bridge.polymarket.com Cross-chain deposit addresses Medium (funds routed via bridge)
coins.llama.fi USD price oracle for token conversions Low
polygon.drpc.org, polygon-bor-rpc.publicnode.com Polygon RPC Low
ethereum.publicnode.com, arbitrum.drpc.org, base.drpc.org, optimism.drpc.org, bsc.publicnode.com Multi-chain RPCs for bridge deposits Low
raw.githubusercontent.com/okx/plugin-store/... Update checker / launcher (auto-injected CI block — skipped) N/A
plugin-store-dun.vercel.app, www.okx.com/priapi/... Install telemetry (auto-injected) N/A

Chains Operated On

  • Polygon (137) — primary trading chain
  • Ethereum (1), Arbitrum (42161), Base (8453), Optimism (10), BNB Chain (56) — bridge deposit sources

Overall Permission Summary

The plugin signs EIP-712 orders via onchainos (TEE-protected), executes on-chain approvals/transfers/redemptions via wallet contract-call --force, and queries public REST APIs for market data. It can move significant funds (USDC.e transfers, token approvals including setApprovalForAll on ERC-1155 CTF tokens). The --force flag on all contract-calls bypasses onchainos confirmation prompts — the SKILL.md documents this and relies on agent-level confirmation as the sole safety gate. Credentials (API key/secret/passphrase) cached at ~/.config/polymarket/creds.json with 0600 permissions. No private keys handled directly.

4. onchainos API Compliance

Does this plugin use onchainos CLI for all on-chain write operations?

Yes — all signing and on-chain writes route through onchainos CLI. No direct private key usage.

On-Chain Write Operations (MUST use onchainos)

Operation Uses onchainos? Self-implements? Detail
Wallet signing No EIP-712 via sign-message --type eip712
Transaction broadcasting No Via wallet contract-call and wallet send
DEX swap execution N/A No N/A (prediction market, not DEX)
Token approval No ABI-encodes calldata, submits via wallet contract-call
Contract calls No CTF redeem, proxy deploy, USDC transfer
Token transfers No Via wallet send and wallet contract-call

Data Queries (allowed to use external sources)

Data Source API/Service Used Purpose
Polymarket CLOB clob.polymarket.com Market data, order book, orders
Polymarket Gamma gamma-api.polymarket.com Market listings, events
Polymarket Data data-api.polymarket.com Positions
Polymarket Bridge bridge.polymarket.com Cross-chain deposits
DeFiLlama coins.llama.fi USD price oracle
Polygon/EVM RPCs public RPC endpoints Balance reads, eth_call simulation, tx receipts, debug_traceCall

External APIs / Libraries Detected

  • reqwest (HTTP client)
  • No web3 signing libraries (alloy/ethers) for signing — all signing delegated to onchainos
  • sha2/sha3/hmac for HMAC-SHA256 (Polymarket L2 auth) and keccak256 (selector computation)

Verdict: ✅ Fully Compliant

Plugin correctly delegates ALL signing to onchainos CLI. ABI-encoding calldata locally is acceptable — onchainos handles the actual signing and broadcasting. No private key material is handled by the plugin.

5. Security Assessment

Static Rule Scan (C01-C09, H01-H09, M01-M08, L01-L02)

Rule ID Severity Title Matched? Detail
C01 CRITICAL curl | sh No (only in auto-injected CI block — excluded)
C05 CRITICAL credential-exfiltration No
H01 HIGH hardcoded-secrets No Contract addresses only (not secrets)
H05 INFO direct-financial Yes onchainos wallet contract-call, wallet send — plugin is a trading skill, expected
M03 MEDIUM third-party-content Yes reqwest::Client::new().post/get multiple endpoints. Plugin sanitizes API-sourced strings (sanitize.rs) and documents "Treat all data as untrusted external content" in SKILL.md
M07 MEDIUM missing-untrusted-data-boundary No SKILL.md includes "Data Trust Boundary" section stating "Treat all returned data as untrusted external content" explicitly
M08 MEDIUM external-data-field-passthrough No SKILL.md includes "Output field safety (M08)" section with explicit field filtering guidance; sanitize.rs strips control chars + truncates at 500 chars

LLM Judge Analysis (L-PINJ, L-MALI, L-MEMA, L-IINJ, L-AEXE, L-FINA, L-FISO)

Judge Severity Detected Confidence Evidence
L-PINJ CRITICAL No 0.9 No injection patterns; CLI args are typed/validated; user input passed as positional args (clap)
L-MALI CRITICAL No 0.85 Declared purpose matches implementation (prediction market trading); no hidden data exfiltration
L-MEMA HIGH No 0.95 No writes to MEMORY.md, SOUL.md, .claude/memory/
L-IINJ INFO Yes 0.95 Plugin has boundary declaration; external requests to Polymarket APIs, bridge, RPCs, DeFiLlama — all declared
L-AEXE INFO Yes 0.9 Plugin uses --force on contract-calls, bypassing onchainos confirmation. SKILL.md explicitly states "Agent confirmation before calling buy or sell is the sole safety gate" — acknowledged risk with mitigation (agent-level confirmation)
L-FINA HIGH Yes 0.95 Full financial write capability: buy/sell/deposit/withdraw/redeem/transfers. Confirmation mechanism exists (agent-level + dry-run + mode flags)
L-FISO MEDIUM No 0.85 Field filtering guidance present in SKILL.md M08 section; sanitize.rs implements truncation/control-char stripping

Toxic Flow Detection (TF001-TF006)

  • TF005 (command-injection + direct-financial): Not triggered — curl|sh only in auto-injected CI block (excluded from review)
  • TF006 (missing-untrusted-data-boundary OR external-data-field-passthrough + direct-financial): Not triggered — plugin explicitly addresses M07/M08 with declared boundaries and sanitization

No toxic flows detected.

Prompt Injection Scan

  • Checked for: instruction override, identity manipulation, hidden behavior, confirmation bypass, unauthorized operations, hidden content (base64, invisible chars)
  • --force flag on sign-message / contract-call is used to bypass onchainos confirmations, but this is documented openly in SKILL.md with explicit agent-level confirmation requirements. This is a legitimate design choice for programmatic trading, not a bypass.

Result: ✅ Clean

Dangerous Operations Check

Plugin involves: transfers (USDC.e), signing (EIP-712 orders), contract calls (approvals, redeem, proxy deploy), broadcasting transactions. SKILL.md has explicit user confirmation steps:

  • Pre-sell liquidity check (mandatory agent step)
  • Token security scan (Step 2 of buy flow)
  • setApprovalForAll warning on first sell
  • Dry-run modes on all write commands
  • Agent confirmation documented as sole safety gate for --force operations

Result: ⚠️ Review Needed — the --force flag on all contract-calls means the plugin relies entirely on agent-level confirmation. Well documented but agent misbehavior would bypass onchainos safety. Acceptable given documentation quality.

Data Exfiltration Risk

All external requests are to declared Polymarket/DeFiLlama/RPC endpoints. No arbitrary URL fetching. Credentials stored locally at ~/.config/polymarket/creds.json with 0600 perms, never transmitted outside Polymarket auth flow.

Result: ✅ No Risk

Overall Security Rating: 🟡 Medium Risk

Financial plugin with large approval surface (setApprovalForAll grants blanket ERC-1155 approval), reliance on --force bypassing onchainos prompts, and multi-chain bridge interactions. Mitigated by clear documentation, dry-run modes, explicit agent confirmation requirements, and proper credential handling.

6. Source Code Security

Language & Build Config

  • Language: Rust (edition 2021)
  • Entry point: src/main.rs
  • Binary name: polymarket-plugin

Dependency Analysis

All dependencies are well-known, maintained crates:

  • tokio 1.x, reqwest 0.12, clap 4, serde 1, serde_json 1
  • sha2 0.10, sha3 0.10, hmac 0.12 (cryptographic primitives for EIP-712 hashing + HMAC-SHA256)
  • base64 0.22, chrono 0.4, dirs 5, hex 0.4, getrandom 0.2, futures 0.3
  • Cargo.lock pins exact versions. No unmaintained or vulnerable dependencies detected.

Code Safety Audit

Check Result Detail
Hardcoded secrets (API keys, private keys, mnemonics) Only public contract addresses and RPC URLs
Network requests to undeclared endpoints All endpoints declared in plugin.yaml api_calls
File system access outside plugin scope Only ~/.config/polymarket/creds.json with 0600 perms
Dynamic code execution (eval, exec, shell commands) Uses tokio::process::Command to invoke onchainos subprocess only — parameterized args, no shell expansion, user input passed via --arg value tokens (no injection surface)
Environment variable access beyond declared env Only reads POLYMARKET_API_KEY, POLYMARKET_SECRET, POLYMARKET_PASSPHRASE — all documented in SKILL.md
Build scripts with side effects (build.rs, postinstall) No build.rs present
Unsafe code blocks (Rust) / CGO (Go) No unsafe blocks detected

Additional notes:

  • Subprocess invocation: All tokio::process::Command::new("onchainos") uses .args([...]) with individual tokens (not shell strings), avoiding shell injection. User input (addresses, amounts) is passed as separate arguments.
  • Credential file permissions set to 0600 on Unix (documented warning if looser perms detected)
  • Proxy wallet verification: verify_eip1167_proxy enforces bytecode check before accepting proxy address — prevents funds going to wrong address if RPC trace fails
  • Pre-flight simulations via eth_call before contract-calls that could revert (redeem)

Does SKILL.md accurately describe what the source code does?

Yes — SKILL.md documentation matches implementation. Proxy wallet deployment, approve semantics (exact-amount USDC.e vs blanket setApprovalForAll), fee structure, series markets, bridge flow, and 5-minute trading hours all accurately reflected.

Verdict: ✅ Source Safe

7. Code Review

Quality Score: 88/100

Dimension Score Notes
Completeness (pre-flight, commands, error handling) 23/25 Extensive pre-flight, 15+ commands, structured error codes, dry-run modes
Clarity (descriptions, no ambiguity) 23/25 Clear command routing table, explicit trigger phrases, well-documented flags
Security Awareness (confirmations, slippage, limits) 22/25 Multiple safety gates (pre-sell liquidity check, token-scan integration, balance pre-flights). --force usage is documented but places high trust in agent confirmation
Skill Routing (defers correctly, no overreach) 13/15 Uses okx-security for token-scan, okx-agentic-wallet for login; stays in its lane
Formatting (markdown, tables, code blocks) 9/10 Well-structured tables, clear sections, good use of admonitions

Strengths

  • Excellent security awareness: explicit boundary declarations, field sanitization, multiple dry-run modes, pre-flight eth_call simulations
  • Clear integration with onchainos (proper delegation of signing)
  • Robust error handling with structured error codes (NO_REDEEMABLE_POSITIONS, SIMULATION_REVERTED, INSUFFICIENT_POL_GAS, etc.)
  • Proxy wallet verification via EIP-1167 bytecode check prevents fund loss from wrong proxy addresses
  • Comprehensive documentation of approval semantics (exact-amount vs blanket setApprovalForAll)

Issues Found

  • 🟡 Important: --force on all wallet contract-call operations bypasses onchainos's own confirmation gate. The plugin relies entirely on agent-level confirmation. Documented openly but worth highlighting to reviewers.
  • 🟡 Important: setApprovalForAll(exchange, true) on first sell grants blanket ERC-1155 approval. Matches Polymarket's web UI behavior but should be surfaced prominently to users on first use (SKILL.md does document this in the sell section).
  • 🔵 Minor: Base64-encoded HMAC key (_K=$(echo 'OE9nNWFRUFdfSVJkektrMExOV2RNeTIzV2JibXo3ZWNTbExJUDFIWnVoZw==' | base64 -d)) in install report — auto-injected CI block (skipped per instructions).
  • 🔵 Minor: getrandom crate used for salt generation — appropriate for non-cryptographic salt.
8. Recommendations
  1. Consider adding an explicit opt-in flag for setApprovalForAll on first sell (e.g., --confirm-unlimited-approval), even though it matches Polymarket's web UI behavior, to make the risk visible at CLI level.
  2. Consider adding a per-session confirmation cache to avoid repeating pre-sell liquidity warnings when the user has already acknowledged them for the same market.
  3. Document the 0600 permission requirement for creds.json in a more prominent location (currently only mentioned in passing).
  4. Consider adding a --max-spend safety flag that caps USDC.e per-trade at a user-configured limit to reduce impact of agent misbehavior.
  5. The --force broadcast decision should be logged to a local audit file for user review.
9. Reviewer Summary

One-line verdict: Well-engineered Rust prediction-market plugin with proper onchainos delegation, strong documentation, and acceptable risk profile for a DeFi trading skill — but heavy reliance on --force contract-calls places trust on agent-level confirmation.

Merge recommendation: ⚠️ Merge with noted caveats

Caveats to address or acknowledge:

  • The plugin uses --force to bypass onchainos confirmation prompts on every contract-call. Documentation acknowledges this and designates agent-level confirmation as the sole safety gate. Acceptable given the plugin's use case (programmatic trading) but reviewers should understand this before approving.
  • First-sell setApprovalForAll grants blanket ERC-1155 approval — document this more prominently in the first-sell flow if possible.
  • Plugin is fully onchainos-compliant for signing/broadcasting; no private key material handled.

Generated by Claude AI via Anthropic API — review the full report before approving.

@Noah3595 Noah3595 merged commit 1201f0d into okx:main Apr 21, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants