> 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/ko/trade/agent-api/x402.md).

# x402

x402는 구독이 필요 없는 종량제 API 접근 방식입니다. Base, Solana 또는 Polygon에서 USDC 같은 스테이블코인을 사용하여 각 호출마다 직접 결제합니다.

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가 이 흐름을 자동으로 처리합니다.

***

## 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/ko/trade/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.
