SDK guide

@velox/sdk is the game side of Velox: cloud saves, achievements, leaderboards, rooms for multiplayer, the pause and mute signals of the overlay, and locale and entitlement information. It is plain ES modules with no Node dependency, so it runs in any browser and in a bundler.

npm install @velox/sdk      # or: bun add @velox/sdk   (the @velox scope is set up in Quickstart, step 1)
import { createVelox } from "@velox/sdk";

const velox = createVelox();
const connected = await velox.ready();

With no bundler, velox init puts the whole SDK next to your game as one file, velox-sdk.js.

Lifecycle #

createVelox(options?) returns the client. It never throws, and every call after it is non-rejecting: a failure is a false, a null or a result object that says why.

await velox.ready()Handshake with the Velox player. Resolves true when the player answered, false when there is no player (or it did not answer within handshakeTimeoutMs, 4 s by default). Idempotent. The game works either way.
velox.connectedtrue once the player has answered.
velox.mode"host" when a Velox player embeds the game, "emulator" when nothing does.
velox.onConnectionChange(fn)Called when the connection comes up (also when the player answers after ready() gave up).
velox.lifecycle.gameplayStart() / gameplayStop()Tell the player when the game is in active play (the loading screen and overlay use it). Playtime for reviews and refunds is measured by the player while the game is open and does not depend on these calls.
velox.loading.progress(fraction)Optional. Tell the player how far your own loading is (0 to 1); the loading screen's bar follows it. The player's three real stages stay visible whether or not you call it, and a game that never calls it loses nothing (a byte percentage cannot be measured across origins, so the number is yours).
velox.lifecycle.onPause(fn) / onResume(fn) / onMute(fn)The overlay (Shift+Tab) pauses and mutes the game: stop your simulation and audio when it does.
velox.i18n.locale / velox.i18n.onLocaleChange(fn)The visitor's language, changing live.
velox.entitlements.tier / isOwned() / isDemo() / hasDlc(id) / onChange(fn)What this player owns: demo, owned, playtest, beta, family.
velox.openOverlay("store")Open the player's overlay on a tab, for example to let a demo player buy the game.
velox.dispose()Remove listeners.

How the player connects #

You do not write any connection code. A game at /play/<slug> runs in a cross-origin iframe. Its entry page is served by the CDN with a small script in front of yours that sets __VELOX_INIT__: the store's address, the game, the branch, the player's language. When createVelox() finds that and sees the page is framed, it:

  1. posts velox:ready to the embedding page, addressed to the store's origin only (never *);
  2. receives velox:init from the player (accepted only from that window and that origin): language, entitlement and the signed-in player;
  3. from then on asks the player to perform cloud calls for it (velox:rpc-request), and the player answers (velox:rpc-response).

The player performs those calls with the player's own session and always for your game's slug; the game never holds the account's token and cannot name another game. A closed list of calls is allowed: saves, achievements, leaderboards, a delegated token for realtime rooms, a signed player ticket for your declared servers and, after the player agreed, a Codai ID ticket. The player refuses any other call.

Tickets. await velox.auth.getTicket("https://game.example.com") asks the player, which asks the store, for a 5-minute ES256 ticket made out to one of the servers your build declares in velox.json (servers). Your server verifies it against the store's public keys (/.well-known/jwks.json) and learns the player's per-game id, name (their Codai ID username) and game, nothing else. It is null for a guest, for an origin you did not declare, when this store has no signing key, and in the local emulator. The whole story, with a verification example, is in Game servers.

Codai ID tickets. await velox.auth.getCodaiIdTicket("https://game.example.com") is for a game that has its own Codai ID account system and declares codaiId in velox.json (codaiId). The first time, the player page (never the game) asks the player whether the game may use their Codai ID account, and the call waits for the answer; with a yes it resolves a 5-minute signed ticket for that declared server whose sub is the player's Codai ID user id, otherwise null (a guest, "Not now", a consent the player withdrew, an origin you did not declare, a build without codaiId, no signing key, and in the local emulator, whose ticket is an unsigned toy). It never rejects. Details, verification and account mapping: Continue with Codai ID.

What the browser lets the game reach. The CDN serves your build with a Content-Security-Policy: the game's own origin, Velox's endpoints and the servers you declared, nothing else (see Game servers).

Outside the player (a local server, velox dev, your tests) there is nobody to talk to: nothing is posted, ready() resolves false, and the SDK runs its local emulator: the same API, held in memory, with simulated sample data (two friends, a small product catalog). Nothing is stored on a server and nothing survives a reload. createVelox({ connect: "off" }) forces the emulator even inside a player.

Next to a real player the emulator's inventions switch off: velox.social.friends() is empty, velox.purchases.available is false, buy() fails with unavailable and a game cannot unlock itself. To sell something from inside the game, open the store tab (velox.openOverlay("store")) and listen for velox.entitlements.onChange. velox.auth.getTicket(audience) next to a player is a real signed ticket for a declared server (or null); in the emulator it is an unsigned toy that no server can verify, on purpose.

Who is playing #

