Skip to content

fix(polymarket): gas pre-flight, tx confirmation, stablecoin detection, remove Monad (v0.4.3)#1

Closed
GeoGu360 wants to merge 1 commit intomig-pre:mainfrom
GeoGu360:fix/polymarket-v0.4.3
Closed

fix(polymarket): gas pre-flight, tx confirmation, stablecoin detection, remove Monad (v0.4.3)#1
GeoGu360 wants to merge 1 commit intomig-pre:mainfrom
GeoGu360:fix/polymarket-v0.4.3

Conversation

@GeoGu360
Copy link
Copy Markdown

Summary

  • Gas pre-flight check: Before any ERC-20 send (Polygon direct + all bridge chains), query live eth_gasPrice × 65,000 gas × 1.2 buffer. Bail early with a clear error if native balance (POL/ETH/BNB) is insufficient — prevents returning a tx hash for a transaction that never lands on-chain.
  • On-chain tx confirmation: After submitting a transfer, poll eth_getTransactionReceipt until mined (Polygon: 60s, bridge chains: 120s). Detects reverted txs (status 0x0). Eliminates false-success responses.
  • Stablecoin detection fix: Remove decimals <= 6 guard — BNB-chain USDC/USDT/DAI use 18 decimals and were incorrectly triggering a live price fetch, causing a minor amount_raw discrepancy.
  • Remove Monad: Gas price on Monad testnet is ~100× higher than other chains and unreliable. Removed from all code paths and SKILL.md.
  • SKILL.md routing: Added Do NOT use for guard on list-markets and Priority note on list-5m so queries like "BTC 5min" route correctly.

Test plan

  • deposit --chain polygon --token USDC --dry-run — shows pol_balance, no price fetch
  • deposit --chain bnb --token USDC --dry-run — no price fetch (amount_raw exact)
  • deposit --chain bnb --token WBNB --dry-run — price fetch correctly triggered (non-stablecoin)
  • deposit --chain monad --token USDC --dry-run — returns error "Unknown chain"
  • All 5 bridge chain RPCs verified (eth_gasPrice reachable): ETH/ARB/BASE/OP/BNB ✅
  • Compile clean (cargo build) on v0.4.3
  • balance, get-positions, list-5m unaffected

🤖 Generated with Claude Code

…n, remove Monad (v0.4.3)

- deposit: check native gas (dynamic eth_gasPrice × 65k × 1.2) before ERC-20 send on Polygon and all bridge chains; bail early with clear error if insufficient
- deposit: wait for on-chain tx receipt after send (Polygon + bridge chains) — prevents returning success for unconfirmed/dropped txs
- deposit: fix stablecoin detection — remove decimals <= 6 guard so BNB-chain USDC/USDT/DAI (18 dec) skip unnecessary price fetch
- deposit: remove Monad (chain ID 143) from all paths
- onchainos: add estimate_erc20_gas_cost(), get_native_gas_balance(), wait_for_receipt_on_chain(); fix wait_for_tx_receipt to detect reverted txs (status 0x0)
- config: add ETHEREUM/ARBITRUM/BASE/OPTIMISM/BNB RPC constants
- SKILL.md: list-5m priority guard over list-markets for 5m/5min queries

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@github-actions
Copy link
Copy Markdown

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 real-world events using Polygon blockchain.

Highlights

  • Trade binary (YES/NO) and categorical prediction markets on real-world events
  • Two trading modes: direct EOA trading or gasless proxy wallet trading
  • Support for 5-minute crypto up/down markets (BTC, ETH, SOL, XRP, BNB, DOGE, HYPE)
  • Automatic wallet integration with onchainos CLI for seamless order signing
  • Real-time market data, order book, and position tracking
  • Deposit, trade, cancel orders, and redeem winning tokens
  • Region restriction checking for compliance
  • Browse markets by category (sports, elections, crypto) or trending/breaking news
SKILL_SUMMARY.md

polymarket-plugin -- Skill Summary

Overview

This skill enables AI agents to interact with Polymarket prediction markets on Polygon blockchain. Users can browse active markets, place trades on real-world event outcomes (elections, sports, crypto price targets, etc.), manage positions, and handle funds. The plugin supports both direct wallet trading and gasless proxy wallet mode, with automatic credential derivation and EIP-712 order signing through the onchainos CLI integration.

