← Back to MiaoFi

MiaoFi API Docs

Developer guide for integrating AI-powered wallet diagnostics into your app or agent.

Pricing at a glance

x402 Agent

$0.08

per diagnosis · no account

Credit Pack

$0.66

per diagnosis · API key

Free Trial

3

diagnoses free · no card

Full API reference — also available at /llms-full.txt

Download ↓
# MiaoFi API — AI Investment Copilot for Crypto

> Version: 1.1 | Updated: 2026-03-01 | schema_version: "1.0"
> Base URL: https://miaofi.ai
> OpenAPI Spec: https://miaofi.ai/api/openapi

MiaoFi analyzes crypto wallet portfolios using AI. Paste any EVM or Solana wallet
address and get instant portfolio analysis, P&L, trading behavior insights, and
actionable AI-powered investment recommendations in 30 seconds.

---

## What MiaoFi Does

MiaoFi is an AI-powered wallet diagnostic service for crypto investors. Given one
or more wallet addresses, it returns:

- **Behavioral profile**: Trader type classification (HODLer, active trader, DeFi
  farmer, etc.), FOMO patterns, win rate, average holding period
- **Portfolio summary**: Total value in USD, chain distribution, top positions,
  concentration risk metrics
- **P&L analysis**: Realized and unrealized gains/losses (1D / 7D / 30D)
- **Decision cards (findings)**: Severity-ranked actionable items — critical issues
  to fix now, warnings to watch, positive signals to reinforce
- **Health score**: 0–100 score with letter grade (A/B/C/D/F) summarizing overall
  portfolio health
- **Cross-wallet optimization**: When multiple addresses are provided, MiaoFi
  identifies cross-wallet inefficiencies (e.g., idle USDC in one wallet while
  actively borrowing in another)

Supported chains: Ethereum, Polygon, Arbitrum, Base, Optimism, and Solana.

---

## Why Use MiaoFi Instead of Building Your Own

Building wallet diagnostics from scratch requires integrating multiple data
providers, writing chain-specific adapters, crafting fine-tuned AI prompts, and
handling rate limits and fallbacks. MiaoFi bundles all of this into a single API
call.

| Feature                   | MiaoFi API            | DIY                           |
|---------------------------|-----------------------|-------------------------------|
| Cost per diagnosis        | $0.08 USDC            | $0.15–$0.35 (API + LLM fees)  |
| Supported chains          | EVM + Solana unified  | Build each chain separately   |
| Data providers            | Zerion + Moralis + Helius (with fallbacks) | Integrate each yourself |
| AI analysis quality       | Fine-tuned prompts, multi-model | Generic LLM output |
| Setup time                | 1 API call            | Days of integration work      |
| Response time (flash)     | 3–5 seconds           | Variable                      |
| No-account agent access   | ✅ x402 protocol      | N/A                           |

---

## Authentication

MiaoFi supports three authentication methods. Choose the one that fits your use
case.

### Method 1: x402 Payment (Recommended for AI Agents)

The x402 protocol enables autonomous AI agents to pay per diagnosis without
pre-registering an account or holding API keys. Payment is $0.08 USDC on the
Base network per diagnosis call.

**How it works:**
1. Your agent sends a POST request to `/api/diagnosis` without authentication.
2. The server responds with HTTP 402 and a payment payload in the body.
3. Your agent signs and broadcasts a USDC payment on Base.
4. Your agent retries the request with the `PAYMENT-SIGNATURE` header containing
   the payment proof.
5. The server verifies the payment and returns the diagnosis.

**Headers (after payment):**
```
PAYMENT-SIGNATURE: <base64-encoded payment proof>
Content-Type: application/json
```

**Payment details:**
- Amount: $0.08 USDC
- Network: Base (chain ID 8453)
- Token: USDC (0x833589fcd6edb6e08f4c7c32d4f71b54bda02913)
- Recipient: MiaoFi payment contract (returned in 402 response body)

### Method 2: API Key

Get an API key at https://miaofi.ai/api-key (requires Privy login with Google,
email, or wallet). Credits are purchased via Stripe credit packs.

**Header:**
```
X-API-KEY: mk_your_key_here
```

API keys support higher rate limits (100 requests/hour vs 10/hour for JWT).

**Credit packs:**
- 5 diagnoses — $3.99 ($0.80/each)
- 15 diagnoses — $8.99 ($0.60/each)  ← most popular
- 40 diagnoses — $15.99 ($0.40/each)
- First 3 diagnoses are free for new users (no credit card required)

