# UnFee (`https://unfee.xyz`) — Public Developer & AI Agent Documentation

> **Non-Custodial Zero-Markup Crypto & Card Checkout + Flat-Rate `1 Call = 1 Credit` JSON-RPC Gateway** on Base Mainnet (`8453`), Ethereum Mainnet (`1`), and Native XRP Ledger (`XRPL`).
>
> **Official Links:** Website: `https://unfee.xyz` · API Gateway: `https://api.unfee.xyz` · Zero-Block Worker Mirror: `https://unfee-gateway.unfee.workers.dev` · Hosted Checkout: `https://unfee.xyz/pay` · Interactive Docs: `https://unfee.xyz/docs` · Raw Markdown Mirror: `https://unfee.xyz/docs.md` · Official X: [@unfeexyz](https://x.com/unfeexyz) · Community Discord: [https://discord.gg/NKcJUXuS7](https://discord.gg/NKcJUXuS7)

---

## Table of Contents

- [Our Mission, Values & Guiding Principles](#mission-values-and-guiding-principles)
- [1. Overview & Architecture](#1-overview-and-architecture)
- [2. 60-Second Quickstart (Mint an API Key & Make Your First Call)](#2-60-second-quickstart)
- [3. Non-Custodial Checkout & 1-Line JS SDK (`/pay` & `/checkout.js`)](#3-non-custodial-checkout-and-js-sdk)
- [4. Gasless `x402` Autonomous AI Agent Payments (`EIP-3009`)](#4-gasless-x402-autonomous-ai-agent-payments)
- [5. Flat-Rate `1 Call = 1 Credit` JSON-RPC Gateway (`/rpc/base`, `/rpc/eth`, `/rpc/xrpl`)](#5-flat-rate-json-rpc-gateway)
- [6. Signed Webhooks (`HMAC-SHA256`) & Instant Email Receipts](#6-signed-webhooks-and-instant-email-receipts)
- [7. Verified Base Mainnet (`8453`) Smart Contracts & Non-Custodial Tax Architecture](#7-verified-smart-contracts-and-tax-architecture)
- [8. AI Agent & LLM Discovery Directory (Machine-Readable Index)](#8-ai-agent-and-llm-discovery-directory)

---

## Our Mission, Values & Guiding Principles {#mission-values-and-guiding-principles}

UnFee is **never** positioned as a custodial middleman or legacy processor replica. We are the **100% non-custodial anti-fee alternative** built from the ground up to eliminate middleman rent extraction and lower costs for all crypto and fiat users:

1. **Lower Costs for All Crypto & Fiat Users:**
   Eliminate extractive middleman tolls—including **Stripe / Legacy Card Processors (`2.9% + $0.30`)**, **Coinbase Commerce (`1.0%`)**, raw XRPL merchant gateways (`0.5%–1.0%` + `1.2 XRP` reserve lockups), and **`500x` compute-unit RPC markups**—so everyday people, merchants, and AI developers keep what they earn.
2. **Radical Pricing Transparency & Never-Overpay Fairness:**
   - **Flat `1 Call = 1 Credit` Metering:** Every JSON-RPC call—whether `eth_blockNumber`, `eth_getLogs`, or `debug_traceTransaction`—costs exactly **`1 credit`** with zero compute-unit multipliers.
   - **`$0/mo Starter (5¢ per $1,000 Micro-Fee)`:** `250,000` free RPC requests/mo + **`0.005%` (`0.5 bps` = `5¢ per $1,000`)** transaction micro-fee (`99.995%` to merchant), with an exact **`$100,000/mo` breakeven** (`$100,000 × 0.005% = $5.00`).
   - **`$5/mo Indie Tier (True 0% Fee)`:** `10,000,000` RPC requests/mo + **`0.000%` (`$0.00`)** transaction fee (`100.000%` to merchant).
   - **Auto-Downshift ("Never Overpay") Billing:** If your monthly request volume finishes in a lower bracket than your subscribed ceiling, UnFee automatically bills you at the lowest tier covering your actual usage and rolls over unused credit.
3. **100% Non-Custodial Sovereignty:**
   Peer-to-peer atomic settlement directly to the merchant's wallet via immutable, un-upgradeable Base Mainnet smart contracts (`0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790`) with **zero custody (`0%`)**, **zero admin keys**, and **zero wallet reserve lockups (`$0`)**.

---

## 1. Overview & Architecture {#1-overview-and-architecture}

**UnFee (`https://unfee.xyz`)** combines two foundational primitives into one unified edge network:

1. **Non-Custodial Zero-Markup Crypto & Card Checkout (`/pay` & `/checkout.js`):**
   Accept **USDC (Gasless EIP-3009 `x402`)**, **XRP (`cbXRP` on Base + Native `XRPL` Ledger)**, **RLUSD**, **ETH (Base Native)**, **USDT**, **EURC**, **cbBTC**, **DAI**, and **Apple Pay / Google Pay / Debit & Credit Card Onramp** with **True `0%` fee** on the `$5/mo Indie Tier` or **`0.005%` (`5¢ per $1,000`)** on the `$0/mo Starter Tier`.
2. **Flat-Rate `1 Call = 1 Credit` Multi-Chain JSON-RPC Gateway (`/rpc/base`, `/rpc/eth`, `/rpc/xrpl`):**
   High-throughput, edge-cached JSON-RPC and Etherscan V2-compatible indexing on **Base Mainnet (`8453`)**, **Ethereum Mainnet (`1`)**, and **XRP Ledger (`XRPL`)** where every request equals exactly `1 credit`.

### Transparent Pricing & Fee Schedule Table

| Tier / Plan | Monthly Price | Included RPC Credits (`1 Call = 1 Credit`) | Transaction Fee | Merchant Keeps | Burst Rate Limit | Key Highlights & Breakeven Math |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **`$0/mo Starter (5¢ per $1,000 Micro-Fee)`** (`free`) | **`$0.00 / mo`** | **`250,000 / mo`** | **`0.005%` (`0.5 bps` = `5¢ per $1,000`)** | **`99.995%`** | `10 RPS` | `$10,000/mo` volume = `50¢` fee. **Exact `$100,000/mo` breakeven** (`$100,000 × 0.005% = $5.00`). |
| **`$5/mo Indie Tier (True 0% Fee)`** (`indie_5`) | **`$5.00 / mo`** | **`10,000,000 / mo`** (`$0.50 / 1M`) | **`0.000%` (`$0.00` · `0 bps`)** | **`100.000%`** | `50 RPS` | **True `0%` transaction fee** on unlimited volume + Auto-Downshift guarantee. Automatic winner above `$100k/mo`. |
| **`$15/mo Pro Tier (True 0% Fee)`** (`pro_15`) | **`$15.00 / mo`** | **`35,000,000 / mo`** (`$0.43 / 1M`) | **`0.000%` (`$0.00` · `0 bps`)** | **`100.000%`** | `200 RPS` | **True `0%` transaction fee** + `35M` flat credits + Auto-Downshift to `$5` or `$0`. |
| **`$49/mo Scale Tier (True 0% Fee)`** (`scale_49`) | **`$49.00 / mo`** | **`125,000,000 / mo`** (`$0.39 / 1M`) | **`0.000%` (`$0.00` · `0 bps`)** | **`100.000%`** | `500 RPS` | **True `0%` transaction fee** + `125M` flat credits + Unlimited signed webhooks + Auto-Downshift. |
| **Pay-As-You-Go / `x402` & Auto Top-Up** (`payg_x402`) | **`$1.00` per `2,000,000` X-Tokens** (`$0.50 / 1M`) | **`+2,000,000` X-Tokens per `$1.00`** (`$0.0005 / 1K`) | **`0.005%` (`0.5 bps` = `5¢ per $1,000`)** | **`99.995%`** | `200 RPS` | Stateless `HTTP 402` machine micro-payments & optional `☑ Automatic Top-Up` at `95%` capacity. |

### Billing Protections Built Into Every API Key

- **Optional `☑ Automatic Top-Up ($1.00 = +2,000,000 X-Tokens)` at `95%` Capacity:**
  Opt-in to automatically add `+2,000,000 X-Tokens` for `$1.00 USDC` whenever your balance reaches `95%` usage (`<= 100,000` credits remaining) so production apps and autonomous AI agents never drop a request.
- **Auto-Downshift ("Never Overpay") Billing:**
  Subscribe to a higher burst ceiling (e.g., `$49 Scale` for `500 RPS`) with zero risk. If your actual monthly usage finishes in a lower bracket (`<= 250K` Free `$0`, `<= 10M` Indie `$5`, `<= 35M` Pro `$15`), UnFee automatically downshifts your bill to the lowest tier (or lower tier + `$0.50/1M` overage if cheaper) and rolls over the difference.
- **Configurable Usage Alerts (`60%, 70%, 80%, 90%, 95%`):**
  Armed by default on every key (`X-Usage-Alert-Status: OK (alerts_on:60,70,80,90,95)`). Receive real-time HTTP headers, signed webhooks, or Discord notifications at every threshold.

---

## 2. 60-Second Quickstart (Mint an API Key & Make Your First Call) {#2-60-second-quickstart}

Mint a live `uf_live_...` API key in under 1 second with **zero signup** and **zero credit card required**. Both `POST https://unfee.xyz/api/keys/free` and `POST https://unfee.xyz/api/billing/instant-free-key` are supported.

### Request: Mint a Free API Key (`curl`)

```bash
curl -sS -X POST https://unfee.xyz/api/keys/free \
  -H "Content-Type: application/json" \
  -d '{
    "label": "production-ai-agent",
    "tier": "free",
    "autoTopUpEnabled": true,
    "alertThresholds": [60, 70, 80, 90, 95]
  }'
```

### Example JSON Response (`201 Created`)

```json
{
  "status": "created",
  "verified": true,
  "apiKey": "uf_live_free_9a8f7c6e5d4b3a210987",
  "plan": "free",
  "planId": "free",
  "planName": "$0/mo Starter (5¢ per $1,000 Micro-Fee)",
  "monthlyPriceUsd": 0,
  "txFeePct": "0.005%",
  "txFeeBps": 0.5,
  "creditsAdded": 250000,
  "creditsRemaining": 250000,
  "totalCreditsRemaining": 250000,
  "maxRps": 10,
  "autoTopUp": {
    "enabled": true,
    "amountUsd": 1.0,
    "tokensAddedPerTopUp": 2000000,
    "triggerAtUsagePct": 95
  },
  "usageAlerts": {
    "enabled": true,
    "alertsEnabled": true,
    "thresholdsPct": [60, 70, 80, 90, 95],
    "statusHeader": "OK (alerts_on:60,70,80,90,95)"
  },
  "create2SplitterAddress": "0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790",
  "depositInvoice": {
    "invoiceAddress": "0x7F3c8a29b410E5D94A1E92c2789aBcDeF0123456",
    "factoryAddress": "0x4e59b44847b379578588920cA78FbF26c0B4956C",
    "merchantWallet": "0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B",
    "protocolTreasury": "0xAF4107196680A0d2Ca7E027D77CcF3Eb2EEBdFd0"
  }
}
```

---

## 3. Non-Custodial Checkout & 1-Line JS SDK (`/pay` & `/checkout.js`) {#3-non-custodial-checkout-and-js-sdk}

UnFee provides a hosted checkout page at `https://unfee.xyz/pay` and a 1-line drop-in JavaScript SDK at `https://unfee.xyz/checkout.js`.

### Hosted Checkout URL Parameters (`GET https://unfee.xyz/pay`)

| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `amount` | `string` | `"25.00"` | Payment amount denominated in USD / USDC (e.g. `25.00`, `5.00`, `100.00`). |
| `merchant` | `address` | `0x04A7...23a8` | Merchant's 0x Base Mainnet recipient wallet address (`^0x[a-fA-F0-9]{40}$`). |
| `merchantName` | `string` | `"Acme Cloud AI"` | Display name shown on the checkout header and email receipt. |
| `tier` | `string` | `"indie_5"` | Merchant tier (`free`, `indie_5`, `pro_15`, `scale_49`, `payg_x402`). |
| `asset` | `string` | `"USDC"` | Settlement asset (`USDC`, `XRP`, `RLUSD`, `ETH`, `USDT`, `EURC`, `cbBTC`, `DAI`). |
| `item` | `string` | `"Pro AI Workflow"` | Line-item description included in signed webhooks and email receipts. |
| `email` / `customer_email` | `string` | `""` | Customer email address for instant HTML/text receipt + Basescan verification link. |
| `webhook` / `webhook_url` | `string` | `""` | Merchant HTTPS endpoint to receive the `HMAC-SHA256` signed `payment.settled` event. |

### Supported Settlement Assets & Onramp Rails

| Asset / Rail | Network / Standard | Contract Address / Rail | Splitter Function / Settlement Mechanism | Fee on `$5/mo Indie` | Fee on `$0/mo Starter` |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **`USDC`** | Base Mainnet (`8453`) · Gasless `EIP-3009` `x402` | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` (6 dec) | `sweepBaseUSDC()` / `transferWithAuthorization` | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |
| **`XRP`** | `cbXRP` on Base (`8453`) + Native `XRPL` Ledger | Base `cbXRP` & Native `XRPL` (`$0` reserve lockup vs `1.2 XRP` on raw XRPL) | `sweepToken(address)` & Native XRPL Payment | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |
| **`RLUSD`** | Ripple USD on Base (`8453`) & Native `XRPL` | Base ERC-20 & XRPL Issued Currency | `sweepToken(address)` | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |
| **`ETH`** | Base Mainnet Native Ether (`8453`) | Native `ETH` (`18` decimals) | `sweepETH()` / `receive()` | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |
| **`USDT`** | Tether USD on Base (`8453`) | `0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2` (6 dec) | `sweepToken(address)` | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |
| **`EURC`** | Euro Coin on Base (`8453`) | `0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42` (6 dec) | `sweepToken(address)` | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |
| **`cbBTC`** | Coinbase Wrapped BTC on Base (`8453`) | `0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf` (8 dec) | `sweepToken(address)` | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |
| **`DAI`** | Dai Stablecoin on Base (`8453`) | `0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb` (18 dec) | `sweepToken(address)` | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |
| **Apple Pay / Google Pay / Debit & Credit Card** | Non-Custodial Fiat-to-Base USDC Onramp | Routes directly into `0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790` | Non-Custodial Card Onramp (`0%` UnFee custody) | **`0.000%` (`$0.00`)** | **`0.005%` (`5¢ / $1k`)** |

### 1-Line Drop-In HTML & Programmatic JS SDK (`https://unfee.xyz/checkout.js`)

```html
<!-- 1-Line Automatic Checkout Button Drop-In -->
<script
  src="https://unfee.xyz/checkout.js"
  data-merchant="0x04A72616B16Aa4b74A93851eF9FBF7Bf9f2223a8"
  data-merchant-name="Acme Cloud AI"
  data-amount="25.00"
  data-asset="USDC"
  data-item="Pro AI Workflow Subscription (Monthly)"
  data-tier="indie_5"
  data-customer-email="builder@acme.xyz"
  data-webhook-url="https://api.acme.xyz/webhooks/unfee"
></script>

<!-- Or Trigger Programmatically in JavaScript / TypeScript -->
<script>
  UnFeeCheckout.open({
    merchant: "0x04A72616B16Aa4b74A93851eF9FBF7Bf9f2223a8",
    merchantName: "Acme Cloud AI",
    amount: "25.00",
    asset: "USDC",
    item: "Pro AI Workflow Subscription (Monthly)",
    tier: "indie_5",
    customerEmail: "builder@acme.xyz",
    webhookUrl: "https://api.acme.xyz/webhooks/unfee",
    onSuccess: function (receipt) {
      console.log("Payment confirmed on Base Mainnet (8453):", receipt);
    }
  });
</script>
```

### Verify Checkout Payment & Dispatch Receipt (`POST https://unfee.xyz/api/checkout/verify`)

```bash
curl -sS -X POST https://unfee.xyz/api/checkout/verify \
  -H "Content-Type: application/json" \
  -d '{
    "plan": "indie_5",
    "asset": "USDC",
    "amountUsdc": "25.00",
    "merchantWallet": "0x04A72616B16Aa4b74A93851eF9FBF7Bf9f2223a8",
    "merchantName": "Acme Cloud AI",
    "item": "Pro AI Workflow Subscription",
    "receiptEmail": "builder@acme.xyz",
    "webhookUrl": "https://api.unfee.xyz/api/webhooks/mock-receiver"
  }'
```

#### Example Verification Response (`200 OK`)

```json
{
  "verified": true,
  "event": "payment.settled",
  "signatureHeader": "sha256=8f4d9c2a1b3e5f7091827364554637281910aabbccddeeff0011223344556677",
  "apiKey": "uf_live_payg_x402_7d8e9f0a1b2c3d4e5f60",
  "plan": "indie_5",
  "asset": "USDC",
  "settlementRail": "Base Mainnet (8453)",
  "create2SplitterAddress": "0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790",
  "payment": {
    "txHash": "0xeb7ee50a30809535faa2bae83efd6748058ccf23b118bdc6ffda0161027749cc",
    "asset": "USDC",
    "amountUsdc": "25.0000",
    "merchantShareUsdc": "25.000000",
    "protocolFeeUsdc": "0.000000"
  },
  "emailReceipt": {
    "status": "dispatched",
    "to": "builder@acme.xyz",
    "feeBreakdown": {
      "plan": "indie_5",
      "unfeeFeePct": "0%",
      "unfeeFeeUsd": "0.000000",
      "merchantNetUsdc": "25.000000",
      "legacyProcessorFeeUsd": "1.03",
      "savingsVsLegacyProcessorUsd": "1.0250"
    },
    "basescanUrl": "https://basescan.org/tx/0xeb7ee50a30809535faa2bae83efd6748058ccf23b118bdc6ffda0161027749cc"
  }
}
```

---

## 4. Gasless `x402` Autonomous AI Agent Payments (`EIP-3009`) {#4-gasless-x402-autonomous-ai-agent-payments}

UnFee natively implements the **HTTP 402 `x402` Machine Payment Protocol** using **EIP-3009 `transferWithAuthorization` (`0xcf092995`)** on Base Mainnet USDC (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`). Autonomous AI agents can pay for API credits or merchant invoices **without holding ETH for gas**.

### 4-Step Autonomous `x402` Handshake Flow

1. **Discover `x402` Parameters:** Agent fetches `GET https://unfee.xyz/.well-known/x402.json` to inspect supported networks (`eip155:8453`), EIP-712 domain parameters (`name: "USD Coin", version: "2", chainId: 8453`), and `Create2FeeSplitter` recipient (`0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790`).
2. **Receive `HTTP 402 Payment Required` Challenge:** Calling a metered resource such as `GET https://unfee.xyz/api/x402/premium-feed` without a funded key returns `HTTP 402` with `WWW-Authenticate: x402 realm="unfee.xyz"...` and a `PAYMENT-REQUIRED` base64 challenge header (`0.0005 USDC` per `1,000` calls = `$0.50 / 1M` requests).
3. **Sign EIP-712 `TransferWithAuthorization` Off-Chain:** Agent signs an EIP-3009 typed message authorizing Base USDC transfer to `0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790`.
4. **Settle & Unlock (`POST https://unfee.xyz/api/x402/settle`):** Agent submits the authorization to `/api/x402/settle` (or passes `X-Payment-Proof` on the original request) and immediately receives a credited `uf_live_...` key, `HMAC-SHA256` webhook receipt, and `200 OK` response.

### TypeScript / Node.js Autonomous Agent Example (`viem`)

```typescript
import { createWalletClient, http, parseUnits } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";
import crypto from "node:crypto";

const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY as `0x${string}`);
const client = createWalletClient({ account, chain: base, transport: http("https://api.unfee.xyz/rpc/base") });

const BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const UNFEE_SPLITTER = "0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790";

async function payWithX402() {
  // 1. Inspect UnFee x402 manifest
  const manifest = await fetch("https://unfee.xyz/.well-known/x402.json").then((r) => r.json());
  console.log("x402 Manifest protocol:", manifest.protocol);

  // 2. Construct EIP-3009 TransferWithAuthorization message ($5.00 USDC = 5,000,000 atomic units)
  const nonce = ("0x" + crypto.randomBytes(32).toString("hex")) as `0x${string}`;
  const validAfter = 0n;
  const validBefore = BigInt(Math.floor(Date.now() / 1000) + 3600);
  const value = parseUnits("5.00", 6);

  const signature = await client.signTypedData({
    domain: {
      name: "USD Coin",
      version: "2",
      chainId: 8453,
      verifyingContract: BASE_USDC,
    },
    types: {
      TransferWithAuthorization: [
        { name: "from", type: "address" },
        { name: "to", type: "address" },
        { name: "value", type: "uint256" },
        { name: "validAfter", type: "uint256" },
        { name: "validBefore", type: "uint256" },
        { name: "nonce", type: "bytes32" },
      ],
    },
    primaryType: "TransferWithAuthorization",
    message: {
      from: account.address,
      to: UNFEE_SPLITTER,
      value,
      validAfter,
      validBefore,
      nonce,
    },
  });

  // 3. Settle authorization & mint 10,000,000-credit Indie API key (0% fee)
  const settleRes = await fetch("https://unfee.xyz/api/x402/settle", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      plan: "indie_5",
      receiptEmail: "agent@acme.xyz",
      authorization: {
        from: account.address,
        to: UNFEE_SPLITTER,
        value: value.toString(),
        validAfter: Number(validAfter),
        validBefore: Number(validBefore),
        nonce,
      },
      signature,
    }),
  });

  const receipt = await settleRes.json();
  console.log("Settled x402 API Key:", receipt.apiKey, "Credits:", receipt.totalCreditsRemaining);
}

payWithX402();
```

### Python Autonomous Agent Example (`eth-account` + `requests`)

```python
import os
import time
import secrets
import requests
from eth_account import Account
from eth_account.messages import encode_typed_data

AGENT_PRIVATE_KEY = os.environ.get("AGENT_PRIVATE_KEY", "0x" + "11" * 32)
acct = Account.from_key(AGENT_PRIVATE_KEY)

BASE_USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
UNFEE_SPLITTER = "0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790"

# 1. Check HTTP 402 Challenge
challenge_resp = requests.get("https://unfee.xyz/api/x402/premium-feed")
assert challenge_resp.status_code == 402
print("Received HTTP 402 Challenge:", challenge_resp.headers.get("WWW-Authenticate"))

# 2. Sign EIP-3009 TransferWithAuthorization off-chain (0 ETH gas required)
nonce_hex = "0x" + secrets.token_hex(32)
valid_before = int(time.time()) + 3600
value_atomic = 5_000_000  # $5.00 USDC (6 decimals) -> Indie Tier (10M credits, 0% fee)

typed_data = {
    "types": {
        "EIP712Domain": [
            {"name": "name", "type": "string"},
            {"name": "version", "type": "string"},
            {"name": "chainId", "type": "uint256"},
            {"name": "verifyingContract", "type": "address"},
        ],
        "TransferWithAuthorization": [
            {"name": "from", "type": "address"},
            {"name": "to", "type": "address"},
            {"name": "value", "type": "uint256"},
            {"name": "validAfter", "type": "uint256"},
            {"name": "validBefore", "type": "uint256"},
            {"name": "nonce", "type": "bytes32"},
        ],
    },
    "domain": {
        "name": "USD Coin",
        "version": "2",
        "chainId": 8453,
        "verifyingContract": BASE_USDC,
    },
    "primaryType": "TransferWithAuthorization",
    "message": {
        "from": acct.address,
        "to": UNFEE_SPLITTER,
        "value": value_atomic,
        "validAfter": 0,
        "validBefore": valid_before,
        "nonce": bytes.fromhex(nonce_hex[2:]),
    },
}

signed = Account.sign_message(encode_typed_data(full_message=typed_data), AGENT_PRIVATE_KEY)

# 3. Settle via POST /api/x402/settle
res = requests.post(
    "https://unfee.xyz/api/x402/settle",
    json={
        "from": acct.address,
        "to": UNFEE_SPLITTER,
        "value": str(value_atomic),
        "plan": "indie_5",
        "nonce": nonce_hex,
        "validAfter": 0,
        "validBefore": valid_before,
        "signature": signed.signature.hex(),
        "receiptEmail": "agent@unfee.xyz",
    },
)
print("x402 Settlement Result:", res.json())
```

---

## 5. Flat-Rate `1 Call = 1 Credit` JSON-RPC Gateway (`/rpc/base`, `/rpc/eth`, `/rpc/xrpl`) {#5-flat-rate-json-rpc-gateway}

Legacy RPC middlemen inflate your bill using arbitrary "Compute Unit (CU)" multipliers—charging `75x` to `500x` more for historical logs, token transfers, or trace calls. **UnFee meters every single RPC call at `1 Call = 1 Credit` flat.**

### Side-by-Side Comparison: UnFee (`1 Call = 1 Credit`) vs. Legacy Compute-Unit Providers

| JSON-RPC / Indexer Method | UnFee Credit Cost | Legacy CU Provider Cost | Cost of 10,000,000 Calls on UnFee (`$5 Indie`) | Cost of 10,000,000 Calls on Legacy CU Providers | Builder Savings |
| :--- | :--- | :--- | :--- | :--- | :--- |
| `eth_blockNumber` / `eth_chainId` | **`1 Credit`** | `10 CUs` | **`$5.00`** | `$47.50+` | **`89.5%` saved** |
| `eth_call` / `eth_getBalance` | **`1 Credit`** | `26 CUs` | **`$5.00`** | `$123.50+` | **`96.0%` saved** |
| `eth_getLogs` (Event & Token Indexing) | **`1 Credit`** | **`750 CUs`** | **`$5.00`** | **`$350.00 – $3,500.00+`** | **`98.6% – 99.8%` saved** |
| `alchemy_getAssetTransfers` / `tokentx` | **`1 Credit`** | `150 – 500 CUs` | **`$5.00`** | `$350.00 – $2,375.00+` | **`98.6%+` saved** |
| `debug_traceTransaction` | **`1 Credit`** | **`2,500 CUs`** | **`$5.00`** | **`$1,187.50 – $11,875.00+`** | **`99.6%+` saved** |
| `XRPL` `server_info` / `account_info` / `tx` | **`1 Credit`** | Paid Add-On / Gateway Fee | **`$5.00`** (`$0` on `250K` Starter) | `$49.00 – $299.00/mo` | **`90.0%+` saved** |

### Live JSON-RPC Endpoints

- **Base Mainnet (`chainId: 8453`):** `POST https://api.unfee.xyz/rpc/base` (or `https://unfee.xyz/rpc/base` / `https://unfee.xyz/rpc/8453`)
- **Ethereum Mainnet (`chainId: 1`):** `POST https://api.unfee.xyz/rpc/eth` (or `https://unfee.xyz/rpc/eth` / `https://unfee.xyz/rpc/1`)
- **Native XRP Ledger (`XRPL`):** `POST https://api.unfee.xyz/rpc/xrpl` (or `https://unfee.xyz/rpc/xrpl`)

### `curl` Examples (`Base`, `Ethereum`, `XRPL`)

```bash
# 1. Base Mainnet (Chain ID 8453) — 1 Call = 1 Credit
curl -sS -X POST https://api.unfee.xyz/rpc/base \
  -H "Content-Type: application/json" \
  -H "X-API-Key: uf_live_YOUR_API_KEY" \
  -d '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}'

# 2. Ethereum Mainnet (Chain ID 1) — 1 Call = 1 Credit
curl -sS -X POST https://api.unfee.xyz/rpc/eth \
  -H "Content-Type: application/json" \
  -H "X-API-Key: uf_live_YOUR_API_KEY" \
  -d '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}'

# 3. Native XRP Ledger (XRPL) — 1 Call = 1 Credit
curl -sS -X POST https://api.unfee.xyz/rpc/xrpl \
  -H "Content-Type: application/json" \
  -H "X-API-Key: uf_live_YOUR_API_KEY" \
  -d '{"method":"server_info","params":[{}]}'
```

### TypeScript / JavaScript (`viem` & `ethers.js`)

```typescript
// Using viem with UnFee Base Mainnet & Ethereum Mainnet RPC
import { createPublicClient, http } from "viem";
import { base, mainnet } from "viem/chains";

const baseClient = createPublicClient({
  chain: base,
  transport: http("https://api.unfee.xyz/rpc/base", {
    fetchOptions: { headers: { "X-API-Key": process.env.UNFEE_API_KEY! } },
  }),
});

const ethClient = createPublicClient({
  chain: mainnet,
  transport: http("https://api.unfee.xyz/rpc/eth", {
    fetchOptions: { headers: { "X-API-Key": process.env.UNFEE_API_KEY! } },
  }),
});

const [baseBlock, ethBlock] = await Promise.all([
  baseClient.getBlockNumber(),
  ethClient.getBlockNumber(),
]);
console.log({ baseBlock, ethBlock });

// Using ethers.js v6
import { JsonRpcProvider, FetchRequest } from "ethers";
const req = new FetchRequest("https://api.unfee.xyz/rpc/base");
req.setHeader("X-API-Key", process.env.UNFEE_API_KEY!);
const provider = new JsonRpcProvider(req, 8453);
console.log("Base Block (ethers):", await provider.getBlockNumber());
```

### Python (`web3.py`)

```python
from web3 import Web3

w3_base = Web3(
    Web3.HTTPProvider(
        "https://api.unfee.xyz/rpc/base",
        request_kwargs={"headers": {"X-API-Key": "uf_live_YOUR_API_KEY"}},
    )
)
w3_eth = Web3(
    Web3.HTTPProvider(
        "https://api.unfee.xyz/rpc/eth",
        request_kwargs={"headers": {"X-API-Key": "uf_live_YOUR_API_KEY"}},
    )
)

print("Base Mainnet Tip:", w3_base.eth.block_number)
print("Ethereum Mainnet Tip:", w3_eth.eth.block_number)
```

### XRP Ledger (`xrpl.js` / HTTP JSON-RPC)

```javascript
// Native XRPL JSON-RPC via https://api.unfee.xyz/rpc/xrpl (1 Call = 1 Credit)
const response = await fetch("https://api.unfee.xyz/rpc/xrpl", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-API-Key": process.env.UNFEE_API_KEY,
  },
  body: JSON.stringify({
    method: "account_info",
    params: [{ account: "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", ledger_index: "validated" }],
  }),
});
const xrplData = await response.json();
console.log("XRPL Validated Ledger Info:", xrplData);
```

---

## 6. Signed Webhooks (`HMAC-SHA256`) & Instant Email Receipts {#6-signed-webhooks-and-instant-email-receipts}

Every settlement (`payment.settled`) and automatic top-up (`topup.completed`) can trigger:
1. **Cryptographically signed `HMAC-SHA256` webhooks** with header `X-Unfee-Signature: sha256=<hex_digest>` signed using your `whsec_unfee_...` secret.
2. **Instant HTML + Plain-Text Email Receipts** showing the exact fee breakdown, savings vs. Legacy Card Processors (`2.9% + $0.30` / Stripe) & Coinbase Commerce (`1.0%`), and a clickable Basescan verification link.

### Webhook & Email Receipt Endpoints

```bash
# 1. Register a Webhook URL & Receipt Email (Returns whsec_unfee_... signingSecret)
curl -sS -X POST https://unfee.xyz/api/webhooks/register \
  -H "Content-Type: application/json" \
  -d '{
    "webhookUrl": "https://api.merchant.xyz/webhooks/unfee",
    "receiptEmail": "finance@merchant.xyz",
    "events": ["payment.settled", "topup.completed"]
  }'

# 2. Fire a Signed Test Webhook + Email Receipt Immediately
curl -sS -X POST https://unfee.xyz/api/webhooks/test \
  -H "Content-Type: application/json" \
  -d '{
    "event": "payment.settled",
    "amountUsdc": "25.00",
    "asset": "USDC",
    "plan": "indie_5",
    "receiptEmail": "finance@merchant.xyz"
  }'

# 3. Generate & Dispatch a Standalone Transaction Email Receipt
curl -sS -X POST https://unfee.xyz/api/receipts/email \
  -H "Content-Type: application/json" \
  -d '{
    "to": "customer@merchant.xyz",
    "amountUsdc": "25.00",
    "asset": "USDC",
    "plan": "indie_5",
    "txHash": "0xeb7ee50a30809535faa2bae83efd6748058ccf23b118bdc6ffda0161027749cc"
  }'
```

### Node.js / Express Webhook Signature Verification (`X-Unfee-Signature`)

```javascript
import express from "express";
import crypto from "node:crypto";

const app = express();
const WEBHOOK_SECRET = process.env.UNFEE_WEBHOOK_SECRET; // e.g. "whsec_unfee_..."

app.post("/webhooks/unfee", express.raw({ type: "application/json" }), (req, res) => {
  const signatureHeader = req.headers["x-unfee-signature"] || "";
  const expectedSig =
    "sha256=" +
    crypto.createHmac("sha256", WEBHOOK_SECRET).update(req.body).digest("hex");

  const valid =
    signatureHeader.length === expectedSig.length &&
    crypto.timingSafeEqual(Buffer.from(signatureHeader), Buffer.from(expectedSig));

  if (!valid) {
    return res.status(401).json({ error: "Invalid X-Unfee-Signature" });
  }

  const event = JSON.parse(req.body.toString("utf8"));
  console.log("Verified UnFee Event:", event.event, "TxHash:", event.txHash);
  res.status(200).json({ received: true });
});
```

### Python / FastAPI Webhook Signature Verification (`X-Unfee-Signature`)

```python
import os
import hmac
import hashlib
from fastapi import FastAPI, Request, HTTPException

app = FastAPI()
WEBHOOK_SECRET = os.environ["UNFEE_WEBHOOK_SECRET"]  # "whsec_unfee_..."

@app.post("/webhooks/unfee")
async def unfee_webhook(request: Request):
    raw_body = await request.body()
    sig_header = request.headers.get("X-Unfee-Signature", "")
    expected_sig = "sha256=" + hmac.new(
        WEBHOOK_SECRET.encode("utf-8"),
        raw_body,
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(sig_header, expected_sig):
        raise HTTPException(status_code=401, detail="Invalid X-Unfee-Signature")

    payload = await request.json()
    print(f"Verified UnFee event: {payload['event']} ({payload['amountUsdc']} {payload['asset']})")
    return {"received": True}
```

---

## 7. Verified Base Mainnet (`8453`) Smart Contracts & Non-Custodial Tax Architecture {#7-verified-smart-contracts-and-tax-architecture}

### Verified On-Chain Contract Addresses (Base Mainnet — Chain ID `8453`)

| Contract / Component | Base Mainnet Address | Basescan Explorer Link | Details |
| :--- | :--- | :--- | :--- |
| **`Create2FeeSplitter`** | `0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790` | [View on Basescan](https://basescan.org/address/0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790) | Deployed in Block `#53038810` ([Tx `0xf03fd333...c30c`](https://basescan.org/tx/0xf03fd33383eb3724d12110c3a9d8524eb445e4b5eb6c2ccdbd7c803869e1c30c)) · `2,190 bytes` · `solc 0.8.24` · Zero admin keys, un-upgradeable. |
| **`Create2FeeSplitterFactory`** | `0x6ED5d52C58b44480aE764DE79a1086b23Aa6De26` | [View on Basescan](https://basescan.org/address/0x6ED5d52C58b44480aE764DE79a1086b23Aa6De26) | Deterministic counterfactual invoice deployment factory ([Tx `0x8f9fa2a0...0662`](https://basescan.org/tx/0x8f9fa2a0b9aca9352d98aa566f8aad243227d81bc784c11be2693fd8f05b0662)). |
| **Protocol Treasury** | `0xAF4107196680A0d2Ca7E027D77CcF3Eb2EEBdFd0` | [View on Basescan](https://basescan.org/address/0xAF4107196680A0d2Ca7E027D77CcF3Eb2EEBdFd0) | Receives protocol subscription & micro-fee share only; never touches merchant principal. |
| **Base Mainnet `USDC`** | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` | [View on Basescan](https://basescan.org/address/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) | Native Circle USD Coin (`6` decimals, EIP-3009 `transferWithAuthorization` enabled). |

### Solidity Interface & ABI (`Create2FeeSplitter`)

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface ICreate2FeeSplitter {
    function merchantWallet() external view returns (address);
    function protocolTreasury() external view returns (address);
    function invoiceId() external view returns (bytes32);

    /// @notice Sweeps canonical Base Mainnet USDC (0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913) atomically to merchant & treasury
    function sweepBaseUSDC() external;

    /// @notice Sweeps any ERC-20 token (USDC, cbXRP, RLUSD, USDT, EURC, cbBTC, DAI) atomically
    function sweepToken(address token) external;

    /// @notice Sweeps accumulated native Base ETH atomically
    function sweepETH() external;

    event TokenPaymentSplit(
        bytes32 indexed invoiceId,
        address indexed token,
        address indexed merchantWallet,
        address protocolTreasury,
        uint256 totalAmount,
        uint256 merchantAmount,
        uint256 protocolFee
    );

    event NativePaymentSplit(
        bytes32 indexed invoiceId,
        address indexed merchantWallet,
        address indexed protocolTreasury,
        uint256 totalAmount,
        uint256 merchantAmount,
        uint256 protocolFee
    );
}
```

### FinCEN `FIN-2019-G001` Section 4.2.1 Non-Custodial Software Provider Exemption & Tax Isolation

- **Zero Custody (`0%`):** Under **FinCEN Guidance `FIN-2019-G001` (Section 4.2.1)**, providers of non-custodial software and deterministic smart contract tools that never take independent control over user funds are classified as software providers, not money transmitters.
- **100% Principal Tax Isolation:** Because `100.000%` of merchant principal on the `$5/mo Indie Tier` (`99.995%` on the `$0/mo Starter Tier`) routes atomically peer-to-peer straight to the merchant's wallet on-chain via `0xA7a15bCEd59f4B687f5356b880DB3dcDaF086790`, **UnFee never holds merchant principal and is never taxed on merchant transaction volume—only on net fee and subscription revenue.**

---

## 8. AI Agent & LLM Discovery Directory (Machine-Readable Index) {#8-ai-agent-and-llm-discovery-directory}

UnFee is designed for zero-friction ingestion by LLMs, RAG pipelines, Cursor `@Docs`, Claude MCP, OpenAI Actions, and autonomous `x402` agents.

### Machine-Readable Endpoints Table

| Resource | URL | Content-Type | Purpose |
| :--- | :--- | :--- | :--- |
| **Interactive Developer & AI Docs** | `https://unfee.xyz/docs` | `text/html` (or `text/markdown` via `Accept: text/markdown` / `?format=md`) | Full interactive dark-mode documentation portal with content-negotiated Markdown support. |
| **Raw Markdown Documentation Mirror** | `https://unfee.xyz/docs.md` | `text/markdown; charset=utf-8` | Clean, exhaustive single-file Markdown documentation for LLMs, RAG crawlers, and `@Docs`. |
| **Concise LLM Index (`llms.txt`)** | `https://unfee.xyz/llms.txt` | `text/plain; charset=utf-8` | Standard `llms.txt` overview, quickstart commands, and discovery links. |
| **Full LLM Reference (`llms-full.txt`)** | `https://unfee.xyz/llms-full.txt` | `text/plain; charset=utf-8` | Complete architecture, contract table, and API reference in plain text. |
| **OpenAPI 3.1 Specification** | `https://unfee.xyz/openapi.json` | `application/json` | Machine-readable OpenAPI 3.1 schema for ChatGPT Actions, LangChain, and SDK generators. |
| **`x402` Machine Payment Manifest** | `https://unfee.xyz/.well-known/x402.json` | `application/json` | EIP-3009 `transferWithAuthorization` domain, contract addresses, and pricing schedule. |
| **A2A AI Agent Discovery Card (`agent.json`)** | `https://unfee.xyz/.well-known/agent.json` | `application/json` | Agent-to-Agent (A2A) discovery manifest with pricing tiers, supported assets, and RPC endpoints. |
| **AI Plugin Manifest** | `https://unfee.xyz/.well-known/ai-plugin.json` | `application/json` | Standard AI agent plugin descriptor pointing to `/openapi.json` and `/docs.md`. |
| **Installable AI Agent Skill (`SKILL.md`)** | `https://unfee.xyz/skills/low-cost-crypto-transaction/SKILL.md` | `text/markdown; charset=utf-8` | Ready-to-install skill for Cursor, Claude Code, OpenClaw, and Smithery agents. |
| **AI Skill Marketplace Registry** | `https://unfee.xyz/skills/index.json` | `application/json` | Structured JSON registry of UnFee agent skills and supported Base/XRPL assets. |

### Integrating UnFee into Cursor `@Docs`, Claude MCP, OpenAI Actions & Smithery

1. **Cursor `@Docs` Integration:**
   In Cursor, type `@Docs` → **Add new doc** → enter `https://unfee.xyz/docs` or `https://unfee.xyz/docs.md`. Cursor automatically receives clean Markdown via content negotiation (`Accept: text/markdown`).
2. **Claude Code / Cursor Skill Installation:**
   Download `https://unfee.xyz/skills/low-cost-crypto-transaction/SKILL.md` into `.cursor/skills/low-cost-crypto-transaction/SKILL.md` or `.claude/skills/low-cost-crypto-transaction/SKILL.md`.
3. **OpenAI Custom GPTs / Actions & LangChain Tools:**
   Import `https://unfee.xyz/openapi.json` directly into your agent's OpenAPI action schema.