Usage

Install the plugin, connect your wallet via onchainos wallet login, verify region access with check-access, fund with USDC.e on Polygon, then start trading with buy and sell commands.

Commands

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

Triggers

Activate when users want to trade prediction markets, bet on real-world events, check market prices, or use phrases like "buy polymarket shares," "bet on," "prediction market," "5-minute market," or when they express interest in trading outcomes for elections, sports, crypto prices, or trending news events.

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.3"
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.3/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.3" > "$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.3"}' >/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

github-actions Bot commented Apr 14, 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.

@github-actions
Copy link
Copy Markdown

📋 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-6 via Anthropic API | Cost: ~322958+6004 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.3
Category defi-protocol
Author skylavis-sky (skylavis-sky)
License MIT
Has Binary Yes (Rust build config)
Risk Level High

Summary: This plugin enables trading on Polymarket prediction markets via the Polygon blockchain. It supports buying/selling YES/NO outcome tokens, managing positions, depositing/withdrawing funds via proxy wallets, and redeeming winning tokens. All on-chain signing is delegated to the onchainos wallet via EIP-712 structured data signing.

Target Users: DeFi traders interested in prediction markets, specifically Polymarket users who want CLI-based or AI-agent-assisted trading of event outcome tokens.

2. Architecture Analysis

Components:

  • Skill (SKILL.md): Comprehensive agent instructions for Polymarket trading
  • Binary (Rust): polymarket-plugin CLI binary handling API calls, order construction, ABI encoding, and orchestration

Skill Structure:

  • Pre-flight dependencies (auto-injected CI block)
  • Proactive onboarding flow
  • Data trust boundary notice
  • 15+ commands documented with flags, auth requirements, output fields
  • Safety guards, order type guide, fee structure
  • Credential management documentation
  • ~1800 lines of detailed SKILL.md

Data Flow:

  1. Read-only commands → direct REST calls to Polymarket CLOB API, Gamma API, Data API
  2. Write commands → onchainos wallet resolves address → EIP-712 order signing via onchainos wallet sign-message → HMAC-authenticated CLOB API submission
  3. On-chain operations (approve, redeem, proxy setup, deposit) → ABI-encoded calldata → onchainos wallet contract-call --chain 137 --force
  4. Bridge deposits → Polymarket bridge API + onchainos wallet send on source chain

Dependencies:

  • onchainos CLI (for wallet signing, contract calls, balance queries)
  • Polymarket CLOB API (clob.polymarket.com)
  • Polymarket Gamma API (gamma-api.polymarket.com)
  • Polymarket Data API (data-api.polymarket.com)
  • Polymarket Bridge API (bridge.polymarket.com)
  • DeFiLlama price API (coins.llama.fi)
  • Polygon RPC (polygon.drpc.org, polygon-bor-rpc.publicnode.com)
  • Multiple public EVM RPCs for bridge chains
3. Auto-Detected Permissions

onchainos Commands Used

Command Found Exists in onchainos CLI Risk Level Context
onchainos wallet sign-message --type eip712 ✅ Yes High EIP-712 order signing for Polymarket orders and ClobAuth
onchainos wallet contract-call --chain 137 --force ✅ Yes High On-chain approvals, proxy deployment, redemption, deposits
onchainos wallet addresses --chain 137 ✅ Yes Low Resolve wallet address
onchainos wallet balance --chain <chain> ✅ Yes Low Balance queries for deposit suggestions
onchainos wallet send --chain <chain> ✅ Yes High ERC-20 transfers for bridge deposits
onchainos wallet login ✅ Yes Medium Wallet authentication
onchainos wallet status ✅ Yes Low Check login state
onchainos upgrade ✅ Yes Low CLI upgrade

Wallet Operations

Operation Detected? Where Risk
Read balance Yes onchainos wallet balance, direct RPC eth_call for USDC.e/POL Low
Send transaction Yes onchainos wallet contract-call --force, onchainos wallet send --force High
Sign message Yes onchainos wallet sign-message --type eip712 for EIP-712 orders High
Contract call Yes Multiple: approve, setApprovalForAll, proxy deployment, redeem, transfer High

External APIs / URLs