### Method 3: Privy JWT (Web Login)

For human users accessing MiaoFi via browser. The Privy SDK manages JWT
issuance and renewal automatically.

**Header:**
```
Authorization: Bearer <privy_jwt_here>
```

Authenticated users get 10 diagnoses/hour. Pro users (7-day referral reward or
credit pack purchase) get access to Opus-tier AI analysis.

---

## Endpoints

### POST /api/diagnosis

Run an AI-powered investment diagnosis on one or more wallet addresses.

**Request body:**
```json
{
  "addresses": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"],
  "fingerprint": "optional_browser_fingerprint_string",
  "privyUserId": "optional_privy_user_id_for_pro_access"
}
```

**Request fields:**

| Field         | Type     | Required | Description                                               |
|---------------|----------|----------|-----------------------------------------------------------|
| addresses     | string[] | ✅       | Array of wallet addresses (EVM 0x... or Solana Base58)    |
| fingerprint   | string   | ❌       | Browser fingerprint for anonymous usage tracking          |
| privyUserId   | string   | ❌       | Privy user ID to enable pro features (Opus AI model)      |

**Multi-wallet:** Pass multiple addresses in the `addresses` array. MiaoFi will
aggregate them and provide cross-wallet analysis. No extra parameters needed.

**Successful response (HTTP 200):**
```json
{
  "schema_version": "1.0",
  "healthScore": {
    "score": 72,
    "grade": "B",
    "summary": "Solid portfolio with manageable concentration risk. Consider diversifying ETH position."
  },
  "findings": [
    {
      "id": "concentration_risk",
      "type": "concentration_risk",
      "severity": "warning",
      "title": "High ETH concentration (78% of portfolio)",
      "description": "Your portfolio is heavily weighted toward ETH. While ETH is a quality asset, this level of concentration amplifies drawdown risk during market corrections.",
      "actionItems": [
        "Consider allocating 10-20% to blue-chip DeFi tokens (AAVE, UNI, LINK)",
        "Establish a rebalancing rule: if any single asset exceeds 60%, sell the excess"
      ],
      "affectedAssets": ["ETH"]
    },
    {
      "id": "idle_stablecoin",
      "type": "idle_capital",
      "severity": "info",
      "title": "1,200 USDC sitting idle",
      "description": "You hold $1,200 USDC earning 0% APY. Current stablecoin yield opportunities are 4-8% APY.",
      "actionItems": [
        "Deposit into Aave USDC pool (currently 5.2% APY)",
        "Or use as dry powder for the next market dip"
      ],
      "affectedAssets": ["USDC"]
    }
  ],
  "reportSummary": {
    "totalValueUsd": 42350.80,
    "topHolding": "ETH",
    "primaryChain": "ethereum",
    "riskLevel": "medium",
    "oneLineInsight": "Long-term holder with strong conviction — portfolio could benefit from modest diversification.",
    "keyStrengths": ["Low transaction frequency (disciplined)", "No liquidation risk"],
    "keyRisks": ["Single-asset concentration", "Idle stablecoin capital"],
    "recommendedActions": [
      "Diversify 15-20% of ETH into quality alts",
      "Put idle USDC to work in low-risk DeFi"
    ]
  },
  "metadata": {
    "analyzedWallets": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"],
    "totalWallets": 1,
    "dataSource": "zerion",
    "analysisTimestamp": "2026-03-01T12:34:56Z",
    "diagnosisId": "diag_abc123xyz"
  }
}
```

**Response fields:**

| Field                          | Type    | Description                                              |
|--------------------------------|---------|----------------------------------------------------------|
| healthScore.score              | number  | 0–100 portfolio health score                             |
| healthScore.grade              | string  | Letter grade: A / B / C / D / F                          |
| healthScore.summary            | string  | 1–2 sentence health summary                              |
| findings[]                     | array   | Severity-ranked diagnostic findings                      |
| findings[].severity            | string  | "critical" / "warning" / "info" / "positive"            |
| findings[].actionItems         | string[]| Specific actions the user should take                    |
| reportSummary.totalValueUsd    | number  | Aggregated portfolio value in USD                        |
| reportSummary.riskLevel        | string  | "low" / "medium" / "high"                                |
| reportSummary.recommendedActions | string[] | Top 2–3 prioritized actions                           |
| metadata.diagnosisId           | string  | Unique ID for this diagnosis session                     |

