Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions skills/uniswap-trading/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# uniswap-trading agent skill

An AI-agent integration for uniswap-python: [SKILL.md](SKILL.md) plus a
subprocess CLI, `scripts/uniswap_agent.py --json`. Agents can quote, inspect
balances, and prepare swaps. Transactions require an explicit `--broadcast`;
production-chain broadcasts additionally require both mainnet opt-ins.

## Install

Use a repository checkout containing this directory and install the library
from its root with `python3 -m pip install .` in a virtual environment. The
Python wheel does not install the skill files.

- **Claude Code:** symlink or copy this directory into
`~/.claude/skills/uniswap-trading` or a project's `.claude/skills/`.
- **gptme:** add this directory to the configured lessons/skills path.
- **Other agents:** invoke the CLI as a subprocess. Stdout contains a JSON
object; errors go to stderr. Exit codes: 0 success, 1 runtime error,
2 safety refusal.

## Sepolia demo

From this directory, with the virtual environment active:

```bash
./demo_sepolia.sh
```

This checks chain ID 11155111, quotes 0.001 native ETH to USDC through v2,
and prints a dry-run swap plan. It needs no wallet or private key.

To send the same swap, provision a **dedicated Sepolia-only wallet** with
0.001 testnet ETH plus gas. Set `UNISWAP_AGENT_ADDRESS` and its matching
`UNISWAP_AGENT_PRIVATE_KEY` securely in the environment, then explicitly run:

```bash
DEMO_BROADCAST=1 ./demo_sepolia.sh
```

The script prints balances before and after, the transaction hash, and the
mined receipt's status, block number, and gas used. A reverted transaction
exits nonzero. If waiting for the receipt times out, inspect the printed hash
on the same RPC before retrying; do not blindly send another swap.
`SEPOLIA_RPC` overrides the default public endpoint.

### Why v2 works without the v3/v4 library changes

The existing library configures this Sepolia v2 deployment:

| Contract | Address |
|---|---|
| Router | `0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008` |
| Factory | `0x7E0987E5b3a30e3f2828572Bb659A548460a3003` |
| Router's WETH | `0x7b79995e5f793A07Bc00c21412e50Ecae098E7f9` |
| USDC | `0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238` |
| WETH/USDC pair | `0x6c1bBfD6330CA6c3f27C29b3a3330dB2B6B0980a` |

