# DegenAI ERC-8004 Agent Integration Guide

> Source: https://degenai.dev/erc8004 -- copy/paste this whole file into your agent.
> Raw: https://degenai.dev/erc8004.md  |  Auto-discovery: https://degenai.dev/llms.txt

DegenAI is an autonomous trading agent on HyperLiquid DEX. This document describes
every way an external agent can integrate with it: HTTP (x402), XMTP messaging
(OpenAgent Market), and on-chain (ACP, ERC-8183, ERC-8004).

---

## Identity

- Agent ID (ERC-8004): 23121
- Identity Registry Contract: 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 (Ethereum Mainnet)
- Owner address: 0xcd1baf2B33781c088B30106289e745972E41b0E8
- XMTP address (OpenAgent Market): 0x23a09674e90d04F18Ea307f420a2AeB0d133d8d6
- OpenAgent Market Agent ID: 8453:19162
- Discovery endpoint: GET https://degenai.dev/x402
- OpenAPI spec: https://degenai.dev/x402/openapi.json
- Claude Code skill: https://degenai.dev/skills/degenai-skill.md

---

## Quickstart (30 seconds)

### 1. Discover capabilities
```
curl https://degenai.dev/x402
```

### 2. Query any wallet (FREE -- no auth, no payment)
```
curl -X POST https://degenai.dev/x402/get_positions \
  -H "Content-Type: application/json" \
  -d '{"wallet":"0x..."}'
```

### 3. Ready to trade?
Complete the one-time authorization flow below, then send trade requests with a
PAYMENT-SIGNATURE header. Pricing: $0.10 base + 0.01% of dollarSize.

---

## Why DegenAI x402

- Simple HTTP API -- no SDK required, works from any language
- Pay per use -- $0.10 + 0.01% per trade, usage-based for AI evaluations, no subscriptions
- 4% HyperLiquid fee discount automatically applied on all trades
- IPFS receipts -- permanent audit trail for every trade
- FREE read queries on any wallet (positions, orders, history)
- Pay with USDC (Base) or USDM (MegaETH)

---

## x402 Protocol

x402 enables pay-per-use trading for AI agents. Built on HTTP 402 Payment Required
semantics, it allows any agent to execute HyperLiquid trades with cryptographic
payment verification.

### Supported networks

| Network | Chain ID | Asset | Token Contract |
|---|---|---|---|
| Base | 8453 | USDC | 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 |
| MegaETH | 4326 | USDM | 0x2c2d8EF0664432BA243deF0b8f60aF7aB43a60B4 |

USDC uses 6 decimals (so "100000" = $0.10). USDM uses 18 decimals.

### Payment schemes

- `exact` (EIP-3009 TransferWithAuthorization) -- you authorize a fixed amount.
  Full amount is settled after execution. Gasless for the buyer.
  Used for: trading, charts, automation credits.
- `upto` (Permit2 permitWitnessTransferFrom) -- you authorize a maximum ceiling.
  After execution, only the actual cost is settled. No on-chain transaction if no
  work was consumed. Requires one-time Permit2 approval (gasless via CDP facilitator).
  Used for: per-evaluation billing (automation_evaluate).

### Discovery endpoint

```
GET https://degenai.dev/x402
```

Returns: capabilities with pricing, serviceHealth (HyperLiquid + Meridian + MegaETH),
authorization endpoints, integration docs.

---

## Authorization Flow (FREE, one-time per wallet)

### Two wallets, two roles

| Wallet | Field | Signs | Purpose |
|---|---|---|---|
| Payer wallet | `payerAddress` | EIP-3009 payment signatures | Holds USDC/USDM, pays per-trade fees |
| Trading wallet | `hyperLiquidWallet` | EIP-712 agent approval + builder fee | Executes trades on HyperLiquid |

These can be the same address if you use one wallet for both.

### Step 1 -- Prepare

```
POST /x402/authorize/prepare
Content-Type: application/json

{
  "payerAddress": "0xYourPayerWallet",
  "hyperLiquidWallet": "0xYourTradingWallet"
}
```

