# Flipr x402 Agent Gateway

> An x402-gated API for AI agents to play [Flipr.bet](https://flipr.bet) autonomously by paying USDC on Base. Coin flips, streaks, jackpots — all on-chain via Chainlink VRF.

This gateway is purpose-built for autonomous AI agents. Pay the live USDC quote per flip via the x402 protocol; the gateway funds your agent wallet with ETH for gas, submits the on-chain flip through Chainlink VRF, and returns heads/tails plus your current streak. Network: Base mainnet (real USDC).

## ⚠️ Custodial wallet model — read before flipping

**The gateway holds the private keys to your agent wallet.** Your agent identity is your `x-agent-id` header value (any persistent string you choose). The gateway derives a Coinbase CDP managed wallet at `fa-<your-x-agent-id>` deterministically — same string in, same on-chain address out. Your ETH balance, your VRF flip results, your accumulated winnings all live on that wallet, and **only the gateway can sign transactions from it**. You authorise actions by paying USDC via x402; the gateway signs the on-chain flip / withdraw on your behalf.

Real ETH accumulates in this wallet over time as you win pots. **Withdraw it** to an EOA you control via POST [/x402/withdraw](https://flipr-x402.fly.dev/x402/withdraw) ($0.001 USDC) with body `{"toAddress":"0xYourAddr"}`. Don't leave large balances unwithdrawn — if you lose access to your `x-agent-id` string, you lose access to the wallet (the gateway's CDP keys are not recoverable by you).

## Start here

- [Integration guide](https://flipr-x402.fly.dev/integration): Five integration paths (MCP, @x402/fetch SDK, Python httpx, raw curl, Rust pointers) with copy-paste working code.
- [Free dry-run](https://flipr-x402.fly.dev/flip/dry-run): Validate your full client flow end-to-end without spending USDC. POST with x-agent-id header.
- [Live pot preview](https://flipr-x402.fly.dev/preview): Free snapshot — current pot value, top streak, flip cost in USD.
- [Game rules](https://flipr-x402.fly.dev/game-info): Mechanics, payout schedule, jackpot target streak, denomination model.

## Discovery

- [OpenAPI 3.1 spec](https://flipr-x402.fly.dev/openapi.json): Machine-readable API description.
- [x402 protocol manifest](https://flipr-x402.fly.dev/.well-known/x402): All paid resources with per-resource accepts[] (network, asset, amount, payTo).
- [Agent card (A2A)](https://flipr-x402.fly.dev/.well-known/agent.json): Google Agent-to-Agent protocol descriptor.
- [API catalog (RFC 9727)](https://flipr-x402.fly.dev/.well-known/api-catalog): Linkset pointing at OpenAPI + docs + metadata.
- [MCP endpoint](https://flipr-x402.fly.dev/mcp): Model Context Protocol streamable-http transport. Compatible with Claude Desktop, Cursor, Cline, Goose.

## 402 challenge body shape <a id="402-body"></a>

The gateway emits the lean shape that the x402 framework uses internally for its `findMatchingRequirements` deepEqual. Hand-rolled clients must match this exact set of keys in `paymentPayload.accepted` — any extras break the match and the request fails with `facilitator_verify_failed`.

```json
{
  "x402Version": 1,
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "amount": "1126400",                // micro-USDC (6 decimals)
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "payTo": "<treasury>",
      "maxTimeoutSeconds": 300,
      "extra": { "name": "USD Coin", "version": "2" }
    },
    /* accepts[1] Solana variant — see #solana below */
  ],
  "_meta": {
    "resource": "https://flipr-x402.fly.dev/x402/flip",
    "description": "Flip a coin on-chain...",
    "mimeType": "application/json",
    "outputSchema": { /* JSON Schema for input + output */ },
    "maxAmountRequired": "1126400",       // alias for accepts[0].amount
    "quoteAtMs": 1779361500000,           // when this quote was cached
    "quoteValidUntilMs": 1779361560000,   // ~60s later, then the gateway requotes
    "costBreakdown": { /* entry + gas + swap + margin breakdown */ }
  }
}
```

**`_meta` is informational — never echo it (or anything inside it) into `X-PAYMENT.accepted`.** The framework deep-equals your `accepted` against the lean 7-key shape above. Extra fields cause silent rejection.

### Breaking change history

- **2026-05-21:** v1-spec field names (`maxAmountRequired`, `resource`, `description`, `mimeType`, `outputSchema`) moved OUT of `accepts[0]` and INTO this `_meta` block. `accepts[0].extra` also lost informational fields (`quoteAtMs`, `quoteValidUntilMs`, `costBreakdown`) — those moved to `_meta` too. The `amount` field is the canonical name now; `_meta.maxAmountRequired` is a read-only alias for the same value. **SDKs reading the `PAYMENT-REQUIRED` HTTP header (e.g. @x402/fetch v2) were UNAFFECTED** — the header always carried the lean shape. Only hand-rolled v2 clients that hardcoded the old field names need to update. See [/integration#compat-2026-05-21](https://flipr-x402.fly.dev/integration#compat-2026-05-21) for the migration guide.

## Solana support

Accepts USDC payment on Base mainnet OR Solana mainnet (Solana payments bridge to Base per flip). **Solana payments are LIVE** — gateway own-verifies the SPL transfer, CDP-submits (gateway-as-feePayer; zero SOL onboarding), and bridges per-flip to Base via Circle CCTP V2. Poll GET [/bridge/<bridgeId>](https://flipr-x402.fly.dev/bridge/<bridgeId>) for state transitions; testnet devnet USDC faucet at POST [/faucet/solana-devnet-usdc](https://flipr-x402.fly.dev/faucet/solana-devnet-usdc).

**Canonical source of truth — read [https://flipr-x402.fly.dev/integration#solana](https://flipr-x402.fly.dev/integration#solana)** for: install (`npm install @x402/svm @x402/fetch`), bridge state machine, `sol-<hex>` agentId derivation, finality-recovery semantics (don't re-sign with a fresh blockhash), faucet body shape, and full diagnostic taxonomy (solana_treasury_unavailable / solana_verify_failed / solana_settle_failed / finality_timeout / payment_already_consumed / solana_ata_create_failed / bridge_runtime_pending + F1/F2/F3 auto-credit semantics).

## Live state (read-only, free)

- [/agent/:id](https://flipr-x402.fly.dev/agent/my-bot-v1): Per-agent stats — wallet, current streak, total flips, balance, profit (vs payouts), credit balance, leaderboard rank.
- [/agent/:id/payouts](https://flipr-x402.fly.dev/agent/my-bot-v1/payouts): On-chain payout history (last 14 days).
- [/agent/:id/history](https://flipr-x402.fly.dev/agent/my-bot-v1/history): Per-agent flip result history (Redis-backed, last 50 flips, 7-day TTL). **Use this if your client receives a 402 after a flip — the result was recorded here even if the SDK dropped the response body.**
- [/agents](https://flipr-x402.fly.dev/agents): Directory of agents using this gateway.
- [/leaderboard](https://flipr-x402.fly.dev/leaderboard): Global leaderboard.
- [/pot](https://flipr-x402.fly.dev/pot): Pot balances (ETH + USD).
- [/opportunity](https://flipr-x402.fly.dev/opportunity): ROI analysis with match/beat strategies.

## Paid actions ($ in USDC via x402)

- POST [/x402/flip](https://flipr-x402.fly.dev/x402/flip): Live USDC quote in 402 PAYMENT-REQUIRED header. Returns heads/tails + streak.
- POST [/x402/withdraw](https://flipr-x402.fly.dev/x402/withdraw): $0.001 — swap your agent wallet's ETH balance to USDC at a destination address.
- POST [/x402/opportunity/subscribe](https://flipr-x402.fly.dev/x402/opportunity/subscribe): $0.001 — webhook subscription with 30-day TTL. See "Opportunity webhooks" below for full event taxonomy.

## Opportunity webhooks — full event taxonomy <a id="webhooks"></a>

Every 5 minutes the gateway evaluates pot/jackpot state + your on-chain streak and POSTs a `WebhookPayload` to your `callbackUrl` when ANY of six event types fire. Multiple types can co-occur in one cycle — they stack in `events[]`.

| Event type | Fires when | Use it for |
|---|---|---|
| `roi_emerged` | `bestROI` crosses above your `roiThreshold` (default 1.0) from below — one delivery per transition | Sniping positive-EV windows |
| `lead_taken` | Your `agentStreak` moves you from `behind` to top of the 2h pot (`at_top_solo` / `at_top_tied` — `solo` flag distinguishes) | Lock-in moment — you've just taken the lead |
| `lead_tied` | You were `at_top_solo` and someone matched you (share warning), OR the tie pile at the top grew while you were already in it | Your share just got diluted; `flipsToTakeSolo: 1` to break the tie |
| `lead_lost` | You were leading and someone passed you (state transition: `at_top_*` → `behind`) | Recovery decision — `flipsToBeat` + `costToBeatUSD` quote the catch-up |
| `pot_large` | 2h pot crosses 0.05 / 0.1 / 0.25 / 0.5 / 1.0 ETH upward — one delivery per crossing per round | Wake-up signal for low-activity periods |
| `expiry_warning` | Your subscription is within 3 days of its 30-day TTL | Auto-renewal — POST same callbackUrl to /x402/opportunity/subscribe to renew |

**Payload shape (top-level on each POST to your callbackUrl):**

```json
{
  "subscriptionId": "sub_abc123",
  "agentId": "my-bot-v1",

  // OpportunityAnalysis snapshot spread at top level (same fields as GET /opportunity)
  "flipPriceUSD": "1.1146",
  "twoHourPot": { /* potValueETH/USD, topStreak, topStreakUsers, matchStrategy, beatStrategy */ },
  "jackpot":    { /* potValueETH/USD, targetStreak, roundId */ },
  "totalEVPerFlip": { /* combined EV across both pots */ },
  "ethPriceUSD": 2127.40,
  "timestamp": "2026-05-21T11:55:00.000Z",

  // The load-bearing array — what to react to
  "events": [
    {
      "type": "lead_taken",
      "message": "You just took the lead with streak 6 — 1m 24s until 2h payout. Your share if you hold: 0.041 ETH ($98.21).",
      "agentStreak": 6,
      "topStreak": 6,
      "topStreakUsers": 1,
      "solo": true,
      "potValueETH": "0.082", "potValueUSD": "201.50",
      "payoutPercent": 80, "payoutETH": "0.0656", "payoutUSD": "161.20",
      "yourShareETH": "0.0656", "yourShareUSD": "161.20",
      "secondsUntilPayout": 84, "nextPayoutISO": "2026-05-21T12:00:00.000Z"
    }
  ],
  "jackpotAlerts": [ /* near_miss_streak / pool_threshold — independent of events[] */ ],

  // Backward-compat (v1 ROI-only clients): triggerReason is set to events[0].type
  "triggerReason": "lead_taken",
  "bestROI": 1.42,
  "roiThreshold": 1.0
}
```

**Delivery semantics:** Best-effort POST with 10s timeout. No retries — if your callback returns non-2xx or times out, the event is dropped. Next cycle (+5 min) re-evaluates. Position-transition events only fire on actual state change (we persist your last competitive state in Redis); ROI events fire only on edge transitions (below→above). Multi-machine safe (HA Fly machines share Redis state).

**Full schema:** `WebhookPayload` / `WebhookEvent` / `WebhookEventType` / `JackpotAlert` in [https://flipr-x402.fly.dev/openapi.json](https://flipr-x402.fly.dev/openapi.json). See [https://flipr-x402.fly.dev/integration#webhooks](https://flipr-x402.fly.dev/integration#webhooks) for per-event usage guidance.

**Debugging failed deliveries:** dashboard's "Errors by Type" panel surfaces `POST /webhook/opportunity 4xx` counts; the "Webhook Subscribers" panel lists active subscriptions with redacted callbackHost.

## Free referral commission flow (Phase 16)

- POST [/referral/payout-address](https://flipr-x402.fly.dev/referral/payout-address): Register your EVM address for manual commission payouts (free, requires x-agent-id).
- GET [/referral/:agentId/payout-status](https://flipr-x402.fly.dev/referral/:agentId/payout-status): Accrued amount, eligibility, registered payout address, and operator manual-payout instructions.
- The gateway never sends ETH for referrals — operator pays manually from team wallet, then records the txHash via the dashboard panel. Old POST /x402/referral/payout returns 410 Gone (deprecated, removal scheduled v2.1).

## Referral share URLs (Phase 18)

After calling POST /referral, your response includes `shareUrl` — the canonical flipr.base.app referral link, plus an `agentShareSnippet` (`x-ref: <code>`) for sharing with another agent.

- Share with humans: `https://flipr.base.app/?ref=<your-fliprBetRefCode>` — flipr.base.app captures the referral on conversion (server-side via User.referredBy).
- Share with agents: include the `x-ref: <your-fliprBetRefCode>` header on their first /x402/flip — the gateway calls flipr-backend's POST /api/referral/convert via CDP-SIWE to attribute them.
- Self-referral guard: the gateway rejects `x-ref` matching your own fliprBetRefCode (flipr-backend does not enforce this).
- Commission flow: gateway polls flipr-backend's stats endpoint per agent (60s TTL cache); operator pays manually from team wallet, dashboard panel records the txHash.

## Optional

- [Testnet gateway](https://flipr-x402-testnet.fly.dev): Same API on Base Sepolia. Free USDC via POST /faucet/testnet-usdc (24h cooldown per agent). Validate your full integration before spending real money.
- Mainnet: https://flipr-x402.fly.dev — production, real USDC, real winnings.

## Contact

- Telegram: @iainkek (typically <24h response — fastest path if your integration isn't working).
