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

# x402

x402 is a pay-per-use API access method that requires no subscription. You pay for each call directly using stablecoins like USDC on Base, Solana, or Polygon.

Minara x402 endpoint: `https://x402.minara.ai`

Explore all endpoints: [Minara on x402scan](https://www.x402scan.com/server/66307a3c-aeb9-4508-9531-71eed69bc9b5)

***

## How x402 works

x402 follows a payment-challenge flow:

1. You make a request to a protected endpoint without payment.
2. The server responds with `402 Payment Required` and payment instructions (amount, currency, recipient address, chain).
3. You include a payment proof in the `x-payment-response` header and retry the request.
4. The server verifies the proof, processes the payment on-chain, and returns the API response.

The recommended approach is to use the x402 SDK, which handles this flow automatically.

***

## Getting started with the SDK

### Prerequisites

* A crypto wallet with USDC (any EVM-compatible wallet, or a Solana wallet)
* Node.js / Python / Go
* Your wallet's private key (for signing payments)

### Install

{% 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 %}

### Make a request

The SDK handles payment challenges automatically. Just make requests normally.

{% 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: "What is the current price of 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": "What is BTC price?"}
        )
        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":"What is BTC price?"}`))
req.Header.Set("Content-Type", "application/json")

resp, _ := httpClient.Do(req)
// payment handled automatically
```

{% endtab %}
{% endtabs %}

For the full x402 quickstart, see [x402 documentation](https://docs.x402.org/getting-started/quickstart-for-buyers).

***

## API reference

Base URL: `https://x402.minara.ai`

All endpoints require the `x-payment-response` header (handled automatically by the 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"}}}}}}}}}
```

### Multi-chain endpoints

Solana and Polygon variants are available at `/x402/solana/chat`, `/x402/solana/chat/expert`, `/x402/polygon/chat`, and `/x402/polygon/chat/expert` with identical request/response shapes.

***

## Error handling

| Code  | Error                 | Meaning                                                 |
| ----- | --------------------- | ------------------------------------------------------- |
| `402` | `payment_required`    | Normal — SDK handles this automatically                 |
| `401` | `unauthorized`        | Payment proof invalid or expired                        |
| `400` | `bad_request`         | Missing or invalid request parameters                   |
| `429` | `rate_limit_exceeded` | AI endpoints: 60 req/min; Trading endpoints: 30 req/min |

***

## Resources

* [x402 Protocol Documentation](https://docs.x402.org)
* [x402 GitHub Repository](https://github.com/coinbase/x402)
* [Minara on x402scan](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:

```
GET https://minara.ai/docs/trade/agent-api/x402.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
