# Machina — Buyer Guide for AI Agents

## Overview

Machina endpoints accept payment via [x402](https://www.x402.org/) — an HTTP-native payment protocol. Agents pay per call in USDC on Base (eip155:8453) using the `exact` payment scheme through the Coinbase CDP Facilitator.

No API keys, accounts, or registration required. Any agent with a Base USDC wallet can pay and use Machina services immediately.

## Payment Flow

### 1. Discovery — Probe the endpoint

Send your request without any payment headers. The server responds with **HTTP 402 Payment Required** and a JSON body containing the payment terms:

```
POST https://mach402.dev/url/extract
Content-Type: application/json

{"url": "https://example.com"}
```

**402 Response:**
```json
{
  "x402Version": 2,
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "maxAmountRequired": "5000",
      "resource": "https://mach402.dev/url/extract",
      "description": "Machina URL to Markdown",
      "payTo": "0x14B21d80bf5776437dD4f1043BDAf31e60B366AD",
      "mimeType": "application/json",
      "maxTimeoutSeconds": 60,
      "extra": {
        "name": "Machina URL to Markdown",
        "description": "Extract readable content from any URL as clean Markdown."
      }
    }
  ]
}
```

Key fields:
- `maxAmountRequired`: Price in token base units (USDC has 6 decimals, so `5000` = $0.005)
- `payTo`: Seller wallet address
- `network`: Chain identifier (Base mainnet)
- `scheme`: Payment mechanism (`exact` = ERC-20 transfer)

### 2. Payment — Sign and send

Using the x402 client SDK, sign the payment authorization and include it in the `X-PAYMENT` header on a retry of the same request:

```
POST https://mach402.dev/url/extract
Content-Type: application/json
X-PAYMENT: <base64-encoded-signed-payment>

{"url": "https://example.com"}
```

The `X-PAYMENT` header contains a base64-encoded JSON payload with:
- The payment amount and token address
- The payer's wallet address
- An EIP-712 typed signature authorizing the transfer
- A nonce and expiration timestamp

The server forwards this to the CDP Facilitator, which verifies the signature, executes the on-chain USDC transfer, and confirms settlement before the server returns the resource.

### 3. Response — Resource + receipt

On successful payment, the server returns **HTTP 200** with:
- The response body (the resource you paid for)
- An `X-PAYMENT-RESPONSE` header containing a base64-encoded settlement receipt

**200 Response headers:**
```
X-PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLC...
```

**Decoded receipt example:**
```json
{
  "success": true,
  "payer": "0x289e52C8677125444430BD32D21D9a8b107Bc184",
  "transaction": "0x<full_transaction_hash>",
  "network": "eip155:8453"
}
```

## SDK Integration

### Python (recommended)

```python
from cdp import CdpClient
from cdp.evm_local_account import EvmLocalAccount
from x402 import x402Client
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact import ExactEvmScheme

async with CdpClient() as cdp:
    account = await cdp.evm.get_or_create_account(name="my-agent-wallet")
    signer = EthAccountSigner(EvmLocalAccount(account))
    
    client = x402Client()
    client.register("eip155:8453", ExactEvmScheme(signer))
    
    async with x402HttpxClient(client) as http:
        response = await http.post(
            "https://mach402.dev/url/extract",
            json={"url": "https://example.com"},
        )
        print(response.json())
```

### JavaScript / TypeScript

```typescript
import { x402Client, ExactEvmScheme, x402FetchClient } from "@x402/sdk";

const signer = /* your ethers.js / viem signer */;
const client = new x402Client();
client.register("eip155:8453", new ExactEvmScheme(signer));

const http = new x402FetchClient(client);
const response = await http.post("https://mach402.dev/url/extract", {
  body: JSON.stringify({ url: "https://example.com" }),
  headers: { "Content-Type": "application/json" },
});
```

### cURL (manual testing)

For manual testing, use the x402 CLI tool or the CDP SDK to generate the `X-PAYMENT` header value, then pass it directly:

```bash
curl -X POST https://mach402.dev/url/extract \
  -H "Content-Type: application/json" \
  -H "X-PAYMENT: <base64-payment-from-sdk>" \
  -d '{"url": "https://example.com"}'
```

## Timeout and Retry Recovery

### Timeouts

- Payment authorizations include an expiration timestamp (typically 60 seconds from signing)
- If the server doesn't respond within the timeout, the payment authorization expires automatically — **your funds are safe**
- The CDP Facilitator only settles if it can verify the signature AND deliver the response

### Retry Strategy

| Scenario | Action |
|---|---|
| **HTTP 402** (no payment sent) | Normal — read the terms and send payment |
| **HTTP 402** (payment sent but rejected) | Check error message: expired signature, insufficient balance, or wrong token/network |
| **HTTP 5xx** (server error) | Retry with a **new** payment signature (old one may have been consumed). Wait 5-10 seconds. |
| **Network timeout** | Check your wallet balance. If unchanged, the payment was not settled — safe to retry with a new signature. If balance decreased, contact support. |
| **HTTP 200** | Success — save the `X-PAYMENT-RESPONSE` receipt for your records |

### Idempotency

Each payment authorization is single-use (nonce-based). If a request fails after payment settlement, the funds are spent. For high-value calls, use `/pdf/inspect` (free) before committing to `/pdf/extract`.

## Endpoints and Pricing

| Endpoint | Method | Price | Description |
|---|---|---|---|
| `/scan/python` | POST | $0.020 | Python code security + quality scan |
| `/validate/email` | POST | $0.007 | Single email validation |
| `/validate/email/bulk` | POST | $0.500 | Bulk email validation (up to 100) |
| `/domain/intel` | POST | $0.050 | Domain intelligence report |
| `/pdf/inspect` | POST | Free | PDF metadata pre-check |
| `/pdf/extract` | POST | $0.050 | PDF → Markdown (≤50 pages) |
| `/pdf/extract/large` | POST | $0.180 | PDF → Markdown (≤200 pages) |
| `/url/extract` | POST | $0.005 | URL → Markdown |

## Discovery Endpoints

| URL | Description |
|---|---|
| `GET /.well-known/x402` | Machine-readable service manifest (endpoints, seller address, network) |
| `GET /docs` | Interactive OpenAPI documentation |
| `GET /health` | Health check (returns `{"status": "ok"}`) |

## Support

- Email: ceo@difftechstore.com
- Documentation: https://mach402.dev/docs
- OpenAPI spec: https://mach402.dev/docs (Swagger UI)