Response includes `agentApprovalTypedData`, `builderFeeTypedData` (if builder fee is
enabled), and two `long` integers: `nonce` and `builderNonce`. Pass these back in step 3.

### Step 2 -- Sign the typed data

Sign BOTH with your HyperLiquid trading wallet:

```
const agentSig = await wallet.signTypedData(
  agentApprovalTypedData.domain,
  agentApprovalTypedData.types,
  agentApprovalTypedData.message
);

const builderSig = builderFeeTypedData
  ? await wallet.signTypedData(
      builderFeeTypedData.domain,
      builderFeeTypedData.types,
      builderFeeTypedData.message
    )
  : '';
```

### Step 3 -- Approve

```
POST /x402/authorize/approve
Content-Type: application/json

{
  "payerAddress": "0xYourPayerWallet",
  "hyperLiquidWallet": "0xYourTradingWallet",
  "agentApprovalSignature": "0xAgentApprovalSig...",
  "builderFeeSignature": "0xBuilderFeeSig...",
  "nonce": 1234567890,
  "builderNonce": 1234567891
}
```

Both signatures are EIP-712 -- sign with the trading wallet (`hyperLiquidWallet`).
`nonce` and `builderNonce` are `long` integers from the prepare response.

### Verify status

```
GET /x402/authorize/status?payerAddress=0xYourPayerWallet
```

---

## FREE Capabilities

All read queries are FREE -- no payment, no authorization. Cache-Control: max-age=5
(5 seconds). For real-time data, use HyperLiquid's WebSocket API directly.

### get_positions
Query active perpetual positions for any wallet.
```
POST /x402/get_positions
{"wallet":"0x..."}
```
Response data: `positions[]` (coin, size, entryPrice, unrealizedPnl), `count`, `wallet`, `accountValue`.

### get_open_orders
Query open (unfilled) orders.
```
POST /x402/get_open_orders
{"wallet":"0x..."}
```
Response data: `orders[]` (coin, side, size, price, orderType, orderId), `count`, `wallet`.

### get_account_summary
Portfolio overview with account value, margin, and leverage.
```
POST /x402/get_account_summary
{"wallet":"0x..."}
```
Response data: `accountValue`, `marginUsed`, `marginAvailable`, `positionCount`, `openOrderCount`, `wallet`.

### get_trade_history
Recent trade fills and execution history.
```
POST /x402/get_trade_history
{"wallet":"0x...", "limit": 20}
```
Response data: `trades[]` (coin, side, size, price, fee, timestamp), `count`, `wallet`.

### get_spot_balances
Spot clearinghouse balances (includes USDC under unified account mode).
```
POST /x402/get_spot_balances
{"wallet":"0x..."}
```
Response data: `balances[]` (coin, total, hold, available), `wallet`.

### get_available_assets
List tradeable assets with current prices and trading parameters. Optional `filter` by symbol prefix.
```
POST /x402/get_available_assets
{"filter":"BTC"}
```

---

## Trading (Paid) -- hyperliquid_order

Execute trades on HyperLiquid: create, modify, cancel, and close positions.

### Pricing

$0.10 base + 0.01% of `dollarSize` (USD notional).

Example: $1,000 trade = $0.10 + $0.10 = $0.20 total.

Preview exact fees:
```
GET /x402/hyperliquid_order/pricing?dollarSize=1000
```

### Actions

All actions go to `POST /x402/hyperliquid_order` -- the `action` field dispatches.

| action | Description |
|---|---|
| `create_market` | Market order (immediate execution) |
| `create_limit` | Limit order at a specified price |
| `create_stop` | Stop/trigger order |
| `create_batch` | Multiple orders in one request |
| `modify_by_oid` | Modify an order by HyperLiquid order ID |
| `modify_by_cloid` | Modify an order by client order ID |
| `modify_batch` | Modify multiple orders |
| `cancel_by_oid` | Cancel by HyperLiquid order ID |
| `cancel_by_cloid` | Cancel by client order ID |
| `cancel_batch` | Cancel multiple orders |

### Request schema -- Market order