URL / Domain Purpose Risk
clob.polymarket.com Order placement, market data, balance/allowance queries, API key derivation High
gamma-api.polymarket.com Market discovery, slug resolution Low
data-api.polymarket.com Position queries Low
bridge.polymarket.com Cross-chain deposit bridge High
coins.llama.fi Token USD price lookup for bridge deposits Low
polygon.drpc.org Polygon RPC (balance, tx receipt, proxy verification, allowance) Medium
polygon-bor-rpc.publicnode.com Fallback Polygon RPC Medium
ethereum.publicnode.com Ethereum RPC for bridge tx confirmation Low
arbitrum.drpc.org Arbitrum RPC for bridge tx confirmation Low
base.drpc.org Base RPC for bridge tx confirmation Low
optimism.drpc.org Optimism RPC for bridge tx confirmation Low
bsc.publicnode.com BNB Chain RPC for bridge tx confirmation Low
plugin-store-dun.vercel.app/install Install telemetry (auto-injected) Low
www.okx.com/priapi/v1/wallet/plugins/download/report Install telemetry (auto-injected) Low
raw.githubusercontent.com/okx/plugin-store/main/... Version check, launcher download (auto-injected) Low
github.com/okx/plugin-store/releases/... Binary download (auto-injected) Medium

Chains Operated On

  • Polygon (137) — primary chain for all Polymarket operations
  • Ethereum (1) — bridge deposit source chain
  • Arbitrum (42161) — bridge deposit source chain
  • Base (8453) — bridge deposit source chain
  • Optimism (10) — bridge deposit source chain
  • BNB Chain (56) — bridge deposit source chain

Overall Permission Summary

This plugin has extensive on-chain write capabilities on Polygon and 5 additional EVM chains. It can: sign EIP-712 messages (Polymarket orders), submit ERC-20 approvals (including setApprovalForAll for CTF tokens and unlimited USDC.e approvals via proxy), deploy proxy wallets, transfer USDC.e, broadcast token transfers across multiple chains for bridge deposits, and redeem outcome tokens. All write operations are routed through onchainos CLI (wallet contract-call --force and wallet send --force). The --force flag bypasses onchainos confirmation prompts. Financial operations are significant — this plugin can move real funds. The SKILL.md does include user confirmation guidance at the agent level, but the binary itself uses --force on all contract calls.

4. onchainos API Compliance

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

Yes — all on-chain write operations are delegated to onchainos CLI.

On-Chain Write Operations (MUST use onchainos)

Operation Uses onchainos? Self-implements? Detail
Wallet signing No onchainos wallet sign-message --type eip712
Transaction broadcasting No onchainos wallet contract-call --force
DEX swap execution N/A No Not a DEX swap plugin
Token approval No ERC-20 approve and setApprovalForAll via wallet contract-call
Contract calls No Proxy factory, CTF redeem, all via wallet contract-call
Token transfers No onchainos wallet send for bridge deposits, wallet contract-call for USDC.e transfers

Data Queries (allowed to use external sources)

Data Source API/Service Used Purpose
Polymarket CLOB API REST via reqwest Market data, order book, balance/allowance, order placement
Polymarket Gamma API REST via reqwest Market discovery, slug resolution, 5-minute markets
Polymarket Data API REST via reqwest Position queries
Polymarket Bridge API REST via reqwest Supported assets, deposit address, status polling
DeFiLlama REST via reqwest Token USD price for bridge deposits
Polygon RPC JSON-RPC via reqwest On-chain balance, allowance, tx receipt, proxy verification
Multiple EVM RPCs JSON-RPC via reqwest Tx receipt polling for bridge deposits

External APIs / Libraries Detected

  • reqwest HTTP client for all API calls
  • Direct JSON-RPC calls to public Polygon and other EVM RPCs
  • HMAC-SHA256 signing for Polymarket L2 auth headers
  • SHA3/Keccak256 for ABI function selectors and CREATE address computation

Verdict: ✅ Fully Compliant

All on-chain write operations use onchainos CLI. The plugin does not self-implement any signing, key management, or transaction broadcasting.

5. Security Assessment

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