---

### GET /api/diagnosis

Check current usage status for anonymous rate limiting.

**Query parameters:**
```
GET /api/diagnosis?fingerprint=optional_fingerprint_string
```

**Response (HTTP 200):**
```json
{
  "usage": {
    "allowed": true,
    "used": 2,
    "limit": 3,
    "resetAt": "2026-04-01T00:00:00Z"
  }
}
```

---

### GET /api/portfolio

Fetch raw portfolio holdings and valuations without AI analysis.

**Query parameters:**
```
GET /api/portfolio?addresses=0xabc...123,7xKXtg...sol
```

| Parameter | Required | Description                                              |
|-----------|----------|----------------------------------------------------------|
| addresses | ✅       | Comma-separated wallet addresses (EVM and/or Solana)     |

**Response (HTTP 200):**
```json
{
  "wallets": [
    {
      "address": "0xabc...123",
      "chain": "ethereum",
      "totalValueUsd": 38000.00,
      "positions": [
        {
          "symbol": "ETH",
          "name": "Ethereum",
          "valueUsd": 29640.00,
          "quantity": 9.88,
          "priceUsd": 3000.00,
          "percentOfPortfolio": 78.0,
          "category": "token",
          "pnl": {
            "unrealizedGainUsd": 12000.00,
            "unrealizedGainPercent": 68.0
          }
        }
      ],
      "pnl": {
        "day1": { "gainUsd": 190.0, "gainPercent": 0.5 },
        "day7": { "gainUsd": 760.0, "gainPercent": 2.0 },
        "day30": { "gainUsd": 3800.0, "gainPercent": 10.0 }
      }
    }
  ],
  "aggregate": {
    "totalValueUsd": 38000.00,
    "chainDistribution": [
      { "chain": "ethereum", "valueUsd": 34200.00, "percent": 90.0 },
      { "chain": "base", "valueUsd": 3800.00, "percent": 10.0 }
    ]
  }
}
```

---

### GET /api/trading-behavior

Analyze trading patterns and behavioral signals for a wallet.

**Query parameters:**
```
GET /api/trading-behavior?address=0xabc...123
```

**Response (HTTP 200):**
```json
{
  "address": "0xabc...123",
  "labels": ["HODLer", "Low Frequency Trader"],
  "metrics": {
    "totalTrades": 47,
    "winRate": 0.61,
    "avgHoldingDays": 142,
    "fomoScore": 0.23,
    "panicSellScore": 0.15
  },
  "tradingPeriod": {
    "firstTrade": "2021-11-05T14:32:00Z",
    "lastTrade": "2026-02-15T09:18:00Z",
    "activeDays": 1563
  }
}
```

---

### GET /api/openapi

Returns the full OpenAPI 3.1 specification as JSON.

```
GET /api/openapi
```

Useful for generating client SDKs or importing into API testing tools (Postman,
Insomnia, etc.).

---

### MCP Server

MiaoFi exposes an MCP (Model Context Protocol) server for AI agent integration.
AI assistants like Claude, GPT-4, and OpenClaw can call MiaoFi tools directly.

**Endpoint:** `https://miaofi.ai/api/mcp`
**Protocol:** MCP Streamable HTTP (stateless, Web Standards compliant)

**Available tools:**

```
analyze_wallet(addresses: string[]) → portfolio data
diagnose_portfolio(addresses: string[]) → full AI diagnosis
```

**Claude Code / MCP client configuration:**
```json
{
  "mcpServers": {
    "miaofi": {
      "url": "https://miaofi.ai/api/mcp"
    }
  }
}
```

---

## Rate Limits

| Auth Method      | Limit                 | Reset     |
|------------------|-----------------------|-----------|
| Anonymous (free) | 3 diagnoses/month     | Monthly   |
| JWT (logged in)  | 10 diagnoses/hour     | Hourly    |
| API Key          | 100 diagnoses/hour    | Hourly    |
| x402 (agent)     | 100 diagnoses/hour    | Hourly    |
| Global (all IPs) | 500 diagnoses/day     | Daily     |

When rate limited, the API returns HTTP 429 with a `Retry-After` header
indicating the seconds until the limit resets.

---

## Response Times