Cloud saves, achievements and leaderboards belong to a signed-in account. A visitor who is not signed in has none of them: velox.cloud.slots.available, velox.social.achievements.available and velox.social.leaderboards.available are false, calls answer unavailable, and nothing is sent. Keep a local fallback (for example localStorage) for those players, and show a hint to sign in. velox.auth.user() is the signed-in player, or null. Its id is a per-game pseudonym: the same every time for one player in your game, different in every other game, and impossible to turn back into the player's account id. Use it as the key of your own data about the player; do not expect to find the same player in another game. name is the player's Codai ID username (or Player when Codai ID has none for the account yet); it is changed at Codai ID, not in the store, and follows a rename within minutes. Signing in happens on the store page; velox.auth.promptLogin() resolves false next to a player for a visitor who is not signed in.

Saves #

const saved = await velox.cloud.slots.load("autosave");           // an envelope, or null
const level = saved ? JSON.parse(saved.payload).level : 1;

const result = await velox.cloud.slots.save("autosave", { level: level + 1 }, { summary: "Level 4", playtimeMs: 123456 });
if (!result.ok) console.log(result.reason);                        // "conflict" | "unavailable" | "invalid"

A save is an envelope:

{
  "meta": {
    "slot": "autosave",
    "version": 3,
    "etag": "v3-1b2c3d4e5f60",
    "updatedAt": 1790000000000,
    "playtimeMs": 123456,
    "byteLength": 14,
    "sha256": "…64 hex characters…",
    "summary": "Level 4",
    "sourceTier": "owned"
  },
  "payload": "{\"level\":4}",
  "compressed": "none"
}

payload is the string you saved (objects are saved as JSON). The server numbers every write (version), derives the etag, and stamps updatedAt.

  • Limits. A slot name is 1 to 64 characters of letters, digits, ., _ and -. A save is at most 1 MiB, an account has at most 64 slots per game. Saves survive refunds.
  • Conflicts. save(slot, data, { ifVersion: n }) writes only if the stored version is still n. On a mismatch you get { ok: false, reason: "conflict", conflict: { slot, local, remote } }, or choose a conflictStrategy: "newest-wins", "custom-merge" (with merge(conflict)), or "overlay-prompt" (the default: velox.cloud.slots.onConflict(fn) fires and resolveConflict(slot, "local" | "remote") decides). Without ifVersion a save overwrites.
  • Other calls. velox.cloud.slots.list(), delete(slot), and a small key-value store, velox.cloud.kv.get/set/remove, kept in one reserved slot (_velox-kv) that the slot list hides.

Achievements #

Declare them in velox.json (achievements); a push makes the store's list equal to yours.

await velox.social.achievements.unlock("first-win");               // true; unlocking twice is fine
await velox.social.achievements.isUnlocked("first-win");           // true | false | null (unavailable)
await velox.social.achievements.setStat("coins", 120);             // unlocks achievements whose statProgress target is reached

Unlocks are permanent on the server: clear() resolves false next to a player. Stats are kept in the page; only the unlock a stat threshold causes is stored. Once the game has a list of achievements the server refuses ids that are not on it.

Leaderboards #

Declare each board in velox.json (leaderboards), including its leaderboards[].plausibilityCeiling.

await velox.social.leaderboards.submitScore("score", 4200);        // true | false; scores are whole numbers
const top = await velox.social.leaderboards.top("score", { limit: 10, period: "week" });
const me = await velox.social.leaderboards.mine("score");

An entry is { rank, name, score, at, me }. A board keeps each player's best score (highest, or lowest for sortOrder: "asc"). A score above the ceiling or below 0 is refused (submitScore resolves false), as is a score for a board that is not declared. top, around (the entries around the player, empty if the player has no score) and mine accept period (all, day, week); the store page shows the top ten.

Multiplayer #

velox.multiplayer talks to the store's realtime service when the game is hosted, and to an in-page emulator otherwise (velox.multiplayer.backend says which: "network" or "local").

const room = await velox.multiplayer.createRoom({ type: "match", maxSeats: 4 });   // or quickMatch() / joinRoom(code)
room?.onMessage((data, meta) => handle(data, meta.from));
room?.send({ x: 10, y: 4 });                                                         // to every other peer

Rooms have seats, a host, a shared key-value state (setState), reconnection with message replay, matchmaking queues (enqueue, onMatchFound) and WebRTC peer-to-peer lobbies with a relay fallback (createP2PLobby). Every call is non-rejecting and answers null or false on failure.

Who joins. A signed-in player joins rooms as themselves, with their real name (the Codai ID username): the player hands the game a delegated token that is valid for this game only and for minutes, and never the account's own session token (it also opens saves and purchases). A guest joins as a guest. You do not pass any token yourself.

The local emulator #

velox.emulator is for tests and local development: switch the entitlement tier (setEntitlementTier("demo")), force the next purchase outcome, trigger a save conflict (triggerCloudConflict), log in as a simulated player (loginAs), toggle the overlay, and read what the game sent to the player (sentHostMessages()). It exists in every mode, but only changes what the emulator itself does.

Telemetry #

velox.telemetry records events, frame-time percentiles and fingerprinted errors in the page (events(), perfStats()). It sends them only when you give createVelox a fetchImpl; this store does not collect them for you.