These are the **library-configured contracts**, not the separate v2 deployment
currently listed in the [Uniswap deployment documentation](https://developers.uniswap.org/docs/protocols/v2/deployments).
Their router/factory/WETH linkage and positive quote were checked directly on
Sepolia on 2026-11-27. This demo uses only testnet assets.

Use native `ETH` input: the library resolves WETH from the router and needs
no approval transaction. The skill's `WETH` alias points to the separate v3
WETH deployment; substituting that alias changes the route. The previous demo
used v3 on Sepolia, which the wrapper deliberately refuses. v3's address/ABI
work and v4's deployment/pool work remain separate from this v2 demonstration.

### Fork replay and acceptance boundary

Run a local Sepolia fork bound to loopback:

```bash
anvil --fork-url https://ethereum-sepolia-rpc.publicnode.com \
--chain-id 11155111 --host 127.0.0.1 --port 18574
```

Use one of that fork's funded development accounts in the environment, then:

```bash
SEPOLIA_RPC=http://127.0.0.1:18574 DEMO_BROADCAST=1 ./demo_sepolia.sh
```

Never use a public Anvil development key for a funded public-chain wallet.
A local fork shares Sepolia's chain ID, so chain ID alone does **not** establish
that a transaction was published on Sepolia.

Replay on 2026-11-27, library master `16614e1cad120ac8836d6c549f33685cc48491fe`:

- Unmodified wrapper trading path, v2 native ETH input: 1,000,000,000,000,000 wei.
- Receipt status 1, gas used 113,656, local block 12,219,864.
- USDC base-unit balance: 65,200,247 → 110,303,356; received 45,103,109.
- **Local fork hash only:**
`0x8f5169e7e540933f7943400edd399d84cb43a329b70a12e64ce9e4f1ba333358`.

The public Sepolia transaction is still outstanding. To close D3, record the
public-network transaction hash, successful receipt and token transfer, exact
source revision, and command used. The fork hash above is implementation
verification, **not** that acceptance receipt.

## Tests and prior dogfood

```bash
python3 -m pytest skills/uniswap-trading/tests/ -q
```

The 41 offline tests cover safety gates, CLI results, exact amount formatting,
and the real v4 calldata minimum. The
repository's default pytest discovery includes these tests. The demo additionally
needs the live or forked contract state described above.

Prior dogfood (2026-08-27): Gordon installed the skill and verified mainnet
v3/v4 and Polygon v3 quoting. His corrections are included: human-readable
amounts, deterministic v3-testnet refusal, and double-armed mainnet broadcast.
This establishes trial use; production trading adoption is not claimed.
107 changes: 107 additions & 0 deletions skills/uniswap-trading/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
---
name: uniswap-trading
description: Quote prices and execute Uniswap v2/v3/v4 swaps via uniswap-python. Use when asked to check on-chain token prices, get swap quotes, or trade tokens on Uniswap. Testnet-first — mainnet requires explicit opt-in. Do NOT use for CEX trading, fiat, or chains without Uniswap deployments.
---

# Uniswap Trading

Trade on Uniswap through [uniswap-python](https://github.com/uniswap-python/uniswap-python)
using a single CLI: `scripts/uniswap_agent.py`. All commands are safe to
explore — state-changing operations are **dry-run unless `--broadcast`** is
passed, and non-testnet chains are refused unless explicitly allowed.

## Setup

Use a checkout containing `skills/uniswap-trading/`, then install the library
from that checkout with `python3 -m pip install .`. The skill files live in the
repository; installing the Python wheel alone does not install this directory.
Until merged, use the branch linked from the D3 pull request.

Then:

```bash
export PROVIDER=https://ethereum-sepolia-rpc.publicnode.com # any JSON-RPC endpoint
export UNISWAP_AGENT_ADDRESS=0xYourWallet # for balances/swaps
export UNISWAP_AGENT_PRIVATE_KEY=0x... # ONLY for --broadcast
```

Never echo `UNISWAP_AGENT_PRIVATE_KEY` or write it to disk. Read-only
commands (status, quote) work with just `PROVIDER`.

## Commands

```bash
SKILL_DIR="$PWD/skills/uniswap-trading" # run from the repository root

# Connectivity + wallet overview on Sepolia
python3 "$SKILL_DIR/scripts/uniswap_agent.py" --json --version 2 status

# Sepolia quote and dry-run: 0.001 native ETH to USDC, no approval needed
python3 "$SKILL_DIR/scripts/uniswap_agent.py" --json --version 2 quote ETH USDC 1000000000000000
python3 "$SKILL_DIR/scripts/uniswap_agent.py" --json --version 2 swap ETH USDC 1000000000000000

# Send only when the user authorizes this testnet transaction and funds the wallet
python3 "$SKILL_DIR/scripts/uniswap_agent.py" --json --version 2 swap ETH USDC 1000000000000000 --broadcast

# Uniswap v4 on a supported production network (set PROVIDER accordingly)
# Single-hop; pool identified by fee + tick spacing
python3 "$SKILL_DIR/scripts/uniswap_agent.py" --json --version 4 \
quote WETH USDC 10000000000000000 --fee 3000 --tick-spacing 60
```

On Sepolia use native `ETH` for this v2 demo. The `WETH` alias names the v3
deployment, which differs from the v2 router's WETH; do not substitute it.
`USDC` resolves automatically. On other chains pass token addresses when an
alias is unavailable.

## Safety rules (enforced by the CLI, exit code 2 on refusal)

1. Read-only commands (status, quote, balance) work on any chain. Broadcasting
outside known testnets (Sepolia, Arbitrum/Base/Optimism Sepolia) is
**double-armed**: it requires BOTH `UNISWAP_AGENT_ALLOW_MAINNET=1` in the
environment AND `--allow-mainnet` on the specific call. Never set the
environment arm yourself — that is the human operator's standing decision;
the flag is your per-call confirmation.
2. Nothing is signed or sent without `--broadcast`.
3. Slippage above 5% is refused (`UNISWAP_AGENT_MAX_SLIPPAGE` to override).
4. v3 on testnets is refused deterministically (exit 2) — the library's v3
contracts are mainnet-hardcoded; use v2 with native ETH for Sepolia.

## Sepolia demo

Run `./demo_sepolia.sh` from this directory for a quote and dry-run. With a
funded, dedicated Sepolia wallet, `DEMO_BROADCAST=1 ./demo_sepolia.sh` sends
one v2 native-ETH swap and checks its mined receipt. See [README.md](README.md)
for the tested deployment, fork replay, and public-testnet acceptance evidence.

The v3/v4 Sepolia library gaps do not block this v2 path. Protocol/network
support still depends on the library's contracts and available liquidity;
an accepted chain ID alone does not establish support.

## Interpreting output

With `--json`, results are a single JSON object on stdout. Errors go to
stderr as `{"error": ..., "kind": "safety"|"runtime"}`; exit code 2 means a
safety guard refused (do not retry with workarounds — report to the human),
1 means a runtime error (bad pool, no liquidity, RPC down — often worth one
retry or a different fee tier).

Amounts are integers in the token's base units (wei for ETH/WETH: 1 ETH =
10^18). Where token decimals are readable on-chain, outputs also carry
advisory `<field>_human` (decimal string) and `decimals_<field>` companions —
prefer those when showing humans, but treat the integer fields as the source
of truth (the human fields are omitted when a decimals lookup fails).

A broadcast result contains a submitted hash, not proof of success. Check the
receipt on the same chain before reporting completion or retrying. A receipt
timeout means pending/unknown; do not send a second swap automatically.

For v2/v3, `estimated_min_out` is advisory: the library requotes when it
builds the swap. For v4, `min_out` is passed to the transaction with no second
slippage reduction.

An approval response with `status: submitted` is not confirmed success. v4
returns the final Permit2 transaction hash; inspect its receipt and both the
ERC-20-to-Permit2 and Permit2-to-router allowances before trading. v2/v3
return `approved: true` only after a successful mined receipt; a reverted
approval exits nonzero and includes its transaction hash in the error.
63 changes: 63 additions & 0 deletions skills/uniswap-trading/demo_sepolia.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
# Quote and dry-run on Sepolia by default. DEMO_BROADCAST=1 sends one swap.
# Requires a dedicated Sepolia wallet with ETH for 0.001 ETH input plus gas.
set -euo pipefail

SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
AGENT=(python3 "$SKILL_DIR/scripts/uniswap_agent.py" --json --version 2)
export PROVIDER="${SEPOLIA_RPC:-https://ethereum-sepolia-rpc.publicnode.com}"
QTY=1000000000000000

# Refuse another chain even if it is accepted by the general-purpose wrapper.
status=$("${AGENT[@]}" status)
python3 - "$status" <<'PYTHON'
import json
import sys

status = json.loads(sys.argv[1])
if status["chain_id"] != 11155111:
sys.exit("This demo requires Sepolia (chain 11155111)")
print(json.dumps(status, indent=2))
PYTHON

# Native ETH uses the router's WETH address, with no ERC-20 approval needed.
echo "== Sepolia v2: quote and dry-run 0.001 ETH -> USDC =="
"${AGENT[@]}" quote ETH USDC "$QTY"
"${AGENT[@]}" swap ETH USDC "$QTY"

if [ "${DEMO_BROADCAST:-0}" != "1" ]; then
echo "Dry-run complete. Set DEMO_BROADCAST=1 with a funded Sepolia wallet to send."
exit 0
fi

: "${UNISWAP_AGENT_ADDRESS:?Set the dedicated Sepolia wallet address}"
: "${UNISWAP_AGENT_PRIVATE_KEY:?Set its private key securely in the environment}"
echo "== USDC balance before =="
"${AGENT[@]}" balance USDC
swap=$("${AGENT[@]}" swap ETH USDC "$QTY" --broadcast)
printf '%s\n' "$swap"

# A submitted hash alone is not a successful transaction. Never resend on timeout:
# inspect this hash on the same endpoint first.
python3 - "$swap" <<'PYTHON'
import json
import os
import sys
from web3 import Web3

swap = json.loads(sys.argv[1])
w3 = Web3(Web3.HTTPProvider(os.environ["PROVIDER"], request_kwargs={"timeout": 30}))
receipt = w3.eth.wait_for_transaction_receipt(swap["tx_hash"], timeout=180)
print(json.dumps({
"chain_id": w3.eth.chain_id,
"tx_hash": Web3.to_hex(receipt["transactionHash"]),
"block_number": receipt["blockNumber"],
"status": receipt["status"],
"gas_used": receipt["gasUsed"],
}, indent=2))
if receipt["status"] != 1:
sys.exit("Swap reverted; do not count this as a successful demo")
PYTHON

echo "== USDC balance after =="
"${AGENT[@]}" balance USDC
Loading
Loading