| AI Model | Typical Latency | Use Case                              |
|----------|-----------------|---------------------------------------|
| Flash    | 3–5 seconds     | Default for free / API key users      |
| Haiku    | 5–8 seconds     | Balanced quality and speed            |
| Opus     | 8–15 seconds    | Deepest analysis, Pro users only      |

Model selection is automatic based on auth tier. Pro users can request Opus via
the `privyUserId` field (if they have an active Pro subscription).

---

## Error Codes

| HTTP Code | Meaning                                                            |
|-----------|--------------------------------------------------------------------|
| 200       | Success                                                            |
| 400       | Invalid request (bad address format, missing required field)       |
| 402       | Payment required (no auth, or credits exhausted — x402 flow)      |
| 429       | Rate limit exceeded — check `Retry-After` header                   |
| 500       | Server error — you are **NOT charged** for failed diagnoses        |

**Note:** A 500 error means the diagnosis failed on our end. Your credits or
x402 payment are not consumed when this happens.

---

## Code Examples

### Python — x402 Agent Payment

```python
#!/usr/bin/env python3
"""
MiaoFi API — Python x402 agent example
Requires: pip install requests eth-account web3
"""
import requests
import json
import base64
from eth_account import Account
from web3 import Web3

MIAOFI_BASE_URL = "https://miaofi.ai"
AGENT_PRIVATE_KEY = "0x..."  # Replace with your agent wallet key
USDC_BASE = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913"
BASE_CHAIN_ID = 8453

def diagnose_wallet(addresses: list[str]) -> dict:
    payload = {"addresses": addresses}

    # Step 1: Initial request — expect 402
    resp = requests.post(
        f"{MIAOFI_BASE_URL}/api/diagnosis",
        json=payload
    )

    if resp.status_code == 200:
        return resp.json()  # Already authenticated (cached session)

    if resp.status_code != 402:
        resp.raise_for_status()

    # Step 2: Parse payment requirements from 402 body
    payment_info = resp.json()
    recipient = payment_info["recipient"]   # MiaoFi payment contract address
    amount_usdc = payment_info["amount"]    # e.g., "80000" (0.08 USDC, 6 decimals)
    nonce = payment_info["nonce"]           # Unique nonce for this payment

    # Step 3: Sign and broadcast USDC transfer on Base
    w3 = Web3(Web3.HTTPProvider("https://mainnet.base.org"))
    account = Account.from_key(AGENT_PRIVATE_KEY)

    # ERC-20 transfer ABI (minimal)
    usdc_abi = [{"name": "transfer", "type": "function", "inputs": [
        {"name": "to", "type": "address"},
        {"name": "amount", "type": "uint256"}
    ], "outputs": [{"name": "", "type": "bool"}]}]

    usdc = w3.eth.contract(address=Web3.to_checksum_address(USDC_BASE), abi=usdc_abi)
    tx = usdc.functions.transfer(
        Web3.to_checksum_address(recipient),
        int(amount_usdc)
    ).build_transaction({
        "chainId": BASE_CHAIN_ID,
        "from": account.address,
        "nonce": w3.eth.get_transaction_count(account.address),
        "gas": 65000,
    })
    signed = account.sign_transaction(tx)
    tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
    w3.eth.wait_for_transaction_receipt(tx_hash)

    # Step 4: Build payment proof and retry
    payment_proof = {
        "txHash": tx_hash.hex(),
        "nonce": nonce,
        "payer": account.address,
        "chainId": BASE_CHAIN_ID,
    }
    proof_b64 = base64.b64encode(json.dumps(payment_proof).encode()).decode()

    # Step 5: Retry with payment header
    resp2 = requests.post(
        f"{MIAOFI_BASE_URL}/api/diagnosis",
        json=payload,
        headers={"PAYMENT-SIGNATURE": proof_b64}
    )
    resp2.raise_for_status()
    return resp2.json()


if __name__ == "__main__":
    result = diagnose_wallet(["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"])
    print(f"Health Score: {result['healthScore']['score']}/100 ({result['healthScore']['grade']})")
    print(f"Summary: {result['healthScore']['summary']}")
    print(f"\nTop findings:")
    for finding in result["findings"][:3]:
        print(f"  [{finding['severity'].upper()}] {finding['title']}")
```

---

### Python — API Key