| Field | Type | Required | Description |
|---|---|---|---|
| `action` | string | yes | `"create_market"` |
| `coin` | string | yes | Asset symbol (e.g. `"ETH"`, `"BTC"`) |
| `isBuy` | boolean | yes | `true` = long, `false` = short |
| `dollarSize` | number | yes | Order size in USD (min 1) |
| `reduceOnly` | boolean | no | Only reduce existing position (default false) |
| `takeProfitPrice` | number | no | Attach take-profit at this price |
| `stopLossPrice` | number | no | Attach stop-loss at this price |
| `cloid` | string | no | Client order ID (`0x` + 32 hex chars) |

### Request schema -- Limit order

Same as market plus:

| Field | Type | Required | Description |
|---|---|---|---|
| `action` | string | yes | `"create_limit"` |
| `price` | number | yes | Limit price (must be > 0) |
| `tif` | string | no | Time-in-force: `"Gtc"` (default), `"Ioc"`, `"Alo"` |

### Request schema -- Cancel order

| Field | Type | Required | Description |
|---|---|---|---|
| `action` | string | yes | `"cancel_by_oid"` or `"cancel_by_cloid"` |
| `coin` | string | yes | Asset symbol |
| `oid` | integer | cond. | HyperLiquid order ID (for `cancel_by_oid`) |
| `cloid` | string | cond. | Client order ID (for `cancel_by_cloid`) |

### Closing a position

Use `create_market` with `"reduceOnly": true` and the opposite `isBuy` direction.
For partial close, set `dollarSize` to the amount you want to close.

### Field aliases

Snake-case variants are accepted: `dollar_size`, `is_buy`, `reduce_only`,
`trigger_price`, `take_profit_price`, `stop_loss_price`, etc.

### Payment flow

1. Create EIP-3009 TransferWithAuthorization signature for the payment amount
2. Base64-encode the payment payload
3. Include as `PAYMENT-SIGNATURE` header
4. Response includes IPFS receipt CID for verification

### Example -- Market buy

```
POST /x402/hyperliquid_order
Content-Type: application/json
PAYMENT-SIGNATURE: base64EncodedPaymentSignature

{
  "action": "create_market",
  "coin": "ETH",
  "isBuy": true,
  "dollarSize": 100
}
```

Response data: `orderIds[]`, `orderCount`, `action`, `ipfsCid`, `ipfsUrl`.

### Example -- Close position

```
{
  "action": "create_market",
  "coin": "ETH",
  "isBuy": false,
  "dollarSize": 100,
  "reduceOnly": true
}
```

---

## Charts (Paid) -- chart_screenshot

$0.005 flat. No authorization needed -- just send payment. Returns base64-encoded PNG.

### Request schema

| Field | Type | Required | Description |
|---|---|---|---|
| `coin` | string | yes | Asset symbol |
| `interval` | string | yes | `1m`, `5m`, `15m`, `1h`, `4h`, `1d` |
| `indicators` | string[] | no | Up to 5 indicators (see formats below) |
| `days` | integer | no | History in days (default depends on interval) |
| `width` | integer | no | 200-1920, default 1200 |
| `height` | integer | no | 200-1080, default 600 |

### Indicator format

Three forms using `Name:param1:param2` syntax:

- No params: `MACD` -- uses defaults
- Single param: `RSI:14`
- Multi param: `BollingerBands:20:2`

### Available indicators

Standard: ADX, ADXFull, Aroon, ATR, BollingerBands, CCI, ChandelierExit, CMF, DEMA, DonchianChannels, EMA, Fill Bubbles, Footprint, Funding Rate, HMA, Horizontal Lines, Ichimoku, KeltnerChannels, KST, Liquidation Heatmap, MACD, MFI, Monday Range, OBV, Orderbook Heatmap, ParabolicSAR, PivotPoints, Real Open, Realized Price, ROC, RSI, Slope, SMA, StdDev, Stochastic, StochasticRSI, Structural Levels, SuperTrend, TEMA, Trade Bubbles, TSI, Volume, VWAP, VWMA, WilliamsR, WMA

Pairs (append `:ASSET` -- e.g. `Correlation:BTC`): Beta, Correlation, PRS, SpreadRatio

### Example

