# API

Base URL `https://api.stomped.dev`. JSON in and out. Every endpoint has its own page in the sidebar, generated from the contract the server implements. Matches, live, leaderboard, health and the platform key need no auth; bots, account and keys need a dashboard session or an API key. You never need the API to play; it exists for scripting, such as a deploy job that re-registers a bot or a cron job that pauses it.

## API Keys

Two kinds, created in the dashboard under API keys or with `POST /keys`. Both share the same scopes and endpoints; scopes are fixed when the key is created.

- **Signature key** (the default). You generate an Ed25519 keypair and register the public half; every request is signed with the private key. No secret crosses the wire, and a captured request cannot be altered or reused elsewhere, only replayed as-is within a five-minute window.
- **Bearer key.** stomped generates a secret token, shown exactly once at creation (`stp_` followed by random base64; stomped keeps a hash). Send it as `Authorization: Bearer stp_…`. Treat it like a password; the `stp_` prefix makes a leaked token greppable. Lost it? Revoke the key and create a new one.

## Signing Requests

Generate a keypair (`ssh-keygen -t ed25519` works) and register the public key: OpenSSH `.pub` lines, PEM blocks and raw base64 are all accepted. The key id shown at creation goes on every request, with a timestamp and the signature:

| header | value |
| --- | --- |
| `x-stomped-key` | the key id |
| `x-stomped-timestamp` | unix milliseconds, as a string; within 5 minutes of stomped's clock |
| `x-stomped-signature` | `base64(ed25519_sign("<timestamp>.<METHOD>.<path>.<body>"))` |

`METHOD` is uppercase, `path` includes the query string (`/bots?status=active`), and `body` is the exact raw bytes sent, empty for a bodyless request.

```js
async function stomped(privateKey, keyId, method, path, body) {
    const raw = body ? JSON.stringify(body) : "";
    const timestamp = String(Date.now());
    const message = `${timestamp}.${method}.${path}.${raw}`;
    const signature = Buffer.from(
        await crypto.subtle.sign("Ed25519", privateKey, new TextEncoder().encode(message)),
    ).toString("base64");
    return fetch(`https://api.stomped.dev${path}`, {
        method,
        headers: {
            "content-type": "application/json",
            "x-stomped-key": keyId,
            "x-stomped-timestamp": timestamp,
            "x-stomped-signature": signature,
        },
        body: raw || undefined,
    });
}

await stomped(privateKey, keyId, "POST", "/bots", {
    name: "my-first-bot",
    url: "https://your-bot.example.com",
});
```

Requests from stomped to your bot (the match socket) are signed with the platform key regardless of which kind of key you use.

## Scopes

Each endpoint page names the scope it requires. A dashboard session carries every scope. A key for a deploy script wants `bots.read` and `bots.write` (the default) and nothing more.

| scope | allows |
| --- | --- |
| `bots.read` | list and inspect your bots |
| `bots.write` | register, update, pause, remove bots |
| `keys.read` | list your API keys |
| `keys.write` | create and revoke API keys |
| `account.read` | read your account |
| `account.write` | change your handle |

## Errors

Errors are JSON, `{"code": "NOT_FOUND", "status": 404, "message": "…"}`, with `data` when there is more to say.

- `400` invalid input (`data.issues` lists the fields), a failed deploy check (the message names the step), or a refused name (`invalid name`).
- `401` no or invalid auth; `403` the key lacks the scope.
- `404` not yours or does not exist. Bots are owner-only, so another account's bot is a `404`.
- `409` a bot name you already use, a URL already registered to a bot, or the bot or API key cap.
- `429` rate limited, with a `Retry-After` header in seconds. Limits are per account, per IP (an IPv6 /64) when anonymous: bot registration and URL changes 10/min, other writes 30/min, replay downloads 30/min, match reads (`/matches`, records) 120/min, everything else 600/min; sign-in emails 3/min per address. Replay downloads also carry `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` (seconds until the bucket is full) on every response, so a crawler can pace itself without ever seeing a `429`. An account holds at most 20 API keys and 5 bots.

## Scoring and Rating

- The match record carries stocks and percent per port. `score` is stocks remaining, 4 against 0 on a forfeit. Placement is 1 for the winner and 2 for the loser, 1 and 1 on a draw.
- Ratings are [openskill](https://openskill.me) (Weng-Lin): a bot starts at `mu = 25`, `sigma = 25/3`, and the number shown is `mu − 3σ`, so new bots start near 0 and climb as sigma shrinks. A draw rates as a tie, a forfeit as a loss.
- The leaderboard ranks every bot with at least one completed match. Rating deltas are on the match record once it completes.

## Matchmaking

- No queue, one game per match, no sets. Every 5 seconds the scheduler starts at most one match. A bot plays one match at a time; the number running at once is capped, so a bot may wait when the arena is busy.
- A bot is due 6 minutes after its last match ended, so expect a game every 7 to 10 minutes while the arena has room, less often when it is full. A new bot is due the moment it registers and its wait climbs to the norm over its first 10 games (6 minutes × (games ÷ 10)², never under the 2-minute cooldown).
- Each tick seats the most overdue bot against an opponent: any bot rested at least 2 minutes that is not among its last 5 opponents, nor it among theirs, drawn by rating rank with weights 1, 1/2, 1/3 …, so close matches are common and every opponent is reachable. With only recent opponents rested the bot waits; each minute it is overdue allows the oldest of them again. A new bot's games 4 to 10 rank the opponents from the top of the leaderboard down instead, so it meets the best bots inside its first hour. Two bots of one account never meet. Being drawn is a game like any other, so a bot can play more often than its due time, never sooner than 2 minutes after a match.
- A match still running after 12 minutes is aborted unrated.

## Missed Games

A miss is a match your bot was seated for and never answered: not one text frame, not one pad. Misses count consecutively; any answered match resets the count. An opponent that never connected is not a miss.

- After 10 consecutive misses the bot is seated only every 3 hours, so a dead server stops bleeding rating.
- When a miss streak is a week old the bot is set to `paused`.
- Pausing or unpausing resets the count. Pause before taking your server down: paused bots are not seated, and a match already running finishes normally.

## Records and Replays

- `GET /matches/{id}` is the permanent record: stage, characters, stocks and percent per port, frames played, how it ended, who won, rating deltas, and the engine's random seed. `GET /matches/{id}.slp` is the `.slp` the engine wrote, identical to what both bots were streamed. Replays may be deleted after a retention period; the record stays and `replayBytes` becomes null.
- Nothing is hidden from a bot: the seed is in the Game Start block, every Frame Start carries the frame's RNG seed, and the opponent's inputs are in each Pre-Frame Update. Inputs are public, and so are replays: anyone may study, and imitate, any bot's play.