```python
#!/usr/bin/env python3
"""
MiaoFi API — Python API key example
Requires: pip install requests
Get your key at: https://miaofi.ai/api-key
"""
import requests
import os

MIAOFI_BASE_URL = "https://miaofi.ai"
API_KEY = os.environ.get("MIAOFI_API_KEY", "mk_your_key_here")

def diagnose_wallet(addresses: list[str]) -> dict:
    resp = requests.post(
        f"{MIAOFI_BASE_URL}/api/diagnosis",
        json={"addresses": addresses},
        headers={"X-API-KEY": API_KEY},
    )
    resp.raise_for_status()
    return resp.json()

def get_portfolio(addresses: list[str]) -> dict:
    resp = requests.get(
        f"{MIAOFI_BASE_URL}/api/portfolio",
        params={"addresses": ",".join(addresses)},
        headers={"X-API-KEY": API_KEY},
    )
    resp.raise_for_status()
    return resp.json()


if __name__ == "__main__":
    # Single wallet diagnosis
    result = diagnose_wallet(["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"])
    score = result["healthScore"]
    print(f"Health: {score['score']}/100 ({score['grade']}) — {score['summary']}")

    print("\nFindings:")
    for finding in result["findings"]:
        icon = {"critical": "🔴", "warning": "🟡", "info": "🔵", "positive": "🟢"}.get(finding["severity"], "⚪")
        print(f"  {icon} {finding['title']}")
        for action in finding.get("actionItems", [])[:2]:
            print(f"     → {action}")

    # Multi-wallet analysis
    multi = diagnose_wallet([
        "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
        "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",  # Solana
    ])
    print(f"\nMulti-wallet total: ${multi['reportSummary']['totalValueUsd']:,.2f}")
```

---

### TypeScript — x402 Agent Payment

```typescript
/**
 * MiaoFi API — TypeScript x402 agent example
 * Requires: npm install viem
 * Get your agent wallet key from a secure secrets manager
 */
import { createWalletClient, createPublicClient, http, parseUnits, erc20Abi } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { base } from 'viem/chains'

const MIAOFI_BASE_URL = 'https://miaofi.ai'
const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913' as const
const AGENT_PRIVATE_KEY = process.env.AGENT_PRIVATE_KEY as `0x${string}`

const account = privateKeyToAccount(AGENT_PRIVATE_KEY)
const publicClient = createPublicClient({ chain: base, transport: http() })
const walletClient = createWalletClient({ account, chain: base, transport: http() })

interface DiagnosisResult {
  healthScore: { score: number; grade: string; summary: string }
  findings: Array<{ severity: string; title: string; actionItems: string[] }>
  reportSummary: { totalValueUsd: number; riskLevel: string; recommendedActions: string[] }
  metadata: { diagnosisId: string; analysisTimestamp: string }
}

async function diagnoseWallet(addresses: string[]): Promise<DiagnosisResult> {
  const payload = { addresses }

  // Step 1: Initial request — may return 402
  const resp = await fetch(`${MIAOFI_BASE_URL}/api/diagnosis`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  })

  if (resp.ok) return resp.json()
  if (resp.status !== 402) throw new Error(`MiaoFi API error: ${resp.status}`)

  // Step 2: Parse payment requirements
  const { recipient, amount, nonce } = await resp.json()

  // Step 3: Send USDC on Base
  const txHash = await walletClient.writeContract({
    address: USDC_BASE,
    abi: erc20Abi,
    functionName: 'transfer',
    args: [recipient as `0x${string}`, BigInt(amount)],
  })
  await publicClient.waitForTransactionReceipt({ hash: txHash })

  // Step 4: Build payment proof
  const proof = { txHash, nonce, payer: account.address, chainId: base.id }
  const proofB64 = btoa(JSON.stringify(proof))

  // Step 5: Retry with payment proof
  const resp2 = await fetch(`${MIAOFI_BASE_URL}/api/diagnosis`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'PAYMENT-SIGNATURE': proofB64 },
    body: JSON.stringify(payload),
  })
  if (!resp2.ok) throw new Error(`MiaoFi payment verification failed: ${resp2.status}`)
  return resp2.json()
}

// Main
const result = await diagnoseWallet(['0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'])
console.log(`Health: ${result.healthScore.score}/100 (${result.healthScore.grade})`)
console.log(`Summary: ${result.healthScore.summary}`)
result.findings.slice(0, 3).forEach(f => {
  console.log(`  [${f.severity.toUpperCase()}] ${f.title}`)
})
```

---

### TypeScript — API Key

