> For the complete documentation index, see [llms.txt](https://minara.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://minara.ai/docs/minara-handbook/zh/jiao-yi/agent-api/x402.md).

# x402

x402 是一种按次付费的 API 访问方式，无需订阅。你可以直接使用 USDC 等稳定币在 Base、Solana 或 Polygon 上为每次调用付费。

Minara x402 端点： `https://x402.minara.ai`

查看所有端点： [x402scan 上的 Minara](https://www.x402scan.com/server/66307a3c-aeb9-4508-9531-71eed69bc9b5)

***

## x402 的工作原理

x402 采用支付挑战流程：

1. 你在未支付的情况下向受保护的端点发起请求。
2. 服务器返回 `402 需要付款` 以及付款说明（金额、货币、收款地址、链）。
3. 你在 `x-payment-response` 请求头中包含付款证明并重试请求。
4. 服务器验证证明，在链上处理付款，并返回 API 响应。

推荐使用 x402 SDK，它会自动处理此流程。

***

## 开始使用 SDK

### 先决条件

* 一个持有 USDC 的加密钱包（任何兼容 EVM 的钱包，或 Solana 钱包）
* Node.js / Python / Go
* 你的钱包私钥（用于签名付款）

### 安装

{% tabs %}
{% tab title="Node.js" %}

```bash
npm install @x402/fetch @x402/evm
```

{% endtab %}

{% tab title="Python" %}

```bash
pip install "x402[httpx]"
```

{% endtab %}

{% tab title="Go" %}

```bash
go get github.com/coinbase/x402/go
```

{% endtab %}
{% endtabs %}

### 发起请求

SDK 会自动处理支付挑战。只需正常发起请求即可。

{% tabs %}
{% tab title="Node.js" %}

```typescript
import { wrapFetchWithPayment } from "@x402/fetch";
import { x402Client } from "@x402/core/client";
import { registerExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);
const client = new x402Client();
registerExactEvmScheme(client, { signer });

const fetchWithPayment = wrapFetchWithPayment(fetch, client);

const response = await fetchWithPayment("https://x402.minara.ai/x402/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ userQuery: "BTC 的当前价格是多少？" })
});

const data = await response.json();
console.log(data.content);
```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio, os
from eth_account import Account
from x402 import x402Client
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact.register import register_exact_evm_client

async def call_minara():
    client = x402Client()
    account = Account.from_key(os.getenv("EVM_PRIVATE_KEY"))
    register_exact_evm_client(client, EthAccountSigner(account))

    async with x402HttpxClient(client) as http:
        response = await http.post(
            "https://x402.minara.ai/x402/chat",
            json={"userQuery": "BTC 价格是多少？"}
        )
        await response.aread()
        print(response.json()["content"] )

asyncio.run(call_minara())
```

{% endtab %}

{% tab title="Go" %}

```go
evmSigner, _ := evmsigners.NewClientSignerFromPrivateKey(os.Getenv("EVM_PRIVATE_KEY"))
x402Client := x402.Newx402Client().
    Register("eip155:*", evm.NewExactEvmScheme(evmSigner))

httpClient := x402http.WrapHTTPClientWithPayment(
    http.DefaultClient,
    x402http.Newx402HTTPClient(x402Client),
)

req, _ := http.NewRequest("POST", "https://x402.minara.ai/x402/chat",
    strings.NewReader(`{"userQuery":"BTC 价格是多少？"}`))
req.Header.Set("Content-Type", "application/json")

resp, _ := httpClient.Do(req)
// 付款自动处理
```

{% endtab %}
{% endtabs %}

完整的 x402 快速入门请参见 [x402 文档](https://docs.x402.org/getting-started/quickstart-for-buyers).

***

## API 参考

基础 URL： `https://x402.minara.ai`

所有端点都需要 `x-payment-response` 请求头（由 SDK 自动处理）。

## Chat (Base Chain)

> Ask Minara AI - Intelligent crypto assistant

```json
{"openapi":"3.0.0","info":{"title":"Minara x402 API","version":"1.0"},"servers":[{"url":"https://x402.minara.ai"}],"security":[{"x402Payment":[]}],"components":{"securitySchemes":{"x402Payment":{"type":"apiKey","in":"header","name":"x-payment-response","description":"Payment proof token obtained from x402 payment challenge flow. Required after completing payment."}},"schemas":{"ChatRequest":{"type":"object","required":["userQuery"],"properties":{"userQuery":{"type":"string","description":"Required. User query content."}}},"ChatResponse":{"type":"object","properties":{"content":{"type":"string","description":"AI response content."}}},"BadRequestError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"UnauthorizedError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"PaymentRequiredError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"},"paymentInstructions":{"type":"object","properties":{"amount":{"type":"string","description":"Payment amount required."},"currency":{"type":"string","description":"Payment currency (e.g., USDC)."},"recipient":{"type":"string","description":"Payment recipient address."},"chain":{"type":"string","description":"Blockchain for payment."}}}}}}},"paths":{"/x402/chat":{"post":{"summary":"Chat (Base Chain)","description":"Ask Minara AI - Intelligent crypto assistant","operationId":"x402Chat","tags":["AI"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatRequest"}}}},"responses":{"201":{"description":"Successful response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatResponse"}}}},"400":{"description":"Bad Request - Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BadRequestError"}}}},"401":{"description":"Unauthorized - Invalid payment response token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"402":{"description":"Payment Required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaymentRequiredError"}}}}}}}}}
```

## Chat Expert (Base Chain)

> Ask Minara AI - Intelligent crypto assistant

```json
{"openapi":"3.0.0","info":{"title":"Minara x402 API","version":"1.0"},"servers":[{"url":"https://x402.minara.ai"}],"security":[{"x402Payment":[]}],"components":{"securitySchemes":{"x402Payment":{"type":"apiKey","in":"header","name":"x-payment-response","description":"Payment proof token obtained from x402 payment challenge flow. Required after completing payment."}},"schemas":{"ChatRequest":{"type":"object","required":["userQuery"],"properties":{"userQuery":{"type":"string","description":"Required. User query content."}}},"ChatResponse":{"type":"object","properties":{"content":{"type":"string","description":"AI response content."}}},"PaymentRequiredError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"},"paymentInstructions":{"type":"object","properties":{"amount":{"type":"string","description":"Payment amount required."},"currency":{"type":"string","description":"Payment currency (e.g., USDC)."},"recipient":{"type":"string","description":"Payment recipient address."},"chain":{"type":"string","description":"Blockchain for payment."}}}}}}},"paths":{"/x402/chat/expert":{"post":{"summary":"Chat Expert (Base Chain)","description":"Ask Minara AI - Intelligent crypto assistant","operationId":"x402ChatExpert","tags":["AI"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatRequest"}}}},"responses":{"201":{"description":"Successful response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatResponse"}}}},"400":{"description":"Bad Request - Invalid parameters"},"401":{"description":"Unauthorized - Invalid payment response token"},"402":{"description":"Payment Required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaymentRequiredError"}}}}}}}}}
```

## Perpetual Trading Suggestion

> Get AI-powered perpetual trading suggestions with long/short recommendations, entry price, stop loss, take profit levels, and confidence score.

```json
{"openapi":"3.0.0","info":{"title":"Minara x402 API","version":"1.0"},"servers":[{"url":"https://x402.minara.ai"}],"security":[{"x402Payment":[]}],"components":{"securitySchemes":{"x402Payment":{"type":"apiKey","in":"header","name":"x-payment-response","description":"Payment proof token obtained from x402 payment challenge flow. Required after completing payment."}},"schemas":{"PerpTradingRequest":{"type":"object","required":["symbol"],"properties":{"symbol":{"type":"string","description":"Required. Trading symbol (e.g., 'BTC', 'ETH', 'SOL')."},"style":{"type":"string","enum":["scalping","day-trading","swing-trading"],"default":"scalping","description":"Optional. Trading style: 'scalping', 'day-trading', or 'swing-trading'. Default: 'scalping'."},"marginUSD":{"type":"number","default":1000,"description":"Optional. Margin in USD. Default: 1000."},"leverage":{"type":"number","default":10,"minimum":1,"maximum":40,"description":"Optional. Leverage multiplier (max: 40). Default: 10."},"strategy":{"type":"string","default":"max-profit","description":"Optional. Strategy type. Default: 'max-profit'. More strategies coming soon."}}},"PerpTradingResponse":{"type":"object","properties":{"entryPrice":{"type":"number","description":"Recommended entry price."},"side":{"type":"string","enum":["long","short"],"description":"Trading side recommendation."},"stopLossPrice":{"type":"number","description":"Recommended stop loss price."},"takeProfitPrice":{"type":"number","description":"Recommended take profit price."},"confidence":{"type":"number","minimum":0,"maximum":100,"description":"Confidence score (0-100)."},"reasons":{"type":"array","items":{"type":"string"},"description":"Analysis reasons based on technical indicators."},"risks":{"type":"array","items":{"type":"string"},"description":"Risk factors to consider."}}},"PaymentRequiredError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"},"paymentInstructions":{"type":"object","properties":{"amount":{"type":"string","description":"Payment amount required."},"currency":{"type":"string","description":"Payment currency (e.g., USDC)."},"recipient":{"type":"string","description":"Payment recipient address."},"chain":{"type":"string","description":"Blockchain for payment."}}}}}}},"paths":{"/x402/perp-trading-suggestion":{"post":{"summary":"Perpetual Trading Suggestion","description":"Get AI-powered perpetual trading suggestions with long/short recommendations, entry price, stop loss, take profit levels, and confidence score.","operationId":"x402PerpTradingSuggestion","tags":["Trading"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PerpTradingRequest"}}}},"responses":{"201":{"description":"Successful response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PerpTradingResponse"}}}},"400":{"description":"Bad Request - Invalid parameters"},"401":{"description":"Unauthorized - Invalid payment response token"},"402":{"description":"Payment Required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaymentRequiredError"}}}}}}}}}
```

## Intent to Swap Transaction

> Convert natural language trading intent into an executable swap transaction payload. Compatible with OKX DEX by default.

```json
{"openapi":"3.0.0","info":{"title":"Minara x402 API","version":"1.0"},"servers":[{"url":"https://x402.minara.ai"}],"security":[{"x402Payment":[]}],"components":{"securitySchemes":{"x402Payment":{"type":"apiKey","in":"header","name":"x-payment-response","description":"Payment proof token obtained from x402 payment challenge flow. Required after completing payment."}},"schemas":{"IntentToSwapRequest":{"type":"object","required":["intent","walletAddress"],"properties":{"intent":{"type":"string","description":"Required. Natural language swap intent (e.g., 'swap 0.1 ETH to USDC')."},"walletAddress":{"type":"string","description":"Required. User wallet address (0x...)."},"chain":{"type":"string","description":"Optional. Chain name (e.g., 'base', 'ethereum', 'bsc', 'arbitrum', 'optimism')."}}},"SwapTransactionResponse":{"type":"object","properties":{"transaction":{"type":"object","description":"Swap transaction details","properties":{"chain":{"type":"string","description":"Chain name."},"inputTokenAddress":{"type":"string","description":"Input token contract address."},"inputTokenSymbol":{"type":"string","description":"Input token symbol."},"outputTokenAddress":{"type":"string","description":"Output token contract address."},"outputTokenSymbol":{"type":"string","description":"Output token symbol."},"amount":{"type":"string","description":"Transaction amount."},"amountPercentage":{"type":"number","description":"Amount percentage."},"slippagePercent":{"type":"string","description":"Slippage percentage."}}}}},"PaymentRequiredError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"},"paymentInstructions":{"type":"object","properties":{"amount":{"type":"string","description":"Payment amount required."},"currency":{"type":"string","description":"Payment currency (e.g., USDC)."},"recipient":{"type":"string","description":"Payment recipient address."},"chain":{"type":"string","description":"Blockchain for payment."}}}}}}},"paths":{"/x402/intent-to-swap-tx":{"post":{"summary":"Intent to Swap Transaction","description":"Convert natural language trading intent into an executable swap transaction payload. Compatible with OKX DEX by default.","operationId":"x402IntentToSwap","tags":["Trading"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntentToSwapRequest"}}}},"responses":{"201":{"description":"Successful response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SwapTransactionResponse"}}}},"400":{"description":"Bad Request - Invalid parameters"},"401":{"description":"Unauthorized - Invalid payment response token"},"402":{"description":"Payment Required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaymentRequiredError"}}}}}}}}}
```

## Prediction Market Analysis (Base Chain)

> AI-powered prediction market analysis. Analyze prediction market events and get probability estimates for each outcome with detailed reasoning.

```json
{"openapi":"3.0.0","info":{"title":"Minara x402 API","version":"1.0"},"servers":[{"url":"https://x402.minara.ai"}],"security":[{"x402Payment":[]}],"components":{"securitySchemes":{"x402Payment":{"type":"apiKey","in":"header","name":"x-payment-response","description":"Payment proof token obtained from x402 payment challenge flow. Required after completing payment."}},"schemas":{"PredictionMarketRequest":{"type":"object","required":["link","mode"],"properties":{"link":{"type":"string","description":"Required. Prediction market page link (e.g., Polymarket event URL)."},"mode":{"type":"string","enum":["fast","expert"],"description":"Required. Chat mode: 'fast' or 'expert'."},"only_result":{"type":"boolean","default":false,"description":"Optional. Only return prediction probabilities without reasoning. Default: false."},"customPrompt":{"type":"string","description":"Optional. Custom instructions to guide the analysis. Use this to specify focus areas, risk preferences, or analysis style."}}},"PredictionMarketResponse":{"type":"object","properties":{"predictions":{"type":"array","description":"Array of prediction outcomes. Each outcome represents an event option with its yes/no probabilities.","items":{"type":"object","properties":{"outcome":{"type":"string","description":"Outcome name (event option, e.g., candidate name, team name)."},"yesProb":{"type":"number","description":"Probability of YES for this outcome (0-1)."},"noProb":{"type":"number","description":"Probability of NO for this outcome (0-1)."}}}},"reasoning":{"type":"string","description":"AI reasoning and analysis (empty if only_result=true)."}}},"BadRequestError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"UnauthorizedError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"}}},"PaymentRequiredError":{"type":"object","properties":{"error":{"type":"string"},"message":{"type":"string"},"paymentInstructions":{"type":"object","properties":{"amount":{"type":"string","description":"Payment amount required."},"currency":{"type":"string","description":"Payment currency (e.g., USDC)."},"recipient":{"type":"string","description":"Payment recipient address."},"chain":{"type":"string","description":"Blockchain for payment."}}}}}}},"paths":{"/x402/prediction-market-ask":{"post":{"summary":"Prediction Market Analysis (Base Chain)","description":"AI-powered prediction market analysis. Analyze prediction market events and get probability estimates for each outcome with detailed reasoning.","operationId":"x402PredictionMarketAsk","tags":["Prediction"],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PredictionMarketRequest"}}}},"responses":{"201":{"description":"Successful response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PredictionMarketResponse"}}}},"400":{"description":"Bad Request - Invalid parameters","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BadRequestError"}}}},"401":{"description":"Unauthorized - Invalid payment response token","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnauthorizedError"}}}},"402":{"description":"Payment Required","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PaymentRequiredError"}}}}}}}}}
```

### 多链端点

Solana 和 Polygon 版本可在以下地址访问： `/x402/solana/chat`, `/x402/solana/chat/expert`, `/x402/polygon/chat`以及 `/x402/polygon/chat/expert` 请求/响应格式相同。

***

## 错误处理

| 代码    | 错误                    | 含义                             |
| ----- | --------------------- | ------------------------------ |
| `402` | `payment_required`    | 正常——SDK 会自动处理                  |
| `401` | `unauthorized`        | 付款证明无效或已过期                     |
| `400` | `bad_request`         | 缺少或无效的请求参数                     |
| `429` | `rate_limit_exceeded` | AI 端点：60 次请求/分钟；交易端点：30 次请求/分钟 |

***

## 资源

* [x402 协议文档](https://docs.x402.org)
* [x402 GitHub 仓库](https://github.com/coinbase/x402)
* [x402scan 上的 Minara](https://www.x402scan.com/server/b9dea1bf-cf70-41d5-96b5-b91c924cfa50)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://minara.ai/docs/minara-handbook/zh/jiao-yi/agent-api/x402.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
