# Matchmaking

## Shared matchmaking

Use the injected `window.VortexMatchmaking` SDK to group signed-in Arcade players and get a roster. Your game provides signaling, connects the roster, and runs the match. Launch from `/play/<slug>/` with separate signed-in accounts to test the full handoff. Keep the game menu and supported guest modes available when the SDK or online services are unavailable.

### Choose the queue

Arcade fills the oldest compatible tickets first. Players are compatible when all of these fields match.

| Join field | Contract |
| --- | --- |
| Game slug | Arcade derives it from the launched game. Each game has its own queues. |
| `queue` | A lowercase slug of at most 48 characters, for example `duel` or `co-op`. Use one name per compatible mode. |
| `version` | A positive safe integer. Bump it when builds use incompatible multiplayer protocols or game rules. |
| `playerCount` | An integer from 2 to 64. Arcade assigns a roster when the queue has the requested number of compatible players. |
| `code` | Omit it or send an empty string for public play. Use 6–24 ASCII letters or digits for a private room. Arcade compares codes case-insensitively. Share a randomly generated code with invited players. |
| `metadata` | Optional JSON object of up to 1,024 UTF-8 bytes. It does not affect compatibility. Use it for public connection identifiers and validate values from other players. Keep credentials and personal data out of it. |

### Manage the matchmaking ticket

| SDK call | Use |
| --- | --- |
| `createTicket()` | Generates the lowercase version 4 UUID for a new search. |
| `join({ ticket, queue, version, playerCount, code?, metadata? })` | Joins the queue. Retry an uncertain join with the same ticket and options. |
| `poll(ticket)` | Checks the ticket and refreshes its heartbeat while waiting. Wait for `pollAfterMs` (currently 2 seconds) between calls. |
| `connection(ticket, outcome)` | Optionally records `'connected'` or `'failed'` for Arcade diagnostics. Report once for a matched ticket before it expires. |
| `leave(ticket)` | Cancels a search or releases the ticket after connecting. Send it before discarding the ticket. |
| `turn(ticket)` | Gets time-limited WebRTC relay credentials for an active ticket. See [WebRTC and TURN](https://www.vortexgame.win/developer/docs/turn/#webrtc-and-turn). |

- **`waiting`** includes `ticket`, `expiresAt`, and `pollAfterMs`. A ticket expires after roughly 30 seconds without a heartbeat. Poll with one loop and one request in flight. On resume from a backgrounded tab, check the ticket before offering to continue.
- **`matched`** includes `ticket`, `matchId`, `expiresAt`, your zero-based `seat`, and the ordered `players` array. Entries include `seat`, `username`, `metadata`, and `left`. Seat zero joined first. Use the two-minute handoff window to connect the roster. If a required player has left, offer a fresh search.
- **`closed`** includes `ticket`. A missing, expired, or cancelled ticket returns this state when polled. Create a new UUID for a new search. All `expiresAt` timestamps are Unix milliseconds.

Each account can have one active ticket per game. A join using a new ticket while another is active returns `409` with `error.ticket`. Offer to resume polling that ticket or cancel it before starting over. A `409` from reusing a ticket for different queue options can omit `error.ticket`. Keep the ticket only as long as the search or handoff needs it. Handle an explicit cancel immediately and let the server expiry cover abrupt tab closes.

### Connect a matched roster

This example hands a matched duel to a game-provided `connect` function and requests TURN during handoff. Have `connect` validate metadata, use `matchId` and the assigned seats in the game's signaling flow, honor cancellation, and resolve when the game's transport is ready.

```js
async function connectDuel({ peerId, code = '', signal, connect }) {
  const matchmaking = window.VortexMatchmaking;
  if (!matchmaking) throw new Error('Open this game from Arcade to play online.');
  signal.throwIfAborted();

  const ticket = matchmaking.createTicket();
  const leave = () => matchmaking.leave(ticket).catch(() => {});
  signal.addEventListener('abort', leave, { once: true });
  try {
    let match = await matchmaking.join({
      ticket, queue: 'duel', version: 1, playerCount: 2, code,
      metadata: { peerId },
    });
    while (match.state === 'waiting') {
      signal.throwIfAborted();
      await new Promise((resolve) => setTimeout(resolve, match.pollAfterMs));
      signal.throwIfAborted();
      match = await matchmaking.poll(ticket);
    }
    signal.throwIfAborted();
    if (match.state === 'closed') return null;

    try {
      if (match.players.some((player) => player.left)) {
        throw new Error('A player left the match.');
      }
      const { iceServers } = await matchmaking.turn(ticket);
      signal.throwIfAborted();
      const connection = await connect({ match, iceServers, signal });
      await matchmaking.connection(ticket, 'connected').catch(() => {});
      return connection;
    } catch (error) {
      if (!signal.aborted) await matchmaking.connection(ticket, 'failed').catch(() => {});
      throw error;
    }
  } finally {
    signal.removeEventListener('abort', leave);
    void leave();
  }
}
```

### Handle matchmaking errors

| Status | Game response |
| --- | --- |
| `400` | Validate the ticket format and join options before retrying. |
| `401` | Prompt the player to sign in through Arcade. |
| `403` | Surface the Arcade message. The player or game may be restricted from matchmaking. |
| `404` or `410` | Stop the search and show that the game is unavailable. |
| `409` | Offer to resume or cancel the existing search if `error.ticket` is present. |
| `503` or network failure | Show that matchmaking is temporarily unavailable. If retrying an uncertain join, reuse the ticket and back off. |

Behind the SDK, the join, poll, leave, and connection operations are JSON `POST` requests under `/api/games/{slug}/v1/matchmaking/`. The body matches the SDK join options for `join`, `{ ticket }` for `poll` and `leave`, and `{ ticket, outcome }` for `connection`. Use the SDK from a game. Arcade supplies the session and the correct origin.