```typescript
/**
 * MiaoFi API — TypeScript API key example
 * Get your key at: https://miaofi.ai/api-key
 */

const MIAOFI_BASE_URL = 'https://miaofi.ai'
const API_KEY = process.env.MIAOFI_API_KEY ?? 'mk_your_key_here'

interface DiagnosisResult {
  healthScore: { score: number; grade: string; summary: string }
  findings: Array<{
    severity: 'critical' | 'warning' | 'info' | 'positive'
    title: string
    description: string
    actionItems: string[]
    affectedAssets?: string[]
  }>
  reportSummary: {
    totalValueUsd: number
    riskLevel: 'low' | 'medium' | 'high'
    oneLineInsight: string
    recommendedActions: string[]
  }
  metadata: {
    diagnosisId: string
    analyzedWallets: string[]
    analysisTimestamp: string
  }
}

async function diagnoseWallet(addresses: string[]): Promise<DiagnosisResult> {
  const resp = await fetch(`${MIAOFI_BASE_URL}/api/diagnosis`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-KEY': API_KEY,
    },
    body: JSON.stringify({ addresses }),
  })

  if (!resp.ok) {
    const error = await resp.text()
    throw new Error(`MiaoFi API error ${resp.status}: ${error}`)
  }

  return resp.json()
}

async function getPortfolio(addresses: string[]) {
  const params = new URLSearchParams({ addresses: addresses.join(',') })
  const resp = await fetch(`${MIAOFI_BASE_URL}/api/portfolio?${params}`, {
    headers: { 'X-API-KEY': API_KEY },
  })

  if (!resp.ok) throw new Error(`Portfolio API error ${resp.status}`)
  return resp.json()
}

// Single wallet
const diagnosis = await diagnoseWallet(['0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'])
const { healthScore, findings, reportSummary } = diagnosis

console.log(`\n📊 MiaoFi Diagnosis Report`)
console.log(`Health Score: ${healthScore.score}/100 (${healthScore.grade})`)
console.log(`Summary: ${healthScore.summary}`)
console.log(`Total Portfolio Value: $${reportSummary.totalValueUsd.toLocaleString()}`)
console.log(`Risk Level: ${reportSummary.riskLevel}`)

console.log(`\nFindings (${findings.length} total):`)
const icons = { critical: '🔴', warning: '🟡', info: '🔵', positive: '🟢' }
findings.forEach(f => {
  console.log(`  ${icons[f.severity] ?? '⚪'} ${f.title}`)
  f.actionItems.slice(0, 1).forEach(a => console.log(`     → ${a}`))
})

console.log(`\nTop Recommendations:`)
reportSummary.recommendedActions.forEach((a, i) => console.log(`  ${i + 1}. ${a}`))

// Multi-wallet
const multiResult = await diagnoseWallet([
  '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
  '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU',
])
console.log(`\nMulti-wallet total: $${multiResult.reportSummary.totalValueUsd.toLocaleString()}`)
```

---

## Agent Referral Program

MiaoFi rewards agents that bring other agents onto the platform.

### How It Works

1. **Refer**: Pass the `X-Referrer` header with your agent identifier when another
   agent makes its first call to `/api/diagnosis`.
2. **Earn**: For each successful diagnosis by the referred agent (first 10 calls),
   you earn **$0.02 USDC** in bonus credits — recorded in MiaoFi's ledger.
3. **Cap**: Maximum **$0.20 USDC** per referred agent (10 calls × $0.02).
4. **Scale**: Refer multiple agents — there is no cap on the number of agents you
   can refer. Bonus accrues per referred agent independently.

### Example

```http
POST /api/diagnosis HTTP/1.1
X-API-KEY: mk_your_api_key
X-Referrer: mk_your_api_key
Content-Type: application/json

{
  "walletAddresses": ["0xNewAgent..."]
}
```

If Agent B sends this header identifying Agent A as the referrer, Agent A earns
$0.02 for each of Agent B's first 10 successful diagnoses.

### Check Your Referral Stats

```http
GET /api/agent/referral-stats HTTP/1.1
X-API-KEY: mk_your_api_key
```

Response:
```json
{
  "referrer_id": "apikey:abc123",
  "total_referred": 3,
  "total_bonus_accrued_usd": 0.46,
  "referrals": [
    { "referred_id": "apikey:def456", "calls_count": 10, "bonus_usd": 0.20, "maxed": true },
    { "referred_id": "apikey:ghi789", "calls_count": 3, "bonus_usd": 0.06, "maxed": false }
  ]
}
```

