> For the complete documentation index, see [llms.txt](https://gotts.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gotts.gitbook.io/docs/skills/skills/03-skills-trading.md).

# Trading Skills

> **Directory**: `packages/safe/skills/` | **Prerequisites**: [02-architecture.md](/docs/skills/skills/02-architecture.md)
>
> Skills for token swaps, limit orders, and cross-chain operations.

***

## Trading Skills

These skills handle token swaps, limit orders, and cross-chain operations.

***

#### A1. `execute-swap`

**Purpose:** Execute a token swap on any supported chain. The primary entry point for all swap operations.

**MCP Tools Used:** `search_tokens`, `check_safety_status`, `get_quote`, `execute_swap`, `simulate_transaction`, `simulate_price_impact`, `validate_token`, `check_allowance`, `approve_token`, `assess_mev_risk`, `compare_venues`, `detect_honeypot` (via trade-executor + safety-guardian)

**Slash Command:** `/execute-swap`

**Frontmatter:**

```yaml
---
description: >-
  Execute a Uniswap token swap. Use when user wants to swap, trade, buy, or sell
  tokens. Handles quotes, safety checks, simulation, and execution autonomously.
  Supports V2, V3, V4, UniswapX, and cross-chain routing on all supported chains.
allowed-tools: >-
  Read, Glob, Grep,
  Task(subagent_type:trade-executor),
  mcp__uniswap__get_supported_chains,
  mcp__uniswap__search_tokens,
  mcp__uniswap__check_safety_status
model: opus
---
```

**Activation Triggers:**

* "Swap X for Y"
* "Buy X with Y"
* "Sell X for Y"
* "Trade X for Y"
* "Exchange X to Y"
* "Convert X to Y"
* Any mention of swapping tokens + Uniswap context

**Parameters Extracted from User Intent:**

| Parameter  | Required | Extracted From            | Example                                  |
| ---------- | -------- | ------------------------- | ---------------------------------------- |
| `tokenIn`  | Yes      | Token name/symbol/address | "USDC", "0xA0b8..."                      |
| `tokenOut` | Yes      | Token name/symbol/address | "ETH", "WETH"                            |
| `amount`   | Yes      | Numeric value             | "500", "1.5"                             |
| `chain`    | No       | Chain name or context     | "Base", "Arbitrum", defaults to Ethereum |
| `slippage` | No       | Explicit or default       | "0.5%", defaults to 0.5%                 |
| `routing`  | No       | Preference if stated      | "via V3", "use UniswapX"                 |

**Workflow:**

```
1. PARSE USER INTENT
   - Extract tokenIn, tokenOut, amount, chain from natural language
   - If ambiguous, ask for clarification (e.g., "Which chain?")
   - Resolve "ETH" to native ETH handling (wrap/unwrap)

2. PRE-FLIGHT VALIDATION
   - Check safety status via check_safety_status
   - Verify spending limits have headroom for this trade
   - If limits would be exceeded, inform user and stop

3. DELEGATE TO TRADE-EXECUTOR
   - Task(subagent_type:trade-executor) with:
     - tokenIn, tokenOut, amount, chain
     - slippageTolerance, routingPreference
   - Trade-executor handles: quote, simulate, safety-guardian, execute

4. PRE-FLIGHT DASHBOARD (NEW)
   Before confirming execution, generate a pre-flight report:
   - Quote summary: input/output amounts, exchange rate, price impact %
   - Route visualization: hops, pool addresses, fee tiers at each step
   - Historical slippage: median slippage for this pair over last 24h
   - Gas cost estimate with current gas prices and L1/L2 comparison
   - Alternative routes: UniswapX Dutch auction vs V3 direct vs V4 hooked pool
   - Venue comparison: Uniswap vs 1inch/Paraswap/CoW (via compare_venues), show delta
   - Approval status: Permit2 allowance check, recommended approval amount
   - Automatic quote refresh if quote age exceeds 15 seconds
   - Memory Insights (when `learning` profile active):
     Surface relevant episodic memories and semantic insights via `search_memory`:
     - Past slippage outcomes for this token pair on this chain
     - Historical route performance (which routing type worked best)
     - Timing patterns (gas cost trends, optimal execution windows)
     - Any active insights with confidence >= 0.5 for this pair
     Memory insights are advisory only — they cannot override safety checks or spending limits

5. FORMAT RESULT
   - Display: tx hash, amounts in/out, price achieved
   - Display: routing type (e.g., "Executed via UniswapX V2 — gasless" or "Executed via V4 CLASSIC")
   - Display: gas cost (or "Gasless" for UniswapX/PRIORITY routing)
   - Display: price impact, slippage
   - Display: explorer link
   - Display: safety checks summary
   - Display: pre-flight dashboard summary (venue chosen, route)
   - Display: memory insights used (when `learning` profile active)
   - If failed: display error reason and suggested action
   - Note: when `learning` profile active, trade outcome is recorded as
     episodic memory via `store_episode` (handled by trade-executor agent)

> **Note:** All swap operations route through the Uniswap Trading API when `GOTTS_UNISWAP_API_KEY` is configured. This is transparent to the user — the output shows routing type and gas savings from UniswapX when applicable.
```

**Output Format:**

```
Pre-Flight Dashboard
  Quote:     500.00 USDC -> 0.1538 WETH ($499.55)
  Route:     USDC -> WETH via V3 0.05% pool
  Venue:     Uniswap V3 (best net output: $499.55 vs $499.10 1inch)
  Routing:   CLASSIC (V3 0.05% pool)
  Gas:       $0.42 (Base, current: below 24h average)
  Slippage:  0.01% (median 24h: 0.02%)

Swap Executed Successfully

  Input:  500.00 USDC
  Output: 0.1538 WETH ($499.55)
  Price:  1 WETH = $3,248.04
  Routing: CLASSIC via V3 0.05% pool
  Impact: 0.01%
  Gas:    $0.42

  Tx: https://basescan.org/tx/0xABC...

  Safety: All 7 checks passed
```

**Error Handling:**

| Error                            | User-Facing Message                                                        | Suggested Action                          |
| -------------------------------- | -------------------------------------------------------------------------- | ----------------------------------------- |
| `SAFETY_SPENDING_LIMIT_EXCEEDED` | "This swap would exceed your $X daily spending limit. $Y remaining today." | Reduce amount or wait for limit reset     |
| `SAFETY_TOKEN_NOT_ALLOWED`       | "TOKEN is not on your allowlist. Add it to your config to trade."          | Add token to allowlist config             |
| `SAFETY_SIMULATION_FAILED`       | "Swap simulation failed: \[reason]. The transaction would revert."         | Check token addresses, try smaller amount |
| `INSUFFICIENT_LIQUIDITY`         | "Not enough liquidity to execute this swap at acceptable slippage."        | Try a smaller amount or different route   |

***

#### A2. `batch-swap`

**Purpose:** Execute multiple swaps in sequence. Useful for rebalancing a portfolio or executing a multi-token strategy.

**MCP Tools Used:** `check_safety_status`, `get_agent_balance`, `get_quote`, `execute_swap`, `simulate_transaction` (via trade-executor)

**Slash Command:** `/batch-swap`

**Frontmatter:**

```yaml
---
description: >-
  Execute multiple token swaps in sequence. Use when user wants to rebalance,
  swap into multiple tokens, or execute a multi-step trading plan. Each swap
  goes through full safety validation independently.
allowed-tools: >-
  Read, Glob, Grep,
  Task(subagent_type:trade-executor),
  mcp__uniswap__check_safety_status,
  mcp__uniswap__get_agent_balance
model: opus
---
```

**Activation Triggers:**

* "Swap X for Y and Z"
* "Rebalance to 50% ETH 50% USDC"
* "Buy 3 different tokens"
* "Execute these swaps: ..."

**Parameters Extracted:**

| Parameter       | Required | Example                                          |
| --------------- | -------- | ------------------------------------------------ |
| `swaps`         | Yes      | List of {tokenIn, tokenOut, amount, chain}       |
| `chain`         | No       | Default chain for all swaps                      |
| `stopOnFailure` | No       | Whether to halt on first failure (default: true) |

**Workflow:**

```
1. PARSE SWAP LIST
   - Extract individual swaps from user intent
   - Validate each swap independently
   - Calculate total spending across all swaps

2. PRE-FLIGHT CHECK
   - Verify total spending is within daily limits
   - Verify sufficient balance for all swaps
   - Order swaps optimally (sell before buy if using proceeds)

3. EXECUTE SEQUENTIALLY
   - For each swap:
     a. Delegate to trade-executor
     b. Wait for confirmation
     c. Log result
     d. If failure and stopOnFailure: halt and report
     e. Update running balance for next swap

4. REPORT
   - Summary table of all executed swaps
   - Total gas spent
   - Any failed swaps with reasons
   - Note: when `learning` profile active, each individual swap generates
     an episodic memory via trade-executor. A batch-level insight is also
     recorded if the batch contains 3+ swaps (e.g., rebalance success rate,
     optimal ordering patterns).
```

***

#### A3. `submit-limit-order`

**Purpose:** Submit a UniswapX limit order (Dutch auction) for potentially better execution through off-chain fillers.

**MCP Tools Used:** `get_quote`, `submit_uniswapx_order`, `get_uniswapx_order_status`, `check_safety_status` (via trade-executor)

**Slash Command:** `/submit-limit-order`

**Frontmatter:**

```yaml
---
description: >-
  Submit a UniswapX Dutch auction limit order. Use when user wants to set a
  limit price, get best-price execution, or submit an order that fills at
  the best available price. No gas cost until filled.
allowed-tools: >-
  Read, Glob, Grep,
  Task(subagent_type:trade-executor),
  mcp__uniswap__get_quote,
  mcp__uniswap__submit_uniswapx_order,
  mcp__uniswap__get_uniswapx_order_status,
  mcp__uniswap__check_safety_status
model: opus
---
```

**Activation Triggers:**

* "Set a limit order"
* "Buy X at price Y"
* "Submit a UniswapX order"
* "Limit buy/sell"

**Parameters Extracted:**

| Parameter    | Required | Example                                              |
| ------------ | -------- | ---------------------------------------------------- |
| `tokenIn`    | Yes      | "USDC"                                               |
| `tokenOut`   | Yes      | "WETH"                                               |
| `amount`     | Yes      | "1000"                                               |
| `chain`      | No       | "ethereum" (default)                                 |
| `limitPrice` | No       | Target price (if specified, calculates decay params) |
| `expiry`     | No       | "5 minutes" (default: 5 min decay)                   |

**Workflow:**

```
1. PARSE INTENT
   - Extract tokens, amount, chain, price target
   - If limit price specified, calculate decay start/end amounts
   - If no price, get current market quote as baseline

2. VALIDATE
   - Check token allowlist
   - Check spending limits
   - Verify chain supports UniswapX

3. SUBMIT ORDER
   - Delegate to trade-executor with UniswapX routing preference
   - Sign the order (gasless -- only signature required)

4. MONITOR (optional)
   - Poll order status periodically
   - Report when filled, expired, or cancelled
```

***

#### A4. `cross-chain-swap`

**Purpose:** Execute a cross-chain token swap or bridge operation via ERC-7683 intents or the Uniswap Trading API bridge routing. When `GOTTS_UNISWAP_API_KEY` is configured, uses CHAINED routing via Trading API (`POST /quote` with `x-chained-actions-enabled` header and different `tokenInChainId`/`tokenOutChainId`). Handles both BRIDGE routing (single source tx) and CHAINED routing (multi-step via `/plan` endpoint).

**MCP Tools Used:** `get_supported_chains`, `check_safety_status`, `submit_cross_chain_intent`, `get_bridge_status`, `simulate_transaction` (via cross-chain-executor)

**Slash Command:** `/cross-chain-swap`

**Frontmatter:**

```yaml
---
description: >-
  Execute a cross-chain swap or bridge. Use when user wants to move tokens
  between chains, swap tokens across different chains, or bridge assets.
  Supports ERC-7683 cross-chain intents for optimal execution. Monitors
  bridge settlement and confirms arrival on destination chain.
allowed-tools: >-
  Read, Glob, Grep,
  Task(subagent_type:cross-chain-executor),
  mcp__uniswap__get_supported_chains,
  mcp__uniswap__check_safety_status
model: opus
---
```

**Activation Triggers:**

* "Bridge X from Y to Z"
* "Swap X on chain A for Y on chain B"
* "Move my tokens to Base"
* "Cross-chain swap"
* "Transfer USDC from Mainnet to Arbitrum"

**Parameters Extracted:**

| Parameter          | Required | Example                                            |
| ------------------ | -------- | -------------------------------------------------- |
| `tokenIn`          | Yes      | "USDC"                                             |
| `tokenOut`         | No       | Same as tokenIn if bridging, different if swapping |
| `amount`           | Yes      | "1000"                                             |
| `sourceChain`      | Yes      | "ethereum"                                         |
| `destinationChain` | Yes      | "base"                                             |
| `bridgeSafety`     | No       | "auto" (default), "strict", "permissive"           |

**Workflow:**

```
1. PARSE INTENT
   - Determine if bridge-only or swap+bridge
   - Resolve token addresses on both chains
   - Validate both chains are supported

1b. BRIDGE SAFETY VERIFICATION
   - Pre-flight check on the bridge that will be used:
     - Audit status: has the bridge been audited? By whom? When?
     - TVL: current bridge TVL (low TVL = higher risk)
     - Validator set: decentralized or multisig? How many signers?
     - Recent incidents: any exploits, pauses, or delays in last 90 days?
   - Risk classification:
     - GREEN: Audited, >$100M TVL, decentralized validators, no recent incidents
     - YELLOW: Audited, >$10M TVL, multisig validators, minor incidents
     - RED: Unaudited, <$10M TVL, centralized, or recent exploit
   - If bridgeSafety="strict" and bridge is YELLOW or RED: block and warn
   - If bridgeSafety="auto" and bridge is RED: warn and require confirmation
   - If bridgeSafety="permissive": proceed with warning only

2. DELEGATE TO CROSS-CHAIN-EXECUTOR
   - Agent handles: quote, route selection, safety, execution, monitoring
   - Monitors bridge settlement (polls every 30s)
   - Confirms arrival on destination chain

3. FORMAT RESULT
   - Source chain tx hash and explorer link
   - Bridge/intent ID and tracking URL
   - Destination chain confirmation
   - Total fees (gas + bridge fee)
   - Settlement time
```

***

#### A5. `bridge-tokens`

**Purpose:** Bridge tokens between chains without swapping. A simplified version of `cross-chain-swap` for same-token transfers.

**MCP Tools Used:** `get_supported_chains`, `get_agent_balance`, `submit_cross_chain_intent`, `get_bridge_status` (via cross-chain-executor)

**Slash Command:** `/bridge-tokens`

**Frontmatter:**

```yaml
---
description: >-
  Bridge tokens between chains without swapping. Use when user wants to move
  the same token from one chain to another. Simpler than cross-chain-swap
  when no token conversion is needed.
allowed-tools: >-
  Read, Glob, Grep,
  Task(subagent_type:cross-chain-executor),
  mcp__uniswap__get_supported_chains,
  mcp__uniswap__get_agent_balance
model: opus
---
```

**Activation Triggers:**

* "Bridge my USDC to Base"
* "Send ETH to Arbitrum"
* "Move tokens between chains"

**Parameters Extracted:**

| Parameter          | Required | Example    |
| ------------------ | -------- | ---------- |
| `token`            | Yes      | "USDC"     |
| `amount`           | Yes      | "1000"     |
| `sourceChain`      | Yes      | "ethereum" |
| `destinationChain` | Yes      | "base"     |

**Workflow:** Delegates to `cross-chain-executor` with `tokenOut` = `tokenIn`.

***

#### A6. `plan-swap`

**Purpose:** Advisory swap planning that generates Uniswap app deep links instead of executing directly. For user-in-the-loop workflows where the agent plans but the human confirms in the browser. When `GOTTS_UNISWAP_API_KEY` is configured, uses `POST /quote` (no execution) to get detailed breakdown including routing type, UniswapX availability, gas estimate, and price impact — providing more accurate pre-trade analysis than SDK-only estimation.

**MCP Tools Used:** `search_tokens`, `generate_uniswap_link`, `assess_mev_risk`, `compare_venues` (via trade-executor). **Requires Phase 7 intelligence tools.**

**Slash Command:** `/plan-swap`

**Frontmatter:**

```yaml
---
description: >-
  Plan a swap and generate a Uniswap app deep link for user confirmation.
  Use when user wants to review a swap in the Uniswap interface before
  executing, or when the agent should advise but not execute autonomously.
allowed-tools: >-
  Read, Glob, Grep,
  Task(subagent_type:trade-executor),
  mcp__uniswap__search_tokens,
  mcp__uniswap__generate_uniswap_link,
  mcp__uniswap__assess_mev_risk,
  mcp__uniswap__compare_venues
model: opus
---
```

**Activation Triggers:**

* "Plan a swap of X for Y"
* "Generate a swap link for X"
* "Show me the Uniswap URL for X to Y"
* "Prepare a swap but don't execute"

**Parameters Extracted:**

| Parameter  | Required | Example                    |
| ---------- | -------- | -------------------------- |
| `tokenIn`  | Yes      | "USDC"                     |
| `tokenOut` | Yes      | "ETH"                      |
| `amount`   | Yes      | "500"                      |
| `chain`    | No       | "base" (default: ethereum) |

**Workflow:**

```
1. RESOLVE TOKENS AND ASSESS
   - Resolve token symbols to addresses
   - Run pre-flight analysis: MEV risk, venue comparison, gas cost

2. GENERATE DEEP LINK
   - Use generate_uniswap_link to create a swap URL
   - Include pre-filled amount and token addresses

3. FORMAT RESULT
   - Pre-flight dashboard (same as execute-swap)
   - Uniswap app deep link for user to click
   - Note: "Click the link to review and confirm in the Uniswap app"
```

***
