> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nilemarkets.com/llms.txt
> Use this file to discover all available pages before exploring further.

# x402 API

> REST API at x402.nilemarkets.com with 14 free read endpoints (GET) and 8 paid write endpoints (POST) protected by x402 micropayment protocol — $0.01 USDC per write on Sepolia.

<Warning>
  **Sepolia Testnet Only** — All data is from Ethereum Sepolia. Token balances and positions have no real-world value. Write payments use Sepolia USDC.
</Warning>

## What is x402?

The [x402 protocol](https://x402.org) enables HTTP-native micropayments using the `402 Payment Required` status code. When you call a paid endpoint without payment, the server returns a `402` response with payment requirements. Your client pays the specified amount (onchain USDC transfer), attaches the payment proof to a retry, and the server fulfills the request.

The Nile Markets x402 API splits access into two tiers:

* **Read endpoints (GET)** — Free, no payment required
* **Write endpoints (POST)** — \$0.01 USDC per request via x402

Base URL: `https://x402.nilemarkets.com`

## Free Endpoints (14 GET)

### Pool and Protocol

| Method | Path                          | Description                                                  | Query Params                  |
| ------ | ----------------------------- | ------------------------------------------------------------ | ----------------------------- |
| GET    | `/api/x402/pool/state`        | Pool metrics: total assets, shares, share price, utilization | `network?`                    |
| GET    | `/api/x402/pool/transactions` | Historical vault deposits and withdrawals                    | `first?`, `skip?`, `network?` |
| GET    | `/api/x402/protocol/mode`     | Operating mode: NORMAL, DEGRADED, REDUCE\_ONLY, or PAUSED    | `network?`                    |
| GET    | `/api/x402/stats/daily`       | Daily volume, fees, position opens/closes, pool PnL          | `days?`, `network?`           |

### Positions

| Method | Path                         | Description                        | Query Params                                                                |
| ------ | ---------------------------- | ---------------------------------- | --------------------------------------------------------------------------- |
| GET    | `/api/x402/positions`        | Positions for an account           | `account` (required), `status?`, `first?`, `skip?`, `network?`              |
| GET    | `/api/x402/positions/search` | Search all positions with filters  | `side?`, `tenor?`, `status?`, `minNotional?`, `first?`, `skip?`, `network?` |
| GET    | `/api/x402/position/[id]`    | Single position with real-time PnL | —                                                                           |

### Oracle and Pricing

| Method | Path                       | Description                                           | Query Params                              |
| ------ | -------------------------- | ----------------------------------------------------- | ----------------------------------------- |
| GET    | `/api/x402/oracle/state`   | Full oracle state: spot, all forward prices, validity | `pairId?`, `network?`                     |
| GET    | `/api/x402/oracle/forward` | Forward price for a specific tenor                    | `tenor` (required), `pairId?`, `network?` |

### Accounts and Fees

| Method | Path                          | Description                                                     | Query Params                  |
| ------ | ----------------------------- | --------------------------------------------------------------- | ----------------------------- |
| GET    | `/api/x402/account/[address]` | Account margin: collateral, locked, available, position count   | —                             |
| GET    | `/api/x402/fees`              | Fee event breakdown (trading, liquidation, termination, oracle) | `first?`, `skip?`, `network?` |

### Token and Simulation

| Method | Path                        | Description                                | Query Params                                                               |
| ------ | --------------------------- | ------------------------------------------ | -------------------------------------------------------------------------- |
| GET    | `/api/x402/token/balance`   | ERC-20 token balance for an address        | `address` (required), `token?`, `network?`                                 |
| GET    | `/api/x402/token/allowance` | ERC-20 allowance for an owner/spender pair | `owner` (required), `spender` (required), `token?`, `network?`             |
| GET    | `/api/x402/simulate/open`   | Preview margin, fee, and entry strike      | `side`, `tenor`, `notional` (all required), `margin?`, `from?`, `network?` |

## Paid Endpoints (8 POST)

Each POST request costs **\$0.01 USDC** on Sepolia, paid via the x402 protocol. The payment is a separate onchain USDC transfer to the configured payee address, verified by an x402 facilitator before the request is fulfilled.

### Trading

| Method | Path                       | Description                                        | Body Fields                                               |
| ------ | -------------------------- | -------------------------------------------------- | --------------------------------------------------------- |
| POST   | `/api/x402/position/open`  | Calldata to open a new FX forward position         | `side`, `tenor`, `notional`, `margin`, `pairId?`, `from?` |
| POST   | `/api/x402/position/close` | Calldata to close a position via early termination | `positionId`, `from?`                                     |

### Margin

| Method | Path                        | Description                                   | Body Fields       |
| ------ | --------------------------- | --------------------------------------------- | ----------------- |
| POST   | `/api/x402/margin/deposit`  | Calldata to deposit USDC as margin collateral | `amount`, `from?` |
| POST   | `/api/x402/margin/withdraw` | Calldata to withdraw available USDC margin    | `amount`, `from?` |

### Vault (Liquidity Providers)

| Method | Path                       | Description                                   | Body Fields                            |
| ------ | -------------------------- | --------------------------------------------- | -------------------------------------- |
| POST   | `/api/x402/vault/deposit`  | Calldata to deposit USDC into the pool vault  | `amount`, `receiver`, `from?`          |
| POST   | `/api/x402/vault/withdraw` | Calldata to withdraw USDC from the pool vault | `amount`, `receiver`, `owner`, `from?` |

### Token Approval and Testnet

| Method | Path                      | Description                                         | Body Fields                            |
| ------ | ------------------------- | --------------------------------------------------- | -------------------------------------- |
| POST   | `/api/x402/token/approve` | Calldata to approve a Nile contract to spend tokens | `spender`, `amount`, `token?`, `from?` |
| POST   | `/api/x402/token/mint`    | Calldata to mint test tokens (testnet only)         | `to`, `amount`, `from?`                |

All amounts are strings in USDC smallest unit (6 decimals). `"1000000000"` = 1,000 USDC.

## Response Format

Every response uses a standard JSON envelope:

```json theme={null}
{
  "success": true,
  "data": { },
  "protocol": { "name": "Nile Markets", "version": "0.3.2" },
  "network": "sepolia",
  "timestamp": "2025-06-15T12:00:00.000Z",
  "blockNumber": "12345678",
  "source": "rpc+subgraph"
}
```

| Field         | Type                | Description                                             |
| ------------- | ------------------- | ------------------------------------------------------- |
| `success`     | `boolean`           | `true` for 2xx responses, `false` for errors            |
| `data`        | `object?`           | Endpoint-specific payload (omitted on errors)           |
| `error`       | `string?`           | Error message (omitted on success)                      |
| `protocol`    | `{ name, version }` | Protocol identity and API version                       |
| `network`     | `string`            | Target network (`"sepolia"`)                            |
| `timestamp`   | `string`            | ISO 8601 response timestamp                             |
| `blockNumber` | `string?`           | Last indexed block (subgraph-sourced responses)         |
| `source`      | `string?`           | Data source: `"rpc"`, `"subgraph"`, or `"rpc+subgraph"` |

Write endpoints return `TransactionCalldata` in the `data` field, identical to the [MCP server](/ai-agents/mcp-server) format.

## Examples

### Free Read — Pool State

```bash theme={null}
curl -s https://x402.nilemarkets.com/api/x402/pool/state | jq
```

```json theme={null}
{
  "success": true,
  "data": {
    "totalAssets": "50000000000",
    "totalShares": "49500000000",
    "sharePrice": "1010101010101010101",
    "riskCapacityUtilization": "3200",
    "longExposure": "10000000000",
    "shortExposure": "6000000000"
  },
  "protocol": { "name": "Nile Markets", "version": "0.3.2" },
  "network": "sepolia",
  "timestamp": "2025-06-15T12:00:00.000Z",
  "source": "rpc+subgraph"
}
```

### Free Read — Forward Price

```bash theme={null}
curl -s "https://x402.nilemarkets.com/api/x402/oracle/forward?tenor=1M" | jq
```

### Paid Write — Open Position

Without payment, the server returns `402 Payment Required` with x402 payment requirements:

```bash theme={null}
curl -s -X POST https://x402.nilemarkets.com/api/x402/position/open \
  -H "Content-Type: application/json" \
  -d '{
    "side": "LONG",
    "tenor": "1M",
    "notional": "10000000000",
    "margin": "20000000"
  }'
```

```json theme={null}
{
  "error": "X-PAYMENT header is required",
  "accepts": [{
    "scheme": "exact",
    "network": "eip155:11155111",
    "maxAmountRequired": "10000",
    "resource": "https://x402.nilemarkets.com/api/x402/position/open",
    "description": "Open a new FX forward position",
    "mimeType": "application/json"
  }]
}
```

To complete the payment, use an x402-compatible client library that handles the `402` → pay → retry flow automatically. See [x402.org](https://x402.org) for client SDKs in TypeScript, Python, and Go.

## x402 Payment Flow

<Steps>
  <Step title="Initial request">
    Your client sends a POST to a paid endpoint without payment headers.
  </Step>

  <Step title="402 response">
    The server returns HTTP 402 with `accepts` containing the payment scheme, amount (\$0.01 USDC), network, and payee address.
  </Step>

  <Step title="Onchain payment">
    Your client transfers the specified USDC amount to the payee address on Sepolia and obtains a payment proof.
  </Step>

  <Step title="Retry with proof">
    Your client retries the original request with the `X-PAYMENT` header containing the payment proof.
  </Step>

  <Step title="Fulfillment">
    The server verifies the payment via the x402 facilitator and returns the requested data (unsigned transaction calldata for write endpoints).
  </Step>
</Steps>

x402 client libraries (available at [x402.org](https://x402.org)) handle steps 2 through 4 automatically.

## Rate Limits

| Tier                  | Limit              | Enforcement                    |
| --------------------- | ------------------ | ------------------------------ |
| Free endpoints (GET)  | 100 req/min per IP | HTTP 429 with `Retry-After`    |
| Paid endpoints (POST) | No rate limit      | Payment itself throttles abuse |

## MCP vs x402

The MCP server and x402 API expose the same 22 operations with identical data. Choose based on your client:

|                     | MCP Server                       | x402 API                                  |
| ------------------- | -------------------------------- | ----------------------------------------- |
| **Transport**       | Streamable HTTP (MCP protocol)   | Standard REST (HTTP)                      |
| **Client**          | AI agents with MCP support       | Any HTTP client (`curl`, `fetch`, SDKs)   |
| **Auth**            | None                             | Free reads; \$0.01 USDC per write         |
| **Response format** | MCP content blocks               | JSON envelope with `success`, `timestamp` |
| **Best for**        | Claude, ChatGPT, Cursor, VS Code | Programmatic integrations, scripts, bots  |