```
curl -X POST https://degenai.dev/x402/chart_screenshot \
  -H "Content-Type: application/json" \
  -H "PAYMENT-SIGNATURE: base64EncodedPaymentSignature" \
  -d '{
    "coin": "ETH",
    "interval": "4h",
    "indicators": ["RSI:14", "SMA:200"],
    "width": 1200,
    "height": 600
  }'
```

Response data: `image` (base64 PNG bytes), `coin`, `interval`, `indicators[]`, `width`, `height`, `contentType`, `timestamp`.

---

## Automations (Paid)

Create automated trading strategies with natural language. Define a condition and an
action -- DegenAI evaluates the condition on a schedule using AI and executes the
action when the condition is met. Trades are charged at standard x402 rates.

### Pricing

| Capability | Cost | Includes |
|---|---|---|
| `automation_create` | $5.00 (exact) | Creates rule + 1000 evaluation credits |
| `automation_topup` | $5.00 (exact) | 1000 additional credits |
| `automation_evaluate` | Up to $0.50 (upto) | Single evaluation, billed by actual LLM usage |
| `automation_manage` | FREE | Start, stop, delete |
| `automation_status` | FREE | State, logs, balance |
| `automation_list` | FREE | List all automations |
| `automation_info` | FREE | Discovery metadata |

### Two billing models

- `automation_evaluate` (upto scheme) -- pay only for actual LLM usage per evaluation.
- `automation_create` / `automation_topup` (exact scheme) -- bulk credits at $5 per 1000 checks.

The background evaluation loop consumes credits from the bulk pool.

### Agent journey

```
# 1. Discover
GET /x402

# 2. Authorize (one-time, FREE)
POST /x402/authorize/prepare
POST /x402/authorize/approve

# 3. Create automation ($5, includes credits)
POST /x402/automation_create
{
  "asset": "ETH",
  "conditionPrompt": "Buy if RSI drops below 30 on the 4h chart",
  "actionPrompt": "Buy $100 of ETH",
  "interval": "4h"
}

# 4. Evaluate on-demand (upto scheme)
POST /x402/automation_evaluate  {"ruleId": 123}

# 5. Monitor (FREE)
POST /x402/automation_status  {"ruleId": 123}

# 6. Manage (FREE)
POST /x402/automation_manage  {"ruleId": 123, "action": "stop"}
```

### Trigger types

| Type | Description |
|---|---|
| `price_cross` | Fires when price crosses above/below an indicator or fixed level |
| `candle_close` | Fires at candle close for a specified interval |
| `exact_time` | Fires at a specific UTC time |
| `order_fill` | Fires when monitored orders are filled |

### State machine

`Created` -> `Active` -> `Sleeping (trigger armed)` -> `Triggered` -> `Executing` -> `Active (loop)`

### Webhook events

If `webhookUrl` is set, events are delivered as HMAC-SHA256 signed POST requests.
Verify with the `X-Webhook-Signature` header. Value format: `sha256=<lowercase-hex>`
(GitHub-style prefix) -- strip the `sha256=` prefix before comparing to your computed HMAC.

| Event | When |
|---|---|
| `condition_met` | Condition evaluated true |
| `trade_executed` | Order placed (includes CLOID, side, size) |
| `error` | Check failed or consecutive errors |
| `needs_attention` | Margin issue, liquidation risk |
| `stopped` | Automation deactivated |
| `credits_low` | Balance below $1.00 (1h cooldown) |
| `credits_depleted` | Balance at $0, automations paused |

### Example prompts

```
# DCA Bot
{ "asset": "ETH", "conditionPrompt": "Buy every 4 hours regardless of price",
  "actionPrompt": "Buy $50 of ETH", "interval": "4h" }

# Breakout Detector
{ "asset": "ETH", "conditionPrompt": "ETH closes above the 200 EMA on the 4h chart",
  "actionPrompt": "Buy $200 of ETH", "interval": "4h" }

# Stop-Loss Guard
{ "asset": "ETH", "conditionPrompt": "My ETH position drops below $3000",
  "actionPrompt": "Close entire ETH position", "interval": "15m" }
```

### Limits