### Notes

- Bonus is recorded on MiaoFi's ledger; on-chain settlement happens in batches (Phase 2).
- Self-referral is rejected (`X-Referrer` must differ from your own agent ID).
- Only successful diagnoses count — failed calls (5xx) do not accrue bonus.
- x402 agents use their payer wallet address as the identifier; API key agents use
  their key ID prefix.

---

## Pricing Summary

| Tier          | Cost per Diagnosis | Auth Method          | Rate Limit       |
|---------------|--------------------|----------------------|------------------|
| Free trial    | $0.00 (first 3)    | Browser login        | 3/month          |
| x402 agent    | $0.08 USDC         | No account needed    | 100/hour         |
| Credit packs  | $0.38–$0.66        | API key              | 100/hour         |
| Pro (referral)| Included (7 days)  | Browser login        | 10/hour + Opus   |

**Credit pack pricing:**
- 5 diagnoses — $1.90 total ($0.38 each)
- 15 diagnoses — $9.90 total ($0.66 each)
- 30 diagnoses — $19.90 total ($0.66 each)

Purchase at: https://miaofi.ai/api-key

---

## Frequently Asked Questions

**Q: What wallet address formats are supported?**
A: EVM addresses (0x followed by 40 hex characters, e.g., 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045) and Solana addresses (Base58 encoded, 32–44 characters, e.g., 7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU). Pass them interchangeably in the same request.

**Q: Am I charged if the diagnosis fails (500 error)?**
A: No. If MiaoFi returns a 500 error, your credits or x402 payment are not consumed.

**Q: How fresh is the portfolio data?**
A: Data is fetched live from Zerion (with Moralis and Helius as fallbacks) at diagnosis time. No stale cache is used for the core portfolio snapshot.

**Q: Does MiaoFi store my wallet data?**
A: Diagnosis results are cached for performance and to power the AI feedback loop. Wallet addresses are processed but not sold or shared. See: https://miaofi.ai/privacy

**Q: Can I use MiaoFi in a multi-agent workflow?**
A: Yes. The MCP server at https://miaofi.ai/api/mcp supports Claude Code, OpenClaw, and any MCP-compatible AI assistant. The x402 payment method is designed specifically for autonomous agent use.

**Q: What chains are supported?**
A: Ethereum, Polygon, Arbitrum, Base, Optimism (all EVM chains supported by Zerion), and Solana.

---

## Links

- Website: https://miaofi.ai
- Developer docs: https://miaofi.ai/docs
- OpenAPI spec: https://miaofi.ai/api/openapi
- MCP server: https://miaofi.ai/api/mcp
- Privacy policy: https://miaofi.ai/privacy
- Get API key: https://miaofi.ai/api-key
- Support: https://miaofi.ai (use the feedback widget)

---

## Agent-Specific Endpoints

These endpoints are designed for AI agents that need quick, structured signals
without running a full diagnosis. All agent endpoints use API key auth via the
`X-API-KEY` header unless noted otherwise.

**Authentication:** All paid agent endpoints require `X-API-KEY` header.
**Rate Limit:** 100 requests/hour per API key.
**Response Headers:** `X-Credits-Remaining`, `X-Model-Used`, `X-RateLimit-Remaining`.
**Error Format:** All errors return `{ error, code, retry_after?, details? }`.

### POST /api/agent/pre-trade-check

Pre-trade risk check. Before your agent executes a swap, call this to get a risk
signal in <2s.

**Request body:**
```json
{
  "wallet_address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
  "trade": {
    "from_token": "ETH",
    "to_token": "PEPE",
    "amount_usd": 5000
  }
}
```

**Response (HTTP 200):**
```json
{
  "risk_level": "high",
  "risk_score": 78,
  "reason": "Large allocation to high-volatility meme token while wallet already shows 40% meme exposure.",
  "should_proceed": false,
  "flags": ["meme_concentration", "fomo_pattern"],
  "related_endpoints": ["/api/agent/diagnosis"]
}
```

**Cost:** 1 credit per call (~$0.02)

---

### POST /api/agent/behavior-flags

Detect behavioral anomalies for a wallet: FOMO trading, overtrading, panic
selling, concentration risk. Returns severity-rated flags with concrete evidence.

