From 8d3b042e815a485af0582af60d791c15a37249d0 Mon Sep 17 00:00:00 2001 From: James Lawton Date: Wed, 15 Apr 2026 18:26:55 +0100 Subject: [PATCH] fix(skills): serve sub-skills at root paths on agentconnect domain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root SKILL.md references sub-skill URLs at /polygon-discovery/SKILL.md (no /skills/ prefix), but the pre-commit hook was only syncing them to public/skills// — making those URLs 404. Update the hook to also copy each skill subdirectory to public// so they're served at /polygon-discovery/SKILL.md as documented. Entire-Checkpoint: 752f71a902fd --- .husky/pre-commit | 19 +- .../connector-ui/public/polygon-defi/SKILL.md | 209 +++++++++++ .../public/polygon-discovery/SKILL.md | 117 +++++++ .../public/polygon-polymarket/SKILL.md | 330 ++++++++++++++++++ 4 files changed, 671 insertions(+), 4 deletions(-) create mode 100644 packages/connector-ui/public/polygon-defi/SKILL.md create mode 100644 packages/connector-ui/public/polygon-discovery/SKILL.md create mode 100644 packages/connector-ui/public/polygon-polymarket/SKILL.md diff --git a/.husky/pre-commit b/.husky/pre-commit index 1941aca..a9909fd 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -9,8 +9,11 @@ # skill entry point for the agent. # # packages/connector-ui/public/skills/ -# Served at https://agentconnect.polygon.technology/skills/ — agents fetch -# skill files at runtime from this URL. +# Served at https://agentconnect.polygon.technology/skills/ — full tree. +# +# packages/connector-ui/public// +# Also served at https://agentconnect.polygon.technology//SKILL.md +# (e.g. /polygon-discovery/SKILL.md) to match the URLs in the root SKILL.md. # # packages/polygon-agent-cli/skills/ # Bundled inside the published npm package so skills are available @@ -41,15 +44,23 @@ function copyDir(src, dest) { // Sync root SKILL.md to connector-ui public root (served at /SKILL.md) fs.copyFileSync('skills/SKILL.md', 'packages/connector-ui/public/SKILL.md'); -// Sync to connector-ui (verbatim) +// Sync to connector-ui (verbatim — full tree under /skills/) copyDir('skills', 'packages/connector-ui/public/skills'); +// Also serve each sub-skill at the root level (e.g. /polygon-discovery/SKILL.md) +// to match the URLs referenced in the root SKILL.md +for (const entry of fs.readdirSync('skills', { withFileTypes: true })) { + if (entry.isDirectory()) { + copyDir(path.join('skills', entry.name), path.join('packages/connector-ui/public', entry.name)); + } +} + // Sync to CLI package (rewrite name field in root SKILL.md only) copyDir('skills', 'packages/polygon-agent-cli/skills'); const cliSkill = path.join('packages/polygon-agent-cli/skills/SKILL.md'); fs.writeFileSync(cliSkill, fs.readFileSync(cliSkill, 'utf8').replace('name: polygon-agent-kit', 'name: polygon-agent-cli')); " -git add packages/connector-ui/public/SKILL.md packages/connector-ui/public/skills packages/polygon-agent-cli/skills +git add packages/connector-ui/public/SKILL.md packages/connector-ui/public/skills packages/connector-ui/public/polygon-* packages/polygon-agent-cli/skills pnpm exec lint-staged pnpm run typecheck diff --git a/packages/connector-ui/public/polygon-defi/SKILL.md b/packages/connector-ui/public/polygon-defi/SKILL.md new file mode 100644 index 0000000..3751d99 --- /dev/null +++ b/packages/connector-ui/public/polygon-defi/SKILL.md @@ -0,0 +1,209 @@ +--- +name: polygon-defi +description: DeFi operations on Polygon using the Polygon Agent CLI. Covers same-chain token swaps, cross-chain bridging, and yield deposits into Aave v3 and Morpho vaults via Trails earn pool discovery. All commands dry-run by default — add --broadcast to execute. +--- + +# Polygon DeFi Skill + +## Swap Tokens (Same-Chain) + +```bash +# Dry-run — shows route and output amount +polygon-agent swap --from USDC --to USDT --amount 5 + +# Execute +polygon-agent swap --from USDC --to USDT --amount 5 --broadcast + +# Custom slippage (default 0.5%) +polygon-agent swap --from USDC --to USDT --amount 5 --slippage 0.005 --broadcast +``` + +## Bridge Tokens (Cross-Chain) + +```bash +# Bridge USDC from Polygon to Arbitrum +polygon-agent swap --from USDC --to USDC --amount 0.5 --to-chain arbitrum --broadcast + +# Bridge to other supported chains +polygon-agent swap --from USDC --to USDC --amount 1 --to-chain optimism --broadcast +polygon-agent swap --from USDC --to USDC --amount 1 --to-chain base --broadcast +polygon-agent swap --from USDC --to USDC --amount 1 --to-chain mainnet --broadcast +``` + +Valid `--to-chain` values: `polygon`, `amoy`, `mainnet`, `arbitrum`, `optimism`, `base`. + +## Query Earn Pools + +Use `getEarnPools` to discover live yield opportunities across protocols before deciding where to deposit. + +### HTTP + +```bash +curl --request POST \ + --url https://trails-api.sequence.app/rpc/Trails/GetEarnPools \ + --header 'Content-Type: application/json' \ + --data '{"chainIds": [137]}' +``` + +All request fields are optional — omit any you don't need to filter on. + +| Field | Type | Description | +|-------|------|-------------| +| `chainIds` | `number[]` | Filter by chain (e.g. `[137]` for Polygon mainnet) | +| `protocols` | `string[]` | Filter by protocol name, e.g. `["Aave"]`, `["Morpho"]` | +| `minTvl` | `number` | Minimum TVL in USD | +| `maxApy` | `number` | Maximum APY (useful to exclude outlier/at-risk pools) | + +### Fetch (agent code) + +The API key is the project access key already available to the agent (`SEQUENCE_PROJECT_ACCESS_KEY`). + +```typescript +const res = await fetch('https://trails-api.sequence.app/rpc/Trails/GetEarnPools', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ chainIds: [137] }), +}); +const { pools } = await res.json(); +``` + +### Response Schema + +```typescript +interface GetEarnPoolsResponse { + pools: EarnPool[]; + timestamp: string; // ISO-8601 fetch time + cached: boolean; +} + +interface EarnPool { + id: string; // "{protocol}-{chainId}-{address}" + name: string; // e.g. "USDC Market" + protocol: string; // "Aave" | "Morpho" + chainId: number; + apy: number; // annualised yield as a decimal percent + tvl: number; // USD + token: PoolTokenInfo; + depositAddress: string; // contract to approve/send to + isActive: boolean; + poolUrl?: string; + protocolUrl?: string; + wrappedTokenGatewayAddress?: string; // non-null for Aave native-token markets +} + +interface PoolTokenInfo { + symbol: string; + name: string; + address: string; + decimals: number; + logoUrl?: string; +} +``` + +> **Tip:** `wrappedTokenGatewayAddress` is set on Aave markets that accept a wrapped native token (WPOL, WETH). Pass this address instead of `depositAddress` when depositing POL/ETH directly. + +--- + +## Deposit to Earn Yield + +Pool discovery uses `TrailsApi.getEarnPools` — picks the most liquid pool (highest TVL) for the asset on the current chain. No hardcoded addresses — the pool is resolved at runtime. + +```bash +# Dry-run — shows pool name, APY, TVL, and deposit address before committing +polygon-agent deposit --asset USDC --amount 0.3 + +# Execute — deposits into the highest-TVL active pool +polygon-agent deposit --asset USDC --amount 0.3 --broadcast + +# Filter by protocol +polygon-agent deposit --asset USDC --amount 0.3 --protocol aave --broadcast +polygon-agent deposit --asset USDC --amount 0.3 --protocol morpho --broadcast +``` + +### Supported Protocols + +| Protocol | Encoding | Description | +|----------|----------|-------------| +| **Aave v3** | `supply(asset, amount, onBehalfOf, referralCode)` | Lending pool deposit | +| **Morpho** | `deposit(assets, receiver)` — ERC-4626 | Vault deposit | + +Vault/pool addresses are resolved dynamically from Trails — they are not hardcoded. The dry-run output includes `depositAddress` so you can inspect the exact contract before broadcasting. + +### Session Whitelisting + +If the deposit is rejected with a session permission error, the pool's contract address needs to be whitelisted when creating the wallet session: + +```bash +# 1. Dry-run first to get the depositAddress +polygon-agent deposit --asset USDC --amount 0.3 +# → note the depositAddress in output + +# 2. Re-create wallet session with that contract whitelisted +polygon-agent wallet create --contract + +# 3. Retry +polygon-agent deposit --asset USDC --amount 0.3 --broadcast +``` + +When creating a wallet specifically for yield, add `--contract` flags for all intended vaults upfront and omit `--usdc-limit`: + +```bash +polygon-agent wallet create \ + --contract 0x794a61358d6845594f94dc1db02a252b5b4814ad \ + --contract 0x781fb7f6d845e3be129289833b04d43aa8558c42 +``` + +### Yield Vault Contract Whitelist + +#### Polygon Mainnet (chainId 137) + +| Protocol | Asset | Address | +|----------|-------|---------| +| Aave V3 Pool (all markets) | USDC, USDT, WETH, WMATIC… | `0x794a61358d6845594f94dc1db02a252b5b4814ad` | +| Morpho Compound USDC | USDC | `0x781fb7f6d845e3be129289833b04d43aa8558c42` | +| Morpho Compound WETH | WETH | `0xf5c81d25ee174d83f1fd202ca94ae6070d073ccf` | +| Morpho Compound POL | POL | `0x3f33f9f7e2d7cfbcbdf8ea8b870a6e3d449664c2` | + +#### Katana (chainId 747474) — Morpho Vaults + +| Vault | Asset | TVL | Address | +|-------|-------|-----|---------| +| Gauntlet USDT | USDT | ~$97M | `0x1ecdc3f2b5e90bfb55ff45a7476ff98a8957388e` | +| Steakhouse Prime USDC | USDC | ~$54M | `0x61d4f9d3797ba4da152238c53a6f93fb665c3c1d` | +| Yearn OG ETH | WETH | ~$16M | `0xfade0c546f44e33c134c4036207b314ac643dc2e` | +| Yearn OG USDC | USDC | ~$16M | `0xce2b8e464fc7b5e58710c24b7e5ebfb6027f29d7` | +| Gauntlet USDC | USDC | ~$8M | `0xe4248e2105508fcbad3fe95691551d1af14015f7` | +| Yearn OG USDT | USDT | ~$8M | `0x8ed68f91afbe5871dce31ae007a936ebe8511d47` | +| Gauntlet WETH | WETH | ~$6M | `0xc5e7ab07030305fc925175b25b93b285d40dcdff` | +| Hyperithm vbUSDC Apex | USDC | ~$3M | `0xef77f8c53af95f3348cee0fb2a02ee02ab9cdca5` | + +--- + +## Full DeFi Flow Example + +```bash +# 1. Check balances +polygon-agent balances + +# 2. Swap POL → USDC +polygon-agent swap --from POL --to USDC --amount 1 --broadcast + +# 3. Deposit USDC into highest-TVL yield pool +polygon-agent deposit --asset USDC --amount 1 --broadcast +# → protocol: morpho (or aave, whichever has highest TVL at the time) +# → poolApy shown in dry-run output + +# 4. Bridge remaining USDC to Arbitrum +polygon-agent swap --from USDC --to USDC --amount 0.5 --to-chain arbitrum --broadcast +``` + +--- + +## Troubleshooting + +| Error | Cause | Fix | +|-------|-------|-----| +| `Deposit session rejected` | Pool contract not whitelisted in session | Re-create wallet with `--contract ` | +| `Protocol X not yet supported` | Trails returned a protocol other than aave/morpho | Use `polygon-agent swap` to obtain the yield-bearing token manually | +| `Fee option errors` | Wallet has insufficient balance | Run `polygon-agent balances` and fund the wallet | +| `swap`: no route found | Insufficient liquidity for the pair | Try a different amount or token pair | diff --git a/packages/connector-ui/public/polygon-discovery/SKILL.md b/packages/connector-ui/public/polygon-discovery/SKILL.md new file mode 100644 index 0000000..27509bb --- /dev/null +++ b/packages/connector-ui/public/polygon-discovery/SKILL.md @@ -0,0 +1,117 @@ +--- +name: polygon-discovery +description: x402 Bazaar — pay-per-call API services accessible via the Polygon Agent CLI. No API keys or subscriptions needed. Each call costs a small USDC amount drawn from the agent's smart wallet. Covers web search, news, AI image generation, Twitter/X data, code review, text summarization, sentiment analysis, and article extraction. +--- + +# x402 Bazaar Services + +Pay-per-call APIs accessible via `x402-pay`. No API keys or subscriptions — each call costs a small USDC amount drawn from your wallet. The CLI detects the 402 response, funds the exact amount, and retries automatically. + +**Catalog:** `GET https://x402-api.onrender.com/api/catalog?status=online` + +--- + +## Prerequisites — Check Before Any x402 Call + +Before running any `x402-pay` command, verify the wallet session exists and is funded: + +```bash +# Check if a wallet is configured +polygon-agent wallet list +``` + +**If no wallet is listed**, the smart session has not been created. Run through the complete setup flow before proceeding: + +1. `polygon-agent setup --name "MyAgent"` — creates EOA and Sequence project +2. `polygon-agent wallet create --usdc-limit 100` — opens browser for session approval; enter the 6-digit code when prompted +3. `polygon-agent wallet address` — get address, then fund via https://agentconnect.polygon.technology +4. `polygon-agent balances` — confirm USDC is available before calling any x402 endpoint + +**If a wallet exists but `balances` shows 0 USDC**, direct the user to fund it via the UI — `x402-pay` will fail with an EOA funding error otherwise. + +Once a funded wallet is confirmed, proceed with the x402 calls below. + +--- + +## Read Twitter/X Profile + +$0.005 USDC per call. + +> **Note:** The catalog proxy (`/api/call/99063826-...`) returns 401 or HTML for this service. +> Use the direct endpoint below instead. + +```bash +# Profile + recent tweets +polygon-agent x402-pay \ + --url "https://x402-api.onrender.com/api/twitter?user=" \ + --wallet main --method POST + +# Specific tweet +polygon-agent x402-pay \ + --url "https://x402-api.onrender.com/api/twitter?tweet=https://x.com/user/status/" \ + --wallet main --method POST +``` + +Returns: follower/following counts and tweet metrics. + +**Troubleshooting:** If the direct endpoint fails, check the live catalog for the current URL: +```bash +curl -s "https://x402-api.onrender.com/api/catalog?status=online" \ + | jq '.[] | select(.name | test("twitter"; "i"))' +``` + +--- + +## Generate an AI Image + +$0.02 USDC per call. Powered by Google Gemini. + +```bash +polygon-agent x402-pay \ + --url "https://x402-api.onrender.com/api/call/2998d205-94d9-4f7e-8f8a-201a090a5530?prompt=&size=512" \ + --wallet main --method GET +``` + +`size` options: `256`, `512`, `1024`. Returns JSON with `data_uri` (base64 PNG) for embedding. + +--- + +## Review Code for Bugs & Security + +$0.01 USDC per call. Powered by GPT-4o. + +```bash +polygon-agent x402-pay \ + --url "https://x402-api.onrender.com/api/call/7f21e675-9fdc-4ba3-9a8d-145c6ac703c7" \ + --wallet main \ + --body '{"code": "", "language": ""}' +``` + +Returns: bugs, security issues, performance problems, and style suggestions — each with line number, severity, and fix suggestion. Plus an overall quality score. + +--- + +## Other Services + +| Service | Price | Endpoint | Key param | +|---------|-------|----------|-----------| +| Web search (DuckDuckGo) | $0.005 | `9b0f5b5f-8e6c-4b55-a264-008e4e490c26` | `?q=&max=10` | +| Latest news (Google News) | $0.005 | `266d045f-bae2-4c71-9469-3638ec860fc4` | `?topic=&lang=en` | +| Summarize text (GPT-4o-mini) | $0.01 | `dd9b5098-700d-47a9-a41a-c9eae66ca49d` | `?text=&maxLength=200` | +| Article → Markdown | $0.005 | `87b50238-5b99-4521-b5e1-7515a9c1526d` | `?url=` | +| Sentiment analysis (GPT-4o-mini) | $0.005 | `66d68ca6-a8d9-41a3-b024-a3fac2f5c7ba` | `?text=` | + +All use GET via `polygon-agent x402-pay --url "https://x402-api.onrender.com/api/call/" --wallet main --method GET`. + +--- + +## How x402 Works + +1. CLI sends the request to the endpoint +2. Endpoint responds with `HTTP 402 Payment Required` + payment details +3. CLI automatically funds the builder EOA with the exact token amount from the smart wallet +4. EOA signs an EIP-3009 payment authorization +5. CLI retries the original request with the payment header +6. Response is returned — the whole flow is transparent to the agent + +Chain and token are auto-detected from the 402 response. No manual configuration needed. diff --git a/packages/connector-ui/public/polygon-polymarket/SKILL.md b/packages/connector-ui/public/polygon-polymarket/SKILL.md new file mode 100644 index 0000000..0cac0ff --- /dev/null +++ b/packages/connector-ui/public/polygon-polymarket/SKILL.md @@ -0,0 +1,330 @@ +--- +name: polymarket-skill +description: Place bets on Polymarket prediction markets using the Polygon Agent CLI. Browse markets, check prices, buy YES/NO positions, sell positions, manage orders. All commands are JSON output. Dry-run by default — always add --broadcast to execute. +--- + +# Polymarket Skill + +## Session Initialization + +Before any polymarket command, initialize the session. Read `~/.polygon-agent/builder.json` and export the access key: + +```bash +export SEQUENCE_PROJECT_ACCESS_KEY= +export SEQUENCE_INDEXER_ACCESS_KEY=$SEQUENCE_PROJECT_ACCESS_KEY +``` + +Also verify the Polymarket key is set: +```bash +polygon-agent polymarket proxy-wallet +``` +If this returns `ok: true` with an `eoaAddress` and `proxyWalletAddress`, the key is configured. If it errors, the user needs to run `set-key` (see Onboarding below). + +--- + +## Understanding the 3 Addresses + +Every Polymarket user has three addresses. Do not confuse them: + +| Name | What it is | Used for | +|------|-----------|---------| +| EOA | Private key owner. Shown as `eoaAddress` in CLI output | Signs transactions and CLOB orders. Holds POL for gas | +| Proxy Wallet | Shown as `proxyWalletAddress` in CLI output. This is what Polymarket shows as "your address" in the UI | Holds USDC.e and outcome tokens. The CLOB `maker` | +| Deposit Address | A cross-chain bridge ingress — only relevant for bridging from other chains | Ignore for Polygon-native usage | + +**For trading:** funds go from the Sequence smart wallet → proxy wallet → CLOB orders. The proxy wallet is the trading identity. + +--- + +## Onboarding: First-Time Setup + +### Option A — Using email login (Polymarket account) + +If the user has a Polymarket account via email login: + +**Step 1: Get the private key from Polymarket** +``` +1. Go to: https://reveal.magic.link/polymarket +2. Connect/authenticate with the same email used for Polymarket +3. Copy the exported private key (0x...) +``` + +**Step 2: Accept Terms of Service** +``` +1. Go to: https://polymarket.com +2. Connect wallet using the exported private key (import to MetaMask or similar) +3. Accept Terms of Service when prompted + — This is REQUIRED for CLOB order placement. Without it, orders will fail. +``` + +**Step 3: Import the key into the CLI** +```bash +polygon-agent polymarket set-key +``` +Output confirms the `eoaAddress` and `proxyWalletAddress`. + +**Step 3b: Confirm your addresses (show this to the user)** +```bash +polygon-agent polymarket proxy-wallet +``` +**Tell the user:** "Your EOA is `` — this needs POL for gas. Your Polymarket trading address (proxy wallet) is `` — this is where your USDC.e and outcome tokens live. The proxy wallet does not need POL. You must fund the EOA with POL and run approvals before trading." + +**Step 4: Fund the EOA with POL for gas** +```bash +# Check EOA address from set-key output, then send ~0.1 POL to it +polygon-agent send-native --to --amount 0.1 --broadcast +``` + +**Step 5: Set proxy wallet approvals (one-time, permanent)** +```bash +polygon-agent polymarket approve --broadcast +``` +This sends a transaction directly from the EOA (not through Polymarket's UI), so the EOA must hold POL for gas. This is different from trading on polymarket.com, where their UI sponsors gas for you. + +### Option B — Using the builder EOA (no Polymarket account needed) + +If the user has done `polygon-agent setup` already, the builder EOA can be used directly. Skip `set-key`. + +**Step 1: Confirm addresses (show this to the user)** +```bash +polygon-agent polymarket proxy-wallet +``` +**Tell the user:** "Your EOA is `` — this needs POL for gas. Your Polymarket trading address (proxy wallet) is `` — this is where your USDC.e and outcome tokens live. The proxy wallet does not need POL. You must accept Polymarket ToS, fund the EOA with POL, and run approvals before trading." + +**Step 2: Accept Terms of Service (required — CLOB orders will fail without this)** +``` +1. Go to https://polymarket.com +2. Connect with the EOA wallet address shown above +3. Accept Terms of Service when prompted +``` + +**Step 3: Fund the EOA with POL for gas** +```bash +polygon-agent send-native --to --amount 0.1 --broadcast +``` + +**Step 4: Set proxy wallet approvals (one-time)** +```bash +polygon-agent polymarket approve --broadcast +``` +This sends a transaction directly from the EOA (not through Polymarket's UI), so the EOA must hold POL for gas. + +--- + +## Commands + +### Browse Markets + +```bash +# List top markets by volume +polygon-agent polymarket markets + +# Search by keyword +polygon-agent polymarket markets --search "bitcoin" --limit 10 + +# Paginate +polygon-agent polymarket markets --limit 20 --offset 20 +``` + +Key output fields per market: +- `conditionId` — the ID needed for all trading commands +- `question` — what the market is asking +- `yesPrice` / `noPrice` — current probability (0 to 1, e.g. `0.65` = 65%) +- `negRisk` — if `true`, set neg-risk approvals before trading this market +- `endDate` — when the market resolves + +### Get a Single Market + +```bash +polygon-agent polymarket market +``` + +Use this to confirm prices and token IDs before placing an order. + +### Show Proxy Wallet Address + +```bash +polygon-agent polymarket proxy-wallet +``` + +Confirms which EOA and proxy wallet are active. The proxy wallet is where USDC.e and tokens are held. + +### Set Approvals (One-Time) + +```bash +# Standard markets +polygon-agent polymarket approve --broadcast + +# Neg-risk markets (if you see negRisk: true on any market you want to trade) +polygon-agent polymarket approve --neg-risk --broadcast +``` + +Run once per EOA. Permanent on-chain — no need to repeat unless enabling neg-risk. +**Dry-run (no --broadcast) shows what will be approved without executing.** + +### Buy a Position + +```bash +# Dry-run first — always check before executing +polygon-agent polymarket clob-buy YES|NO + +# Execute — funds proxy wallet from smart wallet, then places order +polygon-agent polymarket clob-buy YES|NO --broadcast + +# If proxy wallet already has USDC.e (skip the funding step) +polygon-agent polymarket clob-buy YES|NO --skip-fund --broadcast + +# Limit order — fill only at this price or better +polygon-agent polymarket clob-buy YES --price 0.45 --broadcast +``` + +**How it works:** +1. Smart wallet transfers `usdcAmount` USDC.e to the proxy wallet (Sequence tx, USDC.e fee) +2. Posts CLOB BUY order: maker=proxy wallet, signer=EOA (off-chain, no gas) +3. Tokens arrive in proxy wallet on fill + +**Order types:** +- No `--price`: FOK market order (fill entirely or cancel) +- `--fak`: FAK market order (partial fills allowed) +- `--price 0.x`: GTC limit order (stays open until filled or cancelled) + +**Minimum order size: $1 USDC.** The CLOB rejects marketable BUY orders below $1. If the fund step runs but the order is rejected, the USDC.e stays in the proxy wallet — use `--skip-fund` on the retry. + +### Sell a Position + +```bash +# Dry-run first +polygon-agent polymarket sell YES|NO + +# Execute +polygon-agent polymarket sell YES|NO --broadcast + +# Limit sell +polygon-agent polymarket sell YES --price 0.80 --broadcast +``` + +`` is the number of outcome tokens (not USD). Get share count from `positions`. +Selling is pure off-chain — no gas, no on-chain tx. + +### Check Positions + +```bash +polygon-agent polymarket positions +``` + +Shows all open positions in the proxy wallet with current value, P&L, and outcome. + +### Check Open Orders + +```bash +polygon-agent polymarket orders +``` + +Lists GTC limit orders that are still open (FOK/FAK orders are never "open" — they fill or cancel immediately). + +### Cancel an Order + +```bash +polygon-agent polymarket cancel +``` + +Get `orderId` from the `orders` command or from the `orderId` field in `clob-buy` output. + +--- + +## Full Autonomous Trading Flow + +This is the exact sequence to go from zero to a filled trade: + +```bash +# ── SETUP (run once per EOA) ──────────────────────────────────────────── + +# 1. Import your Polymarket private key +# (get it from https://reveal.magic.link/polymarket after email login) +polygon-agent polymarket set-key 0x +# → save eoaAddress and proxyWalletAddress from output + +# 2. Fund the EOA with POL for gas +polygon-agent send-native --to --amount 0.1 --broadcast + +# 3. Set proxy wallet approvals (one-time) +polygon-agent polymarket approve --broadcast +# → save approveTxHash, wait for confirmation + +# ── FIND A MARKET ──────────────────────────────────────────────────────── + +# 4. Search for markets +polygon-agent polymarket markets --search "fed rate" --limit 10 + +# 5. Get details on a specific market +polygon-agent polymarket market 0x +# → check: yesPrice, noPrice, negRisk, endDate +# → if negRisk: true → run approve --neg-risk --broadcast first + +# ── ENTER A POSITION ──────────────────────────────────────────────────── + +# 6. Dry-run to confirm everything +polygon-agent polymarket clob-buy 0x YES 5 +# → review: currentPrice, proxyWalletAddress, flow + +# 7. Execute +polygon-agent polymarket clob-buy 0x YES 5 --broadcast +# → save orderId, check orderStatus === "matched" + +# ── MANAGE ────────────────────────────────────────────────────────────── + +# 8. Check your positions +polygon-agent polymarket positions +# → review: size (shares), curPrice, cashPnl, title, outcome + +# 9. Sell when ready +polygon-agent polymarket sell 0x YES --broadcast +# → orderStatus === "matched" means USDC.e is back in proxy wallet +``` + +--- + +## Decision Logic for an Autonomous Agent + +When deciding whether to buy: +1. Check `positions` — avoid doubling up on already-held positions +2. Check `markets` — use `yesPrice`/`noPrice` as probability inputs +3. Check `negRisk` — if `true`, verify neg-risk approvals were set +4. Check proxy wallet USDC.e balance before buying (use `proxy-wallet` to get address, then check balance externally or via `balances`) +5. Use `--skip-fund` if the proxy wallet already has enough USDC.e from a previous `clob-buy` +6. Always dry-run first, then broadcast + +When deciding whether to sell: +1. Get current `size` (shares) from `positions` +2. Use `curPrice` vs `avgPrice` to assess profit/loss +3. Market sell (`sell --broadcast`) for immediate exit +4. Limit sell (`--price 0.x --broadcast`) to wait for a better price + +--- + +## Troubleshooting + +| Error | Cause | Fix | +|-------|-------|-----| +| `No EOA key found` | `set-key` not run | Run `polygon-agent polymarket set-key ` | +| `Could not create api key` (stderr) | ToS not accepted | Visit polymarket.com, connect EOA wallet, accept terms. This error in **stderr** is non-fatal — the CLI retries with `deriveApiKey` and may still succeed. | +| `CLOB order error: not authorized` | ToS not accepted | Same as above — fatal for order posting | +| `insufficient funds for gas` | EOA has no POL | `polygon-agent send-native --to --amount 0.1 --broadcast` | +| `execution reverted: must be called be owner` | Old code calling proxy directly | Upgrade CLI — fixed in current version (calls factory) | +| `Market not found` | Low-volume or closed market | Market may have resolved; try `--search` with different terms | +| `Market has no tokenIds` | Closed market | Check `endDate` — market resolved | +| `orderStatus: "unmatched"` on FOK | No liquidity at market price | Try `--fak` for partial fill, or `--price 0.x` for limit order | +| `invalid amount for a marketable BUY order ($X), min size: $1` | Amount below CLOB minimum | Use at least $1. If USDC.e was already funded, retry with `--skip-fund` | +| `Wallet not found: main` | No Sequence wallet | Run `polygon-agent wallet create` | + +--- + +## Key Facts for Agents + +- **All commands are dry-run by default.** `approve`, `clob-buy`, `sell` do nothing without `--broadcast`. +- **`clob-buy` transfers USDC.e from the smart wallet to the proxy wallet automatically** (unless `--skip-fund`). +- **Positions live in the proxy wallet**, not the Sequence smart wallet. `positions` queries the proxy wallet. +- **Approvals are one-time.** Don't run `approve` before every trade — only once per EOA (and once more if enabling neg-risk). +- **Sell is free.** No gas, no on-chain tx. Selling via CLOB is a signed off-chain message only. +- **`orderStatus: "matched"`** means the trade filled. `"unmatched"` means FOK failed (no liquidity). +- **The proxy wallet address never changes.** It is deterministic from the EOA via CREATE2.