Max 3 active automations per wallet. Min evaluation interval: 15 minutes. Trading
authorization required. Balance shared across all automations.

---

## Rate Limits & Error Codes

### Rate limits

Sliding-window limits, applied before payment verification:

- Global: 100 requests per minute across all callers
- Per-payer: 10 requests per minute per `payerAddress` (only enforced for paid capabilities where the payer is known)

When exceeded the response is `HTTP 429` with `errorCode: RATE_LIMITED`. No
`X-RateLimit-*` headers are currently emitted -- back off on 429 and retry.

### Error codes

| Code | Description | Action |
|---|---|---|
| `PAYMENT_REQUIRED` | No payment signature provided | Add `PAYMENT-SIGNATURE` header |
| `MISSING_WALLET` | wallet param missing | Include wallet in request body |
| `NOT_AUTHORIZED` | Trading not authorized | Complete /authorize flow first |
| `INSUFFICIENT_BALANCE` | Not enough USDC/USDM | Fund wallet on Base/MegaETH |
| `RATE_LIMITED` | Too many requests | Back off and retry (no headers; exponential backoff) |
| `SIGNATURE_MISMATCH` | Wrong wallet signed | Sign with hyperLiquidWallet |

### HTTP status codes

`200` Success | `400` Bad Request | `402` Payment Required | `403` Not Authorized | `429` Rate Limited | `500` Server Error

### Error response body

All 4xx/5xx responses use the same JSON shape:

```
{
  "success": false,
  "error": "Human-readable error message",
  "errorCode": "MACHINE_READABLE_CODE",
  "requestId": "trace-id"
}
```

`error` (string) and `errorCode` (string) are always present. `requestId` is included when available.

### 402 Payment Required response

When a paid endpoint is called without a valid `PAYMENT-SIGNATURE`:

```
HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: eyJzY2hlbWUiOi... (base64-encoded requirements)

{
  "success": false,
  "error": "Payment required",
  "errorCode": "PAYMENT_REQUIRED",
  "paymentRequirements": {
    "scheme": "exact",
    "network": "base",
    "maxAmountRequired": "100000",
    "resource": "https://degenai.dev/x402/hyperliquid_order",
    "description": "DegenAI hyperliquid_order execution",
    "mimeType": "application/json",
    "payTo": "0x8E7769D440b3460b92159Dd9C6D17302b036e2d6",
    "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
    "maxTimeoutSeconds": 3600
  }
}
```

`maxAmountRequired` is in the asset's smallest unit. USDC uses 6 decimals ("100000" = $0.10), USDM uses 18.

For `upto` capabilities (e.g. `automation_evaluate`), the scheme is `"upto"` and
`maxAmountRequired` is a ceiling -- you will only be charged for actual usage.

### PAYMENT-SIGNATURE payload

The header is a base64-encoded JSON object:

```
{
  "x402Version": 1,
  "scheme": "exact",
  "network": "base",
  "payload": {
    "signature": "0x...",
    "authorization": {
      "from": "0xPayerAddress",
      "to": "0xRecipientAddress",
      "value": "100000",
      "validAfter": "0",
      "validBefore": "2147483647",
      "nonce": "0x..."
    }
  }
}
```

Type notes: `value`, `validAfter`, `validBefore`, and `nonce` in the authorization
block are strings (EIP-3009 uint256 encoding). `validAfter: "0"` is valid (immediately).

---

## OpenAgent Market / XMTP

DegenAI is available as a trading agent on OpenAgent Market via XMTP messaging.
Other agents discover and interact by sending JSON-RPC skill requests to our XMTP address.

- XMTP address: 0x23a09674e90d04F18Ea307f420a2AeB0d133d8d6
- Agent ID (Base): 8453:19162
- Protocol: JSON-RPC over XMTP
- Discovery: GET https://degenai.dev/api/bridge/health
- Chat URL: https://openagent.market/chat?agent=0x23a09674e90d04F18Ea307f420a2AeB0d133d8d6

### Available skills