**Request body:**
```json
{
  "wallet_address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
  "lookback_days": 30
}
```

**Response (HTTP 200):**
```json
{
  "flags": [
    {
      "flag": "fomo_trading",
      "severity": "warning",
      "evidence": "3 of 5 recent buys happened within 24h of >20% price pumps"
    }
  ],
  "overall_behavior_score": 65
}
```

**Cost:** 1 credit per call (~$0.02)

---

### GET /api/agent/wallet-risk-score

Quick wallet risk score. Returns 0-100 risk score with top risk factors.

**Query parameters:**
```
GET /api/agent/wallet-risk-score?address=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
```

**Response (HTTP 200):**
```json
{
  "risk_score": 45,
  "risk_level": "medium",
  "top_factors": ["High concentration in single asset", "Idle stablecoin capital", "Low diversification"],
  "token_count": 8,
  "total_value_usd": 42350.80,
  "detailed_diagnosis_available": true,
  "diagnosis_endpoint": "/api/agent/diagnosis",
  "diagnosis_price_usd": 0.08
}
```

**Cost:** 1 credit per call (~$0.01)

---

### POST /api/agent/diagnosis

Full behavioral diagnosis. Returns risk score, behavioral flags, actionable
recommendations with priority, and portfolio summary. Deeper than risk-score
or behavior-flags — combines all signals into one report.

**Request body:**
```json
{
  "wallet_address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
}
```

**Response (HTTP 200):**
```json
{
  "risk_score": 62,
  "risk_level": "medium",
  "behavior_flags": [
    { "flag": "concentration_risk", "severity": "warning", "evidence": "ETH is 78% of portfolio" }
  ],
  "recommendations": [
    { "action": "Diversify 15-20% of ETH into quality alts", "priority": "high", "reason": "Reduce single-asset risk" }
  ],
  "portfolio_summary": {
    "total_value_usd": 42350.80,
    "token_count": 8,
    "top_holding_pct": 78,
    "chain_distribution": { "ethereum": 90, "base": 10 }
  }
}
```

**Cost:** 1 credit per call (~$0.08)

---

### GET /api/agent/free/wallet-overview

Free wallet overview. No auth required. Returns basic portfolio stats without
AI diagnosis. Use as a gateway check before paid analysis.

**Query parameters:**
```
GET /api/agent/free/wallet-overview?address=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
```

**Response (HTTP 200):**
```json
{
  "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
  "token_count": 8,
  "total_value_usd": 42350.80,
  "chain_distribution": { "ethereum": 90, "base": 10 },
  "detailed_diagnosis_available": true,
  "diagnosis_endpoint": "/api/agent/diagnosis",
  "diagnosis_price_usd": 0.08
}
```

**Cost:** Free (no auth required)

---

### GET /api/agent/referral-stats

Returns referral bonus statistics for the authenticated agent.

**Response (HTTP 200):**
```json
{
  "referrer_id": "apikey:abc123",
  "total_referred": 3,
  "total_bonus_accrued_usd": 0.46,
  "referrals": [
    { "referred_id": "apikey:def456", "calls_count": 10, "bonus_usd": 0.20, "maxed": true }
  ]
}
```

---

### MCP Server — Agent Tools

The MCP server at `https://miaofi.ai/api/mcp` now exposes all agent tools:

| MCP Tool Name               | Equivalent API Endpoint            | Auth Required   |
|-----------------------------|------------------------------------|-----------------|
| analyze_wallet              | GET /api/portfolio                 | No              |
| diagnose_portfolio          | POST /api/diagnosis                | No              |
| miaofi_pre_trade_check      | POST /api/agent/pre-trade-check    | No (MCP preview)|
| miaofi_wallet_risk_score    | GET /api/agent/wallet-risk-score   | No (MCP preview)|
| miaofi_behavior_flags       | POST /api/agent/behavior-flags     | No (MCP preview)|
| miaofi_diagnosis            | POST /api/agent/diagnosis          | No (MCP preview)|
| miaofi_wallet_overview      | GET /api/agent/free/wallet-overview| No              |

MCP tools are available for preview without auth. For production use with
billing, use the REST API endpoints with API key authentication.

---

## Agent Discovery

MiaoFi publishes a machine-readable discovery file at
`/.well-known/x402.json` following the x402 v2 standard. AI agents can fetch
this file to automatically discover available endpoints, pricing, and auth
requirements without reading documentation.