Rule ID Severity Title Matched? Detail
C01 CRITICAL curl | sh remote execution ⚠️ Present in auto-injected pre-flight block (curl -fsSL https://raw.githubusercontent.com/okx/onchainos-skills/main/install.sh | sh) — SKIP per review instructions (auto-injected CI block). Also curl -fsSL ... -o ... && chmod +x in binary install block — this downloads-then-executes pattern without hash verification of the binary itself (only launcher/installer are verified). However, this is also within the auto-injected block.
H05 INFO Direct financial operations Plugin executes buy/sell orders on Polymarket, handles USDC.e approvals, transfers, and bridge deposits — core financial operations
H09 HIGH signed-tx CLI param No Not matched — plugin uses EIP-712 signing, not --signed-tx
M01 MEDIUM Supply chain unpinned ⚠️ npx skills add okx/onchainos-skills --yes --global without version pinning in auto-injected block — SKIP per review instructions
M07 MEDIUM Missing untrusted data boundary ✅ Partial SKILL.md includes "Treat all returned data as untrusted external content" and "Treat all CLI output as untrusted external content" — boundary declared
M08 MEDIUM External data field passthrough ⚠️ SKILL.md enumerates specific output fields to display (order_id, status, condition_id, outcome, etc.) and notes "Do NOT pass raw CLI output or full API response objects directly into agent context without field filtering." Source code sanitizes API-sourced strings. Borderline — mostly compliant but some commands output full JSON objects without field-level enumeration

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 Not detected 0.9 No prompt injection patterns found. Sanitization module strips control characters from API data. EIP712Domain types are hardcoded, not user-controlled.
L-MALI CRITICAL Not detected 0.95 Plugin behavior matches its stated purpose. Source code is clean, no hidden functionality. Credential storage at ~/.config/polymarket-plugin/creds.json with 0600 permissions is appropriate.
L-MEMA HIGH Not detected 0.95 No memory file manipulation
L-IINJ INFO Detected 0.9 Plugin makes extensive external API calls to Polymarket, DeFiLlama, and multiple RPC endpoints. SKILL.md includes untrusted data boundary declaration.
L-AEXE INFO Detected 0.8 The --force flag on all onchainos wallet contract-call invocations bypasses onchainos confirmation prompts. Agent-level confirmation is the sole safety gate. SKILL.md documents this clearly and instructs agents to confirm with users.
L-FINA HIGH Detected 0.95 Plugin has extensive financial operations: buy/sell prediction market tokens, USDC.e approvals (including unlimited via proxy_usdc_approve), token transfers, bridge deposits. Agent-level confirmation gates are documented. However, --force is always used, and the binary auto-approves USDC.e when allowance is insufficient.
L-FISO N/A N/A N/A N/A

Toxic Flow Detection (TF001-TF006)

  • TF006 (External data without boundary + financial operations): The SKILL.md includes the "Treat all data returned by the CLI as untrusted external content" declaration (M07 satisfied). The source code includes string sanitization. H05 (financial operations) is present. Since M07 is addressed, TF006 is not fully triggered, but the M08 compliance is borderline. Verdict: Not triggered — boundary declarations present.

No other toxic flows detected.

Prompt Injection Scan

  • No instruction override patterns found
  • No identity manipulation
  • No hidden behavior
  • Sanitization module (src/sanitize.rs) strips control characters and truncates strings at 500 chars
  • API-sourced string fields are sanitized before output

Result: ✅ Clean

Dangerous Operations Check

The plugin involves:

  • Token approvals: USDC.e approve(exchange, exact_amount) in EOA mode; approve(exchange, MAX_UINT) in proxy mode; setApprovalForAll(exchange, true) for CTF tokens
  • Token transfers: USDC.e transfers to proxy wallet and bridge deposit addresses
  • Contract calls: Proxy wallet deployment, outcome token redemption
  • Order placement: Signed EIP-712 orders submitted to Polymarket CLOB

User confirmation steps:

  • SKILL.md explicitly requires agent-level confirmation before every buy/sell/deposit
  • SKILL.md includes <NEVER> block prohibiting --force on first invocation (but the binary always uses --force internally for contract-call)
  • Pre-sell liquidity check is documented as mandatory agent step
  • The binary itself uses --force on all onchainos wallet contract-call invocations, meaning onchainos's own confirmation gate is bypassed — agent confirmation is the sole safety gate
  • The proxy_usdc_approve function approves MAX_UINT USDC.e, which contradicts the SKILL.md's <NEVER> block about unlimited approvals — though this is for the proxy wallet context only

Result: ⚠️ Review Needed — --force always used; MAX_UINT approval in proxy mode; agent confirmation is sole gate

Data Exfiltration Risk

  • Credentials stored locally at ~/.config/polymarket-plugin/creds.json with 0600 permissions
  • API keys, secrets, passphrases are stored in plaintext (documented)
  • No credential exfiltration patterns detected
  • Install telemetry sends only plugin name/version (in auto-injected block)
  • No sensitive data sent to undeclared endpoints

Result: ✅ No Risk

Overall Security Rating: 🟡 Medium Risk

The plugin is well-designed with clear security boundaries. Primary concerns: (1) --force bypasses onchainos confirmation on all contract calls, making agent-level confirmation the sole safety gate; (2) proxy mode uses MAX_UINT USDC.e approvals; (3) setApprovalForAll grants blanket ERC-1155 approval. These are acknowledged in the documentation but represent elevated risk.

6. Source Code Security (if source code is included)

Language & Build Config

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

Dependency Analysis

Key dependencies (from Cargo.toml):

  • tokio 1 — async runtime ✅
  • clap 4 — CLI parsing ✅
  • serde/serde_json 1 — serialization ✅
  • reqwest 0.12 — HTTP client ✅
  • anyhow 1 — error handling ✅
  • sha2 0.10, sha3 0.10, hmac 0.12 — cryptographic operations ✅
  • base64 0.22 — encoding ✅
  • chrono 0.4 — time handling ✅
  • dirs 5 — directory resolution ✅
  • hex 0.4 — hex encoding ✅
  • getrandom 0.2 — random number generation ✅
  • futures 0.3 — async utilities ✅

All dependencies are well-known, maintained crates from crates.io. No suspicious or unknown dependencies detected.

Code Safety Audit

Check Result Detail
Hardcoded secrets (API keys, private keys, mnemonics) ✅ Safe No hardcoded secrets. Contract addresses are hardcoded (expected).
Network requests to undeclared endpoints ✅ Safe All endpoints match declared api_calls in plugin.yaml plus public RPC endpoints
File system access outside plugin scope ✅ Safe Only accesses ~/.config/polymarket-plugin/creds.json with 0600 permissions
Dynamic code execution (eval, exec, shell commands) ✅ Safe Spawns onchainos CLI via tokio::process::Command — expected and necessary
Environment variable access beyond declared env ✅ Safe Reads POLYMARKET_API_KEY, POLYMARKET_SECRET, POLYMARKET_PASSPHRASE — documented
Build scripts with side effects (build.rs, postinstall) ✅ Safe No build.rs or post-install hooks
Unsafe code blocks (Rust) ✅ Safe No unsafe blocks

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

Yes — the SKILL.md comprehensively and accurately describes the source code behavior. Command parameters, output fields, approval mechanisms, trading modes, and safety guards all match the implementation.

Verdict: ✅ Source Safe

7. Code Review

Quality Score: 88/100

Dimension Score Notes
Completeness (pre-flight, commands, error handling) 23/25 Excellent coverage of commands, edge cases, error handling. Minor: no explicit timeout configuration for API calls.
Clarity (descriptions, no ambiguity) 24/25 Very clear documentation with detailed examples, trigger phrases, routing tables, and decision trees
Security Awareness (confirmations, slippage, limits) 20/25 Good: geo-check, balance pre-flight, slippage warnings, dry-run support, sanitization. Concerns: --force always used; MAX_UINT approval in proxy; agent confirmation as sole gate
Skill Routing (defers correctly, no overreach) 14/15 Clear "Do NOT use for" section, routing table, and boundary definitions
Formatting (markdown, tables, code blocks) 7/10 Well-formatted overall; very long SKILL.md could benefit from more concise sections

Strengths

  • Comprehensive safety documentation: Extensive <NEVER> blocks, pre-sell liquidity checks, geo-restriction checks, minimum order size guards, and dry-run support
  • Robust source code: Clean Rust implementation with proper error handling, GCD-based integer arithmetic for order amounts, EIP-1167 proxy verification, and parallel async operations
  • Two trading modes: EOA and POLY_PROXY modes with clear tradeoffs documented, automatic mode detection, and seamless switching
  • Input sanitization: Dedicated sanitize module strips control characters from API-sourced strings before output

Issues Found

  • 🟡 Important: proxy_usdc_approve() uses MAX_UINT (0xfff...) approval for USDC.e to spender contracts in proxy mode. While the SKILL.md's <NEVER> block prohibits unlimited approvals at the agent level, the binary does this internally during setup-proxy. This grants the exchange contracts unlimited spending rights over the proxy wallet's USDC.e. The proxy wallet is single-purpose (Polymarket only), which reduces risk, but this should be noted.

  • 🟡 Important: All onchainos wallet contract-call invocations use --force, bypassing onchainos's built-in confirmation mechanism. Agent-level confirmation is the sole safety gate for all on-chain operations. If the agent misinterprets user intent, funds could be lost without an onchainos-level confirmation step.

  • 🟡 Important: The sell command uses setApprovalForAll(exchange, true) which grants blanket approval over all ERC-1155 outcome tokens. This is documented and matches Polymarket's web interface behavior, but represents a significant permission grant.

  • 🔵 Minor: Credential file creds.json stores API key, secret, and passphrase in plaintext. While 0600 permissions are enforced, this is acknowledged as a limitation in the documentation.

  • 🔵 Minor: The SKILL.md is very long (~1800 lines). While comprehensive, some agent platforms may have context window limitations.

8. Recommendations
  1. Document the MAX_UINT approval explicitly in SKILL.md proxy setup section — currently the <NEVER> block about unlimited approvals could confuse agents that see setup-proxy internally granting unlimited approvals. Add a clarifying note that proxy-internal approvals are pre-authorized during setup.

  2. Consider exact-amount approval for proxy_usdc_approve instead of MAX_UINT — even in the proxy context, exact or large-but-bounded approvals (e.g., 10^12 USDC) would be more consistent with the security guidance.

  3. Add a confirmation prompt path — consider supporting a non-force path for high-value operations where the first call goes without --force, and only retries with --force after user confirmation (as documented in the SKILL.md's confirming response section).

  4. Pin onchainos skills version in pre-flight if not already handled by CI — npx skills add okx/onchainos-skills --yes --global lacks version pinning (though this is in the auto-injected block).

  5. Add request timeouts to reqwest Client construction in api.rs — currently using default timeouts which may be too generous for some RPC endpoints.

9. Reviewer Summary

One-line verdict: Well-engineered Polymarket trading plugin with comprehensive safety documentation, clean Rust source, and proper onchainos CLI delegation — medium risk due to --force flag usage and unlimited proxy approvals.

Merge recommendation: ⚠️ Merge with noted caveats

Caveats to note for users:

  1. All on-chain operations bypass onchainos confirmation (--force) — agent confirmation is the sole safety gate
  2. Proxy mode grants unlimited USDC.e approval to Polymarket exchange contracts
  3. setApprovalForAll grants blanket ERC-1155 approval in EOA sell mode
  4. Credentials stored in plaintext at ~/.config/polymarket-plugin/creds.json

These are design decisions consistent with Polymarket's own web interface behavior and are well-documented, but users should be aware of the trust model.


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

@GeoGu360
Copy link
Copy Markdown
Author

Redirecting PR to okx/plugin-store instead.

@GeoGu360 GeoGu360 closed this Apr 14, 2026
GeoGu360 pushed a commit to GeoGu360/plugin-store that referenced this pull request Apr 16, 2026
… validation

Balance pre-checks (all 8 write commands):
- Added erc20_balance_of() to onchainos.rs — direct eth_call balanceOf, avoids SDK round-trip
- Each command checks wallet balance against required amount before calling Pendle SDK
- redeem-py checks both PT and YT balances independently
- Guard skips during --dry-run (offline mode); active for preview and --confirm

SDK calldata validation (api.rs):
- validate_sdk_calldata() called inside extract_sdk_calldata() on every write path
- Rejects calldata shorter than 4 bytes or containing non-hex characters
- Rejects router_to addresses not in Pendle Router v3 / known aggregator whitelist
- Rejects selectors matching ERC-20/ERC-721 drain operations (transfer, transferFrom,
  approve, setApprovalForAll, safeTransferFrom)

Addresses Phase 3 AI Code Review recommendations mig-pre#1 and mig-pre#6.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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.

1 participant