| Skill | Description | Pricing |
|---|---|---|
| `trade` | Place market/limit/stop orders on HyperLiquid | $0.10 USDC |
| `authorize` | Authorize your HyperLiquid wallet for trading | Free |
| `authorize_complete` | Complete authorization (submit signatures) | Free |
| `get_assets` | List all tradeable assets | Free |
| `get_positions` | View open positions | Free |
| `get_orders` | View open orders | Free |
| `get_account` | Account summary | Free |
| `get_trades` | Recent trade history | Free |
| `get_spot_balances` | Spot wallet balances | Free |
| `status` | Check if agent is online | Free |

### Example request

Send as XMTP message:
```
{"method": "get_positions", "params": {"wallet": "0x..."}, "id": 1}
```

---

## ACP (Virtuals Job Marketplace)

DegenAI is a registered provider agent on the Agent Commerce Protocol (ACP) via the
Virtuals job marketplace. Buyer-agents discover DegenAI on Virtuals, post funded
trading jobs, and DegenAI executes them on HyperLiquid. Counterparty is another
agent -- not a human end user.

- Protocol: ACP v2 (Virtuals)
- Transport: WebSocket inbound job events
- Counterparty: ACP buyer-agents

### Exposed capabilities (trading-only)

| Capability | Description | Batched |
|---|---|---|
| `place_trading_orders` | Place one or more orders in a single call | yes (array input) |
| `modify_trading_orders` | Modify one or more open orders | yes (array input) |
| `cancel_trading_orders` | Cancel one or more open orders | yes (array input) |

### Payment model

Per-job escrow funded by the buyer-agent on Virtuals. Settlement happens on terminal
job state and is capped at the escrowed budget. DegenAI reserves a 10% buffer against
LLM cost overruns so a single noisy evaluation cannot consume the entire escrow.

Read-only account queries (positions, orders, balances) are not currently exposed via
ACP -- only the three batch trading capabilities above.

---

## ERC-8183 On-Chain Job Marketplace

DegenAI listens for funded jobs on the ERC-8183 job marketplace contract. Any agent
client can post a job with on-chain escrow; DegenAI picks it up, executes the
requested capability, pins the deliverable to IPFS, and submits the deliverable hash
on-chain for settlement.

- Protocol: ERC-8183 (on-chain)
- Transport: on-chain event listener -> IPFS deliverable -> on-chain settlement
- Counterparty: any agent client posting a funded job
- Deliverable: IPFS CIDv0 (sha256 bytes32) submitted on-chain
- Discovery: GET https://degenai.dev/erc8183

### Exposed capabilities

The full universal capability surface -- all trading, read-only queries, chart
rendering, and automation capabilities. The three ACP-scoped batch trading
capabilities (`place_trading_orders`, `modify_trading_orders`, `cancel_trading_orders`)
are NOT exposed here; use singular `hyperliquid_order` for orders instead.

### Payment model

Per-job on-chain escrow. Budget must cover capability price plus a small gas buffer
(see `minimumBudgetUsdc` in `GET /erc8183`). On submit, DegenAI broadcasts the
deliverable hash on-chain; the evaluator (self or external) finalizes settlement.

---

## ERC-8004 Identity

DegenAI is registered on Ethereum mainnet ERC-8004 Identity Registry, enabling
on-chain agent discovery and verification.

- Agent ID: 23121
- Contract: 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432
- Chain: Ethereum Mainnet
- Owner: 0xcd1baf2B33781c088B30106289e745972E41b0E8
- Etherscan: https://etherscan.io/address/0x8004A169FB4a3325136EB29fA0ceB6D2e539a432

---

## Code Examples

### JavaScript / TypeScript

```
import { ethers } from 'ethers';

// 1. Query positions (FREE)
async function getPositions(wallet) {
  const r = await fetch('https://degenai.dev/x402/get_positions', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ wallet })
  });
  return r.json();
}

// 2. Authorize trading
async function authorizeTrading(signer, payerAddress) {
  const prepRes = await fetch('https://degenai.dev/x402/authorize/prepare', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      payerAddress,
      hyperLiquidWallet: await signer.getAddress()
    })
  });
  const prep = await prepRes.json();
  const { agentApprovalTypedData, builderFeeTypedData, nonce, builderNonce } = prep;

  const agentApprovalSignature = await signer.signTypedData(
    agentApprovalTypedData.domain,
    agentApprovalTypedData.types,
    agentApprovalTypedData.message
  );
  const builderFeeSignature = builderFeeTypedData
    ? await signer.signTypedData(
        builderFeeTypedData.domain,
        builderFeeTypedData.types,
        builderFeeTypedData.message
      )
    : '';

  const approveRes = await fetch('https://degenai.dev/x402/authorize/approve', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      payerAddress,
      hyperLiquidWallet: await signer.getAddress(),
      agentApprovalSignature,
      builderFeeSignature,
      nonce,
      builderNonce
    })
  });
  return approveRes.json();
}

// 3. Execute trade (requires payment signature)
async function executeTrade(paymentSignature) {
  const r = await fetch('https://degenai.dev/x402/hyperliquid_order', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'PAYMENT-SIGNATURE': paymentSignature
    },
    body: JSON.stringify({
      action: 'create_market',
      coin: 'ETH',
      isBuy: true,
      dollarSize: 100
    })
  });
  if (r.status === 429) {
    throw new Error('Rate limited - back off and retry');
  }
  return r.json();
}
```

### Python

```
import requests
from eth_account import Account

BASE_URL = "https://degenai.dev"

def get_positions(wallet):
    r = requests.post(f"{BASE_URL}/x402/get_positions", json={"wallet": wallet})
    r.raise_for_status()
    return r.json()

def authorize_trading(private_key, payer_address):
    account = Account.from_key(private_key)
    prep = requests.post(
        f"{BASE_URL}/x402/authorize/prepare",
        json={"payerAddress": payer_address, "hyperLiquidWallet": account.address}
    ).json()

    agent_td = prep["agentApprovalTypedData"]
    agent_sig = account.sign_typed_data(
        domain_data=agent_td["domain"],
        message_types=agent_td["types"],
        message_data=agent_td["message"]
    )

    builder_sig = ""
    if prep.get("builderFeeTypedData"):
        b_td = prep["builderFeeTypedData"]
        builder_sig = account.sign_typed_data(
            domain_data=b_td["domain"],
            message_types=b_td["types"],
            message_data=b_td["message"]
        ).signature.hex()

    return requests.post(
        f"{BASE_URL}/x402/authorize/approve",
        json={
            "payerAddress": payer_address,
            "hyperLiquidWallet": account.address,
            "agentApprovalSignature": agent_sig.signature.hex(),
            "builderFeeSignature": builder_sig,
            "nonce": prep["nonce"],
            "builderNonce": prep["builderNonce"]
        }
    ).json()
```

### cURL

```
# Discover
curl https://degenai.dev/x402

# Query positions (FREE)
curl -X POST https://degenai.dev/x402/get_positions \
  -H "Content-Type: application/json" \
  -d '{"wallet":"0xYourWallet"}'

# Account summary (FREE)
curl -X POST https://degenai.dev/x402/get_account_summary \
  -H "Content-Type: application/json" \
  -d '{"wallet":"0xYourWallet"}'

# Authorization status
curl "https://degenai.dev/x402/authorize/status?payerAddress=0xYourPayer"

# Pricing preview
curl "https://degenai.dev/x402/hyperliquid_order/pricing?dollarSize=1000"
```

---

## Claude Code Skill

A pre-built Claude Code skill exposes `/degenai` slash commands.

Install:
```
curl -o .claude/skills/degenai.md https://degenai.dev/skills/degenai-skill.md
```

Commands: `/degenai positions <wallet>`, `/degenai account <wallet>`,
`/degenai orders <wallet>`, `/degenai history <wallet> [limit]`. Natural language
also supported.

---

## Resources

- Discovery: https://degenai.dev/x402
- OpenAPI spec: https://degenai.dev/x402/openapi.json
- Claude Code skill: https://degenai.dev/skills/degenai-skill.md
- This document (raw): https://degenai.dev/erc8004.md
- Auto-discovery alias: https://degenai.dev/llms.txt
- Page (HTML): https://degenai.dev/erc8004