# ZokoGames developer documentation (full text)

> All pages of the English developer documentation in one file. The index is at https://docs.zokogames.com/llms.txt.

---

Source: https://docs.zokogames.com/getting-started/introduction

# Introduction

ZokoGames is a web game portal. You build an HTML5 game (directly in JavaScript or with an engine that exports to the web), upload it in the developer console, and we host it, review it and put it in front of players. This documentation covers everything between "I have a build" and "my game earns revenue".

## The publishing path

Every game follows the same stages. The status is always visible in the developer console.

1. **Draft and submit.** Create a studio (a short form at `/developer/onboarding` that asks for a studio name, a studio address, optionally your own name and your acceptance of the terms; sign-up is open to every account unless the portal team has switched it to invitation only, see the [walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough)), create a game, upload the build, fill in the title, descriptions, controls, orientation and category, and add the three cover images. Until you submit, the game stays a private draft that only your team can open. The console shows a checklist of what is still missing. See the [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
2. **Review.** (The console shows **Submitted**, then **In review**.) A reviewer plays the build against the [requirements](https://docs.zokogames.com/requirements/overview). You get the outcome by email and in the console: approved, changes requested or rejected. Changes requested and rejections carry reasons you can act on. Fix them, upload a new build and submit again.
3. **Basic launch.** An approved game goes live with **ads switched off**, so it earns no revenue yet. The point of this stage is measurement: we watch average play time, day-1 retention, conversion and click-through rate. A basic launch lasts at least 7 days and 500 plays, and at most 21 days. See [basic launch metrics](https://docs.zokogames.com/guides/basic-launch-metrics). These numbers are defaults: the portal team may adjust the window, and the console shows the values that apply to your game.
4. **Full QA and Full Launch.** A game whose numbers and quality are good enough is moved to Full QA, a second review focused on the full SDK integration (ads, gameplay events, and the data, user and leaderboard modules where they apply). When it passes, the game is in **full launch**: ads run and your revenue share accrues, see [revenue share](https://docs.zokogames.com/business/revenue-share).

> [!NOTE]
> A person makes the promotion decision. The portal scores your basic-launch numbers and gives the reviewer a recommendation, but meeting every target does not guarantee promotion, and missing one does not always rule it out.

## What you need to build

- A game that runs in a modern desktop browser and, if you tick mobile, on phones and tablets.
- The ZokoGames SDK, loaded from `https://sdk.zokogames.com/zokogames-sdk-v1.js`. The upload does not require it, but basic launch measures plays and play time from its `gameplayStart` call, so add `init` and `gameplayStart` (the quick start shows how); full launch requires the full integration.
- English text. Other languages are welcome on top of English.

## Where to go next

Follow these pages in order to go from nothing to a game that pays. The first page takes you all the way to a submitted game; the next three are the details behind its steps, and each is worth reading before you press **Submit for review**:

1. [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start)
2. [Testing with local mode and the Preview tool](https://docs.zokogames.com/getting-started/local-testing)
3. [Testing checklist before you submit](https://docs.zokogames.com/getting-started/testing-checklist)
4. [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough)
5. [Launch stages and KPIs](https://docs.zokogames.com/getting-started/launch-stages)
6. [Updating a live game](https://docs.zokogames.com/getting-started/updating-a-game)
7. [Payouts](https://docs.zokogames.com/business/payouts)

Want a complete game to read first? [Build a minimal game in 15 minutes](https://docs.zokogames.com/getting-started/first-game) and the [one-file example](https://docs.zokogames.com/getting-started/one-file-example) are two you can copy.

Running a studio with several people or many games? Under Guides, the page Team, roles and studios covers roles, working in several studios and the search and filters of the Games page, and the section Upload a build from CI of the developer API page covers automated uploads.

Reference pages you will need along the way:

- [Glossary](https://docs.zokogames.com/getting-started/glossary) and [FAQ](https://docs.zokogames.com/business/faq): words and quick answers.
- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting): symptoms, causes and fixes.
- [For AI coding agents](https://docs.zokogames.com/getting-started/for-ai-agents): fetch the docs as Markdown and integrate without a human in the loop.
- [Requirements checklist](https://docs.zokogames.com/requirements/checklist): everything reviewers check, on one page.
- [SDK reference](https://docs.zokogames.com/sdk/introduction): every module and method.
- [Analytics and metrics reference](https://docs.zokogames.com/guides/analytics-metrics): what every number in the console means.
- [Build validation reference](https://docs.zokogames.com/requirements/build-validation): every upload limit and finding code.
- [Player features](https://docs.zokogames.com/guides/player-features), [notifications](https://docs.zokogames.com/guides/notifications) and [webhooks](https://docs.zokogames.com/guides/webhooks): what players see around your game and what your studio is told.
- [Artwork experiments](https://docs.zokogames.com/guides/artwork-experiments) and [revenue share](https://docs.zokogames.com/business/revenue-share): growing a launched game and how it earns.

**Using an AI coding tool?** Give it the documentation as plain Markdown instead of the web pages: `https://docs.zokogames.com/llms.txt` is an index of every page with a one-line description and a link to its Markdown, `https://docs.zokogames.com/llms-full.txt` is all English pages in one file, and adding `.md` to the address of any page, for example `https://docs.zokogames.com/sdk/introduction.md`, returns that page alone. These files are English only.

---

Source: https://docs.zokogames.com/getting-started/quick-start

# Your first game live in 30 minutes

This is the one path to follow. You finish with a build uploaded, validated and submitted for review. Every step says what you should see when it worked. New words are explained in the [glossary](https://docs.zokogames.com/getting-started/glossary). Which engine you use only changes step 2; the rest is the same.

| Step | Time | You end with |
| --- | --- | --- |
| 0. Get access | 3 min | A studio and an empty developer console |
| 1. Pick a starting point | 1 min | A folder with a game in it |
| 2. Add the SDK and three calls | 5 min | A game that talks to the portal |
| 3. Run it locally | 3 min | Console output proving it works |
| 4. Try it in the Preview tool | 3 min | A ticked requirements checklist |
| 5. Zip it | 2 min | One `.zip` with `index.html` at its root |
| 6. Upload and read the report | 5 min | A passing validation report |
| 7. Fill in the listing and submit | 8 min | A game in review |

## 0. Get access (3 minutes)

1. Sign in or create a player account at [zokogames.com](https://www.zokogames.com/). A developer studio hangs off a normal account. A new account must confirm its email address first: open the link in the mail within 60 minutes (look in spam; **Resend** sends a new one, and a mistyped address means signing up again with the right one). Forgotten password: **Forgot your password?** on the sign-in page mails a link that works once for 60 minutes, and resetting signs you out on every other device. Signing in on the developer host and on zokogames.com are separate sessions of the same account.
2. Open [`/developer/onboarding`](https://developer.zokogames.com/onboarding) and create your studio. The form asks for a **Studio name** (it must differ from every other studio's name, also in case, accents and spacing; you are told as you type), an optional **Your name** (the username teammates and reviewers see; a name is generated if you leave it empty), a **Studio address** (the short name in your studio's page URL, lowercase letters, numbers and hyphens; it is checked as you type and cannot be changed later) and your acceptance of the [developer terms](https://docs.zokogames.com/business/developer-terms). It does not ask for payout details: those can wait until your first statement.
3. Studio sign-up is open to every account unless the portal team has switched it to invitation only. **If the page shows "Studio sign-up is by invitation at the moment" instead of the form,** open the link in your invitation email, or press **Apply to publish** (it opens [`/developers#apply`](https://www.zokogames.com/developers#apply)) and the team replies by email. A link that has expired or was used up shows "Your invitation is no longer valid" instead: apply, or ask the team for a new link. You cannot create a studio before that.

When the studio is created, the form shrinks to a summary and the same page offers the next step, **Create your first game**: a **Game name**, a **Game address** (the game's page will be `/game/<address>`; it is filled in from the name and, like the **URL slug** in step 6, it is locked once a build is uploaded or the game is submitted) and a required **Category** (the closest fit; you can change it later). Press **Create game** and you land in the game's **Edit and submit** wizard with an empty private draft, ready for step 6. If you choose **Go to the console** instead, you see the **developer console** with the **Getting started** checklist, whose first open step is **Create your first game** (**Submit a game** does the same). Once a game exists and has no build yet, the next step is shown as a card, "Next: upload your first build", with a place to drop your zip (it goes to that game), the size limits and links to **Quick start** (this page), **Starter kits** and the **Preview tool**; it goes away once the first build is uploaded. Under the game steps the checklist lists the studio's own: **Complete the studio profile** (a contact person; owners and admins), **Set up payouts** (owners only; it does not hold up submitting or going live, only your first payout) and the optional **Invite your team**; a teammate with the member role sees only the game steps. A five-stop tour of the console opens by itself on your first visit: **Skip tour** closes it and **Take the tour**, at the bottom of the checklist, opens it again. You can do steps 1 to 5 without a studio, so if sign-up is by invitation, apply early and keep going.

## 1. Pick a starting point (1 minute)

| You have | Do this |
| --- | --- |
| A finished plain JavaScript game | Keep it. Go to step 2 and add the tag and the calls to your own `index.html`. |
| A finished Phaser game | Keep it. Add the tag and calls from step 2, or copy the plugin from the [Phaser page](https://docs.zokogames.com/engines/phaser). |
| Nothing yet | Download a [starter kit](https://docs.zokogames.com/getting-started/starter-kits): `html5-minimal` (one file, no build step), `html5-vite-ts` (TypeScript), `phaser`, `playcanvas` or `gdevelop`. Each is a working game already wired to the SDK, so you can skip to step 3. |
| A Unity, Godot, Construct 3, GameMaker, Cocos or Defold game | Do the engine's install on its [engine page](https://docs.zokogames.com/engines/overview), then continue at step 3. The engine pages contain the same three calls in the engine's own language. |

You should see a folder whose top level has an `index.html` (or, for a bundler, a `dist` folder after the build).

## 2. Add the SDK and three calls (5 minutes)

Put the script tag in the `<head>` of `index.html`, before your own code:

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
```

Using a bundler (Vite, webpack)? Keep this script tag in `index.html` and read `window.ZokoGames?.SDK` in your code. For types, download `https://sdk.zokogames.com/1.7.0/index.d.ts`, or start from the `html5-vite-ts` starter kit, which already has them.

Then make the **minimum three calls**. `init` first, `gameplayStart` when the player's input becomes live, `gameplayStop` when a round ends, the game pauses or a menu opens:

```js
const SDK = window.ZokoGames && window.ZokoGames.SDK; // undefined if the script was blocked

// Wrap every SDK call: if the SDK is missing or disabled, the game must still run.
async function zoko(call) {
  try { return await call(); }
  catch (e) { console.warn("SDK:", e.code || e.message); }
}

async function boot() {
  await zoko(() => SDK.init());                      // 1. always first, never rejects
  await zoko(() => SDK.game.loadingStop());          //    recommended: the first screen is ready
  // ... show your menu ...
}

function startRound() { zoko(() => SDK.game.gameplayStart()); } // 2. input is live now
function endRound()   { zoko(() => SDK.game.gameplayStop()); }  // 3. round over, menu showing

boot();
```

`startRound` and `endRound` are placeholders: call them from your own code at the moment a round begins and ends (the sample never calls them itself, so pasted as it is, the checklist in step 4 shows only `init` and `loadingStop`).

Why these three: `init` is required before any other call; `gameplayStart` is the signal that measures real playtime and is the one call [basic launch](https://docs.zokogames.com/getting-started/launch-stages) needs; `gameplayStop` closes the round, and full launch needs the pair. Add `loadingStart()` at the beginning of loading and `loadingStop()` when the first screen is playable (the portal separates load time from play time with them). Between the two you can report progress with `SDK.game.loadingProgress(0..100)`; it is coalesced to one message per 100 ms. Everything else (ads, saves, leaderboards) can wait until the game is live; the [complete example](#a-complete-example) at the end of this page shows them. A complete game in one file, with a rewarded ad and a save, is [Copy-paste example: one index.html](https://docs.zokogames.com/getting-started/one-file-example).

You should see no change on screen. The effect shows in step 3.

## 3. Run it locally (3 minutes)

The SDK runs an in-page mock on `localhost`, so no portal is needed. Serve the folder over HTTP (`file://` does not count as local):

```bash
# plain JavaScript or html5-minimal kit
cd your-game && npx http-server . -p 8080 -c-1
# open http://localhost:8080/?sdk_debug=true

# html5-vite-ts or phaser kit (needs Node 20.19 or later, or 22.12 or later)
npm install && npm run dev
# open http://localhost:5173/?sdk_debug=true
```

`-c-1` switches off the server's cache, so a reload always shows your latest edit. No Node.js? `python3 -m http.server 8080` inside the game folder serves it the same way. Not on `localhost` (for example a LAN address or a tunnel)? Add `?useLocalSdk=true` to the URL instead. The rules are in [environments](https://docs.zokogames.com/getting-started/environments).

You should see in the browser console, first, one line `[ZokoGames SDK] Local mode: the portal is simulated in this page and nothing is sent over the network.` (it appears even without `?sdk_debug=true`), then lines such as `[ZokoGames SDK] call game.loadingStop {}` followed by `result ...`, then `call game.gameplayStart` and `call game.gameplayStop` as you play. `init` itself prints no `call` line, but the calls the SDK makes on its own while it starts are logged: every game shows `call room.snapshot {}` and its `result` (the SDK checks whether the page already holds a multiplayer room). Typing `ZokoGames.SDK.environment` in the console prints `"local"`. If it prints `"disabled"`, the script did not load or the page is neither on `localhost` nor carrying `?useLocalSdk=true` (the console then has one line starting `[ZokoGames SDK] Disabled:` that names the reason); see [troubleshooting](https://docs.zokogames.com/guides/troubleshooting#sdk-and-environment).

## 4. Try it in the Preview tool (3 minutes)

Open [`/preview`](https://www.zokogames.com/preview), type your local address (for example `http://localhost:8080/`) and press **Load game**. No account and no upload: the tool frames your game inside the real portal frame. Play a round.

You should see the requirements checklist tick **SDK initialised (init called)**, **loadingStop called** (if you called it), **gameplayStart called** and **gameplayStop called**, and the event log list every call. Items for ads, banners, data and `happytime` stay grey until you add those calls; they are not needed for a first submission. Fix anything in the log that shows an error before you move on. More in [testing](https://docs.zokogames.com/getting-started/local-testing).

## 5. Zip it (2 minutes)

Zip the **contents** of the folder so `index.html` is at the root of the archive (one top-level folder is also accepted). Keep every path relative.

| Project | Command | Output |
| --- | --- | --- |
| Plain files or `html5-minimal` | `cd your-game && zip -r ../my-game.zip .` | `../my-game.zip` |
| `html5-vite-ts` kit | `npm run package` | `zokogames-html5-vite-ts.zip` in the kit folder |
| `phaser` kit | `npm run package` | `zokogames-phaser-starter.zip` in the kit folder |
| Windows 10 or 11 | In the folder: `tar -a -c -f ..\my-game.zip *` (or select the files inside the folder in File Explorer and choose **Compress to ZIP file**) | `..\my-game.zip` |
| macOS Finder | Select the files inside the folder, then choose **Compress** (compressing the folder itself also works) | `Archive.zip`; one top-level folder is accepted and `__MACOSX` entries are ignored |
| Engine export | Zip the export folder; see the engine page | |

The kit script typechecks, builds, refuses a build with absolute paths and prints `Wrote ...zip: N files, X MB unpacked`. Check the result with `unzip -l my-game.zip | head`: `index.html` must appear without a folder in front of it (or behind exactly one folder).

You should see a zip well under the limits: at most 1,500 files and 250 MB unpacked, an initial download of at most 50 MB (aim for 20 MB or less for mobile).

## 6. Upload and read the report (5 minutes)

1. If you created your first game on the onboarding page, its wizard is already open (or open the game from the [developer console](https://developer.zokogames.com/)). Otherwise choose **Submit a game**, enter the **Game name**, check the **URL slug** (it becomes the game's address and is locked once a build is uploaded or the game is submitted), pick a **Category** and press **Create draft and continue**. The wizard opens with five steps in this order: **Basics**, **Technical**, **Build**, **Artwork** and **Review and submit**. It autosaves. Open **Build** in the list of steps.
2. Drop the zip on "Drop your game zip here" or press **Choose a file**. Large files upload in resumable parts.
3. Read the **validation report** (**Report** on the build). Each finding has a code and, for errors, the offending path; the [build validation reference](https://docs.zokogames.com/requirements/build-validation) explains every code.

A large build (hundreds of files or tens of megabytes) can take a minute or two to check and publish after the upload reaches 100%. The page shows "Checking the build..." with the elapsed time and keeps going, so leave it open; if the connection drops it keeps watching the server, and the build appears in the version list with its report when it is ready. You never need to upload it again.

You should see "Build v1 passed validation and was published" and the build marked **Active** (before launch every new valid build becomes active by itself), with your engine detected and the SDK script found. A warning (for example, a download above 20 MB) does not block you. An error does: fix it and upload the zip again. Press **Preview** on the build to play this exact build in the portal frame with ads switched on, on the **Preview and QA** tab.

## 7. Fill in the listing and submit (8 minutes)

Have the three cover images ready before you start this step (make them while the zip uploads): making artwork is the one task here that can take longer than the time shown. Complete the remaining steps. **Basics**: short description, description, controls, tags and the two required confirmations (suitable for players aged 12 and over, all text available in English). **Technical**: engine, orientation, devices, hosting and the **Audience and distribution** card, where you pick the **Age rating** (12+ or lower) and the **Languages in the game** (English included). **Artwork**: three covers at exact sizes; see [covers](https://docs.zokogames.com/requirements/covers). The **Review and submit** step lists what is still missing; when nothing is left, press **Submit for review** and confirm with **Submit**. The [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) explains each field. Before you press **Submit for review**, tick through the [testing checklist](https://docs.zokogames.com/getting-started/testing-checklist) and the [launch checklist](https://docs.zokogames.com/guides/launch-checklist): a game sent back for something on them costs you a review round.

You should see the game's status change to **Submitted**, then to **In review** once a reviewer starts, and later an email and a console notification with the decision. An approved game starts [basic launch](https://docs.zokogames.com/getting-started/launch-stages): live for players, ads off, numbers being measured.

## If something goes wrong

- Nothing appears in the console log or `environment` is `"disabled"`: [troubleshooting](https://docs.zokogames.com/guides/troubleshooting).
- The validator rejects the zip: [build validation](https://docs.zokogames.com/requirements/build-validation).
- The game is sent back by a reviewer: [requirements checklist](https://docs.zokogames.com/requirements/checklist) and the reasons listed in the console.
- Words you do not know: [glossary](https://docs.zokogames.com/getting-started/glossary) and the [FAQ](https://docs.zokogames.com/business/faq).

## A complete example

Want to see ads, saves and `happytime` too? [Build a minimal game in 15 minutes](https://docs.zokogames.com/getting-started/first-game) is a complete, runnable game in two files. It adds a midgame ad, a rewarded ad, a cloud save, `happytime` and the portal's mute setting to the three calls above, passes upload validation with no warnings, and turns every required item of the Preview checklist green.

## Next steps

- [Launch stages and KPIs](https://docs.zokogames.com/getting-started/launch-stages): what happens after you submit, and what to prepare while you wait. Ads, saves and leaderboards come later; start with the [advertisement rules](https://docs.zokogames.com/requirements/advertisements) when you add them.

---

Source: https://docs.zokogames.com/getting-started/first-game

# Build a minimal game in 15 minutes

This page gives you a complete, small game in two files, `index.html` and `game.js`. It uses plain JavaScript with no build step. You can upload it as it is: the validator accepts it with no errors or warnings, and every required item of the Preview checklist turns green. Use it to learn the SDK, or copy the parts you need into your own game.

Before you start you need a browser and a way to serve a folder over HTTP (the commands below use Node.js with `npx`). You only need a studio for step 5; [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start) shows how to get one. Words such as build and environment are explained in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## What the game does

"Target Tap": the player taps a circle as often as possible in 15 seconds. Each part of the game uses one SDK feature:

| In the game | SDK call | Checklist line it turns green |
| --- | --- | --- |
| Page opens | `SDK.init()` | SDK initialised |
| Menu is ready | `SDK.game.loadingStart()`, `SDK.game.loadingStop()` | loadingStop called when the game is ready |
| Player presses **Play** | `SDK.game.gameplayStart()` | gameplayStart called; First gameplayStart within 20 seconds |
| Round ends, or the player clicks outside the game | `SDK.game.gameplayStop()` | gameplayStop called on pause, menu and game over |
| Break after each round | `SDK.ad.requestAd("midgame", ...)` | A midgame ad was requested; gameplayStop before each ad request |
| Player presses **Play** again after the ad | `SDK.game.gameplayStart()` | Play resumed after an ad finished |
| **Watch an ad** button | `SDK.ad.requestAd("rewarded", ...)` | A rewarded ad was requested |
| New best score | `SDK.data.setItem()`, `SDK.game.happytime()` | Data module used for saves; happytime called at a great moment |
| Portal mute button | `SDK.game.settings`, `SDK.game.addSettingsChangeListener()` | none; reviewers check it |

The lines are worded as on the **Preview and QA** tab of your game in the console. The public Preview tool uses shorter words for some of them (**loadingStop called**, **Midgame ad requested**, **Data module used**) and has no lines for the ad-break rules; the [testing checklist](https://docs.zokogames.com/getting-started/testing-checklist) lists both.

## 1. Create index.html

Create a folder named `target-tap` and save this file in it as `index.html`:

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Target Tap</title>
  <!-- The SDK first, then your own code. -->
  <script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
  <style>
    html, body { margin: 0; height: 100%; overflow: hidden; background: #14161f; color: #fff; font: 18px sans-serif; }
    #game { position: relative; height: 100%; touch-action: none; user-select: none; }
    #hud { padding: 12px; }
    #target { position: absolute; width: 64px; height: 64px; border: 0; border-radius: 50%; background: #ffc531; }
    #panel { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; }
    [hidden] { display: none !important; }
    button { font: inherit; padding: 10px 20px; }
  </style>
</head>
<body>
  <div id="game">
    <div id="hud">Score <b id="score">0</b> | Time <b id="time">15</b> | Best <b id="best">0</b></div>
    <button id="target" aria-label="Target" hidden></button>
    <div id="panel">
      <h1>Target Tap</h1>
      <p>Tap the circle as often as you can in 15 seconds.</p>
      <button id="play" disabled>Play</button>
      <button id="reward" hidden>Watch an ad: +5 seconds next round</button>
      <p id="msg"></p>
    </div>
  </div>
  <script src="game.js"></script>
</body>
</html>
```

The SDK script is loaded in the `<head>`, before `game.js`, and every path is relative. The **Play** button starts disabled and is enabled when the SDK is ready.

## 2. Create game.js

Save this file next to `index.html` as `game.js`:

```js
// Target Tap: hit the circle as often as you can in 15 seconds.
const SDK = window.ZokoGames && window.ZokoGames.SDK; // undefined if the script was blocked
const $ = (id) => document.getElementById(id);
let ready = false, playing = false, running = false, muted = false, audio = null;
let score = 0, best = 0, timeLeft = 0, bonus = 0, timer = 0;

// Every SDK call goes through here, so the game still runs when the SDK is missing,
// disabled or a call fails. SDK errors are plain { code, message } objects.
async function sdk(call) {
  if (!ready) return undefined;
  try {
    return await call();
  } catch (e) {
    console.warn("SDK:", e.code, e.message);
    return undefined;
  }
}

async function boot() {
  if (SDK) {
    await SDK.init(); // never rejects
    ready = SDK.environment !== "disabled"; // "zokogames", "local" or "disabled"
  }
  await sdk(() => SDK.game.loadingStart());
  best = Number((await sdk(() => SDK.data.getItem("best"))) || 0);
  if (ready) {
    muted = SDK.game.settings.muteAudio; // the portal's mute button
    SDK.game.addSettingsChangeListener((settings) => { muted = settings.muteAudio; });
  }
  $("best").textContent = best;
  $("reward").hidden = !ready;
  await sdk(() => SDK.game.loadingStop()); // the menu is ready
  $("play").disabled = false;
}

function beep() {
  if (muted) return;
  audio = audio || new AudioContext(); // created inside a tap, as browsers require
  const osc = audio.createOscillator();
  osc.connect(audio.destination);
  osc.start();
  osc.stop(audio.currentTime + 0.05);
}

// Starts or stops the round clock and tells the portal. Safe to call twice.
function setRunning(on) {
  if (on === running) return undefined;
  running = on;
  if (on) timer = setInterval(tick, 1000);
  else clearInterval(timer);
  return sdk(() => (on ? SDK.game.gameplayStart() : SDK.game.gameplayStop()));
}

function startRound() {
  score = 0;
  timeLeft = 15 + bonus;
  bonus = 0;
  playing = true;
  $("panel").hidden = true;
  $("target").hidden = false;
  moveTarget();
  render();
  setRunning(true); // input is live: gameplayStart
}

function tick() {
  timeLeft -= 1;
  render();
  if (timeLeft <= 0) endRound();
}

async function endRound() {
  playing = false;
  await setRunning(false); // gameplayStop, always before an ad
  $("target").hidden = true;
  $("panel").hidden = false;
  if (score > best) {
    best = score;
    $("best").textContent = best;
    await sdk(() => SDK.data.setItem("best", String(best))); // synchronous; throws on error
    await sdk(() => SDK.game.happytime());
  }
  await showAd("midgame"); // a natural break; the portal decides whether an ad plays
}

// Resolves true only when the ad played to the end.
async function showAd(type) {
  let finished = false;
  $("play").disabled = true;
  await sdk(() => SDK.ad.requestAd(type, {
    adStarted: () => audio && audio.suspend(), // silent while the ad plays
    adFinished: () => { finished = true; },
    adError: (e) => console.info("No ad:", e.code), // adsDisabled before full launch
  }));
  if (audio) audio.resume(); // after adFinished and after adError
  $("play").disabled = false;
  return finished;
}

$("reward").addEventListener("click", async () => {
  const earned = await showAd("rewarded");
  if (earned) bonus = 5; // the reward only after a finished ad
  $("msg").textContent = earned ? "+5 seconds next round" : "No ad right now";
});

$("target").addEventListener("pointerdown", (event) => {
  event.preventDefault();
  if (!running) return;
  score += 1;
  beep();
  moveTarget();
  render();
});

// Clicking outside the game or leaving the tab pauses the round; it continues on return.
window.addEventListener("blur", () => { if (playing) setRunning(false); });
window.addEventListener("focus", () => { if (playing) setRunning(true); });

function moveTarget() {
  const box = $("game").getBoundingClientRect();
  $("target").style.left = `${Math.random() * (box.width - 64)}px`;
  $("target").style.top = `${48 + Math.random() * (box.height - 112)}px`;
}

function render() {
  $("score").textContent = score;
  $("time").textContent = timeLeft;
}

$("play").addEventListener("click", startRound);
boot();
```

## 3. Run it locally

```bash
cd target-tap && npx http-server . -p 8080
# open http://localhost:8080/?sdk_debug=true
```

On `localhost` the SDK runs in local mode: it answers every call itself, with no portal involved. You should see `[ZokoGames SDK]` lines in the browser console for `game.loadingStart`, `game.loadingStop`, and then `game.gameplayStart` when you press **Play**. After 15 seconds a three-second placeholder labelled `Local ad (midgame)` covers the page. A second round within three minutes gets no midgame ad (`adCooldown` in the console), which is expected. See [testing](https://docs.zokogames.com/getting-started/local-testing) for the switches that force other answers.

## 4. Turn the Preview checklist green

1. Open the [Preview tool](https://www.zokogames.com/preview), type `http://localhost:8080/` and press **Load game**.
2. Within 20 seconds, press **Play** and tap the circle until the round ends.
3. Let the placeholder ad finish.
4. Press **Watch an ad: +5 seconds next round** and let that ad finish too.
5. Press **Play** again.

You should see every item of the **Requirements checklist** marked done except **Banner requested**; this game has no banner, and banners are optional. Once the game is uploaded (step 5), the same play-through on the game's **Preview and QA** tab in the console shows every required item as **Passing**: **SDK initialised**, **gameplayStart called**, **First gameplayStart within 20 seconds**, **gameplayStop called on pause, menu and game over**, **A midgame ad was requested**, **gameplayStop before each ad request** and **Play resumed after an ad finished**. The [testing checklist](https://docs.zokogames.com/getting-started/testing-checklist) explains every item.

## 5. Zip and upload

```bash
cd target-tap && zip ../target-tap.zip index.html game.js
unzip -l ../target-tap.zip
```

Both files must be at the root of the zip. Upload `target-tap.zip` on the **Build** step of a new game, as described in [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start). You should see the build pass validation with no errors and no warnings, with the SDK script found and an init call detected.

## How the code keeps the rules

- **The game runs without the SDK.** `sdk()` skips every call when the script was blocked or the environment is `"disabled"`, and catches every failure. `init()` itself never rejects.
- **Play time is measured correctly.** `gameplayStart` is sent when **Play** is pressed, not at page load. `gameplayStop` is sent when the round ends and when the player clicks outside the game or switches tab, so the round pauses there too.
- **Ads only at a break.** The midgame ad is requested after `gameplayStop`, at the end of a round. Play resumes only when the player presses **Play**, so `gameplayStart` follows every ad. The portal decides whether an ad really plays (cooldowns, ad blockers, ad-free members); every outcome continues the game.
- **Rewards only after a finished ad.** `bonus` is granted only when `adFinished` ran. On `adError` the player sees "No ad right now" and keeps playing.
- **Sound obeys the player.** No sound plays before the first tap, the portal's mute setting silences the game at start and whenever it changes, and the audio is suspended while an ad plays. See [audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads).
- **The save is small.** One short string under one key, far below the 1,048,576-byte limit. `getItem` and `setItem` are synchronous and throw on error, which `sdk()` catches.
- **It works on phones.** Pointer events cover mouse and touch, `touch-action: none` stops the page from scrolling, and the layout fills any frame size.

> [!IMPORTANT]
> Ads only run for games in full launch. In basic launch the real portal answers with `adsDisabled` (and `unfilled` when no ad is available), and your `adError` branch runs. Locally you see a three-second placeholder instead. The code path is the same.

## Next steps

- [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start#6-upload-and-read-the-report-5-minutes): upload and submit this game.
- [Audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads)

---

Source: https://docs.zokogames.com/getting-started/one-file-example

# Copy-paste example: one index.html

This page is one file you can paste, run, zip and upload without changing anything. It is the smallest game that uses every part of the SDK a first submission needs: `init`, the loading signals, `gameplayStart` and `gameplayStop`, one rewarded ad with a fallback, and a save. It takes about 10 minutes. The longer, two-file tutorial with a midgame ad and `happytime` is [Build a minimal game in 15 minutes](https://docs.zokogames.com/getting-started/first-game); the numbered path that includes the console is [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start).

## 1. Save this as index.html

Make an empty folder named `coin-tap` and save the file inside it as `index.html`. Nothing else is needed.

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Coin Tap</title>
  <!-- The real SDK script. It must come before your own code. -->
  <script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
  <style>
    html, body { margin: 0; height: 100%; background: #14161f; color: #fff; font: 18px sans-serif; text-align: center; }
    main { padding-top: 12vh; }
    button { font: inherit; padding: 12px 24px; margin: 6px; }
    #coin { width: 120px; height: 120px; border-radius: 50%; border: 0; background: #ffc531; touch-action: manipulation; }
    [hidden] { display: none !important; }
  </style>
</head>
<body>
  <main>
    <h1>Coin Tap</h1>
    <p>Score <b id="score">0</b> | Time <b id="time">10</b> | Best <b id="best">0</b></p>
    <p><button id="coin" aria-label="Coin" hidden></button></p>
    <p id="msg">Loading...</p>
    <button id="play" disabled>Play</button>
    <button id="bonus" hidden>Watch an ad for +5 seconds</button>
  </main>
  <script>
    var SDK = window.ZokoGames && window.ZokoGames.SDK; // undefined if the script was blocked
    var $ = function (id) { return document.getElementById(id); };
    var usable = false, running = false, score = 0, best = 0, left = 10, extra = 0, timer = 0;

    // Every SDK call goes through here: if the SDK is missing, disabled or a call fails, the game still runs.
    // SDK errors are plain { code, message } objects, not Error instances.
    function zoko(call) {
      if (!usable) return Promise.resolve(undefined);
      return Promise.resolve().then(call).catch(function (e) {
        console.warn("SDK:", e && e.code, e && e.message);
      });
    }

    function boot() {
      var ready = SDK ? SDK.init() : Promise.resolve(); // init() never rejects
      return ready
        .then(function () { usable = !!SDK && SDK.environment !== "disabled"; })
        .then(function () { return zoko(function () { return SDK.game.loadingStart(); }); })
        .then(function () {
          if (usable) { // saves are synchronous and throw on error, so keep them inside try
            try { best = Number(SDK.data.getItem("best")) || 0; } catch (e) { console.warn("SDK:", e.code); }
          }
          $("best").textContent = best;
          $("bonus").hidden = !usable;
          return zoko(function () { return SDK.game.loadingStop(); }); // the first screen is ready
        })
        .then(function () { $("msg").textContent = "Tap the coin as often as you can."; $("play").disabled = false; });
    }

    function setRunning(on) {
      if (on === running) return;
      running = on;
      clearInterval(timer);
      if (on) timer = setInterval(tick, 1000);
      zoko(function () { return on ? SDK.game.gameplayStart() : SDK.game.gameplayStop(); });
    }

    function startRound() {
      score = 0; left = 10 + extra; extra = 0;
      $("play").hidden = $("bonus").hidden = true;
      $("coin").hidden = false;
      $("msg").textContent = "";
      render();
      setRunning(true); // input is live now: gameplayStart
    }

    function tick() { left -= 1; render(); if (left <= 0) endRound(); }

    function endRound() {
      setRunning(false); // round over: gameplayStop
      $("coin").hidden = true;
      $("play").hidden = false;
      $("bonus").hidden = !usable;
      $("msg").textContent = "Round over: " + score;
      if (score > best) {
        best = score;
        $("best").textContent = best;
        if (usable) {
          try { SDK.data.setItem("best", String(best)); } catch (e) { console.warn("SDK:", e.code); }
        }
      }
    }

    // Rewarded ad with a fallback: the reward is granted only when the ad finished; every other outcome just carries on.
    $("bonus").addEventListener("click", function () {
      var finished = false;
      $("bonus").disabled = $("play").disabled = true;
      zoko(function () {
        return SDK.ad.requestAd("rewarded", {
          adFinished: function () { finished = true; },
          adError: function (e) { console.info("No ad:", e.code); } // adsDisabled before full launch, unfilled, adblock...
        });
      }).then(function () {
        $("bonus").disabled = $("play").disabled = false;
        if (finished) { extra = 5; $("msg").textContent = "+5 seconds next round."; }
        else { $("msg").textContent = "No ad right now. Play on."; } // the fallback
      });
    });

    $("coin").addEventListener("pointerdown", function (e) { e.preventDefault(); if (running) { score += 1; render(); } });
    $("play").addEventListener("click", startRound);
    window.addEventListener("blur", function () { if (running) setRunning(false); });  // pause when focus leaves
    window.addEventListener("focus", function () { if (!$("coin").hidden) setRunning(true); });
    function render() { $("score").textContent = score; $("time").textContent = left; }
    boot();
  </script>
</body>
</html>
```

The game keeps working when the SDK is blocked or `SDK.environment` is `"disabled"`: `zoko()` skips every call and the buttons that need the portal stay hidden. The SDK script URL is the real one, `https://sdk.zokogames.com/zokogames-sdk-v1.js`; do not copy the file into your build.

## 2. What each part does

| Part | SDK call | Why it is there |
| --- | --- | --- |
| Script tag in `<head>` | none | Defines `window.ZokoGames.SDK`. The upload report warns `no_sdk` without it. |
| `boot()` | `SDK.init()`, then `SDK.environment` | `init()` is required first and never rejects; a failure shows as `"disabled"`. |
| Loading | `SDK.game.loadingStart()`, `SDK.game.loadingStop()` | Separates load time from play time. Call `loadingStop` when the first screen is playable. |
| **Play** and the end of the round | `SDK.game.gameplayStart()`, `SDK.game.gameplayStop()` | `gameplayStart` is the first call the Preview checklist waits for (within 20 seconds of load); `gameplayStop` closes the round and also runs when the window loses focus. |
| Bonus button | `SDK.ad.requestAd("rewarded", { adFinished, adError })` | Reward only in `adFinished`. In basic launch the portal answers `adsDisabled`, so the fallback branch is the one you will see first. |
| Best score | `SDK.data.getItem`, `SDK.data.setItem` | Synchronous and string-only; they throw `{ code, message }` on error, so they sit in `try`. |

## 3. Run it on your machine

On `localhost` the SDK answers every call itself: no portal, no account. Serve the folder over HTTP (`file://` does not count as local), then open the address with `?sdk_debug=true`.

```bash
cd coin-tap
npx http-server . -p 8080
# or, without Node.js:
python3 -m http.server 8080
# open http://localhost:8080/?sdk_debug=true
```

You should see one `[ZokoGames SDK] Local mode: ...` line when the page opens, `[ZokoGames SDK] call game.loadingStart` and `call game.loadingStop` before **Play** becomes active, then `call game.gameplayStart` when you press **Play** and `call game.gameplayStop` after ten seconds. Pressing **Watch an ad for +5 seconds** covers the page for three seconds with a placeholder labelled `Local ad (rewarded)`, then the message changes to "+5 seconds next round." Typing `ZokoGames.SDK.environment` in the console prints `"local"`. Add `&ad_response=unfilled` to the address to see the fallback ("No ad right now. Play on."), and `&ad_response=adsDisabled` to see what basic launch looks like. Every switch is in [testing](https://docs.zokogames.com/getting-started/local-testing).

Then open the [Preview tool](https://www.zokogames.com/preview), type `http://localhost:8080/` and press **Load game**, play one round and press the bonus button: the checklist ticks **SDK initialised (init called)**, **loadingStop called**, **gameplayStart called**, **gameplayStop called**, **Rewarded ad requested** and **Data module used**, and the timing line shows the time to the first `gameplayStart` under 20 s. Items for midgame ads and `happytime` stay grey, which does not block a first submission.

## 4. Zip it

`index.html` must be at the root of the archive. One top-level folder is also accepted, and system files such as `__MACOSX` and `.DS_Store` are ignored.

| System | Command or action | Result |
| --- | --- | --- |
| macOS or Linux | `cd coin-tap && zip ../coin-tap.zip index.html` | `coin-tap.zip` next to the folder |
| Windows 10 or 11 | In the folder, run `tar -a -c -f ..\coin-tap.zip index.html` | `coin-tap.zip` next to the folder |
| Any system, with a file manager | Select the files inside the folder (not the folder), then compress them | A zip with `index.html` at the root |

Check it with `unzip -l coin-tap.zip` (macOS, Linux) or `tar -tf coin-tap.zip` (Windows): the list must show `index.html` and nothing in front of it. Older Windows PowerShell versions can write backslashes into zip entry names with `Compress-Archive`; the validator rejects those as `unsafe_path`, so use `tar` or the file manager.

## 5. Upload it

Follow steps 6 and 7 of [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start#6-upload-and-read-the-report-5-minutes): drop `coin-tap.zip` on **Drop your game zip here** on the **Build** step. You should see "Build v1 passed validation and was published." with the SDK detected and no errors. The listing still needs your own description, controls, tags and covers before **Submit for review**.

## Next steps

- [Build a minimal game in 15 minutes](https://docs.zokogames.com/getting-started/first-game): the same ideas with a midgame ad, `happytime` and the portal mute setting.
- [SDK introduction](https://docs.zokogames.com/sdk/introduction): `init`, environments and every error code.
- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting): when the console stays silent or the upload is rejected.

---

Source: https://docs.zokogames.com/getting-started/starter-kits

# Starter kits

The fastest way to a game that passes review is to start from one that already follows the rules. Four of the kits are the same tiny game, "Target Tap" (tap the targets before they vanish), so you can compare how the SDK is wired in; the GDevelop kit is a project that exercises the extension instead. Each is small and dependency-light, runs when the SDK is missing or disabled (`html5-minimal` even when `index.html` is opened straight from disk; the Vite, Phaser and PlayCanvas kits need `npm run dev` or a web server, because a bundled page is not served from `file://`), keeps every asset path relative and loads the SDK from `https://sdk.zokogames.com/zokogames-sdk-v1.js`.

| Kit | Use it when | Needs | Download |
| --- | --- | --- | --- |
| `html5-minimal` | You write plain JavaScript or want to read every SDK call in one file. | A static web server. No build step. | [html5-minimal.zip](https://www.zokogames.com/starter-kits/html5-minimal.zip) |
| `html5-vite-ts` | You want TypeScript, a bundler and typed SDK access. | Node 20.19 or later (or 22.12 or later), `npm install`. | [html5-vite-ts.zip](https://www.zokogames.com/starter-kits/html5-vite-ts.zip) |
| `phaser` | You build with Phaser. The kit's `package.json` depends on Phaser `^4.2.1` and is type-checked and built against it. | Node 20.19 or later (or 22.12 or later), `npm install`. | [phaser.zip](https://www.zokogames.com/starter-kits/phaser.zip) |
| `playcanvas` | You build an engine-only PlayCanvas game (no Editor). The kit's `package.json` depends on PlayCanvas `2.24.2` and is type-checked and built against it. | Node 20.19 or later (or 22.12 or later), `npm install`. | [playcanvas.zip](https://www.zokogames.com/starter-kits/playcanvas.zip) |
| `gdevelop` | You build with GDevelop 5. A project with the ZokoGames extension already embedded. | GDevelop. No build step. | [gdevelop.zip](https://www.zokogames.com/starter-kits/gdevelop.zip) |

## What each kit demonstrates

| SDK area | Where to look |
| --- | --- |
| `init()` and the `disabled` fallback | A small wrapper (`zoko()` in `html5-minimal`, `src/zoko.ts` in the Vite kit, `safe()` in the Phaser and PlayCanvas kits) so one failing call never breaks the game. |
| Loading signals and portal settings | `loadingStart` / `loadingStop` at boot; `muteAudio` applied at start and on change. |
| Gameplay events | `gameplayStart` when a round begins, `gameplayStop` when it ends, the tab is hidden or an ad starts. |
| Ads | A midgame ad every second round at a natural break; a rewarded button that grants the reward only after `adFinished`. |
| Banners | A container on the menu screen only, cleared before play (`html5-minimal`, Phaser, PlayCanvas). |
| Cloud save | The best score through `SDK.data`. |
| Users and leaderboard | `html5-minimal` shows `getUser`, an auth listener, a sign-in button and `submitScore` with the AES-GCM helper. |
| Invites | `html5-minimal` shows `inviteLink`, `getInviteParam` and a join listener. |

## Test, package, upload

All kits follow the same loop. The kit READMEs list the details.

1. **Run on `localhost`.** The SDK switches to its in-page mock: ads are a three-second overlay, banners are dashed boxes, users and friends are fake. Add `?sdk_debug=true` to log every call. See [testing](https://docs.zokogames.com/getting-started/local-testing).
2. **Open the [Preview tool](https://www.zokogames.com/preview).** Enter your local address and play: the requirements checklist ticks as your game makes the calls.
3. **Package.** `html5-minimal` is already uploadable: the downloaded zip has `index.html` at its root, so you can upload it as it is, or zip your edited folder's contents again. In the Vite, Phaser and PlayCanvas kits, `npm run package` typechecks, builds and writes a zip named after the package, refusing to zip a build with absolute paths. All three set Vite's `base` to `./`. In the GDevelop kit, open `game.json` in GDevelop, export as HTML5 and zip the exported folder with `index.html` at its root.
4. **Upload** the zip in the [developer console](https://docs.zokogames.com/getting-started/submission-walkthrough) and read the validation report.

The whole path with what you should see at each step is in [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start). Kit file names, scripts and commands in this page match the kit `package.json` files: `npm run dev`, `npm run build`, `npm run typecheck` and `npm run package`.

> [!NOTE]
> The Phaser kit uses the ZokoGames Phaser plugin, copied into `src/zoko/`. See the [Phaser page](https://docs.zokogames.com/engines/phaser) for what the plugin adds on top of the raw SDK. The plugin source in `packages/sdk-engines/phaser` is written for Phaser 3 and has not been compiled against every Phaser release; the kit uses Phaser 4.2, the release it was checked with.

> [!NOTE]
> The PlayCanvas kit uses the ZokoGames PlayCanvas integration, copied into `src/zoko/` without its Editor scripts, and the real `playcanvas` package. See the [PlayCanvas page](https://docs.zokogames.com/engines/playcanvas). The GDevelop kit is the example project from the GDevelop extension; it was exported with GDevelop's exporter and played headlessly, but nobody has yet clicked through opening it in the editor window. There is no Wonderland kit yet: the [Wonderland page](https://docs.zokogames.com/engines/wonderland) has the plugin on its own.

## Next steps

- [Testing with local mode and the Preview tool](https://docs.zokogames.com/getting-started/local-testing)
- [Build a minimal game in 15 minutes](https://docs.zokogames.com/getting-started/first-game)

---

Source: https://docs.zokogames.com/getting-started/local-testing

# Testing with local mode and the Preview tool

There are three places to test, from fastest to most realistic.

| Where | Needs | What it gives you |
| --- | --- | --- |
| **Local mode** (your machine) | Nothing: a local web server | The SDK answers from an in-page mock. Instant feedback, works offline. |
| **[Preview tool](https://www.zokogames.com/preview)** (`/preview`) | Nothing: no account, no upload | Your game, served from any `http(s)` address such as `localhost`, runs inside the real portal frame with a live requirements checklist and an event log. |
| **Build preview** (developer console, game, **Preview and QA** tab) | An uploaded, validated build | Your uploaded build inside the real portal frame, with ads switched on so every module can be exercised. Tracking, votes and reports are blocked, so testing never touches your numbers. |

## Local mode

Open your game from `localhost`, `127.0.0.1`, `[::1]` or any `*.localhost` host, or add `?useLocalSdk=true` to the URL on any other host. The SDK then runs an in-page mock instead of talking to the portal. Serve over HTTP; `file://` pages have no host name and are not treated as local (add `?useLocalSdk=true` if you must open one).

### Exactly when local mode starts

`SDK.init()` decides once, when it is called:

1. **Top-level page** (not inside an iframe): `local` if the host is a local one or the URL contains `useLocalSdk=true`; otherwise `disabled`.
2. **Inside an iframe**: the SDK first asks the parent page for the portal handshake and waits up to **1.5 seconds** (15 seconds when the parent page is the portal itself). If the portal answers, the environment is `zokogames` and `useLocalSdk` is ignored. If nothing answers, it falls back to `local` under the same rule as above (local host or `?useLocalSdk=true`), and to `disabled` otherwise. So `?useLocalSdk=true` on a game framed by your own test page works, with a 1.5 second delay at startup.

`useLocalSdk` is read from the game's own URL, not from the parent's. After `init()`, `SDK.environment` is `"local"`. Use `?sdk_debug=true` to log every call, and look for the `[local host]` lines.

Since SDK 1.6.2: the SDK also writes one console line, once per page, when it ends up `disabled` (it names the page that framed the game when that page is not the portal or did not answer, or says the page is neither framed nor on a local host) and the first time a member is used before `init()` resolved (`sdkNotInitialized`). Both are info lines that point back here. A cloud save that fails to reach the portal logs one warning saying the save is kept locally and the SDK retries. None of them contains player data.

What the mock does:

| Module | Local behaviour |
| --- | --- |
| Ads | A full-screen overlay labelled `Local ad (midgame)` or `Local ad (rewarded)` for 3 seconds, firing `adStarted` and `adFinished`. A midgame request less than three minutes after the previous ad (of either type) fails with `adCooldown`. A second request while an ad is on screen fails with `other`. Like the portal, local mode (SDK 1.6.4) refuses a midgame request with `adCooldown` and the message "Midgame ads are available after gameplay starts: call game.gameplayStart() first" until your game has called `gameplayStart()` or 30 seconds of visible page time have passed. Rewarded requests are not gated. SDK 1.6.3 and earlier played the ad in that case. |
| Banners | A dashed placeholder box appended to your container (for a responsive request, the largest listed size that fits). The SDK's own checks still run, so `missingId`, `invalidSize`, `notVisible`, `bannerCooldown` (30 seconds per container) and `maxRefreshReached` happen locally too. A missing container fails with `notCreated`. |
| User | Two fake users, `LocalUser1` and `LocalUser2` (`LocalUser1` is signed in at start), twelve fake friends, and an unsigned test token. Friends, inventory and purchases need a signed-in user and fail with `userNotAuthenticated` otherwise. |
| Store | `SDK.store.isAvailable` is `true`. A fake catalog of three items (`local-coins-100`, `local-gems-50`, `local-no-ads`) and an inventory that starts with three `local-coins-100` and one `local-no-ads`. `buyItem` and `consumeItem` update it in memory; it resets on reload. `getPurchaseToken` returns a placeholder string that your server cannot verify. |
| Data | Saved in the browser's `localStorage` under the key `zoko-sdk-data`, so it survives reloads on the same origin. The 1,048,576 byte limit still applies. |
| Game | Settings come from the query string. `happytime()` shows a short "Happy time!" toast. Invite links are your own URL with the parameters added. Room, loading, context and completion calls and `trackOrder` are accepted and do nothing visible. `submitScore` records nothing and logs one console line; offline (`?offline=true`) with a signed-in player and `delayed` (SDK 1.6.4) it shows "Score saved offline". |

Local mode is for developing. By default every ad is filled, so force a failure with `ad_response` (below) and always re-test in the Preview tool.

### Query switches

Add any of these to the page URL.

| Parameter | Values | Effect |
| --- | --- | --- |
| `sdk_debug` | `true` | Logs every SDK call and result to the console. Works in every environment. |
| `disableChat` | `true` | `SDK.game.settings.disableChat` becomes `true`. |
| `kidsMode` | `true` | From SDK 1.5.0: `SDK.game.settings.kidsMode` and `disableChat` become `true`; without it `kidsMode` is `false`. The other kids rules are not simulated; test them in the build preview. |
| `muteAudio` | `true` | `SDK.game.settings.muteAudio` becomes `true`. |
| `user_account_available` | `false` | Simulates a host without accounts: no user, `isUserAccountAvailable` is `false`. |
| `ad_response` | `unfilled`, `adblock`, `adsDisabled`, `other` | Every ad request fails with that code. `adblock` also makes `hasAdblock()` return `true`. |
| `user_response` | `user1`, `user2`, `logged_out` | Who `getUser()` returns at start (any other value means signed out). |
| `show_auth_prompt_response` | `user1`, `user2`, `user_cancelled` | What `showAuthPrompt()` does (default `user1`; any other value fails with `userCancelled`). It fails with `userAlreadySignedIn` when someone is already signed in, so combine it with `user_response=logged_out`. |
| `link_account_response` | `yes`, `no`, `logged_out` | What `showAccountLinkPrompt()` answers (`logged_out` fails with `userNotAuthenticated`). |
| `token_response` | `user1`, `user2`, `expired_token`, `logged_out` | Which user the token is for, or that it is already expired, or that it fails with `userNotAuthenticated`. |
| `offline` | `true` | `SDK.game.isOffline` is `true` and stays so; without it the mock follows the browser's online and offline events. |
| `instantJoin` | `true` | `SDK.game.isInstantMultiplayer` becomes `true`. |
| `qaTool` | `true` | Sets `SDK.isQaTool`, so the game can show extra diagnostics. Read in every environment. |

> [!NOTE]
> In local mode every query parameter is also an invite parameter: `SDK.game.inviteParams` is not `null` as soon as the URL has any query string (even `?sdk_debug=true`), and `getInviteParam("room")` reads `?room=...`. Do not treat "has invite parameters" as "was invited" while testing locally; test join flows with explicit parameters. Also, `SDK.data` is always enabled locally, so `dataModuleDisabled` never appears; the portal raises it when the data module is switched off for the game.

```text
http://localhost:8080/?sdk_debug=true&user_response=logged_out&show_auth_prompt_response=user2&ad_response=unfilled
```

> [!WARNING]
> The local token is unsigned (`alg: none`, `local: true` in the payload). Your server must reject it. If your backend accepts a local token, your verification is broken.

### Simulating portal events

From SDK 1.5.1, local mode can also play the events that only the portal sends, so you can test your listeners without the portal. Dispatch a `CustomEvent` on `window`:

| Event | `detail` | What the SDK does |
| --- | --- | --- |
| `zokogames:local-settings` | Any of `disableChat`, `kidsMode` and `muteAudio`, as booleans | Fires `settingsChange` with the updated settings. `kidsMode: true` also turns chat off, as `?kidsMode=true` does. |
| `zokogames:local-join-room` | Invite parameters as strings, for example `{ room: "abc" }` | Fires `joinRoom` with those parameters. |
| `zokogames:local-offline` | `{ offline: true }` or `{ offline: false }` | Fires `offlineChange`. Ignored while `?offline=true` pins the state. |

```js
window.dispatchEvent(new CustomEvent("zokogames:local-settings", { detail: { muteAudio: true } }));
window.dispatchEvent(new CustomEvent("zokogames:local-join-room", { detail: { room: "abc" } }));
window.dispatchEvent(new CustomEvent("zokogames:local-offline", { detail: { offline: true } }));
```

Run the lines from the browser console or wire them to a debug button. Outside local mode nothing listens for these events.

## The Preview tool

Open [`/preview`](https://www.zokogames.com/preview), type the address of your game (for example `http://localhost:8080/index.html`) and press **Load game**. No account is needed and nothing is uploaded: the game loads straight from your address inside a sandboxed frame, and the event log stays in your tab.

The portal frame answers SDK calls with test data: ads are placeholder screens, there is no signed-in user, and cloud saves stay in your browser. Use it to:

- Play at every window size from the [gameplay requirements](https://docs.zokogames.com/requirements/gameplay) with one-click **Frame size** presets.
- Watch every SDK call as it happens in the **event log**; filter it by method or text and export it as JSON to attach to a support request.
- Tick off the **requirements checklist**: SDK initialised, `loadingStop`, `gameplayStart`, `gameplayStop`, a midgame ad, a rewarded ad, a banner, data module use and `happytime`. Items turn green when your game makes the call.
- Check **time to the first `gameplayStart`**. The tool flags a start later than 20 seconds; trim your initial download if it does (see [first frame fast](https://docs.zokogames.com/guides/first-frame)).
- Toggle **Simulate settings** (mute audio, disable chat) and confirm your game reacts. The **Kids mode (SDK 1.5.0)** switch sends a settings change with `kidsMode` and `disableChat` set to `true`, as the portal does.

If the Preview page is served over `https`, browsers block plain `http` games unless they run on `localhost`. Serve your game over `https` or from `localhost`. Addresses with a username or password, and pages on this site (other than the bundled demos), are refused.

### Run a build zip from your computer

The Preview tool can also run a build zip chosen from your computer without uploading it. Pick the file under **Or run a build zip from this computer**: the zip is unpacked in your tab and served to the frame from memory. Local zips run on a separate preview origin. Each run starts with empty storage, so saves from an earlier run are gone, and only one zip preview can run at a time.

Before anything runs, the zip is checked like an upload: `index.html` must sit at the root of the zip (or inside a single top-level folder), and the build may hold at most 1,500 files and 250 MB unpacked. A zip that fails a check shows the reason instead of running.

## The build preview in the console

After you upload a build and it passes validation, the game's **Preview and QA** tab in the console runs that exact build in the real portal frame, with ads enabled and your game's own data, leaderboard and multiplayer settings applied; **Preview** on a build in the build list opens it there. The checklist is grouped into **Basic Launch**, **Full Launch**, **Limits the docs set** and **For your settings**, and it shows **SDK ready** and **First gameplay** timings. Play through the menus, a round, a pause and an ad break, then check that every item you need has ticked. The checks are advice and never stop the **Submit for review** button; a game waiting in its menu shows **Waiting for you to play**, not a failure, until you press Play. If the frame stays blank or the notice **The frame loaded but the SDK never started** appears, open the browser console (F12): *Refused to display in a frame* means your own server sends `X-Frame-Options` or a `frame-ancestors` rule that excludes zokogames.com; *Mixed Content* means an `http://` address on the https page; a Content-Security-Policy error means `https://sdk.zokogames.com` is not allowed in `script-src`. Each fix is also listed on the troubleshooting page.

### Simulate the player

The **Simulate the player** card in the build preview changes what the portal tells your game, so you can test situations that are hard to create. It works only in the console's build preview. Public game pages never honour it. Every simulated answer appears in the event log under **Portal replies**, next to the calls your game made.

| Setting | What the SDK reports |
| --- | --- |
| Player: Guest | `user.getUser()` resolves `null`, `SDK.user` is `null` at start, and token, score and friends calls fail as for a signed-out player. |
| Accounts unavailable | `user.isUserAccountAvailable` is `false`, no user is reported and `showAuthPrompt()` is cancelled. |
| Ad blocker installed | `ad.hasAdblock()` is `true` and `ad.requestAd()` fails with the `adblock` error code. Not in kids mode. |
| Ad-free member | A midgame break resolves at once as a finished ad, with no error. Banners fail with `bannersDisabled`. |
| Ads switched off for the game | `ad.requestAd()` fails with `adsDisabled`. |
| Banners unavailable | `banner.requestBanner()` fails with `bannersDisabled`. |
| Offline | `game.isOffline` is `true` and an `offlineChange` event arrives. Ad and banner requests fail as without a connection (`unfilled`, `bannersDisabled`). |
| Platform mute is on | `game.settings.muteAudio` is `true` and a `settingsChange` event arrives live. |
| Kids mode | `game.settings.kidsMode` and `game.settings.disableChat` are `true`, no ad blocker check runs, and sign-in, leaderboards and multiplayer are not offered. |
| Language | `user.systemInfo.locale` is the language you pick. |
| Device type and orientation | `user.systemInfo.device.type` follows the window size group (or the type you pick), and **Portrait** swaps the frame's width and height. |

Settings the game reads once at start (player, accounts, ad-free, ads off, kids, language, device type) restart the game when you change them. Ad blocker, banners, offline and mute reach the running game live.

## Checklist before you submit

- [ ] No console errors on load or during the first minute of play.
- [ ] `gameplayStart` is the first SDK event after the player acts, not at page load.
- [ ] A failed ad never leaves the game paused or muted.
- [ ] The game works with the SDK `disabled` (open it on a plain web server without `?useLocalSdk=true`).
- [ ] Nothing depends on `localStorage` surviving; use the [data module](https://docs.zokogames.com/sdk/data).
- [ ] The first `gameplayStart` arrives well within 20 seconds on a throttled connection.

Every line of the three checklists your game meets, word for word as the Preview tool, the build preview and the reviewer show them, is on the [testing checklist](https://docs.zokogames.com/getting-started/testing-checklist).

## Next steps

- [Testing checklist before you submit](https://docs.zokogames.com/getting-started/testing-checklist)
- [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough)

---

Source: https://docs.zokogames.com/getting-started/testing-checklist

# Testing checklist before you submit

Run this page against the build you are about to submit. It has three parts, one for each checklist the portal really uses: the public Preview tool, the **Preview and QA** tab of your game in the console, and the list a reviewer answers. The lines are quoted exactly as those tools show them. If every line holds, the reviewer has nothing to send back on these points.

You need a game you can serve from your own machine for part 1, and an uploaded build that passed validation for parts 2 and 3 (see [build validation](https://docs.zokogames.com/requirements/build-validation)). The rules behind each line are on the [requirements checklist](https://docs.zokogames.com/requirements/checklist).

## 1. The Preview tool

Open the [Preview tool](https://www.zokogames.com/preview), enter your game's address and press **Load game**. The **Requirements checklist** marks a line done as soon as your game makes the call; nothing turns red except the timing line.

| Line in the tool | Done when your game calls | Needed for |
| --- | --- | --- |
| SDK initialised (init called) | `SDK.init()` | Every game that uses the SDK; call it before `gameplayStart` |
| loadingStop called | `SDK.game.loadingStop()` | Recommended |
| gameplayStart called | `SDK.game.gameplayStart()` | Every game (basic-launch plays and play time are measured from it) |
| gameplayStop called | `SDK.game.gameplayStop()` | Full launch |
| Midgame ad requested | `SDK.ad.requestAd("midgame", ...)` | Full launch |
| Rewarded ad requested | `SDK.ad.requestAd("rewarded", ...)` | Optional |
| Banner requested | `SDK.banner.requestBanner(...)` or `SDK.banner.requestResponsiveBanner(...)` | Optional |
| Data module used | `SDK.data.setItem(...)`, `removeItem(...)` or `clear()`, once the save is sent | Games that use the data module |
| happytime called | `SDK.game.happytime()` | Optional |
| Time to first gameplayStart under 20 s | The first `gameplayStart` within 20 seconds of the frame appearing; later, the line is marked over the guideline | Every game |

Use **Frame size** to play at phone and desktop sizes, and **Simulate settings** to send **Mute audio** and **Disable chat** to the running game.

## 2. The build preview in the console

Open your game in the developer console, go to the **Preview and QA** tab (or press **Preview** on a build) and play through the menus, a round, a pause and an ad break. Each line shows a tick (passed), **Failed**, **Recommended** or **Not run yet**; every line that is not passing says what it measures, what is expected, how to trigger it, the number measured and links to the docs. The checks are advice: none of them switches **Submit for review** on or off (that depends only on the checklist on the Review step); a reviewer applies the Basic Launch and Full Launch rules. The line **SDK initialised** also shows the SDK version your game reported, which is the copy of the SDK your build loaded (the file in your zip, or the script from `sdk.zokogames.com`, which can serve the previous release for up to an hour after a new one is published). The summary does not count optional lines that were never seen. Ads are switched on here, so ad lines can pass before your game reaches full launch.

| Group | Line | Passing when | Required |
| --- | --- | --- | --- |
| Basic Launch | SDK initialised | The SDK finished its start-up with the portal. | Yes |
| Basic Launch | gameplayStart called | `gameplayStart` arrived. A game waiting in its menu is not failing: with none 20 seconds after load the line reads **Waiting for you to play**; press Play in the frame. | Yes (for the reviewer) |
| Basic Launch | First gameplayStart within 20 seconds | The first `gameplayStart` came no later than 20 seconds after the frame loaded. The time includes your own time in the menu, so a slower one shows **Recommended** (to review), not **Failed**: restart and press Play at once to time the game itself. | Yes (for the reviewer) |
| Full Launch | loadingStop called when the game is ready | `loadingStop` arrived. Without it after 20 seconds the line shows **Recommended**. | No |
| Full Launch | gameplayStop called on pause, menu and game over | `gameplayStop` arrived. | Yes |
| Full Launch | A midgame ad was requested | A midgame request arrived. | Yes |
| Full Launch | A rewarded ad was requested | A rewarded request arrived. | No |
| Full Launch | Play resumed after an ad finished | After an ad finished, a `gameplayStart` followed. Until it does, the line shows **Recommended**. | Yes |
| Limits the docs set | gameplayStop before each ad request | No ad was requested between `gameplayStart` and `gameplayStop`. Shown after the first ad request. | Yes |
| Limits the docs set | Banner rules respected | No banner was requested during gameplay, none within 30 seconds on the same container, no more than 60 refreshes and no more than two on screen. Shown after the first banner. | No |
| Limits the docs set | Saves stay under 1 MiB | Every save sent was under 1,048,576 bytes. Shown after the first save. | No |
| For your settings | Data module used for saves | A save was sent. | When **Uses the SDK data module** is ticked |
| For your settings | A leaderboard score was submitted | `SDK.user.submitScore(...)` arrived. | When **Has a leaderboard** is on |
| For your settings | Multiplayer room or invite call made | `updateRoom` or `inviteLink` arrived. | When **Multiplayer game** is ticked |
| For your settings | happytime called at a great moment | `happytime` arrived. Shown once called. | No |

Calls that break a rule are marked **Requirement broken** in the **SDK event log**. Then repeat one round with each **Simulate the player** setting that applies to your game, and check that the game keeps working: **Guest**, **Ad blocker installed**, **Ads switched off for the game**, **Ad-free member**, **Offline**, **Platform mute is on** and **Kids mode**. What each one reports is listed in [testing](https://docs.zokogames.com/getting-started/local-testing).

## 3. The reviewer's QA list

A reviewer answers every line below with pass, fail or not applicable. Lines with a condition appear only when it applies to your game. A reviewer can approve only when every line is answered and none failed.

### Technical

| Line the reviewer answers | How to check it yourself |
| --- | --- |
| Game loads in the portal frame without console errors that block play | Open the build preview with the browser console open and play the first minute. |
| Initial load is reasonable on a mid-range phone (under about 10 s on 4G) | Throttle the network to a 4G profile in the browser's developer tools and read the **First gameplay** timing. |
| Initial download is within the size budget | The build report shows the initial download as passing: 20 MB is the mobile target, 50 MB the limit. |
| Fullscreen and resize work; no layout break at 360 px wide | Play in the phone frames and with the portal's fullscreen button; resize the window during a round. |
| Touch controls work on mobile (when **Works on mobile** is ticked) | Play a whole round on a real phone with touch only. |
| No unapproved external requests, popups or redirects | The Network tab shows only your game's own files and the SDK; the build report has no `external_url` or `origin_*` finding. |
| Audio starts only after user interaction and can be muted | Reload: nothing plays before the first tap. Turn on **Platform mute is on**: the game is silent at once. |

### Gameplay

| Line the reviewer answers | How to check it yourself |
| --- | --- |
| A new player can start playing within 30 seconds | In a fresh browser profile, time from opening the page to controlling the game. |
| Controls match the description and are explained in-game | Compare the **Controls and instructions** text of your listing with what the game shows on screen. |
| No soft-locks or unwinnable states in the first 10 minutes | Play for 10 minutes; lose, quit to the menu and restart at least once each. |
| Game pauses on gameplay blur and on ad breaks | Click outside the game and switch tabs during a round; trigger an ad. The game must stop and stay silent. |

### Ads (when ads are on for your game)

| Line the reviewer answers | How to check it yourself |
| --- | --- |
| Ad breaks use the SDK and never block gameplay start | No ad is requested before the first round. With **Ads switched off for the game** or **Ad blocker installed**, play still starts. |
| Rewarded ads grant the reward only after a finished ad | With **Ad blocker installed**, press your rewarded button: no reward is granted. |
| Banners use approved sizes and do not cover controls | Only the sizes on [banners](https://docs.zokogames.com/sdk/banners); check every banner screen in the phone frames. |
| No third-party ad code or house ads inside the game | The build report has no `origin_ads` or `third_party_sdk` finding, and the game shows no promotion of its own. |

### Accounts and saves (when you use the data module or a leaderboard)

| Line the reviewer answers | How to check it yourself |
| --- | --- |
| Playable as guest; sign-in is optional | Simulate **Guest** and play a full round. |
| Progress saves and restores through the SDK data module | Make progress, reload the page and check it is still there. |
| Leaderboard scores submit and display correctly (when the game has a leaderboard) | Signed in, finish a round; **A leaderboard score was submitted** turns **Passing** and the score appears on the board. |

### Multiplayer (multiplayer games only)

| Line the reviewer answers | How to check it yourself |
| --- | --- |
| Lobby, invites and join links work | Use two browser tabs as in [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms). |
| A player leaving or dropping does not freeze the room | Close one tab in the middle of a match. |
| Minimum and maximum lobby size match the listing | Compare with **Minimum lobby size** and **Maximum lobby size** on the Technical step. |

### Quality and presentation

| Line the reviewer answers | How to check it yourself |
| --- | --- |
| Original work or properly licensed; no stolen assets or brands | Keep the licence for every asset, font and sound you did not make. |
| Content is suitable for the declared audience (kids flag respected) | Compare the game with the age rating you chose; for a game made for children, read [kids mode](https://docs.zokogames.com/guides/kids-mode). |
| Covers and video meet the size, ratio and clarity requirements | Check each file against [covers](https://docs.zokogames.com/requirements/covers). |
| Title, descriptions and controls text are accurate and free of spam | Read your listing as a stranger would. |
| Overall quality is competitive for its category | Play the games in your category on the portal and compare honestly. |

If a line fails, the reviewer sends the game back with reasons from a fixed list; what each reason means is on [quality guidelines](https://docs.zokogames.com/requirements/quality).

## Next steps

- [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough)
- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting)
- [Launch stages and KPIs](https://docs.zokogames.com/getting-started/launch-stages)

---

Source: https://docs.zokogames.com/getting-started/submission-walkthrough

# Submission walkthrough

This page follows the developer console from an empty account to a submitted game, then explains what happens in review.

## 1. Create your studio

Go to [`/developer/onboarding`](https://developer.zokogames.com/onboarding). You need a ZokoGames account first (a studio hangs off a normal account).

> [!NOTE]
> Studio sign-up is open unless the portal team switches it to invitation only. In that mode the page shows "Studio sign-up is by invitation at the moment" instead of the form: open the link in your invitation email, or press **Apply to publish** (it opens [`/developers#apply`](https://www.zokogames.com/developers#apply)); the team replies by email. One application per email address is accepted a day; if the confirmation email to your address could not be sent, you can send the form again straight away. Staff accounts are not affected.

The form asks for:

- **Studio name** (2 to 60 characters; it must differ from every other studio's name, also in case, accents and spacing, and you are told as you type), an optional **Your name** (the username teammates and reviewers see in the team list and the audit trail; a name is generated if you leave it empty and you can change it later in your account settings) and a **Studio address**, the short name in your studio's page URL (lowercase letters, numbers and single hyphens, up to 40 characters; it is checked as you type and cannot be changed later).
- Acceptance of the [developer terms](https://docs.zokogames.com/business/developer-terms), with the version you are accepting shown next to them.

Nothing else is asked at this point. The studio's **support email** starts as the email you signed up with and is shown to players as a Contact button once the studio page is live; change it, and add a website, in the studio settings. The **payout profile** (legal name, country, payout currency (USD or EUR) and method (bank wire, PayPal or ACH)) is filled in on the **Payouts** page and can wait until your first statement; bank details are never entered in the console, a payout provider collects them later.

When the studio is created, the form shrinks to a summary and the page offers **Create your first game**: a game name, a game address and a category. **Create game** opens the game's **Edit and submit** wizard (step 2 below). You can also choose **Go to the console** and create the game later.

You become the studio's owner. Invite teammates on the **Team** page. A **Member** creates and edits games, uploads artwork, uploads and activates builds, submits games for review, and reads and answers player feedback and stats; members do not see revenue or payouts. An **Admin** can also delete games and builds, unpublish a live game, send new artwork of a live game for review, run artwork experiments, manage achievements, leaderboards, the in-game store, promotions, API tokens and webhooks, edit the studio settings and profile, read revenue, statements, payouts and the audit trail, invite members and remove members. The **Owner** can also add admins, change roles, transfer ownership, name the owner of record, accept updated developer terms and delete the studio, and is the only one who can change the payout profile and the payout provider connection (see [payouts](https://docs.zokogames.com/business/payouts)). The console's **Team** page shows the same list under **What each role can do**. Managing API tokens and webhooks, changing payout details, making someone an admin, unpublishing a live game, transferring ownership and deleting the studio ask you to confirm it is you with a passkey or an authenticator app: set one up in your player account on zokogames.com: in the console open the account menu, choose **Settings** (not the studio **Settings** page in the side menu) and then **Account**.

**Studio profile.** Open **Settings** in the console to set up how players see your studio. None of it is reviewed, and a save shows on your public studio page at once (lists and search results can take up to 5 minutes). A studio with nothing filled in still gets a complete page: the first letter of its name in place of a logo and a short sentence written from its games.

| Field | Where players see it |
| --- | --- |
| Studio name | The studio page, and "by your studio" on each game page. |
| Studio logo | The studio page and the studio card on each game page (a kids game shows the first letter instead). Square PNG, JPEG or WebP, 128 to 2048 px, up to 2 MB; saved as soon as you choose the file. |
| About the studio | The top of the studio page, up to 1,000 characters. Its first 160 characters are also the text of link previews and search results. |
| Website, links | Buttons beside the studio name. A link you leave empty is not shown. |
| Support email | A Contact button on the studio page, so use an address you want strangers to write to. A new studio starts with the email you signed up with. |
| Studio country, contact person, contact email | Not shown to players; the portal team uses them to reach you. |

The public studio page exists once your first game is published; until then its address shows "not found". The studio address (URL name) is fixed after creation: to change it, ask support.

## 2. Create the game and fill in the steps

If you created your first game on the onboarding page, the draft already exists and its wizard is open, with the name, address and category you chose there (you can change the name and category on **Basics**; the address is locked once a build is uploaded or the game is submitted). Carry on with the steps below. Otherwise, on the dashboard choose **Submit a game**: enter a name (2 to 60 characters), check the **URL slug** (locked once a build is uploaded or the game is submitted), pick a category and press **Create draft and continue**. The wizard has five steps, **Basics**, **Technical**, **Build**, **Artwork** and **Review and submit**, and it autosaves. A studio can hold 50 drafts at once; submit or delete one before you start a 51st.

| Step | What you provide |
| --- | --- |
| **Basics** | Name, URL slug and category, short description (20 to 160 characters), description (at least 80 characters of text), controls (at least 5 characters), tags (up to 10; one is recommended), optional FAQ, and the two required confirmations (suitable for players aged 12 and over, and all text available in English). |
| **Technical** | Engine, orientation (landscape, portrait or both), how progress is saved, hosting, the device checkboxes (mobile, iOS, Safari), popups, the data module, multiplayer (with minimum and maximum lobby size), whether the leaderboard is on (the switch itself is on the **Leaderboard** tab), optional store links, the **Audience and distribution** card (age rating, languages, made for children, devices and platforms, embedding, allowed sites and sitelock notes) and the optional video and multiplayer extras. |
| **Build** | Upload a zip, see the validation report. See below. |
| **Artwork** | Three covers (required) and two preview videos (needed for full launch). See [covers and videos](https://docs.zokogames.com/requirements/covers). |
| **Review and submit** | A checklist of what is missing, an optional note for the reviewer, and the **Submit for review** button. |

**Age rating and languages are required.** Both are in the **Audience and distribution** card on the **Technical** step: pick an age rating (all ages, 7+, 12+, 16+ or 18+) and tick every language the game's text is available in. You cannot submit until the rating is 12+ or lower and the language list includes English; the **Review and submit** step lists either one as missing. A game marked **Made for children** needs an all-ages or 7+ rating, has ads switched off, is reviewed against stricter rules and cannot be embedded. The same card holds **Allow embedding on partner sites** (off by default, see [embedding](https://docs.zokogames.com/requirements/embedding)) and optional sitelock notes for the reviewer.

**Hosting** is either *hosted by ZokoGames* (you upload a zip, recommended) or *on your own server* (an `https` address that allows being framed from zokogames.com). Games on your own host only earn when they use the SDK.

**Devices and store links.** Tick **Tested and works well on iOS** only after you have tested the game on an iPhone or iPad. It is a quality claim: it adds the iOS feature to the game page, and without it players on iPhone and iPad see a "may not run well" notice. It does not hide the game; to do that, switch off **iPhone and iPad** under **Platforms**. **Store links** are optional and must start with `https://` (a plain `http://` link is upgraded to `https://` when it is saved); they are shown on the game page, never inside the game.

> [!TIP]
> Use the **note for the reviewer** to say how to reach a specific level, which button opens the leaderboard, or how to start a multiplayer room. Reviewers have a few minutes per game; the note saves them hunting. If the game talks to a server of your own, the host and how to try it alone go in **Server host and notes for reviewers** on the Technical step; the reviewer sees that text with your submission, and the card also shows the origin your server must allow.

## 3. Upload and validate the build

Drop a zip with `index.html` at its root (or inside a single top-level folder). Large uploads are sent in parts and can be resumed. The validator then checks, without trusting the archive:

- At most **1,500 files** and **250 MB** unpacked.
- An estimated initial download of at most **50 MB** (a warning above **20 MB**, the mobile target).
- No absolute or traversing paths, backslashes, symbolic links, encrypted entries or duplicate paths.
- No executable or server-side files (`.php`, `.exe`, `.sh`, `.jar`, `.py` and similar).
- No suspicious compression ratios.
- No code or files that the safety scan blocks, such as native programs, miners or password forms that post to another site. Some patterns only flag the build for a moderator, who looks at it before the game goes live (see [the safety scan](https://docs.zokogames.com/requirements/build-validation#the-safety-scan)).
- It also detects your engine, whether the SDK script is referenced, and warns about case collisions and ignored system files such as `__MACOSX`.

A build that fails shows each problem with the offending path. A build that passes is stored. Until the game is live, every build that passes also becomes the active build at once: Preview plays it and it is the version you submit (press **Activate** on an older one to go back). Once the game is live, new builds wait for you to switch to them; see [updating a live game](https://docs.zokogames.com/getting-started/updating-a-game). See the [technical requirements](https://docs.zokogames.com/requirements/technical) for details.

## 4. Preview

Open the **Preview and QA** tab of the game in the console to run the exact build in the portal frame with ads on, and tick through the checklist. See [testing](https://docs.zokogames.com/getting-started/local-testing).

## 5. Submit

The **Submit for review** button enables when every required checklist item is done (each person can send at most 10 submissions an hour; the page says how long to wait if you hit that). Optional items (tags, preview videos) show as **Optional**; videos are needed for full launch. Once submitted, the game is **locked for editing** and builds cannot change. While the status is **Submitted** (waiting for a reviewer) you can press **Withdraw submission** to edit again. Once a reviewer has started (**In review**), the game stays locked until the decision.

## What reviewers check

A reviewer plays the game and works through a checklist that adapts to your game's settings. It covers:

- **Technical.** Loads in the portal frame without blocking console errors; initial load reasonable on a mid-range phone (about 10 seconds on 4G); within the size budget; fullscreen and resize work with no layout break at 360 px wide; touch controls on mobile; no unapproved external requests, popups or redirects; audio starts only after interaction and can be muted.
- **Gameplay.** A new player can start playing within 30 seconds; controls match the description and are explained in game; no soft-locks in the first 10 minutes; the game pauses when focus is lost and during ad breaks.
- **Ads** (when ads apply). Ad breaks use the SDK and never block gameplay start; rewarded ads grant the reward only after a finished ad; banners use approved sizes and do not cover controls; no third-party ad code.
- **Accounts and saves** (when the data module or a leaderboard is used). Playable as a guest; progress saves and restores through the data module; leaderboard scores submit and display.
- **Multiplayer** (when enabled). Lobby, invites and join links work; a player leaving does not freeze the room; minimum and maximum lobby size match the listing.
- **Quality and presentation.** Original work or properly licensed; content suitable for the declared audience; covers and videos meet the specs; title, descriptions and controls are accurate and free of spam; overall quality competitive for its category.

The full matrix is on the [requirements checklist](https://docs.zokogames.com/requirements/checklist).

## The decision

You get an email and a console notification with one of three outcomes:

- **Approved.** The game moves to basic launch.
- **Changes requested.** The reasons are listed (for example: game does not run, performance, ad integration, external links, unclear controls, quality, artwork, listing information, audience flag). A reason that one editor step can fix shows a link to that step (for example **Fix it on the Artwork step**). Fix them, upload a new build if needed and submit again.
  Each check the reviewer failed comes with **How to fix**, **Check it yourself** (usually a step in the game's **Preview and QA** tab or on the **Build** step; on a very long list one or both may be left out, never the link) and a link to the exact section of the requirements; the reviewer's own note is shown in full, paragraphs kept.
- **Rejected.** Some reasons are fixable; others are final: copyright or brand misuse, a copy of another game, inappropriate content, or unsafe code. Each reason in the history is marked **Final** when it is one of those. Editing the game does not remove a final reason; if you think the decision is wrong, use **Ask Support about this game** and name the reason. A reason that is not final can be fixed: edit the game and submit again.

**Submitting again.** A resubmission is reviewed from the start: a reviewer plays the whole game and goes through the full checklist again, not only the checks that failed. Say in the note what you changed. Your earlier submissions and decisions stay in the **Review history**, and a reason the reviewer names again is marked **Named in an earlier decision too**. While the new submission waits the listing, builds and artwork are locked, so what the reviewer sees is what you submitted. Not sure what a point means? **Ask Support about this game** opens a request with the game already chosen.

The **Review history** on the submit step and at the foot of the game's Overview tab lists every submission, newest first, with its state (**Submitted**, **In review**, **Approved**, **Changes requested**, **Rejected** or **Withdrawn**), the date of the decision, the reasons and the reviewer's own words, and the status changes in between. When our team ends Basic Launch or unpublishes a game, the reason is shown there too; when Basic Launch ends on its own because the results were below the bar, the Overview tab says so in plain words. The Overview tab also repeats the latest decision at the top while the game is waiting for you. A game sent back or rejected in Full QA goes offline; when you resubmit it, it joins the review queue again and starts again in Basic Launch once approved.

## After approval

Use the **Builds and updates** tab of the game for new builds. During [basic launch](https://docs.zokogames.com/guides/basic-launch-metrics) pressing **Activate** on a new build puts it live right away. In full launch the button is **Send for review**: the update waits for a reviewer before it replaces the live build, the current build stays live until then, and you can withdraw the update while nobody has picked it up. To change artwork on a live game, stage the new files and submit them as one artwork review, or compare them first with an [artwork experiment](https://docs.zokogames.com/guides/artwork-experiments).

**Text and settings on a live game.** Changes on **Basics** and **Technical** autosave and reach the public game page at once, without a review; search and lists follow within a few minutes. Write a long rewrite elsewhere and paste it in when it is ready. Renaming a live game does not move its page: the URL slug cannot change once a build is uploaded or the game is submitted. On a live game only a studio admin or owner can change the kids setting, embedding, allowed sites, device switches, pop-ups or the game address (the Team and roles guide lists who can do what).

**Finding your game.** The **View on ZokoGames** button at the top of every game tab opens the public page. During basic launch the game page, site search and your studio page show the game to everyone. Category, tag and New lists show every full-launch game first and then only a few basic-launch games, so your game may not appear in them yet, and the Hot and Updated rows on the home page carry full-launch games only. Share the game page link to bring your own players.

**Other languages.** You write the listing in English. On the other language versions of the site players see your English text unless staff have added a translation for that language, and only the English page and fully translated languages are listed in search engines. The **Basics** step shows which languages are translated and when they were last updated. Translations are not edited in the console and an English edit does not change them: tell support when your English text changes or a translation needs a fix.

## Next steps

- [Launch stages and KPIs](https://docs.zokogames.com/getting-started/launch-stages)
- [Basic launch metrics explained](https://docs.zokogames.com/guides/basic-launch-metrics)

---

Source: https://docs.zokogames.com/getting-started/launch-stages

# Launch stages and KPIs

Every game follows the same path. Knowing what each stage is for tells you what to build next.

| Stage | Ads and revenue | Purpose | How you leave it |
| --- | --- | --- | --- |
| **Draft** | None | Private to your team. Build, upload, fill in the listing. | You submit. |
| **Submitted**, then **In review** | None | **Submitted** waits for a reviewer and can be withdrawn. **In review** means a reviewer is playing the build against the [requirements](https://docs.zokogames.com/requirements/overview). The game is locked for editing until the decision. | Approved, **Changes requested** (fix and resubmit with a note on what changed) or **Rejected**. |
| **Basic Launch** | Ads off, no revenue | Measure whether players like the game. | The window is complete after 7 days and 500 plays, or after 21 days whatever the plays. A reviewer then promotes it to Full QA, extends it or ends it. |
| **Full QA** | Ads off until it passes | A second review of the full SDK integration. The game stays playable; its listing and builds are locked until the decision. | Approved for Full Launch. **Changes requested** or a rejection takes the game offline until you fix it and submit it again (a rejection leaves it **Unpublished**). A reviewer can also send it back to Basic Launch, where it stays playable. |
| **Full Launch** | Ads on, revenue share accrues | Growth, artwork experiments, updates. | Ongoing. |

The console always shows the current stage on the game's launch card.

## How much traffic a basic launch gets

A basic-launch game is live and playable by direct link and in search; those are not limited. In the discovery listings it gets a limited share. It never appears in the Hot or Updated rows. In the New row and in category, tag and other listings, listings show all full-launch games first, in the requested sort, and then at most a fixed number of basic-launch positions across the **whole** listing, in the same sort order. The default is **4** positions; the portal team can change it (0 hides basic-launch games from listings). That is a deliberately small, steady sample: enough to measure the KPIs below, not the exposure of a proven game. Moving to full launch removes the limit.

## When the window ends

The window is over after **7 days and 500 plays**, or after **21 days** regardless of plays. These are the defaults; the portal team can adjust them. When the window is due, the game is flagged for a reviewer, who promotes it to full QA, extends it or ends it. The game stays live meanwhile, the launch card says the window is complete, and the decision arrives as a console notification. An extension starts a new window from that day, so the card's days-live count starts again. By default nothing ends automatically; automatic ending is a switch that is off unless the portal team turns it on, and even then it applies only when the score recommends ending and there are at least 200 plays. The console shows the values that apply to your game. Until the window is complete, the launch card names the earliest and the latest moment it can end and how many plays are still missing.

## Skipping basic launch

For multiplayer or invite-only titles, where a thin player pool makes the sample unrepresentative, an administrator can move a game from In review straight to Full QA. It needs a written reason of at least 10 characters, which is recorded in the audit log. Reviewers cannot do this, and developers cannot request it from the console; mention the need in your submission notes or contact [support](https://docs.zokogames.com/business/support).

## KPIs during basic launch

Four numbers are measured automatically. Plays and play time come from your `gameplayStart` and `gameplayStop` calls, so integrate them before basic launch.

| KPI | Target for full marks | Weight |
| --- | --- | --- |
| Average play time per session | 10 minutes or more | 30 % |
| Day-1 retention | 15 % or more | 30 % |
| Conversion (views that last at least a minute) | 80 % or more | 20 % |
| Click-through rate (tile seen to game opened, versus your category) | 50th percentile or better | 20 % |

Playtime is the playtime of players who allow analytics divided by their plays, conversion is sessions of at least a minute divided by views, and day-1 retention only counts days that already have a next day. CTR is ranked as a percentile against other games in your category over the last 30 days. These numbers are measured over the basic-launch stage only; see the [metrics reference](https://docs.zokogames.com/guides/analytics-metrics) for exact definitions and the effect of player consent.

Scoring, in short: playtime 10 minutes or more earns full points (5 minutes or more, half); day-1 retention of 15 % or more is full, 10 % or more 0.75, 5 % or more 0.4; conversion of 80 % or more is full (60 % or more, half); CTR at the 50th percentile or better is full (25th, half). The weighted score is 0 to 1. Advice is *promote* at 0.75 or more with playtime and retention both above zero, *end* below 0.4, and *extend* otherwise. Under 200 plays the advice is always *extend*.

The score is advice, not a decision. The details, partial credit and tips for each number are on [basic launch metrics explained](https://docs.zokogames.com/guides/basic-launch-metrics).

## What changes at full launch

- Midgame and rewarded ads and banners switch on, served only through the SDK. See [advertisement rules](https://docs.zokogames.com/requirements/advertisements).
- The SDK integration becomes required: `gameplayStart` and `gameplayStop`, ads at natural breaks, and the data, user and leaderboard modules where they apply.
- Two preview videos are needed in addition to the three covers.
- Updates wait for a reviewer. See [updating a live game](https://docs.zokogames.com/getting-started/updating-a-game).
- Your revenue share applies and statements are prepared monthly. No ad network is connected yet, so no ad revenue is earned today; see [feature status](https://docs.zokogames.com/business/faq#feature-status), [revenue share](https://docs.zokogames.com/business/revenue-share) and [payouts](https://docs.zokogames.com/business/payouts).

## KPIs to watch after full launch

The developer console shows revenue and traffic by day, game and country. These are the numbers that usually decide whether a game grows:

| Number | Why it matters |
| --- | --- |
| Plays and unique players | Reach. Driven by cover, title and category. |
| Average play time and retention | Whether players come back. |
| Ad impressions per session | Whether your ad breaks fit natural pauses. |
| Revenue per thousand plays | Combined effect of players, geography, devices and ad pacing. |

Compare against games in your own category and split by device. Use [artwork experiments](https://docs.zokogames.com/guides/artwork-experiments) to lift click-through and the [monetisation guide](https://docs.zokogames.com/guides/ad-monetisation) to tune ad pacing.

## Preparing early

You can do the full-launch work while basic launch runs: add `gameplayStop`, ad breaks, cloud save and the second video. The [requirements checklist](https://docs.zokogames.com/requirements/checklist) lists everything in one place.

## Next steps

- [Basic launch metrics explained](https://docs.zokogames.com/guides/basic-launch-metrics)
- [Updating a live game](https://docs.zokogames.com/getting-started/updating-a-game)
- [Revenue share overview](https://docs.zokogames.com/business/revenue-share)

---

Source: https://docs.zokogames.com/getting-started/updating-a-game

# Updating a live game

Games are never frozen. You can upload a new build, change the listing text or swap artwork at any time. What happens next depends on the stage your game is in.

| Stage | New build | Artwork and listing |
| --- | --- | --- |
| Before launch (draft, changes requested, rejected, unpublished) | Each new valid build becomes active at once, and the **Review and submit** step names the version you will submit. To go back to an older one, press **Activate** on it (the button only reads **Roll back to this** once players have a build to be taken back from). | Edit freely. |
| Submitted, in review or full QA | Locked. While the status is **Submitted** you can withdraw the submission to edit, then submit again. Once a reviewer has started, wait for the decision. | Locked. |
| Basic launch | Stored after it passes the validator; players keep the current build until you press **Activate**, which switches every player who opens the game from then on, with no review. A build the safety scan flags as **Needs review** is the exception: its button is **Send for review** and it goes to a moderator first (the safety scan section of build validation explains why). | Listing text is saved as you type and shows on the game page at once, with no review. Artwork is staged and reviewed; see below. |
| Full launch | Stored after it passes the validator; **Send for review** sends it to a reviewer, and the current build stays live until it is approved. You can withdraw it while it waits. | Listing text shows at once, with no review. Artwork is staged and reviewed. |

## Shipping a new build

1. Make the change locally and test it in [local mode and the Preview tool](https://docs.zokogames.com/getting-started/local-testing).
2. In the developer console open the game, go to the **Builds and updates** tab and upload the new zip. The validator runs exactly as for the first upload and shows every problem with the offending path.
3. Run **Preview and QA** on the new build (ads are on there) and tick through the checklist.
4. Switch to the new build in the **Version history** list (the console numbers builds v1, v2 and so on). In basic launch the button is **Activate** and every player gets the build immediately. For a build the safety scan flagged for a moderator the button is **Send for review** instead, even in basic launch, and players keep the current build until a moderator approves it. In full launch the button is **Send for review**: it queues an update, and the dialog has a **Note to the reviewer** field; say what changed and where to see it. Short, specific notes get faster decisions. Only one update can wait for review at a time, and only builds that passed validation can be switched to.

Uploading and switching builds are console actions: the [developer API](https://docs.zokogames.com/guides/developer-api) is read-only and cannot upload. A pipeline can still follow the result: the [build check script](https://docs.zokogames.com/guides/developer-api#check-a-build-from-your-pipeline) waits until a build is live, failed its checks or is waiting for review, and the `build.published` and `build.activated` [webhooks](https://docs.zokogames.com/guides/webhooks) tell your server without polling.

While an update still waits for a reviewer (the build shows **In review** and a **Withdraw** button), you can withdraw it: players keep the current build and you can send this or another build at once. Withdrawing a build the safety scan flagged does not clear it: sent again, it still goes to a moderator. Once a reviewer has started it can no longer be withdrawn, so wait for the decision. A build that waits for review cannot be deleted.

A waiting update blocks only a second update. While it waits you can still edit the listing text (it shows at once), stage and submit artwork (a separate review that does not wait for the update), edit release notes and upload more builds; they are stored and wait their turn. The console and the notices name builds by number: the build marked **Live for players** is the live one, the one marked **In review** is the update waiting, and every other row is stored.

## A game on your own server

A game with **Hosting** set to your own server has no builds in the console: you update it by deploying to your server, and players get the new version the next time they load the game. The portal does not scan or review those deploys, so test them yourself before you ship. The game's address can be changed by a studio admin or owner while the game is in basic launch, and it takes effect at once. In full launch the address cannot be changed in the console: the console refuses it with a message to contact [support](https://docs.zokogames.com/business/support), and the portal team reviews the new address first. Listing text and artwork follow the same rules as for any other game (see the table above).

## Release notes

Each build has its own release notes: type them in the upload form (you can do it while the zip uploads) or later with **Add notes** or **Edit notes** in the version history. Reviewers see them, and players read them in the **Updates** tab of the game page, which lists the live build and up to five builds with lower numbers, newest first. Builds that are not live yet and builds that failed validation are not shown there, so after a roll back the notes of the build you left disappear from the page until it is live again. Write the notes for players; put anything meant only for the reviewer in the note to the reviewer instead. Formatting rules are on [text formatting](https://docs.zokogames.com/requirements/text-formatting).

> [!TIP]
> Keep the `index.html` path stable and every asset path relative. A build that only changes a few files still needs to be a complete zip.

## What a reviewer looks at in an update

Every new build goes through the same automatic validator and safety scan as the first upload. What happens after that depends on the stage, not on what the build changes: in basic launch an update goes live when you activate it, with no person reviewing it first; in full launch every update, a rollback included, is reviewed by a person before players get it. A review of an update focuses on what changed, but a rule break anywhere in the build can still lead to a request for changes or, in serious cases, removal. An update that was not approved never reaches players: the current build stays live, and the decision and the reviewer's notes are in the **Review history** on the game's **Overview** tab. Re-read the [requirements checklist](https://docs.zokogames.com/requirements/checklist) when you add ads, accounts, multiplayer or external links.

## Saved data across builds

Players keep their cloud save when you upload a new build. Plan for old saves meeting new code:

- Store a `schema` number in your save (a key such as `saveSchema`) and migrate on load.
- Ignore keys you no longer use instead of deleting them.
- Never rename a key without reading the old one first.
- Expect saves to meet older code too: after a roll back (see Rolling back below) the build players get may read a save that a newer build wrote.

The portal does not compare save formats between builds and does not warn when you switch, so test an upgrade and a roll back with a real save in Preview first.

See [cloud saves in practice](https://docs.zokogames.com/guides/cloud-saves).

## Changing artwork

Covers and preview videos are part of the listing and go through their own review. Stage the new files, submit them as one artwork change, or compare options first with an [artwork experiment](https://docs.zokogames.com/guides/artwork-experiments). Specs are on [covers and videos](https://docs.zokogames.com/requirements/covers).

## Rolling back

If an update breaks something, open the **Builds and updates** tab and press **Roll back to this** on the previous build (every build stays stored until you delete it). In basic launch every player who opens the game from then on gets that build, with no review (players already in a session keep the build they loaded until they reload), unless the safety scan flagged that build and no moderator has approved it yet: then the button reads **Send rollback for review** and a moderator checks it first. In full launch the button reads **Send rollback for review**: it queues an update, so say in the note that it is a rollback; if another update is already waiting, withdraw it first. Deleting a build removes its files for good, and neither the active build nor a build waiting for review can be deleted. Do not delete the build you rolled back from right away: a player who still has it open can fail to load files it has not fetched yet. Saves written by the newer build will meet the older code; the portal does not check that (see Saved data across builds above). Test updates in the Preview tool before you switch so you rarely need this.

## Unpublishing a game

A studio admin or owner can take a game in basic or full launch offline from the **Overview** tab: in **Unpublish this game** press **Unpublish**, type the game's URL slug, optionally give a reason (kept in the audit trail) and confirm with **Unpublish game**. Players can no longer find or play the game and its public page stops working; builds, covers and stats stay. Unpublishing needs a passkey or an authenticator app on your account: you confirm with it when you press **Unpublish game** (a confirmation in the last 5 minutes counts). Set one up first under **Settings → Account** of your player account on www.zokogames.com (the account menu there, not the studio's **Settings** page in the console) if you have neither, so you are not held up when you need to take the game down fast. While the game is unpublished it is edited like a draft: each new valid build becomes active at once.

To bring it back, update the game if needed and submit it for review again: a reviewer must approve it before it goes live, and an approved resubmission starts again in basic launch. If the game had reached full launch, contact [support](https://docs.zokogames.com/business/support) instead of resubmitting: the portal team can restore it to full launch. Only a game in basic or full launch can be unpublished; for a game in full QA, contact support.

## Deleting a game

Only a game in **Draft** that was never public can be deleted, from the **Overview** tab (studio admin or owner, typed slug to confirm). It removes the game with its builds, covers, leaderboards, achievements, cloud saves and stats for good. A game that has been public cannot be deleted; unpublish it instead. A game with **Changes requested** or **Rejected** keeps its review record and cannot be deleted either. To delete a game that is **Submitted**, withdraw the submission first.

## Telling players

Your release notes appear in the game page's **Updates** tab once the build is live (see above). The portal does not message players about an update, so put a short "what is new" line in the game or on your community page as well.

## Next steps

- [Payouts](https://docs.zokogames.com/business/payouts)
- [Statements, PDFs and sandbox payouts](https://docs.zokogames.com/guides/statements-and-pdf)

---

Source: https://docs.zokogames.com/getting-started/environments

# Environments and query overrides

`SDK.environment` is a string you can read after `init()` resolves. It is `"disabled"` until then.

| Value | Meaning |
| --- | --- |
| `zokogames` | The game is inside the portal's iframe (the live site, the Preview tool or the build preview in the console). All features are real. |
| `local` | The in-page mock described in [local testing](https://docs.zokogames.com/getting-started/local-testing). |
| `disabled` | Neither of the above. Every SDK module member (methods reject, properties throw) fails with `sdkDisabled`. Only `init()`, `environment` and `isQaTool` keep working. You see it, for example, when you open your build's own address directly or frame the game on your own site. |

## How the SDK decides

1. If the page is the top-level window (not in an iframe), it is `local` when the host is `localhost`, `127.0.0.1`, `[::1]` or `*.localhost`, or when the URL has `useLocalSdk=true`. Otherwise it is `disabled`.
2. If the page is in an iframe, the SDK sends a handshake to the parent and waits up to 1.5 seconds for the portal to answer. When the parent page is the portal itself (`https` on `zokogames.com`), it waits up to 15 seconds. A valid answer gives `zokogames`. Only an answer from a ZokoGames page (`https` on `zokogames.com` or one of its subdomains, except the game hosts `g-<slug>` and the preview runner `preview-run`), a local host (only while the game itself runs on a local host) or the game's own origin counts: an answer from any other site is ignored, so a site that frames your game cannot pose as the portal. If nothing answers, the SDK falls back to `local` when local mode is allowed by the rules above, and to `disabled` otherwise.

The practical consequence: a game uploaded to a random web host does not get a mock unless you add `?useLocalSdk=true`, which is deliberate. A game that ships its own copy of itself elsewhere keeps working, it just does not talk to the portal.

```js
await SDK.init();
switch (SDK.environment) {
  case "zokogames": break;                  // production behaviour
  case "local": showDevBadge(); break;      // your machine
  case "disabled": hidePortalFeatures(); break;
}
```

## Query parameters the SDK reads

| Parameter | Where it applies | Purpose |
| --- | --- | --- |
| `useLocalSdk=true` | Any host | Allows local mode off `localhost`. |
| `sdk_debug=true` | Everywhere | Logs every call. Turn it on to diagnose a problem in the preview tool. |
| `qaTool=true` | Everywhere | Makes `SDK.isQaTool` `true`. |
| `ad_response=...` | Local mode only | Forces ad requests to fail with the given code. |
| Mock switches (`disableChat`, `muteAudio`, `user_response` and so on) | Local mode only | Listed in [local testing](https://docs.zokogames.com/getting-started/local-testing). |

In the portal these parameters are ignored for anything except logging. Players cannot change their identity or ad behaviour by editing the URL.

## Initialisation errors

`init()` itself never rejects. Failures show up as `disabled`. After that:

- Calling a method before `init()` resolved rejects (or throws, for synchronous members) with `sdkNotInitialized`.
- Calling it while disabled gives `sdkDisabled`.

See [errors](https://docs.zokogames.com/sdk/introduction#errors) for the full list.

## Next steps

- [Testing with local mode and the Preview tool](https://docs.zokogames.com/getting-started/local-testing)
- [Introduction, init and errors](https://docs.zokogames.com/sdk/introduction)

---

Source: https://docs.zokogames.com/getting-started/glossary

# Glossary

Words are grouped by topic and listed alphabetically inside each group. The docs use each word in exactly one sense.

## People and accounts

**Developer.** A person who works on games for a studio. Role names in the console are member, admin and owner.

**Studio.** The team account that owns games, builds, payouts and statements. A person can belong to several studios. Created at `/developer/onboarding`; see [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

**Player, guest, signed-in player.** A player is anyone playing. A guest has no account; a signed-in player does. Guests must always be able to play; saves for guests stay in the browser until sign-in. See [accounts requirements](https://docs.zokogames.com/requirements/accounts) and [data](https://docs.zokogames.com/sdk/data).

**Ad-free member.** A player with a membership or pass that removes midgame ads and banners. Rewarded ads still play, because the player asks for them. See [ads](https://docs.zokogames.com/sdk/ads). The membership is planned, so no player is ad-free yet.

## Files and testing

**Build.** The set of files you upload as a zip, with `index.html` at its root. A game can have several builds; one is active, and you switch with **Activate** or **Roll back to this** in the console. The console numbers builds (v1, v2), but in these docs "version" means only an SDK version (for example 1.2.0). See [updating a game](https://docs.zokogames.com/getting-started/updating-a-game).

**Validator, finding.** The automatic check that runs on every upload. Each problem it reports is a finding with a code. See [build validation](https://docs.zokogames.com/requirements/build-validation).

**Game origin.** The web address a build is served from, `https://g-<name>.zokogames.com/<build id>/`. Every game has its own origin, so one game cannot read another game's storage.

**Portal frame.** The page on zokogames.com that holds your game in a sandboxed iframe and answers its SDK calls (ads, saves, users, settings). See [requirements: technical](https://docs.zokogames.com/requirements/technical).

**Local mode.** The SDK's in-page mock, used on `localhost` or with `?useLocalSdk=true`. See [testing](https://docs.zokogames.com/getting-started/local-testing).

**Environment.** What `SDK.environment` returns: `zokogames` (inside the portal frame), `local` (the mock) or `disabled` (neither). See [environments](https://docs.zokogames.com/getting-started/environments).

**Preview tool.** The public page at [`/preview`](https://www.zokogames.com/preview) that frames any address you type, such as `localhost`, and ticks a requirements checklist. **Build preview** is the same idea inside the console for an uploaded build. See [testing](https://docs.zokogames.com/getting-started/local-testing).

**Starter kit.** A small working game wired to the SDK. See [starter kits](https://docs.zokogames.com/getting-started/starter-kits).

## The SDK

**SDK.** The script at `https://sdk.zokogames.com/zokogames-sdk-v1.js`. It defines `window.ZokoGames.SDK`, which your game uses to talk to the portal. See [SDK introduction](https://docs.zokogames.com/sdk/introduction).

**Module.** A group of SDK members: `ad`, `banner`, `game`, `user`, `data`, `store`, `analytics` and `achievements`.

**`gameplayStart` / `gameplayStop`.** Calls that say real play has begun or paused. They measure playtime and decide when ad breaks make sense. See [game module](https://docs.zokogames.com/sdk/game).

**`loadingStart` / `loadingStop`.** Calls that bracket your own loading, so load time is not counted as play time.

**`happytime`.** A call that marks a moment of success, such as a new best score. Use it sparingly.

**Midgame ad.** A video ad at a natural break between rounds. **Rewarded ad:** a video ad the player chooses to watch for a reward, granted only after `adFinished`. **Banner:** a fixed-size ad on a menu or results screen. See [ads](https://docs.zokogames.com/sdk/ads), [banners](https://docs.zokogames.com/sdk/banners) and the [advertisement rules](https://docs.zokogames.com/requirements/advertisements).

**Data module, cloud save.** `SDK.data`, a `localStorage`-shaped store of up to 1,048,576 bytes that follows a signed-in player across devices. See [data](https://docs.zokogames.com/sdk/data).

**Leaderboard board key.** The key you generate in the console to encrypt scores before `submitScore`. See [leaderboards](https://docs.zokogames.com/sdk/leaderboards).

**Token.** A signed proof of who the player is, from `SDK.user.getUserToken()`, that your own server can verify. See [user](https://docs.zokogames.com/sdk/user).

**Error code.** Every SDK failure is a plain `{ code, message }` object. See [errors](https://docs.zokogames.com/sdk/introduction#errors).

## Launch and money

**Launch stage.** Where a game stands on its way to players: Draft, Submitted, In review, Basic Launch, Full QA or Full Launch. The console shows it on the game's launch card. See [launch stages](https://docs.zokogames.com/getting-started/launch-stages).

**Basic launch.** The first live stage: the game is public, ads are off, and the portal measures play time, retention, conversion and click-through. See [launch stages](https://docs.zokogames.com/getting-started/launch-stages) and [basic launch metrics](https://docs.zokogames.com/guides/basic-launch-metrics).

**Full QA.** The second review, focused on the full SDK integration.

**Full launch.** The stage where ads run and revenue share accrues. See [revenue share](https://docs.zokogames.com/business/revenue-share).

**Revenue share.** The part of ad revenue paid to the studio. **Statement:** the per-period summary of it. **Payout profile:** the legal and payment details of the studio. See [payouts](https://docs.zokogames.com/business/payouts).

**Webhook.** A message the portal posts to your server when something happens, such as a review outcome or a published build. See [webhooks](https://docs.zokogames.com/guides/webhooks).

**Sandbox (iframe).** The browser restriction on your game's frame: no popups unless approved, no access to the parent page. See [technical requirements](https://docs.zokogames.com/requirements/technical).

**Sandbox (store, payouts).** A mode with no real money: in-game store purchases made in sandbox mode grant items without a charge, and a studio whose payout account is still the built-in test provider (a `stub_` reference) gets statements watermarked SANDBOX that are not payable. Production payouts are made by hand by the portal team. See [purchases](https://docs.zokogames.com/sdk/purchases) and [payouts](https://docs.zokogames.com/business/payouts).

## Next steps

- [Introduction](https://docs.zokogames.com/getting-started/introduction)
- [FAQ](https://docs.zokogames.com/business/faq)

---

Source: https://docs.zokogames.com/getting-started/for-ai-agents

# For AI coding agents

This page is written for a coding agent that was handed a game and told to make it run on ZokoGames, and for the person who supervises it. Everything an agent needs to integrate, test and package the game is public Markdown. Only the console steps (a signed-in studio account, the upload, the submit button) need a human.

## What to fetch

All of these are plain text, English only, with no JavaScript needed. Prefer the smallest file that answers the question.

| URL | What it is | Size |
| --- | --- | --- |
| `https://docs.zokogames.com/llms.txt` | An index of every documentation page with a one-line description and a link to its Markdown. Start here. | A few thousand words |
| `https://docs.zokogames.com/<section>/<page>.md` | One page as Markdown: add `.md` to the page address, for example `https://docs.zokogames.com/sdk/ads.md`. Links inside are absolute. | One page |
| `https://docs.zokogames.com/llms-full.txt` | Every English page in one file, each after a `Source:` line. | About 1 MB. Too large for most context windows; use it for search, not for reading in full. |
| `https://sdk.zokogames.com/zokogames-sdk-v1.js` | The SDK script your game loads. Do not copy it into the build. | One script |
| [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json) | The engine plugins with version, size and SHA-256. | Small |
| [Starter kits](https://docs.zokogames.com/getting-started/starter-kits) | Five runnable templates already wired to the SDK. | Zip files |

Code samples on a page may use a `:::tabs` block with `== Label` lines to group alternatives; each tab is a normal Markdown body. A `> [!NOTE]` or `> [!IMPORTANT]` quote is a callout.

Which pages to read for which task:

| Task | Fetch |
| --- | --- |
| Add the SDK to a plain JavaScript or Phaser game | `getting-started/one-file-example.md`, `sdk/introduction.md`, `sdk/game.md`, `sdk/ads.md`, `sdk/data.md` |
| Use an engine | `engines/<unity, godot, construct-3, gamemaker, cocos, defold, phaser>.md`, then `engines/overview.md` |
| Port a game that already runs on other web portals | `porting/overview.md`, then `porting/<unity, godot, construct-3, gamemaker, defold, cocos, phaser-html5>.md` for the engine, and `guides/migrating.md` for the call-by-call mapping |
| Make the upload pass | `requirements/build-validation.md`, `requirements/limits.md` |
| Fix an error message | `guides/troubleshooting.md` |
| Know what reviewers check | `requirements/checklist.md`, `requirements/quality.md` |

## The minimal integration, with a check per step

Do the steps in order. Each has a check an agent can run without a human.

1. **Load the SDK.** Put `<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>` in the `<head>` of `index.html`, before your own code. Check: `grep -c "zokogames-sdk-v1.js" index.html` prints at least `1`. Keep every asset path relative (`./game.js`, not `/game.js`): `grep -nE '(src|href)="/[^/]' index.html` prints nothing.
2. **Wrap every SDK call.** The SDK can be missing, disabled or slow, and any call can reject with a plain `{ code, message }` object. The game must run in all cases. A `try`/`catch` around each `await` or a `.catch()` on each promise is enough. `SDK.data` is the exception: it is synchronous and throws.
3. **Call `init()` first.** `await window.ZokoGames.SDK.init()`. It never rejects. Afterwards read `SDK.environment`: `"zokogames"` in the portal, `"local"` on your machine, `"disabled"` anywhere else.
4. **Send the loading and gameplay signals.** `loadingStart()` when loading begins and `loadingStop()` when the first screen is playable. `gameplayStart()` when player input becomes live, `gameplayStop()` at every pause, menu, game over, and before any ad.
5. **Add one rewarded ad with a fallback.** `SDK.ad.requestAd("rewarded", { adStarted, adFinished, adError })`. Pause and mute in `adStarted`, grant the reward only in `adFinished`, and carry on in `adError`. A request can fail with `adsDisabled`, `unfilled`, `adblock`, `adCooldown`, `timeout` or `other`, and every one must leave the game playable.
6. **Save with `SDK.data`.** `getItem`, `setItem` and `removeItem` are synchronous, use strings only, and share a 1 MiB budget.
7. **Respect the portal's settings.** Read `SDK.game.settings.muteAudio` at start and listen with `addSettingsChangeListener`.
8. **Run it locally.** Serve the folder over HTTP on `localhost` (for example `python3 -m http.server 8080`) and open `http://localhost:8080/?sdk_debug=true`. Check in the page's console: `ZokoGames.SDK.environment` is `"local"`, and the log shows `[ZokoGames SDK] call game.loadingStop` and, after the first interaction, `call game.gameplayStart`. A headless browser works; use a `localhost` address, because the SDK is disabled on any other host unless the URL has `?useLocalSdk=true`.
9. **Force the failure paths.** Reload with `&ad_response=unfilled`, then `&ad_response=adsDisabled`, then `&user_response=logged_out`. The game must stay playable each time. All switches are in [testing](https://docs.zokogames.com/getting-started/local-testing).
10. **Zip.** `cd <build output folder> && zip -r ../game.zip .` so `index.html` is at the root of the archive. Zip the exported build (`dist`, `build`, the engine's web export), never the project root: source files, `node_modules` and `.git` would be packed too, and files whose names start with a dot are never served. Check: `unzip -l ../game.zip` lists `index.html` with nothing in front of it.

A complete game that does all of this is on [Copy-paste example: one index.html](https://docs.zokogames.com/getting-started/one-file-example). The same steps for an engine are on that engine's page.

## Rules the validator and reviewers enforce

A build that breaks one of these is rejected on upload or sent back in review. The numbers are all in [limits at a glance](https://docs.zokogames.com/requirements/limits).

- `index.html` at the zip root, or inside exactly one top-level folder.
- At most 1,500 files and 250 MB unpacked; an estimated first download of at most 50 MB (aim for 20 MB).
- No absolute paths, `..`, backslashes, symbolic links, encrypted or duplicate entries.
- No server-side or executable files such as `.php`, `.exe`, `.sh`, `.py` or `.jar`; the host serves static files only.
- No other portal's SDK, no ad network code, no threaded WebAssembly (`SharedArrayBuffer` is unavailable).
- Bundle fonts, libraries and assets into the zip: external hosts are warned about (`origin_*`), can be blocked, and rule out offline play; ad networks are never allowed.
- The first `gameplayStart` within 20 seconds of load.
- Sound starts only after a player gesture and obeys `muteAudio`.

Each rejection has a code listed with its fix in [build validation](https://docs.zokogames.com/requirements/build-validation) and by its exact message in [troubleshooting](https://docs.zokogames.com/guides/troubleshooting).

## What needs a human

| Step | Why |
| --- | --- |
| Create the studio and the game draft | It needs a signed-in player account and acceptance of the [developer terms](https://docs.zokogames.com/business/developer-terms). |
| Upload the zip and press **Submit for review** | These are console actions on a signed-in session. The [developer API](https://docs.zokogames.com/guides/developer-api) is read-only: it can list builds and show their state once a human has uploaded one. |
| Cover images and the description | They must be made for the game; see [covers](https://docs.zokogames.com/requirements/covers). |

An agent can do everything else, and can prepare the listing text and the covers for the human to upload. The human then follows steps 6 and 7 of [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start#6-upload-and-read-the-report-5-minutes).

## Next steps

- [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start)
- [SDK introduction](https://docs.zokogames.com/sdk/introduction)
- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting)

---

Source: https://docs.zokogames.com/requirements/overview

# Requirements overview

The same rules apply to every game, but not all of them apply at every stage. Basic launch is a measurement stage and asks for little. Full launch is where ads run, so it asks for a complete integration and a polished experience. Every rule on the pages below says why it exists and how to check it before you submit. Terms such as **build**, **basic launch**, **full launch** and **studio** are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

| Area | Basic launch | Full launch |
| --- | --- | --- |
| Build size | 250 MB unpacked, 1,500 files. | Same limits. |
| Initial download | Estimated at most 50 MB; a warning above 20 MB (the mobile target). | Same, and the game reaches gameplay quickly. |
| SDK | The upload does not require it (the validator only warns when the script is missing), but the basic-launch numbers are measured from `gameplayStart`, so call `init` and `gameplayStart`; that is enough. | Required: `gameplayStart` and `gameplayStop`, ads, and the data, user and leaderboard modules where they apply. |
| Ads | None. No revenue. | Midgame and rewarded ads through the SDK, optional banners. |
| Accounts and progress | Progress saved in whatever way works. | Cloud save through the data module or your own linked backend, see [accounts](https://docs.zokogames.com/requirements/accounts). |
| Language | English, and a declared list of supported languages. | English, with the player's `locale` honoured where you have translations. |
| Multiplayer | Lobby size supplied at upload. | Rooms, invites and chat settings integrated. |
| Covers and videos | Three covers (required to submit). | Three covers and two preview videos. |
| Review | Initial review (In review). | A second review (Full QA) before ads switch on. |
| Landing in play | A menu is acceptable. | New players reach gameplay with at most one click. |

## The pages

- [Technical requirements](https://docs.zokogames.com/requirements/technical): sizes, files, browsers, mobile, audio, scroll and key handling, paths, sitelock.
- [Gameplay requirements](https://docs.zokogames.com/requirements/gameplay): resolutions, language, age rating (required) and cross-promotion.
- [Quality guidelines](https://docs.zokogames.com/requirements/quality): what reviewers look for.
- [Advertisement rules](https://docs.zokogames.com/requirements/advertisements).
- [Account integration scenarios](https://docs.zokogames.com/requirements/accounts).
- [Multiplayer](https://docs.zokogames.com/requirements/multiplayer).
- [Game covers and preview videos](https://docs.zokogames.com/requirements/covers).
- [Requirements checklist](https://docs.zokogames.com/requirements/checklist): everything on one page to tick through.
- [Build validation reference](https://docs.zokogames.com/requirements/build-validation): every limit and every finding code in the upload report.
- [Limits at a glance](https://docs.zokogames.com/requirements/limits): every number in one table, with its unit.
- [Embedding and sitelock](https://docs.zokogames.com/requirements/embedding): the sandbox, partner-site embedding and domain locks.

## How the checks run

1. **Upload validation (automatic).** Every build is checked for file count, size, estimated initial download, unsafe paths, blocked file types and a safety scan for hidden programs and malicious scripts, and a report with a code per finding is stored with the build. See [build validation](https://docs.zokogames.com/requirements/build-validation).
2. **Your own checks before you submit.** Run the game on `localhost` in local mode, then in the [Preview tool](https://www.zokogames.com/preview) (or the **Preview and QA** tab of your game once a build has passed). Its checklist ticks from the SDK calls your game makes and flags a first `gameplayStart` later than 20 seconds. The [checklist](https://docs.zokogames.com/requirements/checklist) lists everything else.
3. **Review (a person).** A reviewer plays the game in the portal frame against these pages, with a checklist that adapts to your game's settings. A decision that is not an approval always lists the reasons, picked from a fixed list. See [how review works](https://docs.zokogames.com/requirements/quality#how-review-works) and the [typical reasons](https://docs.zokogames.com/requirements/quality#reasons-a-submission-is-sent-back-or-rejected).
4. **Basic launch, then full launch.** An approved game starts a basic launch with ads off. The window is due after at least 7 days and 500 plays, or after 21 days whatever the play count (defaults the portal team can change); a reviewer then promotes, extends or ends it using the numbers the portal collected: average play time, day-1 return, conversion and click-through rate. Promotion to full QA and full launch is always a person's decision. See [launch stages](https://docs.zokogames.com/getting-started/launch-stages) and [basic launch metrics](https://docs.zokogames.com/guides/basic-launch-metrics).

See the [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

Before you submit, work through the [launch checklist](https://docs.zokogames.com/guides/launch-checklist).

## Next steps

- [Requirements checklist](https://docs.zokogames.com/requirements/checklist)
- [Technical requirements](https://docs.zokogames.com/requirements/technical)

---

Source: https://docs.zokogames.com/requirements/checklist

# Requirements checklist

Work through this list before you press **Submit for review**. Every rule has a reason and a check on the page it links to; the validator's report codes are listed on [build validation](https://docs.zokogames.com/requirements/build-validation). Terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary). Items marked *validator* are checked automatically on upload; the rest are checked by a reviewer. Each links to the page with the detail.

## Listing (required to submit)

- [ ] Name (2 to 60 characters), category and at least one tag (recommended).
- [ ] Short description of 20 to 160 characters; description of 80 to 5,000 characters of text; controls text of 5 to 2,000 characters, accurate and explained in game (the [text formatting](https://docs.zokogames.com/requirements/text-formatting) page lists which Markdown each field supports).
- [ ] Confirmation that all visible text is available in English and that the game fits the age rating ([gameplay](https://docs.zokogames.com/requirements/gameplay#age-rating)).
- [ ] An **age rating** of 12+ or lower chosen in the Audience and distribution card (a game made for children needs all ages or 7+).
- [ ] **Languages** listed in the same card, English included.
- [ ] Embedding decided: off unless you want partner sites to show the game ([embedding](https://docs.zokogames.com/requirements/embedding#letting-other-sites-embed-your-game)).
- [ ] For multiplayer games, minimum and maximum lobby size ([multiplayer](https://docs.zokogames.com/requirements/multiplayer)).
- [ ] Three covers at the exact sizes ([covers](https://docs.zokogames.com/requirements/covers)). Two preview videos are needed for full launch.

## Build (validator)

- [ ] A zip with `index.html` at the root (or inside one top-level folder).
- [ ] At most 1,500 files and 250 MB unpacked.
- [ ] Estimated initial download at most 50 MB; under 20 MB for mobile.
- [ ] Relative paths only; no `..`, backslashes, symbolic links, encrypted or duplicate entries.
- [ ] No executable or server-side files (`.php`, `.exe`, `.sh`, `.jar`, `.py` and similar).
- [ ] No blocked safety findings: no native programs, miners, hidden `eval` of base64 data or password forms posting to other sites ([the safety scan](https://docs.zokogames.com/requirements/build-validation#the-safety-scan)). A build flagged "needs review" waits for a moderator.
- [ ] The SDK script is referenced (a warning if not; needed for full launch).
- [ ] The build report has no errors and you have read each warning ([finding codes](https://docs.zokogames.com/requirements/build-validation#findings-by-topic)).

Details: [technical requirements](https://docs.zokogames.com/requirements/technical).

## Technical (reviewer)

- [ ] Loads in the portal frame with no console errors that block play; initial load about 10 seconds or less on 4G.
- [ ] Time to the first `gameplayStart` is within 20 seconds (the [Preview tool](https://www.zokogames.com/preview) flags slower starts).
- [ ] Fullscreen and resize work; no layout break at 360 px wide; legible at every [required resolution](https://docs.zokogames.com/requirements/gameplay#resolutions).
- [ ] Touch controls with the same features, if you tick mobile; device detection through `SDK.user.systemInfo`, not touch events.
- [ ] Audio starts only after interaction, can be muted and obeys `muteAudio`.
- [ ] No threaded WebAssembly (no `SharedArrayBuffer`): export single-threaded ([technical](https://docs.zokogames.com/requirements/technical#no-threaded-webassembly)).
- [ ] No page scroll under the game; no own fullscreen button; no popups unless the game was approved for them.
- [ ] No unapproved external requests, links, redirects or third-party ad or tracking code.

## Gameplay (reviewer)

- [ ] A new player can start playing within 30 seconds; full launch needs at most one click from load to play.
- [ ] No soft-locks or unwinnable states in the first 10 minutes.
- [ ] The game pauses when focus is lost and during ad breaks; physics use a time delta.
- [ ] Returning players can continue where they stopped.

## SDK integration

- [ ] `init()` called once; the game also runs when the SDK is `disabled` ([environments](https://docs.zokogames.com/getting-started/environments)).
- [ ] Basic launch: `gameplayStart` is sent when play begins. Full launch: `gameplayStart` and `gameplayStop` in the right places, `loadingStart` / `loadingStop` recommended.
- [ ] Portal settings (`muteAudio`, `disableChat`) applied at start and on change.
- [ ] Progress is saved through the [data module](https://docs.zokogames.com/sdk/data) or your own backend linked through the [user module](https://docs.zokogames.com/requirements/accounts); guests can always play.

## Ads (full launch)

- [ ] Midgame ads only at natural breaks, never at start or mid-action; pause and mute in `adStarted`, always resume on `adFinished` and `adError`.
- [ ] Rewarded ads are optional, labelled, never shown mid-play, grant the reward only after `adFinished`, and have a no-ad alternative.
- [ ] Banners use approved sizes, sit on menu or results screens, never over controls, at most two per screen (the portal itself allows three live at once).
- [ ] No other ad network, no affiliate links, no house ads of your own.

Details: [advertisement rules](https://docs.zokogames.com/requirements/advertisements).

## Leaderboard and multiplayer (when enabled)

- [ ] Scores submit and display; the board rules in the console match your scoring ([leaderboards](https://docs.zokogames.com/sdk/leaderboards)).
- [ ] Rooms, invites and join links work; a player leaving does not freeze the room; chat is moderated and obeys `disableChat`.

## Quality and presentation (reviewer)

- [ ] Original work or properly licensed; no stolen assets, characters or brands; not a re-skin of another game.
- [ ] Content suits the declared audience; no gore, sexual content, real-money gambling or hate content.
- [ ] No promotion of other portals; no logos of other sites; store links only in the submission's metadata fields.
- [ ] No paid random rewards: nothing bought with money or coins has content decided by chance (loot boxes, card packs, spins, mystery items); no prizes of money or other real-world value; no cashing out, trading or selling items outside the game.
- [ ] Covers and videos match the game; title, descriptions and controls are accurate and free of spam.
- [ ] Looks and sounds finished: no placeholder text or debug overlays; loading shows progress; a restart is reachable without reloading.

## Made for children (when ticked)

Every line must hold; a single failure means the game is not listed in the kids area ([age rating](https://docs.zokogames.com/requirements/gameplay#age-rating)).

- [ ] Rating is all ages or 7+.
- [ ] Cartoon-level violence at most; nothing frightening; no gambling, betting, loot boxes or chance-based rewards.
- [ ] No link the player can open: no guide link, store links, social links or other sites.
- [ ] No text input, chat, names, user names, sign-in, friends, multiplayer, leaderboards or sharing.
- [ ] No real-money purchases and no "unlock" or "premium" prompts.
- [ ] No ads and no "watch an ad" buttons (ad requests fail with `adsDisabled`).
- [ ] No personal data asked for or sent anywhere; only local saves; no hosts other than the game's own.
- [ ] No pressure mechanics (return timers, streak penalties, last-chance prompts).
- [ ] Short plain instructions; an easy first level; understandable without reading much.

## Common reasons a submission is sent back

The reviewer picks from a fixed list. Fixable reasons: game does not run, performance, ad integration, external links or popups, unclear controls, quality below the bar, artwork not meeting specs, inaccurate listing, audience flag. Final reasons (the message says the game cannot be published): copyright or brand misuse, a copy of another game, inappropriate content, unsafe code. What each one means is on [quality guidelines](https://docs.zokogames.com/requirements/quality#reasons-a-submission-is-sent-back-or-rejected).

## Next steps

- [Testing checklist before you submit](https://docs.zokogames.com/getting-started/testing-checklist)
- [Build validation reference](https://docs.zokogames.com/requirements/build-validation)

---

Source: https://docs.zokogames.com/requirements/limits

# Limits at a glance

Every hard number in the requirements, in one place, each with its unit and what happens when you cross it. A value in this page is checked against the portal's code every time the documentation is built, so it cannot drift from what the validator and the console enforce. The reasons behind the rules are on the linked pages.

## The build

| Limit | Value | Over the limit | Details |
| --- | --- | --- | --- |
| Unpacked size of the build | 250 MB | Rejected (`too_large`) | [Technical requirements](https://docs.zokogames.com/requirements/technical#size-and-files) |
| Number of files | 1,500 files | Rejected (`too_many_files`) | [Build validation](https://docs.zokogames.com/requirements/build-validation) |
| Zip entries (files plus folders) | 6,500 entries | Rejected (`too_many_entries`) | [Build validation](https://docs.zokogames.com/requirements/build-validation) |
| Initial download (estimated) | 50 MB | Rejected (`initial_too_large`) | [First frame fast](https://docs.zokogames.com/guides/first-frame) |
| Initial download, mobile target | 20 MB | Warning (`mobile_initial_large`) | [First frame fast](https://docs.zokogames.com/guides/first-frame) |
| One file | 20 MB | Warning (`large_file`) | [Build validation](https://docs.zokogames.com/requirements/build-validation) |
| Expansion of one file above 1 MB | 200 to 1 | Rejected (`compression_ratio`) | [Build validation](https://docs.zokogames.com/requirements/build-validation) |
| Expansion of the whole archive | 400 to 1 | Rejected (`compression_ratio`) | [Build validation](https://docs.zokogames.com/requirements/build-validation) |
| Path length | 1,024 characters (255 per segment) | Rejected (`unsafe_path`) | [Build validation](https://docs.zokogames.com/requirements/build-validation) |
| Build that can be saved for offline play | 60 MB | Not offered for offline play | [Offline play](https://docs.zokogames.com/guides/offline-play) |

## Time

| Limit | Value | Over the limit | Details |
| --- | --- | --- | --- |
| First `gameplayStart` after the page loads | 20 seconds | The Preview check **First gameplayStart within 20 seconds** fails | [Testing checklist](https://docs.zokogames.com/getting-started/testing-checklist) |
| Time between two midgame ads | 180 seconds | `adError` with `adCooldown` (the default; the portal can set another value per game) | [Ads](https://docs.zokogames.com/sdk/ads) |
| Wait for an ad to start | 30 seconds | `adError` with `timeout` | [Ads](https://docs.zokogames.com/sdk/ads) |
| Same banner container again | 30 seconds | `bannerCooldown` | [Banners](https://docs.zokogames.com/sdk/banners) |
| Banner refreshes in one session | 60 refreshes | `maxRefreshReached` | [Banners](https://docs.zokogames.com/sdk/banners) |
| Lifetime of a user token | 3600 seconds | The token no longer verifies; ask for a new one | [User](https://docs.zokogames.com/sdk/user) |

## The listing

These are the limits of the console's **Basics**, **Technical** and **Artwork** steps. The step's counters show the same numbers.

| Field | Limit | Details |
| --- | --- | --- |
| Game name | 2 to 60 characters | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) |
| URL slug (Game address) | 3 to 48 characters: lowercase letters, numbers and single hyphens | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) |
| Short description | 20 to 160 characters | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) |
| Description | 80 to 5,000 characters of text (formatting not counted) | [Requirements checklist](https://docs.zokogames.com/requirements/checklist) |
| Controls and instructions | 5 to 2,000 characters of text | [Requirements checklist](https://docs.zokogames.com/requirements/checklist) |
| Tags | 10 tags at most; each tag 1 to 40 characters of lowercase letters, numbers and hyphens | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) |
| Questions and answers (FAQ) | 10 entries at most; a question is 3 to 200 characters, an answer up to 1,000 | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) |
| Sitelock notes for reviewers | 1,000 characters | [Embedding](https://docs.zokogames.com/requirements/embedding) |
| Allowed sites for embedding | 10 origins | [Embedding](https://docs.zokogames.com/requirements/embedding) |
| Gameplay video link | 300 characters | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) |
| Release notes of a build | 2,000 characters | [Updating a game](https://docs.zokogames.com/getting-started/updating-a-game) |
| Multiplayer lobby size | 1 to 100 players | [Multiplayer](https://docs.zokogames.com/requirements/multiplayer) |
| Studio description | 1,000 characters | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) |
| Studio logo | 2 MB; square PNG, JPEG or WebP, 128 to 2048 px | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough) |

## Covers and videos

| Item | Limit | Details |
| --- | --- | --- |
| Landscape cover | exactly 1920 x 1080 px (16:9) | [Covers](https://docs.zokogames.com/requirements/covers) |
| Portrait cover | exactly 800 x 1200 px (2:3) | [Covers](https://docs.zokogames.com/requirements/covers) |
| Square cover | exactly 800 x 800 px (1:1) | [Covers](https://docs.zokogames.com/requirements/covers) |
| Cover file | PNG, JPG or WebP, 5 MB at most, one still picture (no animation) | [Covers](https://docs.zokogames.com/requirements/covers) |
| Landscape preview video | exactly 1920 x 1080 px, MP4 (H.264), no audio | [Covers](https://docs.zokogames.com/requirements/covers) |
| Portrait preview video | exactly 720 x 1080 px, MP4 (H.264), no audio | [Covers](https://docs.zokogames.com/requirements/covers) |
| Preview video length | 15 to 20 seconds | [Covers](https://docs.zokogames.com/requirements/covers) |
| Preview video file | 50 MB at most | [Covers](https://docs.zokogames.com/requirements/covers) |

## The SDK

| Limit | Value | Over the limit | Details |
| --- | --- | --- | --- |
| Cloud save, all keys together | 1,048,576 bytes (1 MiB) | `setItem` throws `dataLimitExceeded` | [Data](https://docs.zokogames.com/sdk/data) |
| Friends per page | 50 friends | An argument error (`invalidArgument`) | [User](https://docs.zokogames.com/sdk/user) |
| Answer from the portal | 10 seconds | `timeout` | [SDK introduction](https://docs.zokogames.com/sdk/introduction#errors) |

## Upload and console

| Limit | Value | Details |
| --- | --- | --- |
| Drafts one studio can hold at once | 50 drafts | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough#2-create-the-game-and-fill-in-the-steps) |
| Submissions for review per hour | 10 submissions per person | [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough#5-submit) |
| Upload starts per hour | 20 uploads | [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting#upload-and-review) |
| Problems listed in the upload report | 40 errors and 40 warnings | [Build validation](https://docs.zokogames.com/requirements/build-validation) |
| Webhook endpoints per studio | 5 endpoints | [Webhooks](https://docs.zokogames.com/guides/webhooks) |

## Next steps

- [Requirements checklist](https://docs.zokogames.com/requirements/checklist): the same rules as tick boxes.
- [Build validation](https://docs.zokogames.com/requirements/build-validation): what each finding code means.
- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting): what to do when a limit is hit.

---

Source: https://docs.zokogames.com/requirements/technical

# Technical requirements

Each rule below says why it exists and how to check it before you submit. The upload validator produces a report with a code per finding; the codes are listed on [build validation](https://docs.zokogames.com/requirements/build-validation) and linked from the sections they belong to. A **build** is one set of uploaded files; the reviewer's checklist is on the [requirements checklist](https://docs.zokogames.com/requirements/checklist). Terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Size and files

| Limit | Value |
| --- | --- |
| Total uncompressed build size | 250 MB |
| Number of files | 1,500 |
| Initial download | 50 MB. Above this the build is rejected. |
| Initial download, mobile target | 20 MB. Above this the validator warns and reviewers test on a phone. |

"Initial download" is what a first-time visitor must fetch before they can play. The upload validator estimates it from the uncompressed size of `index.html`, every file it references and the engine bootstrap payload (the Unity `Build/` folder, Godot `.pck` and `.wasm`, Defold archives and scripts). Files you fetch later, after the game is running, do not count, so load levels and audio lazily. Separately, the [Preview tool](https://www.zokogames.com/preview) times the first `gameplayStart` and flags anything later than 20 seconds. For techniques see [optimisation tips](https://docs.zokogames.com/guides/optimisation) and [first frame fast](https://docs.zokogames.com/guides/first-frame).

**Why:** the size and file caps keep a build quick to unpack and serve, and the initial download decides how long a visitor waits before play. **Check before submitting:** the console's **Build** step shows the size, file count and estimated initial download against these limits; the [Preview tool](https://www.zokogames.com/preview) shows the time to first gameplay. **Finding codes:** see [size and file codes](https://docs.zokogames.com/requirements/build-validation#size-and-file-codes) (`too_large`, `too_many_files`, `initial_too_large`, `mobile_initial_large`, `large_file`).

Games hosted on your own server (an `https` address that allows being framed from zokogames.com) are judged on time to gameplay and only earn if the SDK is integrated.

## Relative paths only

Every asset URL in your build must be relative (`assets/hero.png`, `./js/game.js`). Absolute paths (`/assets/hero.png`) and hard-coded domains break when we host the game under its own build folder (`g-<slug>.zokogames.com/<build-id>/`). Bundlers need a relative base: `base: "./"` in Vite, `homepage: "."` in Create React App, `publicPath: ""` in webpack.

**Why:** the build folder name is part of the address, so a root-absolute path points at the wrong place and returns 404; file names are case sensitive on the host; `http` addresses are blocked on an `https` page. **Check before submitting:** run the game from a sub-folder on `localhost` and watch the network tab for 404s, then read the report. **Finding codes:** see [path codes](https://docs.zokogames.com/requirements/build-validation#path-codes) (`absolute_path`, `case_mismatch`, `missing_reference`, `mixed_content`).

## What the validator rejects

The zip must have `index.html` at its root (or inside a single top-level folder, which is stripped). The upload is refused when it contains:

- more than 1,500 files (or more than 6,500 zip entries), or more than 250 MB unpacked;
- unsafe paths: absolute paths, drive letters, `..`, backslashes, `?` or `#` in a name, control characters, empty or dot segments, names over 1,024 characters or segments over 255;
- symbolic links, encrypted entries, unsupported compression methods or duplicate paths;
- executable or server-side files: `.php`, `.exe`, `.dll`, `.bat`, `.sh`, `.ps1`, `.jar`, `.py`, `.rb`, `.pl`, `.cgi`, `.asp`, `.jsp`, `.so`, `.apk`, `.lnk` and similar, and `.htaccess`, `web.config`, `php.ini`;
- suspicious compression ratios (a file over 1 MB that expands more than 200 to 1, or an archive that expands more than 400 to 1 overall);
- an estimated initial download over 50 MB;
- code or files that the safety scan blocks: native programs, miners, hidden `eval` of base64 data, password forms that post to another site, scripts loaded from raw IP addresses or URL shorteners, and cookies sent to another host.

Warnings do not block the upload: `__MACOSX`, `.DS_Store` and similar system files are ignored, paths that differ only by case, file types the portal does not recognise (served as generic binary), external hosts referenced from your code, root-absolute paths (`/game.js`) in `index.html`, files `index.html` references that are missing from the zip, an `index.html` that does not look like HTML, an initial download above 20 MB, and a missing SDK script. A `.gz` file that is not real gzip data is rejected. The validator also detects your engine (Unity, Godot, Construct, GameMaker, Cocos, Defold, Phaser) and whether the SDK script is referenced. Asset files must match their extension: a `.wasm` that is not WebAssembly fails validation, and mismatched images, audio or fonts are flagged for review.

**Why:** the host serves static files only, so executable and server-side files cannot run and are a security risk; unsafe paths and hostile archives could escape the build folder or exhaust memory. **Check before submitting:** the validator runs on upload and every error is shown with its path; fix it and upload again, the check costs nothing. **Finding codes:** [archive and file type codes](https://docs.zokogames.com/requirements/build-validation#archive-and-file-type-codes), [the safety scan](https://docs.zokogames.com/requirements/build-validation#the-safety-scan) and [SDK codes](https://docs.zokogames.com/requirements/build-validation#sdk-codes).

## No threaded WebAssembly

Game pages are served without cross-origin isolation headers (COOP and COEP), so `SharedArrayBuffer` is unavailable and threaded WebAssembly builds (Unity multithreading, Godot with thread support, native threads in plugins) cannot run. Export single-threaded. Check before submitting: the build must start in the [Preview tool](https://www.zokogames.com/preview) with no `SharedArrayBuffer` error in the console.

## Iframe

The game runs in a sandboxed iframe with these tokens: `allow-scripts allow-same-origin allow-forms allow-pointer-lock allow-orientation-lock allow-modals allow-downloads allow-presentation`. Popups are opt-in per game (the **Needs popups** option). Permissions delegated to the frame include autoplay, fullscreen, gamepad, clipboard write, accelerometer, gyroscope, XR tracking and keyboard map. Camera and microphone are off unless staff grant them for one game; see the embedding page. Kids games, and any game played in kids mode, run without `allow-downloads`, as they already run without popups.

Do not rely on `window.top`, cookies or third-party storage; use the [data module](https://docs.zokogames.com/sdk/data). The frame has its own `localStorage` (the sandbox allows its own origin), but it is separate from the data module and is not synced; a guest's data-module save is kept by the portal page, not by the frame. Do not add your own fullscreen button, the portal provides one.

**Why:** each game runs on its own origin in a sandbox so one game cannot read another's data or navigate the portal. **Check before submitting:** play in the [Preview tool](https://www.zokogames.com/preview), which uses the real frame, with the console open. **Finding codes:** [`service_worker`, `cookie_access`, `top_navigation`](https://docs.zokogames.com/requirements/build-validation#external-host-and-frame-behaviour-codes).

## Browsers

Why: players use all of them, and reviewers play the game on more than one. Check: open the game in the Preview tool in each browser you ticked.

- Chrome and Edge (current versions) are the baseline.
- Safari and Firefox must work as well. A game that fails on a browser can be disabled there.
- A game that does not run smoothly on a low-end 4 GB Chromebook can be switched off for Chromebooks (see the platform switches under Mobile).

## Mobile

- Support touch if you tick mobile in the submission, and keep the same features as desktop.
- Detect the device with `SDK.user.systemInfo.device.type`, not with touch events. Laptops have touch screens, and tablets have keyboards.
- Orientation is set at submission and the portal prompts players to rotate. You do not need to lock orientation in code.
- On iOS and low-memory Android, cap `devicePixelRatio` at 1 for canvases to avoid running out of memory. Tick **Tested and works well on iOS** and **Works in Safari** on the **Technical** step only when you have tested them: players on a device you did not confirm see a compatibility notice ("may not run well") before they play, with a "Play anyway" choice.
- Respect safe-area insets (`env(safe-area-inset-*)`) near screen edges, especially inside the mobile app shell where `applicationType` is not `"web"`.
- Test with the on-screen keyboard open if you have text input.

Besides the **Works on mobile** tick, you can switch **desktop**, **phone** and **tablet** availability on or off per game (`desktopEnabled`, `phoneEnabled`, `tabletEnabled` in the [developer API](https://docs.zokogames.com/guides/developer-api#game-settings); all are on by default). A player on a device class you switched off sees that the game is not available on that device instead of a broken start, and the mobile game lists leave out games with both phone and tablet off.

Three more switches work by platform instead of by screen size: **Chromebook** (ChromeOS), **Android** (phones and tablets, in any browser) and **iPhone and iPad** (iOS and iPadOS in any browser, including an iPad that asks for the desktop site). They are in the **Devices** card of the game's console settings, under **Platforms** (`chromebookEnabled`, `androidEnabled`, `iosEnabled`; all on by default). A game can run on iPhone Safari and not on Android Chrome. A platform switch applies only to players on that platform and comes on top of the device switches; on Windows, macOS or Linux none of them applies. A player on a platform you switched off sees the same "not available on this device" message instead of a broken start, on the game page and in the [embed](https://docs.zokogames.com/requirements/embedding) alike. The review and Preview views ignore the switches so you can still test. At least one device class must stay on.

**Why:** most players arrive on a phone, and the laptop-with-touch and tablet-with-keyboard cases break touch-event detection. **Check before submitting:** use the mobile (800x450) and tablet presets in the [Preview tool](https://www.zokogames.com/preview) and a real phone for the final pass; the reviewer checks touch controls only when you tick mobile.

## Audio on iOS

Mobile Safari starts the `AudioContext` suspended and only lets you resume it inside a user gesture handler:

```js
const ctx = new AudioContext();
function unlock() {
  if (ctx.state !== "running") ctx.resume();
}
window.addEventListener("touchend", unlock, { once: true });
window.addEventListener("click", unlock, { once: true });
```

Also honour `SDK.game.settings.muteAudio` and silence everything when an ad starts.

**Why:** browsers refuse sound before a user gesture, and a game that ignores the mute setting breaks the player's choice. **Check before submitting:** reload the game in the Preview tool and confirm nothing plays before your first tap, then trigger an ad break in local mode.

## Scroll and keys

The page must never scroll underneath the game. Cancel the default for wheel events and the keys the browser uses to scroll:

```js
window.addEventListener("wheel", (e) => e.preventDefault(), { passive: false });
const SCROLL_KEYS = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Space"];
window.addEventListener("keydown", (e) => {
  const typing = e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement;
  if (!typing && SCROLL_KEYS.includes(e.code)) e.preventDefault();
});
```

Add `user-select: none` to the body so a drag does not highlight text, and `touch-action: none` on the canvas.

**Why:** the game sits inside a portal page, and scrolling that page under the game moves the player away from it. **Check before submitting:** in the Preview tool, scroll over the game and press the arrow keys and space; the page must not move.

## Sitelock

You may lock the game to run only on ZokoGames, which stops copies being re-hosted. The portal serves games from `zokogames.com` and subdomains of it:

```js
const host = location.hostname;
const allowed =
  host === "zokogames.com" || host.endsWith(".zokogames.com") ||
  host === "localhost" || host === "127.0.0.1";   // keep local development working

if (!allowed) {
  document.body.textContent = "Play this game on zokogames.com";
  throw new Error("sitelock");
}
```

**Hostnames, for a sitelock or portal detection.** A hosted game document is served from `g-<slug>.zokogames.com`, and its scripts and the SDK come from `sdk.zokogames.com` (covers from `imgs.zokogames.com`). Today the portal frames it from `zokogames.com`, `www.zokogames.com`, `developer.zokogames.com` (Preview and QA), `kids.zokogames.com` and `admin.zokogames.com` (review); the embed player is a page on `www.zokogames.com` that frames the game for partner sites. In the game's frame, `location.hostname` is the `g-<slug>` host, `document.referrer` and `location.ancestorOrigins` describe the parent, and `location.ancestorOrigins[0]` is the page that frames the game directly: `https://www.zokogames.com` on the portal and in the embed player, with the partner site as the next entry when the embed player sits on one. `ancestorOrigins` does not exist in Firefox, so never make play depend on it. These hosts can change: allow `zokogames.com` and every subdomain, never one exact name. To know whether you are on the portal, read `SDK.environment` (`"zokogames"` on the portal, `"local"` in local mode, `"disabled"` when the SDK is off) instead of reading hostnames.

The full embedding and sandbox policy is on [embedding and sitelock](https://docs.zokogames.com/requirements/embedding). Never lock to a single exact hostname; we may serve from other subdomains. **Why:** a lock that is too tight shows players a blank page and reviewers cannot tell it from a crash. **Check before submitting:** open the game in the Preview tool and on `localhost`; both must start. If you host the game on your own server, set a Content-Security-Policy such as `frame-ancestors 'self' https://zokogames.com https://*.zokogames.com` (see [hosting on your own server](https://docs.zokogames.com/requirements/embedding#hosting-on-your-own-server)).

## Privacy and your own game server

If your game collects any personal data beyond what the SDK gives you, show a notice and link a privacy policy. Do not load third-party advertising or tracking scripts.

**Your own game server is allowed.** Calling a server you run for the game itself (multiplayer, your own login and saves, a leaderboard) is permitted: use `https`, let it accept requests from the game's address, and say so on the **Technical** step (set **Progress saving** to **Own backend**, and turn on **Multiplayer game** where it applies). The validator lists such hosts as `origin_unknown` so a reviewer can see them. What the terms forbid is different: ad networks other than the SDK, third-party analytics and tracking scripts, and using the server to follow players for purposes other than running the game. Send your server only what the game needs, such as the player id from a token you verified on the server and game state.

**Origin: where your game runs.** An uploaded build runs on `https://g-<your-game-slug>.zokogames.com`. Your server sees exactly that origin in the `Origin` header in the build preview (the **Preview and QA** tab), in review, live, and inside a partner's embed, because the embed player frames the same address. The **Your own game server and notes for reviewers** card on the **Technical** step shows the origin for your game with a **Copy code** button. The slug is fixed once the first build is uploaded; until then it can still change. Three setups differ: a zip you run from your computer in the Preview tool runs on `https://preview-run.zokogames.com`, local mode runs on `http://localhost` with your port, and a game that is framed from your own address (hosting set to your own server) runs on that address. Keep the allowed origins in your server's configuration, not in code, so a change is one edit.

**Allow that origin, and only that origin.** In your server's CORS settings answer with `Access-Control-Allow-Origin` set to the origin above (add the test origins while you test) and answer the preflight `OPTIONS` request with the methods and the headers you use, at least `Authorization` and `Content-Type`. Do not allow `*.zokogames.com`: every other studio's game runs on that domain too. Do not rely on cookies: cookies of another site are not available inside the frame, so send identity in an `Authorization` header and leave `Access-Control-Allow-Credentials` off. A WebSocket upgrade is not covered by CORS, so check the `Origin` header on the upgrade yourself and refuse other origins.

**Which outbound connections work.** `https://` and `wss://` to any public host. The portal sets no list of hosts that an ordinary game may contact, so nothing has to be registered for the game to run and there is no field for it; declare your host in the notes for reviewers (below). Plain `http://` and `ws://` are blocked by the browser as mixed content, and a WebSocket to a raw IP address is flagged for review (`websocket_raw_ip`). A game made for children may call no host other than its own build. When a call is refused, the player's browser console shows one of the messages listed in the troubleshooting page under "Users, tokens and leaderboards", each with its fix.

**Who the player is.** A signed-in player's game calls `SDK.user.getUserToken()` and sends the token to your server; a guest has no token (the call rejects with `userNotAuthenticated`) and must still be able to play, with an anonymous id of your own that you never merge silently into a signed-in account. Your server verifies the token as a signed RS256 JWT against `https://www.zokogames.com/.well-known/jwks.json`, checking the issuer `zokogames`, the audience (your game id), `gameId`, `sub` and the expiry, with a few seconds of clock allowance. The complete samples, the claims and key rotation are on the user module page under "Verifying on your server"; the Node.js samples there are run against the real signing code in the portal's own tests.

**What reviewers test.** The reviewer plays the build as a guest and, when you offer sign-in, as a signed-in player, with the browser's Network tab open, and reads the notes you wrote in the card. The line "No unapproved external requests" passes when every host in the Network tab is your own files, the SDK or a host you declared in the notes and explained (the validator shows hosts it cannot classify as `origin_unknown`). The multiplayer lines need a way to start without waiting for strangers. Write in the notes: the host (for example `game.example.com`), what it is used for (rooms, login, saves, scores), what a guest can do and what needs sign-in, how to try it alone (for example "open the game in two tabs and press Create room", or a practice mode), and any limit (regions, a daily cap). Keep the server running for the whole review.

**Latency, regions and uptime.** The portal does not choose, measure or proxy your server. The game's files come from a global network; your calls go from the player's browser to your server, so put it (or an edge or serverless platform) near most of your players and avoid a slow cold start on the first call, because reviewers judge time to gameplay. No uptime figure is asked of you.

**When your server is down.** The portal does not watch your server and shows players nothing about it: no banner, no retry, no message. The game must handle it: give every call a timeout of a few seconds, show a short message with a **Retry** button instead of a spinner, and keep the game playable offline or as a guest where you can. **Check before submitting:** stop your server and start the game.

**Rate limits and data you receive.** The portal limits only what it serves, for example 60 token requests a minute per player. Calls to your server do not pass through the portal, so no portal limit applies and yours should. Many players can share one IP address (a school or an office), so limit signed-in players by their verified `userId` and not by address alone. What you may collect and what you must show players is in the privacy paragraph above and the developer terms.

**Why:** the developer terms forbid your own ad networks and tracking, and the portal's privacy policy only covers data the SDK passes on. **Check before submitting:** the report's `origin_ads` and `origin_analytics` findings list every such host the scan found. See [advertisement rules](https://docs.zokogames.com/requirements/advertisements).

## Next steps

- [Gameplay requirements](https://docs.zokogames.com/requirements/gameplay)
- [Build validation reference](https://docs.zokogames.com/requirements/build-validation)

---

Source: https://docs.zokogames.com/requirements/gameplay

# Gameplay requirements

Each rule says why it exists and how to check it before you submit. The reviewer applies the same rules from the [requirements checklist](https://docs.zokogames.com/requirements/checklist); a decision that is not an approval lists the reasons, see [quality guidelines](https://docs.zokogames.com/requirements/quality#how-review-works). Terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Resolutions

Text and controls must be readable at `devicePixelRatio` 1 and not break at any of these viewport sizes. The preview tool has one-click presets for each.

| Device | Sizes (width x height) |
| --- | --- |
| Desktop, in the page | 907x510, 1216x684, 1077x606, 821x462 |
| Desktop, fullscreen | 1366x768, 1920x1080, 1536x864, 1280x720 |
| Mobile | 800x450 |
| Tablet | 1080x607 |

Use responsive layout, not fixed pixel sizes. Check the smallest sizes first.

**Why:** players use many window sizes, and the portal frame is smaller than a full screen. **Check before submitting:** the [Preview tool](https://www.zokogames.com/preview) and the **Preview and QA** tab of your game have one-click presets for exactly these sizes, plus a real phone for the final pass.

Physics and movement must behave the same on 60, 144 and 165 Hz displays. Use a time delta, not a per-frame increment.

```js
let last = performance.now();
function frame(now) {
  const dt = Math.min((now - last) / 1000, 0.05);
  last = now;
  update(dt);
  render();
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```

**Why:** a per-frame increment runs the game 2.75 times faster on a 165 Hz screen than on a 60 Hz one. **Check before submitting:** the reviewer checks that the pace of the game does not change with the display; if you have a high-refresh display, confirm it yourself.

## Language

In the **Audience and distribution** card on the **Technical** step you list the languages your game supports, under **Languages in the game** (English is always required, and the list is shown to players). English is required for every visible string, including errors and the tutorial. Add more languages freely and pick one from `SDK.user.systemInfo.locale`, falling back to English. Do not make players choose a language before they can play. See the [localisation guide](https://docs.zokogames.com/guides/localisation).

**Why:** English is the shared language of the portal's reviewers and of the listing; the declared language list is shown to players. **Check before submitting:** the submission cannot be sent until English is in the language list and you confirm that all visible text is available in English. Play your own tutorial and error paths once in English.

## Age rating

You declare a rating in the submission's **Audience and distribution** card: all ages, 7+, 12+, 16+ or 18+. It is required, and the submission cannot be sent with a rating above 12+: the portal is for a general audience. A game marked as made for children must be all ages or 7+.

ZokoGames is for a general audience, and games must fit a PEGI 12 rating. Not accepted: graphic violence or gore, sexual content, real-money gambling mechanics, hate content and strong language.

Games made for young children are accepted, but only as **made for children** games, and they follow stricter rules. The **Basics** step also warns that games are not listed in the kids area unless the studio is invited, and asks you not to target children under 13. Tick the option in the **Audience and distribution** card. A game is listed in the kids area only when every rule below holds; the reviewer ticks them one by one ([checklist](https://docs.zokogames.com/requirements/checklist#made-for-children-when-ticked)):

- **Rating.** All ages or 7+. Anything higher cannot be marked as made for children.
- **Content.** Violence only as cartoon abstraction (no blood, injury or death shown, no realistic weapons aimed at people or animals), nothing frightening, no sexual content, strong language, alcohol, tobacco or drugs. No gambling or gambling-like loops: no betting, casino or slot themes, loot boxes or chance-based rewards. A patience or card game with no stakes is fine; collecting in-game points or coins for upgrades is fine as long as nothing can be bought with real money and nothing is staked.
- **No links out.** No URL the player can open, no guide link, no store links, no social or community links, no promotion of other sites. Links between kids games of the same series are the only exception.
- **No user-generated text.** No chat, comments, names, free-text fields or user names on screen. No sign-in, no friends, no multiplayer rooms, no leaderboards, no sharing or invites. Players report a problem only with preset reasons.
- **No purchases.** No real-money items, no store module, no "unlock" or "premium" prompts.
- **No ads.** SDK ad requests fail with `adsDisabled`, so the game earns no ad revenue. Treat that as permanent: do not show a "watch an ad" button or any text that promises a reward for an ad, because it would be a dead button.
- **No data collection.** No name, email, age, location or contact details are asked for, and nothing is sent to hosts other than your own build. Progress and best scores may be saved on the device through the SDK data module or local storage, nothing else. Analytics events and push notifications are never available.
- **No pressure.** No countdowns to come back, streaks or rewards that punish absence, "last chance" prompts or other nudges to keep playing.
- **Easy to start.** Instructions are short, in plain words and shown with pictures where they can be. A seven-year-old can start playing with at most a sentence of reading, and the first level is easy.
- **What the console checks.** The console refuses the kids setting with `kids_blocked` while the game has **Needs popups** on, is hosted on your own server, has a store link or has **Moderated chat** on, and with `kids_rating`, `kids_no_iap` or `kids_no_leaderboard` for a rating above 7+, in-game purchases or a leaderboard. See [kids mode](https://docs.zokogames.com/guides/kids-mode#what-the-console-refuses). The reviewer still checks the rules above that no code can.
- The game is never embeddable on partner sites, and chat and social prompts are switched off while it is played, so do not build your own.
- **Calls in kids mode.** Account, store and room calls are refused with documented codes (`userNotAuthenticated`, `userCancelled`, `catalogFetchFailed`, `roomUnavailable`). Branch on `SDK.user.isUserAccountAvailable` and `SDK.store.isAvailable`; see [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode).

A game that is clearly aimed at young children but is not marked as made for children is sent back in review with the reason **Audience flag**, and so is a made-for-children game that breaks any rule above.

**Why:** children's games must be isolated from ads, chat and partner sites to protect players. **Check before submitting:** the console refuses a made-for-children game with a rating above 7+; confirm yourself that every rule above holds: no links out, no text input, no purchases, no ad offers and no data collection.

## Cross-promotion

No promotion of other portals, other game sites or unrelated products inside the game. Exceptions:

- Links to your community pages (Discord, social channels).
- Links to the game's own store page on a native store, shown on desktop only. Store links belong in the submission's metadata fields.
- Links between games in the same series.

No logos or branding of other portals, no external ads, no watermark of another site.

**Why:** the developer terms forbid other portals' branding and your own ad networks, and promotion of other sites sends players away. **Check before submitting:** search your build and credits screen for outside links; the report's `origin_*` findings list hosts your code references, see [external host codes](https://docs.zokogames.com/requirements/build-validation#external-host-and-frame-behaviour-codes).

## Fullscreen and landing

Do not add your own fullscreen button. For full launch, new players should reach active gameplay with at most one click after the load. A single "Play" button is fine; a five-screen menu is not. Returning players should be able to continue where they stopped.

**Why:** the first seconds decide whether a visitor stays, and basic launch measures exactly that: conversion counts views that reach at least 60 seconds of play. **Check before submitting:** time yourself from load to play in the Preview tool; its checklist flags a first `gameplayStart` later than 20 seconds. See [launch stages](https://docs.zokogames.com/getting-started/launch-stages). Midgame ads need it too: the portal refuses them until the game has called `gameplayStart()` once, see [Gameplay first](https://docs.zokogames.com/sdk/ads#gameplay-first).

## Controls

Document the controls in the submission's controls field. Support mouse and keyboard on desktop and touch on mobile. See [control pitfalls](https://docs.zokogames.com/guides/input-controls).

**Why:** the controls field is shown on the game page and the reviewer compares it with the game. It must be at least 5 characters and at most 2,000 characters of text. **Check before submitting:** ask someone who has not seen the game to play it using only your controls text.

## Next steps

- [Advertisement rules](https://docs.zokogames.com/requirements/advertisements)
- [Quality guidelines](https://docs.zokogames.com/requirements/quality)

---

Source: https://docs.zokogames.com/requirements/advertisements

# Advertisement rules

Every rule below says why it exists and how to check it before you submit. Terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

Only ads served through the SDK are allowed. No other ad network, no affiliate links, no sponsor logos you were paid for. Ads run only for games in full launch with ads enabled: basic launch has no ads and no revenue share, and games the portal marks as kids' games never show ads. Today the ads in full launch are the portal's own house ads, because no ad network is connected yet, so they earn no revenue. **Why:** ad revenue is the only thing the revenue share is paid from, and the SDK is how the portal counts it and keeps ad pacing fair to players. **Check before submitting:** in local mode and in the [Preview tool](https://www.zokogames.com/preview) the SDK simulates a three-second ad, so you can test every callback. In the portal during basic launch `requestAd` fails with `adsDisabled`; your game must continue anyway. **Finding codes:** `origin_ads` and `origin_analytics` in the [build report](https://docs.zokogames.com/requirements/build-validation#external-host-and-frame-behaviour-codes) list ad and tracking hosts the scan found in your code, and `third_party_sdk` flags another portal's SDK.

## Midgame ads

- Request them at **natural breaks**: after a level, after a death screen, when returning to the menu.
- Never on a navigation button the player presses repeatedly, never mid-action, never at game start.
- Block input while the request is pending so the player cannot click through.
- Pause and mute in `adStarted`. Do not mute earlier. *Why:* the player must not lose progress or hear two sounds at once.
- Call `SDK.game.gameplayStart()` before your first break (see [Gameplay first](https://docs.zokogames.com/sdk/ads#gameplay-first)). The portal refuses a midgame request with `adCooldown` until the game has called it once (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not affected. Local mode shows this refusal too since SDK 1.6.4; before that only the Preview tool and the site did.
- Handle `adError` and always resume.
- Check: the **Preview and QA** tab of your game ticks **A midgame ad was requested**, **gameplayStop before each ad request** and **Play resumed after an ad finished** when your game makes the calls (the public Preview tool ticks **Midgame ad requested**).
- The portal limits midgame ads to one every three minutes by default. The portal team can set a longer gap, a cap on ads per session, or switch midgame or rewarded ads off, so treat `adCooldown` and a failed request as normal. A rewarded ad also restarts that timer, so a midgame request right after a rewarded ad is declined.

## Rewarded ads

- The rewarded button must not appear in the middle of active gameplay. Show it on a pause, results, shop or menu screen.
- The offer is optional. A "no thanks" choice is as prominent as the ad button and appears with it.
- Label it clearly as an ad and say what the reward is before the player taps.
- Give the reward only after `adFinished`. **Never reward on `adError`.**
- Offer another way to earn the same reward (play, wait, or a lower amount) for players without ads.
- Do not chain rewarded ads, and do not offer one every single time a player runs out of lives.
- Do not show a midgame ad and a rewarded "keep playing" offer between the same two levels.
- Check: the reviewer tries the reward flow, so confirm in the Preview tool that a failed or closed ad grants nothing and that the no-ad alternative works. *Why:* a reward on error pays players for nothing and revenue from pretend reward ads is not shared.

## Banners

- Place them only on screens that normally stay open for at least five seconds on average.
- Never during gameplay. Never over UI the player needs.
- At most two banners on one screen.
- Use the sizes the SDK accepts, listed on the [banners page](https://docs.zokogames.com/sdk/banners). A static request with another size fails with `invalidSize`. *Why:* the ad provider only fills known sizes. Check: request a banner in local mode.
- Respect the [banner limits](https://docs.zokogames.com/sdk/banners#limits): 30 seconds between refreshes of the same container, 60 refreshes per session.

## Adblock

Players with an adblocker must still be able to play. You may disable features that need a rewarded ad and say so with a short, neutral message. You may not show pop-ups begging them to disable the blocker, and may not lock core content. Detect it with `await SDK.ad.hasAdblock()` (it returns a promise). *Why:* ads are optional for the player. Check: turn on an ad blocker in the Preview tool and play through.

## Pacing

Ads are a revenue source and a player-retention risk at once. The [monetisation guide](https://docs.zokogames.com/guides/ad-monetisation) explains how to space them. Games that over-serve ads lose players, which also lowers revenue.

## Next steps

- [Video ads](https://docs.zokogames.com/sdk/ads)
- [Audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads)
- [Ad monetisation guide](https://docs.zokogames.com/guides/ad-monetisation)

---

Source: https://docs.zokogames.com/requirements/quality

# Quality guidelines

Every rule here has a reason and a way to check it before you submit. The technical limits are on [technical requirements](https://docs.zokogames.com/requirements/technical) and in the [build validation reference](https://docs.zokogames.com/requirements/build-validation); the full tick list is the [requirements checklist](https://docs.zokogames.com/requirements/checklist). Terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## How review works

1. You press **Submit for review**. The game and its listing are locked while the submission is open. You can withdraw it to edit only while it is still waiting for a reviewer.
2. A reviewer plays the game in the portal frame against these pages. The checklist adapts to your game: ad items appear only when ads apply, multiplayer items only for multiplayer games, mobile items only when you tick mobile, and account items when you use the data module or a leaderboard. The groups are technical, gameplay, ads, accounts and saves, multiplayer, and quality and presentation.
3. The reviewer can only approve when every applicable item has an answer and none failed. Otherwise they request changes or reject, and must pick at least one reason or write a note. You get the reasons in the console and by [notification](https://docs.zokogames.com/guides/notifications), and an email for the outcome.
4. An approved game starts a **basic launch** with ads off. The basic launch measures play time, day-1 return, conversion and click-through, and is due for a decision after at least 7 days and 500 plays, or after 21 days whatever the play count (these are the defaults; the portal team can change them). A reviewer then promotes, extends or ends it: a person moves it to **full QA** (a second review of the full integration) and on to **full launch**, where ads run and revenue share accrues. See [launch stages](https://docs.zokogames.com/getting-started/launch-stages) and [basic launch metrics](https://docs.zokogames.com/guides/basic-launch-metrics).

The portal scores your basic-launch numbers against these targets: average play time of at least 600 seconds, day-1 return of 10 to 15 percent or more, at least 80 percent of views playing for 60 seconds, and a tile click-through rate in the top half of your category. It needs at least 200 plays before the numbers count as reliable. The score is advice for the reviewer; meeting every target does not guarantee promotion and missing one does not always rule it out.

Review time depends on the queue, so no duration is promised.

## What reviewers look at

1. **It works.** No crashes, no soft-locks, no console error storms, no blank screens on load. *Why:* a game that does not run cannot earn or be measured. *Check:* test on a cold cache in a clean browser profile, play for 10 minutes, and read the Preview tool's checklist.
2. **It is original.** A recognisable clone, an asset flip or a game made of purchased templates with minimal changes is rejected. A title that is generic ("Racing Game") is asked to change. *Why:* you confirm in the developer terms that you hold the rights, and players find copies worthless. *Check:* list every asset and its licence.
3. **It is fun fast.** The first minute teaches by playing, not by reading. A clear goal appears within seconds. *Why:* conversion, the share of views that reach 60 seconds of play, is a launch metric. *Check:* watch someone new play the first minute.
4. **It looks and sounds finished.** Consistent art, readable UI, no placeholder text or debug overlays, audio that does not clip and can be muted. *Why:* it is the first impression and the cover must match it. *Check:* play with the sound off and then on, at the smallest [required resolution](https://docs.zokogames.com/requirements/gameplay#resolutions).
5. **It respects the player.** No dark patterns, no fake buttons, no misleading ads, no forced sign-in, no requests to rate or follow. *Why:* the portal is for a general audience and ad revenue depends on trust. *Check:* play as a guest.
6. **It is safe.** Content fits the [age rating](https://docs.zokogames.com/requirements/gameplay#age-rating), user-generated text is moderated, and nothing is loaded from untrusted hosts. *Why:* the terms require a PEGI 12 bar. *Check:* read the `origin_*` findings in the [build report](https://docs.zokogames.com/requirements/build-validation#external-host-and-frame-behaviour-codes).

## Reasons a submission is sent back or rejected

Reviewers pick from a fixed list. Each reason carries a message that tells you what to do. The first nine are fixable: you change the game and submit again. The last four are final: the message says the game cannot be published.

| Reason | What it means | How to avoid it |
| --- | --- | --- |
| Game does not run | It fails to load or crashes before play. | Test the exact build you upload in a clean profile. Read the report's errors and warnings. |
| Performance | It loads slowly or runs poorly on a mid-range phone. | Reduce the initial download, see [first frame fast](https://docs.zokogames.com/guides/first-frame); the report flags above 20 MB. |
| Ad integration | Ads are not through the SDK or they interrupt play. | Follow the [advertisement rules](https://docs.zokogames.com/requirements/advertisements); remove other ad code (`origin_ads`). |
| External links or popups | Unapproved popups, redirects or external links. | Remove them, or tick **Needs popups** with a reason. |
| Controls unclear | Players cannot tell how to play. | Add an in-game tutorial and an accurate controls field. |
| Quality below bar | Too little content, rough art or audio, or too short. | Compare with games in your category. |
| Artwork does not meet specs | Covers or video missing, blurry, wrongly sized or with wrong text. | Follow the [cover guide](https://docs.zokogames.com/requirements/covers); the console refuses wrong sizes. |
| Listing information | Title, description or categorisation is inaccurate or misleading. | Describe the real game; pick the right category and tags. |
| Audience flag | Content does not match the declared audience, or a kids game has ads, links or data collection. | See [age rating](https://docs.zokogames.com/requirements/gameplay#age-rating). |
| Copyright or brand misuse (final) | Assets, characters or brands you have no rights to. | Use only work you hold or license. |
| Copy of another game (final) | A direct copy or re-skin without meaningful changes. | Make a game of your own. |
| Inappropriate content (final) | Content that breaks the content policy. | Keep to the PEGI 12 bar. |
| Security (final) | Suspicious or unsafe code. | Remove it; the validator also refuses executables. |

Other things that cost a review round, from the checklist: no English text, a failed ad that leaves the game paused (resume in `adError`), absolute paths that break in the frame.

## Updates

You may upload a new build at any time. During basic launch an update goes live at once and is recorded as auto-approved. In full launch every update waits for a reviewer, and the previous build keeps running until it is approved; only one update can wait at a time. A game that breaks the rules in an update can be taken down, see [developer terms](https://docs.zokogames.com/business/developer-terms).

## Polish checklist

- [ ] Pause when the tab is hidden, mute when the page is hidden.
- [ ] Settings for sound and, if relevant, music separately.
- [ ] The cursor is visible when it should be and hidden only during pointer lock.
- [ ] A "restart" is reachable without a reload.
- [ ] Loading shows progress, not a frozen screen.
- [ ] Credits, if any, are short and do not point to other portals.

## Next steps

- [Game covers and preview videos](https://docs.zokogames.com/requirements/covers)
- [Testing checklist before you submit](https://docs.zokogames.com/getting-started/testing-checklist)

---

Source: https://docs.zokogames.com/requirements/accounts

# Account integration scenarios

Each rule has a reason and a way to check it before you submit. Terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

Pick the scenario that matches your game. All of them must keep guests playing.

## 1. Your game has no accounts

Use the [data module](https://docs.zokogames.com/sdk/data) for saves. Nothing else is required. Showing the player's portal name in the HUD via `getUser()` is optional.

## 2. Use the ZokoGames profile

Use the portal identity as the account. Read `getUser()` for the name and avatar, and listen with `addAuthListener` for sign-ins. Offer `showAuthPrompt()` on a button, never automatically. Store progress with the data module or your backend keyed by the verified `userId`.

## 3. Your own backend, guests allowed (basic integration)

You run your own login and server saves.

- Guests must be able to play without creating an account.
- Remove or disable external login methods (social login buttons) in the portal build.
- Call `getUserToken()` on every launch, verify it [server-side](https://docs.zokogames.com/sdk/user#verifying-on-your-server), and use it to look up or create the account for that `userId`.
- If the call fails with `userNotAuthenticated`, let the player continue as a guest. Do not open the sign-in dialog on your own.

## 4. Your own backend, linked accounts (full integration)

Players who already have a game account can link it to their ZokoGames identity.

1. Player signs in to the portal (`showAuthPrompt`).
2. Your game verifies the token on the server.
3. If the `userId` is already linked, load that account.
4. If not, call `showAccountLinkPrompt()`. The call resolves to `{ response: "yes" | "no" }`. On `"yes"`, link the `userId` to the player's game account. On `"no"`, continue as a guest.
5. From then on the ZokoGames identity wins: log them in with it on every launch.

Guidance:

- Refresh the stored username and avatar when they change.
- Prefer linking to a new account over merging two accounts that both have progress.
- Never trust `__dangerousUserId` from the client. Use the token.

## Saving progress

Progress must be saved one of three ways: the data module, your own backend linked through the user module, or both. A game that loses progress when the tab closes will not pass full launch.

**Why:** players come back, and day-1 return is one of the basic-launch metrics; guests must always be able to play because sign-in is the player's choice. **Check before submitting:** run the game in the [Preview tool](https://www.zokogames.com/preview) as a guest and signed out, close the tab, reopen it and confirm progress survives. The Preview tool's checklist ticks **Data module used** when your game syncs; the **Preview and QA** tab of your game, which runs the game with your leaderboard settings, also has **Data module used for saves** and **A leaderboard score was submitted**. The reviewer's account items are: playable as a guest, progress saves and restores, and leaderboard scores submit and display. In local mode `getUserToken()` returns an unsigned test token that a correct verifier rejects, and `?token_response=logged_out` tests the guest path; see the [user module](https://docs.zokogames.com/sdk/user#tokens). See [environments](https://docs.zokogames.com/getting-started/environments) and [cloud saves](https://docs.zokogames.com/guides/cloud-saves).

## Next steps

- [Data (cloud save)](https://docs.zokogames.com/sdk/data)
- [Player accounts and your backend](https://docs.zokogames.com/guides/player-accounts)

---

Source: https://docs.zokogames.com/requirements/multiplayer

# Multiplayer

Each rule here has a reason and a check you can run before you submit. Terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

Multiplayer games must integrate the room and invite features. Rooms and invites need a signed-in player: for guests the calls are accepted but there is no realtime identity, so show the sign-in button before offering invites. Rooms are never available in kids mode or for a game made for children (see [kids mode](https://docs.zokogames.com/guides/kids-mode)), and a signed-in account without a 13+ birthday on file has no realtime identity either. The guide [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms) walks through the whole flow with a runnable example.

## Required integration

- Call `updateRoom({ roomId, isJoinable, inviteParams })` whenever the player enters or changes a room. See [game module](https://docs.zokogames.com/sdk/game#rooms-and-invites).
- Call `leftRoom()` when they leave.
- If your game lets players copy a link, build it with `inviteLink(params)` instead of your own URL.
- On start, read `inviteParams` and join the room it describes. Also register `addJoinRoomListener` for invites accepted while the game is open.
- When `isInstantMultiplayer` is true, skip the menu and go straight into matchmaking or a lobby.

**Why:** the portal's friends, invites and join links work only through these calls; without them a friend cannot join. **Check before submitting:** the **Preview and QA** tab of your game ticks **Multiplayer room or invite call made** once your game calls `updateRoom` or `inviteLink` (it appears when **Multiplayer game** is ticked). Then open an invite link in a second window as a signed-in player and confirm you land in the same room. The reviewer repeats this (lobby, invites and join links; a player leaving does not freeze the room).

## Playing together: the room data channel

SDK 1.3.0 adds `SDK.game.room`, a small data channel between the players of one room: `send(data, { to })`, `onMessage`, a host-written shared state (`setState`, `getState`, `onState`), `members`, `onMembers`, `isHost` and `onHostChange`. Use it for moves, positions, ready flags and lobby settings. Limits: 8 KB per message or state patch, 20 messages per second per player (a burst of 20), 64 KB of shared state. You can still run your own server for anything bigger or authoritative; the channel does not replace one for physics or anti-cheat.

- The platform sets the sender (`from`) and a sequence number and timestamp on every message; the client cannot fake them.
- The **first player to join is the host** and the only one who can write the shared state. When the host leaves, the longest-standing player becomes host and `onHostChange` fires. Handle it: hosting duties (starting a round, keeping the counter) move with it.
- The room holds as many players as your maximum lobby size, never more than 100 (8 when no size is set). The state is deleted when the last player leaves, and the empty room itself one minute later. A player whose connection stays down for 30 seconds leaves the room. Nothing is stored or logged.
- It is a game data channel, **not a text chat**. Free text between players still needs the moderation described below, and `disableChat` is unaffected.

**Check before submitting:** open the game in two tabs in local mode (the channel is mocked through the browser), send a message from each and make the host tab leave to confirm the other tab takes over. The reference is in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel); a complete example and the error codes are in [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms) and [troubleshooting](https://docs.zokogames.com/guides/troubleshooting#multiplayer-rooms).

## Flow guidance

- The first player in a session should land in a private, joinable room so a friend can join immediately.
- Round-based games keep the group together between rounds instead of sending everyone back to the menu.
- Show portal usernames in game (`getUser()` and the friend list), not only anonymous ids.

## Lobby size

Enter minimum and maximum players (1 to 100) on the **Technical** step (**Minimum lobby size** and **Maximum lobby size**); both are required for a multiplayer game, and the minimum cannot exceed the maximum. They drive the "play together" listings, and the maximum is passed to the portal as the room capacity when a room is created (capped at 100). Reviewers check that the sizes match what the game really allows. The submission cannot be sent for a multiplayer game while either size is empty.

## Chat and user content

- Respect `SDK.game.settings.disableChat` fully, including hiding your own input boxes and incoming text.
- Chat and any user-generated content need moderation: at least a profanity filter, plus a way for players to report. Unmoderated free text is rejected.
- Never display raw HTML from other players.

**Why:** unmoderated free text is how a general-audience portal ends up with abuse, and children's games must have chat off. In the submission you confirm that chat is moderated. **Check before submitting:** set `disableChat` in local mode and confirm your input boxes and incoming text disappear.

## Server hosting

Real-time servers are yours. Keep the first connection fast; show matchmaking progress. If your server is down, the game must say so instead of hanging: the portal does not watch your server and shows players nothing about it, so use a connection timeout of a few seconds and a message with a **Retry** button. Allow the game's origin (`https://g-<your-game-slug>.zokogames.com`, shown with a copy button on the **Technical** step) in your CORS settings and in the `Origin` check of your WebSocket upgrade, connect over `wss://`, and write the host and a way to try it alone in the notes for reviewers. Check: stop your server and start the game.

## Next steps

- [Multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms) for the room channel with an example.
- [Multiplayer and invites](https://docs.zokogames.com/guides/multiplayer-invites) for join links.
- [Launch checklist](https://docs.zokogames.com/guides/launch-checklist) for the reviewer's multiplayer lines.

---

Source: https://docs.zokogames.com/requirements/covers

# Game covers and preview videos

Every game needs three covers to be submitted. They are the first thing a player sees, so most of the click-through rate is decided here. Specs below are exact. The reason: the portal derives every tile, rail and game-page image from these three files, and an exact size means nothing is stretched or cropped by surprise. The console checks every cover's size and file format and refuses one that misses them, and the server checks again, so you can test a cover simply by uploading it to the **Artwork** step before you submit.

## Covers

| Cover | Ratio | Size |
| --- | --- | --- |
| Landscape | 16:9 | 1920 x 1080 px |
| Portrait | 2:3 | 800 x 1200 px |
| Square | 1:1 | 800 x 800 px |

Covers must be **exactly** the size shown, as PNG, JPG or WebP, and at most 5 MB. All three are required to submit: a submit with one missing is refused and names the missing ones. A cover is one still picture: an animated PNG or WebP is refused, and a GIF, HEIC, AVIF, SVG or PDF is refused even when it is named `.png` (the portal reads the file itself, not its name). The console checks the file in your browser before it uploads anything, and every refusal names what it found (for example `3840 x 2160 px, 7.3 MB`) next to what is required. A cover whose shape is right but whose size is not needs a plain resize; one with another shape needs a crop, and the message says which. To prepare a cover, export one still picture from your image editor at exactly the size above, as PNG, JPG or WebP in the sRGB colour profile, with a solid background and under 5 MB; if a PNG is too heavy, export it as JPG or WebP at quality 85. A cover with see-through areas or in the CMYK colour mode (a print mode) is accepted with a note, because pages show transparent pixels over their own background and some browsers and link previews show CMYK with wrong colours.

When you upload a cover, your browser also makes smaller WebP copies of it at a fixed set of widths, and the portal serves each player the smallest copy that fills the tile, row or page on their screen; the full-size file is used only where nothing smaller fits. If your browser cannot make WebP copies, the cover is uploaded without them and the full-size file is served everywhere. The smallest copies are only a few hundred pixels wide or less, so check that the cover still reads at that size.

**Where players see each cover:**

| Cover | Where it appears |
| --- | --- |
| Landscape | Every tile on the home page, in category, tag and New lists and in the related games rows; the game page before Play; the phone list view, cropped to a box about 114 x 64 px; and the picture in a link preview when someone shares the game. |
| Square | Search suggestions and the bar that follows the game page as it scrolls, at 40 to 48 px. |
| Portrait | Required, but no player page shows it today: it is kept for phone layouts. Until then it only stands in for a landscape or square cover that is missing or fails to load. |

The preview video that plays when a desktop player points at a tile is the landscape one; it is also the video in link previews of a game page that has no trailer. The portrait video is needed for full launch too, but no player page plays it today: it is kept for phone layouts. The **Artwork** step shows your covers at these shapes and sizes under **How it looks on the portal**.

Guidelines:

- Show the game's own art, a character or a recognisable scene. Do not use a screenshot with UI clutter.
- Put the title in the picture only if it is large and legible at thumbnail size. The portal also displays the title separately.
- Keep important content away from the edges; the portal crops and rounds corners.
- No logos of other portals, no store badges, no "free" or "new" stickers, no rating labels.
- The image must match the game. Misleading covers are rejected.

## Preview videos

| Property | Requirement |
| --- | --- |
| Format | MP4 with an H.264 video track, one landscape and one portrait |
| Size in pixels | Landscape exactly 1920 x 1080; portrait exactly 720 x 1080 |
| Length | 15 to 20 seconds |
| File size | At most 50 MB |
| Audio | None. A video with an audio track is rejected. |
| Frame rate | Constant, for example 30 frames a second. A variable frame rate is accepted with a warning. |
| Streaming | The index at the front of the file (`faststart`). A file with the index at the end is accepted with a warning. |
| First frame | Make it identical to the cover so the video does not jump when it starts |
| Content | Gameplay only: no cursor, no text overlays, no black bars |

A video with the right ratio but another size (1080 x 1620 for the portrait slot, say) is refused too: the portal does not rescale it. The refusal names the size it found and the size it needs, and shows a command with a **Copy command** button. **Prepare your files:** to convert a file yourself, run `ffmpeg -i in.mp4 -vf scale=720:1080 -an -c:v libx264 -pix_fmt yuv420p -crf 20 -movflags +faststart out.mp4` for the portrait slot, or the same with `scale=1920:1080` for the landscape slot. In the console the command carries your own file name and writes a new file beside it (`my-clip-zoko.mp4`), so you can paste it as it is.

The console reads the video in your browser before it uploads anything, with the same parser the server uses, so a file the server would refuse is refused at once and not after a 50 MB upload. It refuses a video that is not MP4 (the message says what the file looks like, for example QuickTime MOV or WebM), is not H.264 (it names the codec found, such as HEVC, VP9 or AV1, which do not play in every browser), is the wrong size, is too long or too short (half a second of tolerance), is too large, or has an audio track. Each refusal names what it found next to what is required and, where one command fixes it, shows that command: the `ffmpeg` line above also removes audio, re-encodes to H.264, cuts a long video to 20 seconds (it adds `-t 20`) and compresses an oversized file harder (`-crf 28`). All the findings of one file are listed together and one command fixes them all. A clip that is too short has no command: extend the edit or loop the gameplay. A video of another shape (not 16:9 or 2:3) is not stretched: the refusal tells you to re-export it from your editor at the right shape, and shows a second command that fills the frame and crops the overflow instead (`-vf "scale=1920:1080:force_original_aspect_ratio=increase,crop=1920:1080"` for the landscape slot) for when losing some of the edges is fine. Two things are accepted but flagged: a variable frame rate (screen and phone recordings; add `-r 30` to write a constant 30 frames a second) and an index at the end of the file (the `-movflags +faststart` in the command moves it to the front so the video starts playing before it has downloaded). A cover over 5 MB is refused too: export it as WebP or JPG at quality 85. Show the most engaging action in the first few seconds. Loop-friendly endings play better. Preview videos are not needed to submit, but they are needed for full launch. Reviewers check that covers and videos match the game; a mismatch is sent back as **Artwork does not meet specs** or **Listing information**, see [quality guidelines](https://docs.zokogames.com/requirements/quality#reasons-a-submission-is-sent-back-or-rejected).

## Artwork changes

A live game must always keep all three covers, so you replace a cover instead of removing it. New files are staged in the **Artwork** step, then sent with **Submit artwork for review**; they replace the live artwork only after a reviewer approves them, and only one artwork review can be open at a time. The live game keeps showing its current artwork until the approval: while a new cover or video waits, players still see the current one (or nothing, if that slot was empty), each card says so, and the **How it looks on the portal** previews include the staged files and say that they do. You can cancel an upload while it is sent (not during the last step, when the portal checks and saves it), and after a dropped connection, a storage hiccup or a session that ended mid-upload (sign in again in a new tab from the notice, then come back) the console offers **Try again with the same file** so you do not have to choose it again; after a refusal, fix the file and choose it again, which replaces nothing until it passes. Files go straight from your browser to storage, so a 5 MB cover is not held back by a request size limit. The number of uploads is limited: at most 40 cover uploads an hour per game, 60 per person, and 20 preview videos an hour per person; past that the card says how many minutes to wait and keeps the artwork already saved. A cover that is waiting for review, or already approved, keeps its smaller WebP copies: a new upload of that same image is refused with a sentence that says whether to wait for the decision or to upload the changed image as a new cover. While a review is open the console says so and does not offer to send again; replacing a staged file in that time changes what the reviewer sees. A video recorded on a phone is often stored sideways with a rotation flag, so its stored size is the reverse of what you see; if the refusal names a size you did not expect, re-encode it with the command above. If you want to compare two versions, use [artwork experiments](https://docs.zokogames.com/guides/artwork-experiments).

## Next steps

- [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough)
- [Artwork experiments](https://docs.zokogames.com/guides/artwork-experiments)

---

Source: https://docs.zokogames.com/requirements/embedding

# Embedding and sitelock policy

Every rule here has a reason and a check you can run before you submit. Terms such as **build**, **basic launch** and **studio** are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Where your game runs

A game uploaded to ZokoGames is served from its own origin:

```text
https://g-<your-game-slug>.zokogames.com/<build-id>/index.html
```

Covers come from `https://imgs.zokogames.com/`. Because each game has its own origin, your `localStorage`, cookies and service workers are isolated from every other game and from the portal. This is also the `Origin` your own game server sees; the **Technical** step of the game's editor shows it with a copy button. The portal page embeds the game in an `iframe` and the SDK talks to it through `postMessage`.

## Letting other sites embed your game

Partner sites can show your game with an iframe that points at the portal's embed player:

```text
https://www.zokogames.com/embed/<your-game-slug>
```

Embedding is **off by default** and you decide per game. In the submission wizard, open the **Technical** step and find the **Audience and distribution** card. Switch on **Allow embedding on partner sites** (you can change it later on the game's **Edit and submit** tab). When it is off, `/embed/<slug>` shows a short notice with a link to the game page instead of the game, and the game is only shown on ZokoGames pages and apps.

- **Games made for children can never be embedded.** Turning on **Made for children** switches embedding off automatically and the toggle stays unavailable.
- The embed player is a minimal page: the cover, the game name and a **Play** button. The game loads only after the visitor clicks, in the same sandboxed iframe the portal uses, so the rules in the next section apply unchanged. A **Play on ZokoGames** link and a fullscreen button are always visible.
- The embed route may be framed by any website (`frame-ancestors *`). The normal game page stays restricted to ZokoGames.
- Your game origin (`g-<slug>.zokogames.com`) still only lets the portal frame it. Partner sites frame the embed player, never your build directly. The embed player is a plain frame without portal services, so the SDK finds no portal to answer its handshake and reports `"disabled"` there: no ads, accounts, cloud saves or purchases. Make sure the game still starts and plays without them (see [environments](https://docs.zokogames.com/getting-started/environments)).
- A game with embedding on shows an "Embed this game" snippet builder on its page, with responsive, 960x540, 640x360 and portrait sizes.

### Restrict which sites may embed (allowed sites)

By default, with embedding on, any `https` site may frame the embed player. To lock it down, add **Allowed sites** to the game (the same card, or the `allowedOrigins` field of the [developer API](https://docs.zokogames.com/guides/developer-api#game-settings)). The list is enforced by our game host through `frame-ancestors`: a site that is not on it gets a blocked frame, even if it copies the embed code.

| Entry | Meaning |
| --- | --- |
| `https://partner.example` | That exact site (and port, if you give one). |
| `https://*.partner.example` | Every sub-domain of `partner.example`, but **not** `partner.example` itself. List both when you need both. |

Rules, checked when you save: `https` only; an origin and nothing else (no path, query, fragment or credentials); no IP addresses or `localhost`; a wildcard is only a leading `*.` on a registrable domain (`*.example.com` is fine, `*.com` and `*.co.uk` are not) and cannot carry a port; our own domain is always rejected; at most **10** distinct entries. Entries are lower-cased and de-duplicated, and a default port (`:443`) is dropped. An empty list keeps today's behaviour. The list only matters while **Allow embedding on partner sites** is on, and games made for children are never embeddable whatever the list says. Changes reach the game host within about two minutes.

If your build has a domain lock, make sure it allows the embed player's host (it is `zokogames.com`, so the [sitelock rules](#sitelock) already cover it). Put anything unusual in the **Server host and notes for reviewers** field of the **Your own game server and notes for reviewers** card, further down the **Technical** step of the game's editor (up to 1,000 characters).

**Why embedding is off by default:** a partner page would show your game outside the portal's own pages, so it is your decision, and children's games must never leave the portal. **Check before submitting:** open `/embed/<slug>` once the listing is saved: with embedding off you see the notice, with it on you see the cover and the Play button. Then press Play and confirm the game starts without ads, accounts or cloud saves.

## The iframe sandbox

The frame carries these sandbox tokens:

```text
allow-scripts allow-same-origin allow-forms allow-pointer-lock
allow-orientation-lock allow-modals allow-downloads allow-presentation
```

Popups are opt-in per game: tick **Needs popups** in the technical step of the submission if you need one (for example an OAuth window). Without it, `window.open` and `target="_blank"` links are blocked. Kids games, and any game played in kids mode, run without `allow-downloads`, as they already run without popups.

The frame also delegates these permissions: `autoplay`, `fullscreen`, `gamepad`, `clipboard-write`, `accelerometer`, `gyroscope`, `xr-spatial-tracking` and `keyboard-map`. Camera and microphone are off by default. If your game needs one, say so in the submission notes; staff can grant it for that game after review. The **Builds and updates** tab of the game shows whether it has a grant. A grant covers the build staff checked: the next build you submit, send for review or activate ends it, so ask again in the note for that build (for a Basic Launch update, which has no review, ask [support](https://docs.zokogames.com/business/support)). Kids games never get them. A browser still asks the player before it grants camera or microphone.

What this means in practice:

- Do not depend on `window.top`, `window.parent` content or cookies shared with another site. Use [`SDK.data`](https://docs.zokogames.com/sdk/data) for saves.
- Do not add your own fullscreen button. The portal provides one.
- Pointer lock works after a user gesture. Handle Escape by pausing.
- Navigation of the top window is blocked. Do not redirect players away from the game.

**Why:** each game runs on its own origin in a sandbox, so one game cannot read another's data or move the portal page. **Check before submitting:** play in the [Preview tool](https://www.zokogames.com/preview), which uses the real frame, with the console open; the first red error is usually the one a reviewer sees. **Finding codes:** `service_worker` (a game worker can clash with the portal's offline saving), `cookie_access` (cookies are not shared inside the frame) and `top_navigation` (a sandboxed frame cannot navigate the portal) in [frame behaviour codes](https://docs.zokogames.com/requirements/build-validation#external-host-and-frame-behaviour-codes). `cookie_access` and `top_navigation` are only a note when the code looks like a known vendor library.

## Sitelock

Sitelock stops people re-hosting your build. It is optional, and it must never lock out the portal or your own testing.

```js
const host = location.hostname;
const allowed =
  host === "zokogames.com" || host.endsWith(".zokogames.com") ||
  host === "localhost" || host === "127.0.0.1" || host.endsWith(".localhost");

if (!allowed) {
  document.body.textContent = "Play this game on zokogames.com";
  throw new Error("sitelock");
}
```

Rules:

1. Allow `zokogames.com` and every subdomain of it. Game origins use the `g-<slug>` pattern today and may change; never lock to one exact hostname. (This is about locking the build itself. A server's CORS allow-list is different: it should name the game's own origin exactly, never `*.zokogames.com`.)
2. Allow `localhost` so the SDK's local mode and the [Preview tool](https://www.zokogames.com/preview) keep working.
3. Run the check before you load assets, but do not block the first frame on a network call.
4. A visible message beats a blank screen. Reviewers must be able to tell a sitelock from a crash.

**Why:** a lock that is too tight locks out the portal, the embed player and the reviewer. **Check before submitting:** open the game in the Preview tool and on `localhost`; both must start. A hard-coded host also shows as an external host in the report.

## Store apps

The portal's phone apps (an Android Trusted Web Activity and an iOS wrapper; they are being prepared and are not in the stores yet) open the portal website itself, so your game is still framed by a `www.zokogames.com` page. You do not add an app origin, a package name or a scheme such as `capacitor://` to the allowed sites, and the [sitelock](#sitelock) check passes as it does in a browser. One thing does change inside a store app: the portal serves no ads there (see [ads](https://docs.zokogames.com/sdk/ads), error `adsDisabled`), so keep your game working when an ad request ends in an error. If you embed the game on your own site and that site is also wrapped in an app, the wrapper must load your site from its `https` domain name: the allowed sites accept only `https` domain names, so an origin such as `https://localhost`, an IP address or a custom scheme cannot be added.

Inside the Android app the portal also shows no ad before the game starts, banner requests fail with `bannersDisabled`, and in-game purchases are off: `SDK.store.isAvailable` is `false` and `buyItem` rejects with `purchaseInitFailed` (see [in-game purchases](https://docs.zokogames.com/sdk/purchases#when-the-player-is-a-guest-offline-or-ad-free)). Hide your shop when the store is not available.

## Hosting on your own server

This section is for a game whose page is hosted on your own server. A game that is uploaded to ZokoGames and only calls your server needs none of it: it needs your server to allow its origin, described under privacy and your own game server in the technical requirements. If you choose "on your own server" in the submission, your `https` page must allow being framed by the portal:

```text
Content-Security-Policy: frame-ancestors 'self' https://zokogames.com https://*.zokogames.com
```

Do not send `X-Frame-Options: DENY` or `SAMEORIGIN`. Cross-origin cookies are not available in the frame, so use the [data module](https://docs.zokogames.com/sdk/data) and the [verified token](https://docs.zokogames.com/sdk/user#tokens) for identity. Games on your own host only earn when they use the SDK, and they are judged on time to gameplay. See [technical requirements](https://docs.zokogames.com/requirements/technical). **Check before submitting:** enter your address in the [Preview tool](https://www.zokogames.com/preview). It frames the page in the same portal frame, so a header that forbids framing shows up at once.

## Embedding the SDK handshake

You do not need to code the handshake. `SDK.init()` posts a request to the parent window, pins the origin that answers and ignores messages from anywhere else. Only an answer from ZokoGames (`https` on `zokogames.com` or one of its subdomains, except the game hosts `g-<slug>` and the preview runner `preview-run`), a local host (only while the game itself runs on a local host) or the game's own origin counts: another site that frames the game cannot pose as the portal. If no portal answers within 1.5 seconds, the SDK falls back to local mode on `localhost` (or when the URL has `useLocalSdk=true`), and otherwise reports `"disabled"`. See [environments](https://docs.zokogames.com/getting-started/environments).

## Next steps

- [Technical requirements](https://docs.zokogames.com/requirements/technical)
- [Introduction, init and errors](https://docs.zokogames.com/sdk/introduction)

---

Source: https://docs.zokogames.com/requirements/build-validation

# Build validation reference

When you upload a build zip, the portal unpacks it in memory, checks it and produces a **validation report**. Errors block the build; warnings and notes do not. Blocking safety findings count as errors. The report is stored with the build, so you can open it again later in the console, and your studio gets a notification when a build passes or is rejected (see [notifications](https://docs.zokogames.com/guides/notifications)). Builds validated before the structured report existed show only the older list of issues.

The size and file limits are summarised on [technical requirements](https://docs.zokogames.com/requirements/technical); this page lists everything by code. Terms used here: a **build** is one set of uploaded files; the report belongs to that build. A **version** always means an SDK version.

## If your build was rejected

The validator rejects a build when you upload it; a reviewer sends a game back after you submit it. The two are fixed differently:

- **Build rejected.** The report lists at least one error. Find each error code in [errors](#errors-the-build-is-rejected) below, fix the cause and upload a new zip. A rejected build is never served to players, and warnings never reject a build.
- **Game sent back.** Your studio receives the decision with numbered reasons and a note. [Quality guidelines](https://docs.zokogames.com/requirements/quality) explain each reason, and the [testing checklist](https://docs.zokogames.com/getting-started/testing-checklist) lists every line the reviewer answers.

## Check a build before you submit

The validator runs when you upload, and the report opens from the **Build** step of the submission. You can see most findings earlier:

1. Zip the contents of your export folder and look at the size and file count against the table below.
2. Run the game from `localhost` (the SDK mocks the portal, see [local testing](https://docs.zokogames.com/getting-started/local-testing)) and watch the console for 404s: they are what `missing_reference`, `case_mismatch` and `absolute_path` warn about.
3. Open the [Preview tool](https://www.zokogames.com/preview) with your address, or the **Preview and QA** tab of the game once a build has passed. Its checklist ticks from the SDK calls your game makes and flags a first `gameplayStart` later than 20 seconds.
4. Upload, open the report and clear every error. Read each warning: they do not block the build, but reviewers see them too.

Every finding in the report links to the page that explains it. The groups below say which requirement page covers which codes.

## Limits

| Limit | Value |
| --- | --- |
| Unpacked size | 250 MB |
| Files | 1,500 |
| Initial download | Error above 50 MB; warning above 20 MB (mobile target) |
| Single file | A warning for any file above 20 MB (up to the three largest are listed) |
| Compression ratio | Error for a file above 1 MB that expands more than 200 to 1, or an archive that expands more than 400 to 1 overall |
| Zip entries | Error for an archive with more than 6,500 entries (the file limit plus room for folder entries) |
| Path length | A path over 1,024 characters or a single segment over 255 is unsafe |
| Problems listed | The first 40 errors and the first 40 warnings; further ones are summarised as one `more` entry |
| Findings in the report | 60 at most |
| Text scan, per file | Files above 3 MB are not scanned |
| Text scan, total | Stops after 24 MB of text |
| Text scan, time | Stops after 8 seconds |

"Initial download" is estimated from the uncompressed size of `index.html`, every file it references and the engine bootstrap payload. Files fetched after the game starts do not count.

Why these limits exist: the size and file caps keep a build fast to unpack and serve; the 50 MB initial-download cap keeps first play short for a visitor on a phone; the ratio and path rules stop archives that could exhaust memory or write outside the build folder; blocked types keep the host static.

## Errors (the build is rejected)

| Code | Meaning | Fix |
| --- | --- | --- |
| `not_zip`, `corrupt`, `central_mismatch`, `size_mismatch`, `total_bytes` | The file is not a readable zip, is damaged, or its entries are inconsistent or inflate beyond their declared or total size. The portal never trusts the sizes a zip declares, so it inflates every entry under a hard cap. | Re-create the zip with a standard tool. |
| `zip64`, `too_many_entries` | Zip64 archives are not supported, or the archive has more than 6,500 entries. | Split large data into fewer, smaller files and zip without Zip64. |
| `empty` | The archive has no files. | Zip the contents of your export folder. |
| `no_index` | No `index.html` at the root, or inside a single top-level folder (which is stripped and reported as `nested_root`). | Put `index.html` at the root. |
| `unsafe_path` | An absolute path, drive letter, `..`, backslash, `?` or `#` in a name, control or bidirectional-override character, empty or dot segment, or an over-long name. | Rename the file. |
| `symlink` | The zip contains a symbolic link. | Zip real files. |
| `encrypted` | An entry is password protected. | Remove the password. |
| `compression` | An unsupported zip compression method. | Use Deflate or store. |
| `duplicate` | The same path appears twice. | Remove the duplicate. |
| `blocked_type` | An executable or server-side file such as `.php`, `.exe`, `.dll`, `.bat`, `.sh`, `.jar`, `.py`, `.htaccess`, `.htpasswd`, `web.config`, `php.ini`. | Remove it; games are static. |
| `compression_ratio` | A suspicious ratio, per file or overall. | Do not zip data that expands this far. |
| `too_many_files` | More than 1,500 files. | Combine files, for example into an atlas or pack. |
| `too_large` | Unpacked size above 250 MB, or a single entry that is too large. | Compress assets and load some later. |
| `initial_too_large` | Estimated initial download above 50 MB. | See [first frame fast](https://docs.zokogames.com/guides/first-frame). |
| `bad_precompressed` | A `.gz` file that is not gzip data. | Re-export with gzip, or upload uncompressed. |
| `unsafe_<rule>` | The safety scan matched a blocking rule, one of `unsafe_native_executable`, `unsafe_executable_extension`, `unsafe_double_extension`, `unsafe_shell_script`, `unsafe_invalid_wasm`, `unsafe_nested_archive_executable`, `unsafe_crypto_miner`, `unsafe_credential_phishing`, `unsafe_obfuscated_eval`, `unsafe_script_from_ip`, `unsafe_script_from_shortener`, `unsafe_cookie_exfiltration` or `unsafe_reputation_malicious`. The rule names are in [the safety scan](#the-safety-scan). Not to be confused with `unsafe_path`, which is a path problem. | Remove the file or code the finding names. |

## Warnings and notes (the build is accepted)

| Code | Severity | Meaning |
| --- | --- | --- |
| `mobile_initial_large` | warn | Initial download above 20 MB. Reviewers test on a phone. |
| `large_file` | warn | A single file above 20 MB. |
| `missing_reference` | warn | `index.html` references a file that is not in the zip. |
| `case_mismatch` | warn | A referenced file differs from the real name only by letter case, so it returns 404 on our host (names are case sensitive there, unlike on many desktops). |
| `external_url` | warn | The build references external hosts (the first eight are named). Bundle what the game needs into the zip. The report replaces it with one `origin_*` finding per kind of host. |
| `case_collision` | warn | Two paths differ only by case. |
| `reserved_name` | warn | A file name starts with `_zoko`. The game origin never serves such a file (404). |
| `reserved_path` | warn | A file sits in the top-level `__zk/` folder, which the portal reserves for offline play. Nothing in it is served (404). |
| `hidden_file` | warn | A file or folder whose name starts with a dot (`.git`, `.env`, `.vite`). The game origin never serves it (404). |
| `absolute_path` | warn | A root-absolute path such as `/game.js` in `index.html`. Use relative paths. |
| `index_not_html` | warn | `index.html` does not look like an HTML document. |
| `unknown_type` | warn | A file type the portal does not recognise, served as generic binary. |
| `no_sdk` | warn | The ZokoGames SDK script is not referenced, so ads, saves and scores will not work. |
| `sdk_bundled` | warn | A copy of the SDK appears to be bundled. Load the hosted script so fixes reach players. |
| `third_party_sdk` | warn | Another portal's SDK was detected. Remove it. |
| `non_utf8_name` | warn | A file name is not stored as UTF-8 and may be garbled. |
| `origin_fonts`, `origin_cdn`, `origin_analytics`, `origin_ads`, `origin_unknown` | warn | External hosts referenced from your code, grouped by kind. They may break under the sandbox, and a build that needs external hosts cannot be saved for offline play. Ad networks other than the SDK are not allowed (see [advertisement rules](https://docs.zokogames.com/requirements/advertisements)). |
| `mixed_content` | warn | Absolute `http://` URLs, blocked on an https page. |
| `service_worker` | warn | The build registers a service worker, which can clash with the portal's offline handling. |
| `cookie_access` | warn, or info when the code looks like a known vendor | Code uses `document.cookie`. Cookies are not shared inside the frame; use the [data module](https://docs.zokogames.com/sdk/data). |
| `top_navigation` | warn, or info for a known vendor | Code touches `window.top` or opens `_top`. A sandboxed frame cannot navigate the portal. |
| `unity_unityweb` | warn | `.unityweb` files get no content encoding, so the loader unpacks them in JavaScript and the game starts slower. Turn **Decompression Fallback** off and re-export with Brotli or Gzip. |
| `unity_mixed_compression` | warn | `.br` and `.gz` files are mixed. Re-export. |
| `unity_compression_mismatch` | warn | Some Build files are compressed and others not. |
| `sdk_pinned` | info | The SDK URL is pinned to a version; it will not receive fixes until you update it. |
| `sdk_no_init` | info | No SDK init call was found by a static scan. Engine wrappers and minified code can hide it; check the [Preview tool](https://www.zokogames.com/preview). |
| `sdk_compat_shim` | info | The SDK is used through the [compat shim](https://docs.zokogames.com/guides/migrating), so its init call goes through the legacy global, which a static scan cannot follow. Nothing to do if the [Preview tool](https://www.zokogames.com/preview) shows the init call; otherwise check that the shim script loads after the SDK script. |
| `nested_root` | info | Everything was inside one folder; it was detected as the root. |
| `junk_ignored` | info | System files such as `__MACOSX` and `.DS_Store` were ignored. |
| `engine_low_confidence` | info | The engine was guessed from text signatures only. |
| `scan_truncated` | info | The static scan hit its time or size budget, so some findings may be missing. |

## Finding reference {#finding-reference}

Each finding in the report links to its entry here. An entry says what was found and how to fix it. The report adds the file, and the line in `index.html` where the validator can place it. Several findings with the same code about different files are shown once, with a count and an expandable list of files. **Copy report** and **Download report** put the whole report into plain text you can paste to a teammate or a coding agent. Safety scan rules (`unsafe_<rule>`) are explained in [the safety scan](#the-safety-scan).

### `not_zip` {#code-not-zip}

The file is not a zip, or is too small to be one. **Fix:** Create the zip again with your system's zip tool. `.rar`, `.7z` and `.tar.gz` are not accepted.

### `corrupt` {#code-corrupt}

The zip could not be unpacked, usually because the upload was cut short or the archive is damaged. **Fix:** Create the zip again from your export folder and upload it again.

### `central_mismatch` {#code-central-mismatch}

The zip's file list (central directory) does not match the files inside it. **Fix:** Create the zip again with a standard tool; archives edited or merged by hand break this way.

### `size_mismatch` {#code-size-mismatch}

A file inflates to a different size than the zip declares for it. **Fix:** Create the zip again with a standard tool.

### `total_bytes` {#code-total-bytes}

The zip inflates beyond the total size limit while being unpacked. **Fix:** Remove unneeded files and compress textures and audio. See the [limits](#limits).

### `zip64` {#code-zip64}

The archive uses Zip64, which is not supported. **Fix:** Reduce the number and size of files so a normal zip is enough, and zip again.

### `too_many_entries` {#code-too-many-entries}

The archive has more than 6,500 entries. **Fix:** Combine small files into atlases or packs.

### `empty` {#code-empty}

The zip contains no files. **Fix:** Select the files inside your export folder and zip those.

### `no_index` {#code-no-index}

There is no `index.html` at the root of the zip, or inside a single top-level folder. The report shows the nearest `index.html` it found, if any. **Fix:** Zip the contents of your export folder, not the folder itself. If the entry page is two folders deep, move its folder's contents up to the root. The name must be exactly `index.html` in lower case.

### `unsafe_path` {#code-unsafe-path}

A name is an absolute path (`/game.js`), has a drive letter (`C:\\`), a `..` segment, a backslash, `?` or `#`, a control character, or is too long. The details line says which. **Fix:** Rename the file or zip again with relative paths. Zip tools that store absolute paths usually do so because the zip was made from the wrong folder.

### `symlink` {#code-symlink}

The zip contains a symbolic link. **Fix:** Replace the link with a real copy of the file.

### `encrypted` {#code-encrypted}

An entry is password protected. **Fix:** Zip again without a password.

### `compression` {#code-compression}

An entry uses a compression method other than Deflate or store. **Fix:** Zip again with the standard method.

### `duplicate` {#code-duplicate}

The same path appears twice. **Fix:** Remove the duplicate and zip again.

### `blocked_type` {#code-blocked-type}

The zip contains an executable or server-side file (`.php`, `.exe`, `.sh`, `.py`, `.htaccess` and similar). The report names the file. **Fix:** Delete it from your export folder (a stray build script, `.sh`, `.exe`, `.php` or `.htaccess`) and zip again. Games are static files only; nothing in the zip is ever run on the server.

### `compression_ratio` {#code-compression-ratio}

A file above 1 MB expands more than 200 to 1, or the archive expands more than 400 to 1 overall. **Fix:** Do not zip data that expands this far.

### `too_many_files` {#code-too-many-files}

The zip has more than 1,500 files. **Fix:** Combine files into atlases or packs.

### `too_large` {#code-too-large}

The build unpacks to more than 250 MB, or one entry is too large. **Fix:** Compress assets and load optional content after the game starts.

### `initial_too_large` {#code-initial-too-large}

The estimated first download is above 50 MB. **Fix:** See [first frame fast](https://docs.zokogames.com/guides/first-frame).

### `bad_precompressed` {#code-bad-precompressed}

A `.gz` file is not gzip data. **Fix:** Re-export with gzip, or upload the file uncompressed.

### `more` {#code-more}

More errors were found than the report lists (40 are listed). **Fix:** Fix the ones shown and upload again.

### `mobile_initial_large` {#code-mobile-initial-large}

The estimated first download is above 20 MB. **Fix:** Load levels and audio after the first frame. See [first frame fast](https://docs.zokogames.com/guides/first-frame).

### `large_file` {#code-large-file}

A single file is above 20 MB. **Fix:** Split or compress it, or load it after the game starts.

### `missing_reference` {#code-missing-reference}

`index.html` references a file that is not in the zip. The report lists each file, grouped under one finding when there are several, with the line in `index.html`. **Fix:** Add the file to the export folder, or correct the path; the path is read from the zip root. See [relative paths only](https://docs.zokogames.com/requirements/technical#relative-paths-only).

### `case_mismatch` {#code-case-mismatch}

A referenced file differs from the real name only by letter case. **Fix:** Match the exact case; the host is case sensitive.

### `external_url` {#code-external-url}

The build references external hosts. The report shows one `origin_*` finding per kind instead. **Fix:** Bundle what the game needs into the zip.

### `case_collision` {#code-case-collision}

Two paths differ only by letter case. **Fix:** Delete or rename one of the two files so no two names are the same when letter case is ignored (for example `Hero.png` and `hero.png`), and update the code that loads it. The portal keeps both, but a zip unpacked on Windows or a Mac overwrites one of them.

### `reserved_name` {#code-reserved-name}

A file name starts with `_zoko` (any case, in any folder). The portal keeps these names for its own files, and the game origin answers a request for one with 404, so the file is in the build but never reaches the player. **Fix:** Rename the file (for example without the underscore prefix) and the code or data that loads it, then zip again. Nothing breaks if the game never loads it.

### `reserved_path` {#code-reserved-path}

A file sits in a folder named `__zk` at the top of the zip. The portal uses `/__zk/` on the game address for offline play and answers every other request there with 404. **Fix:** Move the files of that folder to another one (for example `assets/`), update the paths that load them and zip again. A folder named `__zk` deeper down, such as `assets/__zk/`, is fine.

### `hidden_file` {#code-hidden-file}

A file or folder whose name starts with a dot (`.git`, `.env`, `.vite`, `.well-known`). The game origin never serves such a name, so a request for it answers 404. `.DS_Store` and `__MACOSX` are ignored separately (`junk_ignored`). **Fix:** If the game does not load it, delete it from the export folder and zip again; a `.git` folder or a `.env` file should not be in the zip at all. If the game does load it, rename it without the dot and update the path.

### `absolute_path` {#code-absolute-path}

`index.html` uses a root-absolute path such as `/game.js`, which 404s under the build folder. **Fix:** Make the path relative: `./game.js`, not `/game.js`. If a bundler writes it, set a relative base and build again: Vite `base: './'` in `vite.config`, webpack `output.publicPath: ''`, Create React App `"homepage": "."` in `package.json`. Links to `/sdk/` and `/_shared/` are fine.

### `index_not_html` {#code-index-not-html}

`index.html` does not look like an HTML document. **Fix:** Open `index.html` in a text editor: it must start with `<!doctype html>` and contain `<html>`. If it holds a redirect, an error message or an engine template that was not filled in, export the game again and zip the new `index.html`.

### `unknown_type` {#code-unknown-type}

The zip has files of a type the portal does not recognise; they are served as generic binary. **Fix:** Nothing to do unless the engine needs a specific Content-Type.

### `no_sdk` {#code-no-sdk}

The SDK script is not referenced, so ads, saves and scores will not work. **Fix:** Add `<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>` to the `<head>` of `index.html` and call `ZokoGames.SDK.init()` when the game starts. The engine plugins do both for you. See the [SDK introduction](https://docs.zokogames.com/sdk/introduction).

### `sdk_bundled` {#code-sdk-bundled}

A copy of the SDK appears to be bundled in the build. **Fix:** Delete the copied SDK file and load `https://sdk.zokogames.com/zokogames-sdk-v1.js` from `index.html` instead, so SDK fixes reach players without a new upload. See [versioning](https://docs.zokogames.com/sdk/versioning#do-not-self-host-an-old-copy).

### `third_party_sdk` {#code-third-party-sdk}

Another portal's SDK was detected. **Fix:** Delete the other portal's `<script>` tag and its init and ad calls, then add this portal's SDK instead (see [migrating](https://docs.zokogames.com/guides/migrating)). Only this portal's SDK is supported.

### `non_utf8_name` {#code-non-utf8-name}

A file name is not stored as UTF-8 and may be garbled. **Fix:** Zip again with UTF-8 names, or use plain ASCII names.

### `origin_fonts` {#code-origin-fonts}

The code calls an external font host. **Fix:** Download the font files (`woff2`) into the zip and load them with `@font-face` and a relative `url(./fonts/name.woff2)`.

### `origin_cdn` {#code-origin-cdn}

The code loads from an external CDN. **Fix:** Download the script or asset into the zip and load it with a relative path (`./lib/name.js`), or install it with npm so the bundler includes it.

### `origin_analytics` {#code-origin-analytics}

The code calls an external analytics host. **Fix:** Remove the analytics script and its calls; measurement comes from the SDK's own events.

### `origin_ads` {#code-origin-ads}

The code calls an ad network other than the SDK. **Fix:** Remove the ad network's script and calls; ads in a game come only from the SDK's ad calls. See the [advertisement rules](https://docs.zokogames.com/requirements/advertisements).

### `origin_unknown` {#code-origin-unknown}

The code calls an external host that could not be classified. **Fix:** If it is your own game server (multiplayer, login, saves) it is allowed over `https://` and `wss://`: write its host name in the **Server host and notes for reviewers** field of the **Your own game server and notes for reviewers** card on the Technical step, where the reviewer reads it next to this finding, and make that server accept the game's origin (shown on the same card). Bundle everything else.

### `mixed_content` {#code-mixed-content}

The code uses absolute `http://` URLs, which are blocked on an https page. **Fix:** Use `https://` or relative paths.

### `service_worker` {#code-service-worker}

The build registers a service worker. **Fix:** Ship no worker of your own, because the portal handles offline saving. Construct 3: Project Properties, **Offline support: No**. Godot: turn **Progressive Web App** off in the Web export preset. Vite or webpack: disable the PWA plugin (`vite-plugin-pwa`, Workbox) for this build. Hand-written code: delete the `navigator.serviceWorker.register` call and the worker file, then export again.

### `cookie_access` {#code-cookie-access}

Code uses `document.cookie`. **Fix:** Use the [data module](https://docs.zokogames.com/sdk/data); cookies are not shared inside the frame.

### `top_navigation` {#code-top-navigation}

Code touches `window.top` or opens `_top`. **Fix:** Remove it; a sandboxed frame cannot navigate the portal.

### `unity_unityweb` {#code-unity-unityweb}

`.unityweb` files are served without `Content-Encoding`, so the loader unpacks them in JavaScript and the game starts slower. This is Unity's Decompression Fallback, or a 2019 or older export. **Fix:** In Player Settings > Publishing Settings turn **Decompression Fallback** off, set **Compression Format** to Brotli or Gzip and build again; the portal then serves `.br` and `.gz` with the right header and the loader has nothing to unpack.

### `unity_mixed_compression` {#code-unity-mixed-compression}

`.br` and `.gz` Build files are mixed. Stale files from an earlier build are the usual cause. **Fix:** Choose one **Compression Format** in Publishing Settings, delete the build output folder and build again, so every file in `Build` ends in the same `.br` or `.gz`.

### `unity_compression_mismatch` {#code-unity-compression-mismatch}

Some Build files are compressed and others are not. **Fix:** Delete the build output folder and build again with one **Compression Format**. The report names the uncompressed file; check that `dataUrl`, `frameworkUrl` and `codeUrl` in `index.html` name the same set of files.

### `sdk_pinned` {#code-sdk-pinned}

The SDK URL is pinned to a version. **Fix:** Use the latest URL unless you need a fixed version.

### `sdk_no_init` {#code-sdk-no-init}

No SDK init call was found by a static scan. **Fix:** Check the [Preview tool](https://www.zokogames.com/preview); engine wrappers and minified code can hide the call.

### `sdk_compat_shim` {#code-sdk-compat-shim}

The SDK is used through the compat shim, which a static scan cannot follow. **Fix:** Check the init call in the [Preview tool](https://www.zokogames.com/preview).

### `nested_root` {#code-nested-root}

Everything was inside one folder, which was used as the root. **Fix:** Nothing to do; zip the folder's contents to avoid the note.

### `junk_ignored` {#code-junk-ignored}

System files such as `__MACOSX` and `.DS_Store` were ignored. **Fix:** Nothing to do.

### `engine_low_confidence` {#code-engine-low-confidence}

The engine was guessed from text signatures only. **Fix:** Nothing to fix.

### `scan_truncated` {#code-scan-truncated}

The static scan hit its time or size budget, so some findings may be missing. **Fix:** Run the build in the [Preview tool](https://www.zokogames.com/preview).

## The safety scan

Every upload also goes through a safety scan that looks for code and files with no place in a game. It runs on the same upload, and its findings appear in a **Safety scan** section of the report, each with the rule, the file and a short excerpt. A finding has one of three severities:

| Severity | Effect |
| --- | --- |
| Blocked | The build is rejected with the code `unsafe_<rule>`. |
| Needs review | The build passes, but a moderator checks it before players get it (see below). |
| Note | Shown to you only. |

A build that needs review is held for a moderator at every stage. Before launch it can be your active build for Preview, and the moderator checks it in the review of your submission. In basic launch, where updates normally go live with no review, **Activate** and **Roll back** on such a build turn into **Send for review**: it waits in the review queue like a full-launch update, and players keep the current build until a moderator approves it (an approval counts for good, so switching back to that build later is instant). Calling the activate endpoint for it returns `outcome: "queued_for_review"` with `reason: "safety_review"`. Size and download-budget warnings never hold a build.

| What it catches | Rule name | Severity | What triggers it |
| --- | --- | --- | --- |
| Native program | `native_executable` | Blocked | A file whose first bytes are a Windows, Linux, macOS or Java executable, or a Windows shortcut, whatever its name. |
| Program or script extension | `executable_extension` | Blocked | A program, installer or script extension such as `.exe`, `.msi`, `.sh`, `.ps1`, `.jar`, `.apk` or `.dylib`. |
| Disguised file name | `double_extension` | Blocked | An executable name hidden behind a harmless one, such as `report.exe.png`. |
| Not WebAssembly | `invalid_wasm` | Blocked | A `.wasm` file that does not start with the WebAssembly header (`\0asm`), or is really another file type. Re-export the build; never rename another file to `.wasm`. |
| Shell script | `shell_script` | Blocked | A file that starts with a shebang line (`#!`), unless it is JavaScript. |
| Program inside a nested zip | `nested_archive_executable` | Blocked | A zip inside your zip that contains a program or script. |
| Cryptocurrency miner | `crypto_miner` | Blocked | Code that matches a known browser miner. |
| Password phishing form | `credential_phishing` | Blocked | A form with a password field that posts to another website. |
| Hidden eval | `obfuscated_eval` | Needs review for 1 to 3, blocked for 4 or more | `eval` of base64 data (`eval(atob(...))`). |
| Script from an IP address | `script_from_ip` | Blocked; needs review for a private address | A script loaded from a raw IP address. |
| Script from a URL shortener | `script_from_shortener` | Blocked | A script loaded through a URL shortener. |
| Cookie theft | `cookie_exfiltration` | Blocked | `document.cookie` next to a network request to another host. |
| Reputation lookup | `reputation_malicious` | Needs review at 3 to 9 engine flags, blocked at 10 or more | A reputation lookup reports a file as malicious (see below). |
| Other review flags | `frame_breakout`, `popup_loop`, `password_input`, `websocket_raw_ip`, `disguised_archive`, `nested_archives`, `ole_container`, `type_mismatch`, `service_worker` | Needs review (some are notes) | Assigning `top.location`, opening windows in a loop, a password field in a page, a WebSocket to a raw IP, an archive stored under another name, more than 3 nested archives, a legacy Office or installer container, a file whose content does not match its extension, or a service worker that is external, computed or missing from the build. A worker shipped in the build is a note. |

Limits of the scan: it reads at most 2 MB of each HTML and JavaScript file, 16 MB of text in total and stops after 6 seconds; if it stops early the report says so (`scan_truncated`). It keeps at most 40 findings. Absence of a finding is not a guarantee.

When the portal has a reputation service configured, the scan sends only the SHA-256 hash (never the file) of up to 20 large binaries, such as `.wasm` files above 64 KB and engine data files above 1 MB. A failed lookup never blocks a build. Unsafe code found by a reviewer is rejected with the final reason **Security** (see [quality guidelines](https://docs.zokogames.com/requirements/quality#reasons-a-submission-is-sent-back-or-rejected)).

## What else the report contains

- **Engine:** the detected engine (Unity, Godot, Construct, GameMaker, Cocos, Defold, Phaser, plain HTML5 or unknown), a version where one can be read, the evidence, and any rendering libraries spotted on top.
- **Totals:** unpacked bytes, file count, bytes by file type and the ten largest files.
- **Initial download:** the estimate with its pass, warn or fail status against 20 MB and 50 MB.
- **SDK:** whether the hosted SDK, a pinned version or a bundled copy is used, and whether an init call was found.
- **Origins:** the external hosts (at most 25 are recorded) and their kinds: fonts, CDN, analytics, ads or unknown.
- **Scan:** how many text files were scanned. The scanner reads only text files below a per-file cap, stops at a total byte cap and at a time budget, so absence of a finding is not a guarantee.

The scan is static: it cannot prove your game works. Always run the build in the [Preview tool](https://www.zokogames.com/preview) before submitting.

## What the build check returns

The console uploads a build in two requests. `POST /api/developer/games/{id}/builds/presign` prepares the upload and says where to send the zip; `POST /api/developer/games/{id}/builds/confirm` checks the zip once it has arrived. The check runs in the confirm request, which answers `200` whether the build passes or not, so read `ok` rather than the status:

| Field | Meaning |
| --- | --- |
| `ok` (top level) | `true` when the build was accepted and stored, `false` when the check rejected it. |
| `buildId`, `version` | The new build's id and number, or `null` for a rejected build. |
| `activated` (top level) | `true` when the build became the game's active build straight away: every valid build does while the game is not live (draft, changes requested, rejected, unpublished). On a live game it is `false`, and players keep the current build until you switch. |
| `validation.ok` | The same value as `ok`. |
| `validation.issueDetails` | One entry per error, in order: a stable `code` from [the errors table](#errors-the-build-is-rejected), a `message` for people and, when the error concerns one file, its `path`. |
| `validation.issues` | The same errors as plain messages, in the same order, with the path in brackets. |
| `validation.warnings` | Warnings as plain messages. They never reject a build. |
| `validation.engine`, `fileCount`, `totalBytes`, `initialBytes`, `usesSdk`, `externalHosts` | What the check measured: the detected engine, the file count, the unpacked and initial-download bytes, whether the SDK script is referenced, and up to 25 external hosts. |
| `validation.report` | The full validation report described on this page. |

The archive is read in two passes, and a build that fails the first one (the zip structure, paths, file types, size and file count) is not scanned further. A fixed build can therefore show new errors on the next upload. When the first pass finds more than 40 errors, the list ends with one entry with the code `more` instead of the rest. Limits are in the [limits table](#limits).

A rejected build (the `report` object is left out of both examples):

```json
{
  "ok": false,
  "buildId": null,
  "version": null,
  "validation": {
    "ok": false,
    "issues": [
      "Executable or server-side files are not allowed (tools/export.sh)",
      "index.html must be at the root of the zip (not found; multiple top-level folders)"
    ],
    "issueDetails": [
      {
        "code": "blocked_type",
        "message": "Executable or server-side files are not allowed",
        "path": "tools/export.sh"
      },
      {
        "code": "no_index",
        "message": "index.html must be at the root of the zip (not found; multiple top-level folders)"
      }
    ],
    "warnings": [],
    "engine": "unknown",
    "externalHosts": [],
    "initialBytes": 0,
    "usesSdk": false,
    "totalBytes": 0,
    "fileCount": 37
  },
  "activated": false
}
```

An accepted build:

```json
{
  "ok": true,
  "buildId": "3f9c2a71-6b4e-4d0a-9e85-2c1f7a604b19",
  "version": 4,
  "validation": {
    "ok": true,
    "issues": [],
    "issueDetails": [],
    "warnings": [
      "Initial download ~24 MB is above the 20 MB mobile target"
    ],
    "engine": "godot",
    "externalHosts": [],
    "initialBytes": 25165824,
    "usesSdk": true,
    "totalBytes": 41943040,
    "fileCount": 12
  },
  "activated": false
}
```

Branch on `code`, not on `message`: codes are stable, while the wording of messages may change. `issues` stays for compatibility with older clients, and `issueDetails` is absent on builds checked before it existed. In the console, the **Build** step shows the report, and every finding links to the part of this page that explains it.

### When the check does not run {#when-the-check-does-not-run}

These answers carry `{"error": "<code>", "message": "..."}` instead of a check result, with a non-`200` status:

| Status | Code | When |
| --- | --- | --- |
| 400 | `invalid_body` | The request is malformed, for example a declared zip size below 22 bytes or above 266 MB (250 MB plus 16 MB), or release notes over the limit. |
| 400 | `parts_required` | A multipart upload was confirmed without its parts. |
| 404, 409 | `upload_not_found` | The upload does not exist, belongs to another account or game, or its file is gone from storage (a 409; upload again). |
| 409 | `locked_in_review` | The game is in review, so its builds cannot change. |
| 409 | `not_uploaded` | The zip has not arrived in storage yet. Finish the upload, then confirm again. |
| 409 | `upload_in_progress`, `already_processed` | This upload is already being checked, or was checked before. |
| 409 | `upload_invalid` | The uploaded file is not the size declared when the upload was prepared. Upload again. |
| 429 | `too_many_open_uploads` | Too many uploads are still open (see below). |
| 429 | `daily_upload_limit` | Too many build or video uploads were started in the last 24 hours and never confirmed (see below). |
| 429 | `rate_limited` | More than 20 prepare or 20 confirm requests in an hour. |
| 503 | `storage_unavailable` | Storage is not reachable right now. The upload stays open: confirm it again in a minute, without sending the file again. |

You can hold at most 20 open uploads at a time, counting every upload you have prepared but not yet confirmed, across all your games; one more answers `429 too_many_open_uploads`. A single-request upload that was never sent stops counting 20 minutes after it was prepared (its 15-minute upload link plus 5 minutes), while a multipart upload (a zip above 50 MB) counts for 24 hours, because its parts can be signed again. Separately, the build and video uploads you started in the last 24 hours but have not confirmed may add up to at most 40 uploads or 4 GiB in total; reaching either limit answers `429 daily_upload_limit`. Confirmed uploads do not count, so confirm the uploads you have finished, or wait: unconfirmed uploads are cleaned up 24 hours after they were prepared, and the budget frees itself.

The public [developer API](https://docs.zokogames.com/guides/developer-api#builds) cannot upload builds. Its build list returns `validation` with `ok` and `issues` only.

## Findings by topic

Each finding in the report links to its own entry in the finding reference above; these pages explain the topics behind the entries. Warnings and notes never block a build, but a reviewer can still send a game back for them.

### Size and file codes

`too_large`, `too_many_files`, `too_many_entries`, `initial_too_large`, `mobile_initial_large` and `large_file` are explained under [size and files](https://docs.zokogames.com/requirements/technical#size-and-files). The reason: a first-time visitor must fetch the initial download before play can start, and most of them are on a phone.

### Path codes

`absolute_path`, `case_mismatch`, `missing_reference` and `mixed_content` are explained under [relative paths only](https://docs.zokogames.com/requirements/technical#relative-paths-only). The reason: the game is served from its own build folder on its own host, so anything that assumes a different root or an `http` address fails there.

### Archive and file type codes

`not_zip`, `corrupt`, `central_mismatch`, `size_mismatch`, `total_bytes`, `zip64`, `empty`, `no_index`, `unsafe_path`, `symlink`, `encrypted`, `compression`, `duplicate`, `blocked_type`, `compression_ratio`, `bad_precompressed`, `case_collision`, `index_not_html`, `unknown_type`, `non_utf8_name`, `junk_ignored` and `nested_root` are covered under [what the validator rejects](https://docs.zokogames.com/requirements/technical#what-the-validator-rejects) (`nested_root` also in the [quick start](https://docs.zokogames.com/getting-started/quick-start)).

### SDK codes

`no_sdk`, `sdk_no_init` and `third_party_sdk` are explained in the [SDK introduction](https://docs.zokogames.com/sdk/introduction); `sdk_bundled` and `sdk_pinned` in [versioning](https://docs.zokogames.com/sdk/versioning). The SDK is optional for a basic launch and required for a full launch, so a build without it cannot go to full launch. See the [requirements overview](https://docs.zokogames.com/requirements/overview).

**Accepted forms of the SDK script URL.** The check reads every text file in the zip (`.html`, `.htm`, `.js`, `.mjs`, `.css`), not only `index.html`. The SDK counts as used when a file contains `sdk.zokogames.com` or the global name `ZokoGames`. A script is classed as **hosted** when it is written as `https://sdk.zokogames.com/<path>`, `http://sdk.zokogames.com/<path>` or protocol-relative `//sdk.zokogames.com/<path>`. If the path starts with a version such as `1.6.0/`, it is **pinned** to that version (`sdk_pinned`); any other path, for example `https://sdk.zokogames.com/zokogames-sdk-v1.js`, is the **latest** alias that receives fixes. A file that mentions the global without the hosted address is read as a bundled copy (`sdk_bundled`). Use `https`: an `http://` script is also blocked as mixed content when the page runs on the portal.

### External host and frame behaviour codes

`external_url` and the `origin_*` codes cover hosts your code calls; the [advertisement rules](https://docs.zokogames.com/requirements/advertisements) explain why ad hosts are not allowed. `service_worker`, `cookie_access` and `top_navigation` are explained in [embedding and sitelock](https://docs.zokogames.com/requirements/embedding), because the game runs in a sandboxed frame.

### Engine codes

`unity_unityweb`, `unity_mixed_compression` and `unity_compression_mismatch` are explained in the [Unity guide](https://docs.zokogames.com/engines/unity); `engine_low_confidence` in [HTML5 libraries](https://docs.zokogames.com/engines/html5-libraries).

## Next steps

- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting)
- [Testing checklist before you submit](https://docs.zokogames.com/getting-started/testing-checklist)

---

Source: https://docs.zokogames.com/requirements/text-formatting

# Text formatting

Fields that players or reviewers read as formatted text use **Markdown** in a small editor with a toolbar, a **Preview** tab and a character counter. The portal supports a fixed set of formatting and removes everything else when you save, on the server, so what you see in **Preview** is what players get. The counter counts the text people read: markup and link addresses do not count.

This page lists what every field supports. The editor shows a one-line reminder under each field and links here.

## The three levels

| Level | Formatting you can use | Syntax |
| --- | --- | --- |
| Inline | Bold, italic, code, links. One line of running text, no paragraphs. | `**bold**`, `*italic*`, `` `code` ``, `[text](https://example.com)` |
| Basic | Everything in Inline, plus paragraphs, line breaks, bulleted lists and numbered lists. | A blank line starts a new paragraph. A single new line is a line break. `- item` and `1. item` make lists. |
| Article | Everything in Basic, plus headings, quotes, code blocks and dividers. | `## Heading` and `### Subheading`, `> quote`, a fenced block between two lines of three backticks, `---` for a divider. |

A single `#` heading is saved as `##`, because the page title is the only top-level heading on a game page.

A construct a field does not support is not an error: it is flattened to plain text when you save. A heading in a Basic field becomes a normal paragraph, and a list in an Inline field becomes one line.

## Links

- Only `https://`, `http://` and `mailto:` addresses work. A link with any other address, such as `javascript:`, `data:` or a relative path, is removed and its text stays.
- A `mailto:` link keeps only the address: anything after `?`, such as `subject=` or `cc=`, is removed.
- If the text of a link is a web or email address that is not where the link goes, or a sentence that contains one, the text is replaced by the real address. An address whose host has letters outside A-Z (an internationalised domain) is shown in its ASCII form, which starts with `xn--`, so a look-alike host cannot pass for a familiar one.
- Links open in a new tab and carry `rel="nofollow ugc noopener"`, so they pass no ranking credit and cannot reach back into the portal page.
- You can also write a bare address in angle brackets, `<https://example.com>`.
- Reference links (`[text][id]` with a line `[id]: https://example.com`) are turned into ordinary links on save.

## What is removed

- **HTML.** Tags such as `<b>`, `<div>`, `<script>`, `<iframe>`, `<style>` and event attributes like `onclick` are removed. Their text stays, except the content of scripts, styles, frames and other embedded objects, which goes with the tag. Write `**bold**`, not `<b>bold</b>`.
- **Pasted formatting.** Text copied from a web page, a mail or a document keeps what the field supports when you paste it: bold, italic, links and lists (and headings and quotes where the field has them) become Markdown, and the preview shows the result at once. Anything the field does not support keeps its words. Colours, fonts and other styles are not carried over, so bold set only by a style, as in some word processors, pastes as plain words. Code, tables and images paste as plain text.
- **Images.** There are no images in text fields; the alt text stays. Upload images as store art, covers or screenshots.
- **Invisible and direction-changing characters**, such as zero-width spaces and right-to-left overrides, also when written as a character reference like `&#x202E;`. Joiners that emoji and some scripts need are kept.
- **Deep nesting.** Lists and quotes nest three levels deep; anything deeper is flattened. Very long runs of list or quote markers on one line, or hundreds of `*` and `_` markers in one paragraph, are kept as plain characters.

## Text you wrote before the editor existed

Descriptions and controls saved earlier as plain text or as simple formatted text keep showing as they did. When you open one, the editor shows it as Markdown. Nothing changes until you edit and save the field. Underline has no Markdown form and is dropped at that point.

## Which field supports what

The table below lists every text field that supports formatting. Fields not listed (names, URL names, one-line taglines, tags and similar) are plain text.

| Field | Where you edit it | Level | Limit (characters of text) | Where it shows |
| --- | --- | --- | --- | --- |
| Description | Game, **Edit and submit**, step **Basics** | Article | 5,000 | The **About** tab of the game page |
| Controls (how to play) | Game, **Edit and submit**, step **Basics** | Article | 2,000 | The **How to play** tab; key names such as WASD and Space turn into keycaps |
| FAQ answers | Game, **Edit and submit**, step **Basics** | Basic | 1,000 each | The **Questions** tab and the page's search data |
| Release notes | Game, **Builds and updates** | Basic | 2,000 | The version history in the console, on the game page (links are kept as text on a kids game) and in the reviewer's view |
| Note to the reviewer | Game, **Edit and submit**, step **Review and submit** | Basic | 2,000 | The review history and the reviewer's view |
| Studio description | **Settings**, studio profile | Basic | 1,000 | Your public studio page |
| Reply to player feedback | Game, **Player feedback** | Basic | 2,000 | Your feedback thread; the email to the player carries the reply as plain text with link addresses written out |

Notes the review team writes to you use the Basic level too. They show formatted in the review history of your game; notifications and emails about the decision carry them as plain text with link addresses written out.

Text that also feeds search-engine data (FAQ answers, the studio description) or an email is converted to plain text first, so markup never appears there. On a kids game page, links in the description, controls and release notes keep their words but are not clickable.

Plain-text fields stay plain on purpose: names, URL names, one-line taglines, achievement and store item descriptions, tags, sitelock notes, support requests, reports and a player's profile bio. They are short, shown inside other layouts, or sent as written.

---

Source: https://docs.zokogames.com/sdk/introduction

# SDK introduction

**Purpose:** this page shows how to load the ZokoGames SDK, start it with `init()`, and read the error objects every call can return. The SDK is a small browser library that connects your game to the portal page that embeds it. Version 1.7.0 has eight modules. New to a word used here (portal, build, studio)? See the [glossary](https://docs.zokogames.com/getting-started/glossary).

| Module | Purpose |
| --- | --- |
| [`SDK.ad`](https://docs.zokogames.com/sdk/ads) | Midgame and rewarded video ads, adblock detection. |
| [`SDK.banner`](https://docs.zokogames.com/sdk/banners) | In-game banner placements. |
| [`SDK.game`](https://docs.zokogames.com/sdk/game) | Gameplay events, loading, settings, rooms and invites. |
| [`SDK.user`](https://docs.zokogames.com/sdk/user) | Player identity, friends, tokens, sign-in and account linking. |
| [`SDK.data`](https://docs.zokogames.com/sdk/data) | Cloud save with a `localStorage`-shaped API. |
| [`SDK.analytics`](https://docs.zokogames.com/sdk/analytics) | Custom events and purchase tracking (in-game purchases are invite-only). |
| [`SDK.store`](https://docs.zokogames.com/sdk/purchases) | In-game purchases (invite-only); check `SDK.store.isAvailable` first. |
| [`SDK.achievements`](https://docs.zokogames.com/sdk/achievements) | Achievements you define in the console: unlock them and list the player's progress. |

Leaderboards use `SDK.user.submitScore` plus a server API, see [leaderboards](https://docs.zokogames.com/sdk/leaderboards).

## Loading

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script>
  const SDK = window.ZokoGames.SDK;
</script>
```

The sample assumes the script loaded. If the game must also run when the script is blocked or offline, read `window.ZokoGames?.SDK` and skip every SDK call when it is `undefined`, as the quick start does. If you use a bundler, keep loading the script tag (the validator looks for it) and read the global. For TypeScript, download the complete, self-contained declaration file of the release (every module, including `achievements` and `game.room`, plus `AdCallbacks`, `BannerOptions`, `RoomApi`, `StoreItem`, `AchievementInfo`, the error-code types and `ERROR_CODES`). It is published next to the script: `https://sdk.zokogames.com/<version>/index.d.ts` for a pinned release (for example `1.6.2`, available from 1.5.0 on) and `https://sdk.zokogames.com/index.d.ts` for the latest one. It is also the type file of the module build `@zoko/sdk`. It exports the types but does not declare the global, so add `declare global { interface Window { ZokoGames?: { SDK: ZokoSdk } } }`, or copy `src/zoko-sdk.d.ts` from the `html5-vite-ts` [starter kit](https://docs.zokogames.com/getting-started/starter-kits), which is that file with the global already added. Download it into your project instead of loading it from the network at build time, and update it when you update the script. If your game sets its own Content-Security-Policy, the only entry the SDK needs is `script-src https://sdk.zokogames.com`: it makes no network request of its own (it talks to the portal with `postMessage`), uses no `eval` and writes no inline script, style attribute or style element, so no `connect-src`, `'unsafe-eval'` or `'unsafe-inline'` is needed. Only a screenshot handler that returns a Blob or an image data URL makes the SDK load that image, which needs `img-src blob: data:`.

## Lifecycle at a glance

The order that matters for a typical game:

```text
init() resolves
  -> loadingStart() -> (loadingProgress 0..100) -> loadingStop()   optional loading signals
  -> gameplayStart()                                                the player is playing
       ... gameplayStop() at a pause, menu or result screen ...
       requestAd(): adStarted (pause game + mute) -> adFinished or adError (resume) -> gameplayStart()
```

Every member except `init()`, `SDK.environment` and `SDK.isQaTool` needs `init()` to have resolved first. Before that it throws or rejects with `sdkNotInitialized`. When the environment is `"disabled"` it throws or rejects with `sdkDisabled`.

## init()

```ts
init(): Promise<void>
```

Resolves once the SDK has chosen an [environment](https://docs.zokogames.com/getting-started/environments). Safe to call more than once (every call returns the same promise). Call it before anything else. It never rejects; a failed handshake leaves `SDK.environment` at `"disabled"` (or `"local"` when local mode applies). The handshake waits up to 15 seconds for the portal to answer when the page that embeds your game is the portal itself (`https` on `zokogames.com`), and 1.5 seconds on any other page.

How the environment is chosen: a page that is not inside a frame is `"local"` on `localhost`, `127.0.0.1`, `[::1]`, `*.localhost` or with `?useLocalSdk=true` in the address, and `"disabled"` everywhere else. Inside a frame the SDK asks the embedding page first. The answer counts only when it comes from the portal (`https` on `zokogames.com` or a subdomain other than a game host `g-<slug>` or the preview runner `preview-run`), from a local host (`localhost`, `127.0.0.1`, `[::1]`, `*.localhost`) while the game itself also runs on a local host, or from the game's own origin, and only when it speaks protocol version 1. Any other answer, a missing answer or a refusal counts as no answer: the SDK falls back to `"local"` when local mode applies and to `"disabled"` otherwise, so a game that is framed by a stranger's site never reads as `"zokogames"`.

<!-- docs-sample: uses runStandalone, startGame -->
```js
await SDK.init();
if (SDK.environment === "disabled") runStandalone();
else startGame();
```

Other top-level members (none of them needs `init()` and none throws):

| Member | Type | Notes |
| --- | --- | --- |
| `SDK.environment` | `"local" \| "zokogames" \| "disabled"` | `"disabled"` before `init()` resolves. |
| `SDK.isQaTool` | `boolean` | `true` when the game's own page address carries `qaTool=true`; set during `init()`, so read it after. |

The module build `@zoko/sdk` is not published on npm at present, so load the SDK with the script tag. The module exports `SDK` (its own instance, separate from `window.ZokoGames.SDK`), `createSdk({ win? })` for an isolated instance, `SDK_VERSION` (`"1.7.0"`), the `ERROR_CODES` table (see [errors](#errors)), `ERROR_CODE_DESCRIPTIONS` (one English line per code: when it happens and what the game should do) and the types `ZokoSdk`, `SdkError`, `SdkErrorCode` and one error-code type per module. The script tag build exposes `window.ZokoGames.SDK` and, since SDK 1.6.4, `window.ZokoGames.SDK_VERSION` (the version as a string). The script tag and the module build are two ways to load the same API: use one of them in a game, never both, since each creates its own SDK instance. The script tag is the recommended way, and the build check looks for it: when the tag is loaded, read `window.ZokoGames.SDK` and import only types from the package (`import type`), never its `SDK` value.

## In local mode, and for guests, offline and ad-free players

| Situation | What the SDK does |
| --- | --- |
| Local mode | `SDK.environment` is `"local"`; a mock answers every call inside the page. Details are on each module page and in [local testing](https://docs.zokogames.com/getting-started/local-testing). |
| Disabled | Every module member throws or rejects with `sdkDisabled`, except `SDK.data.mirrorLocalStorage`, which returns a function that does nothing. Check `SDK.environment` and run without the SDK. |
| Guest | `init()` works the same. Individual members that need an account fail with `userNotAuthenticated`; each page lists them. |
| Kids mode | `init` reports no user, `isUserAccountAvailable` is `false` and `SDK.store.isAvailable` is `false`; account, store and room calls are refused with documented codes. See [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode). |
| Basic launch | Ads and banners are off: `requestAd` fails with `adsDisabled` and banner requests with `bannersDisabled`. The game is live, so sign-in, cloud saves, achievements and leaderboard scores are recorded, and the portal counts plays and play time from `gameplayStart` and `gameplayStop`. See the launch stages page. |
| Player offline | `SDK.game.isOffline` is `true` (SDK 1.2.0). Ads fail with `unfilled` and banners with `bannersDisabled`; see [game](https://docs.zokogames.com/sdk/game#offline-state). |
| Ad blocker | `SDK.ad.requestAd` fails with `adblock`; see [video ads](https://docs.zokogames.com/sdk/ads). |
| Ad-free member | Midgame ads and banners do not show; rewarded ads still play. See [video ads](https://docs.zokogames.com/sdk/ads#ad-free-members). |

## Sync and async members

Calls that cross the frame boundary return promises. In the portal, `analytics.trackOrder` is counted as an anonymous order event (the order object is not stored); `game.reportGameCompletedPercentage` and `game.setGameContext` have small effects described on the [game](https://docs.zokogames.com/sdk/game) page. A handful of members read state that `init()` already loaded and are synchronous: `SDK.game.settings`, `SDK.game.isOffline`, `SDK.game.isInstantMultiplayer` (and its deprecated alias `isInstantJoin`), `SDK.game.gameId` (SDK 1.6.2), `SDK.game.inviteParams`, `SDK.game.getInviteParam`, `SDK.store.isAvailable`, `SDK.store.setSandbox`, the add and remove listener methods of `SDK.game` and `SDK.user`, `SDK.user.isUserAccountAvailable`, `SDK.user.systemInfo`, `SDK.game.onScreenshotRequest`, `SDK.achievements.onUnlock`, the five `SDK.data` methods (`getItem`, `setItem`, `removeItem`, `clear` and `mirrorLocalStorage`) and the `SDK.game.room` getters and listener methods (`getState`, `members`, `isHost`, `selfId`, `on*`, `add*Listener`, `remove*Listener`). Synchronous members **throw** the error object instead of rejecting. A listener argument that is not a function throws `invalidArgument`; an exception thrown inside your listener is caught and logged, and does not reach the SDK.

## Call limits

The portal limits how often a game may call it, per method, so a runaway loop cannot flood the player's page. Normal play never reaches the limits. Each method has a burst it accepts at once and a rate (calls per second) at which the allowance refills:

| Methods | Burst | Per second | A call over the limit |
| --- | --- | --- | --- |
| `SDK.ad.requestAd` | 10 | 5 | `adCooldown` (through `adError`) |
| `SDK.banner.requestBanner`, `SDK.banner.requestResponsiveBanner` | 10 | 5 | `bannerCooldown` |
| `SDK.user.getUserToken`, `SDK.user.listFriends`, `SDK.store.getPurchaseToken` (and its alias `getXsollaUserToken`) | 10 | 5 | `rateLimited` |
| `SDK.store.getCatalogItems`, `SDK.store.getPlayerInventory`, `SDK.store.buyItem`, `SDK.store.consumeItem` | 10 | 5 | `requestInProgress` |
| `SDK.game.gameplayStart`, `gameplayStop`, `loadingStart`, `loadingStop`, `happytime`, `reportGameCompletedPercentage` | 10 | 5 | The call is dropped and resolves with nothing |
| `SDK.game.loadingProgress`, `setGameContext`, `clearGameContext`, `updateRoom`, `leftRoom`, `SDK.banner.clearBanner`, `clearAllBanners` | 30 | 10 | The call is dropped and resolves with nothing; for `loadingProgress`, the game context and `updateRoom` the newest dropped value is applied once the allowance refills |
| `SDK.user.getUser`, `SDK.ad.hasAdblock`, `SDK.achievements.list` | 30 | 10 | Resolves the previous answer again (before the first answer: `null`, `false` and `[]`) |
| `SDK.achievements.unlock` | 30 | 10 | Resolves `{ ok: false, reason: "rate_limited" }` |
| `SDK.user.showAuthPrompt`, `SDK.user.showAccountLinkPrompt` | 30 | 10 | `userCancelled` |
| `SDK.user.submitScore`, `SDK.game.reportChat`, `SDK.analytics.trackOrder`, `room.send`, `room.setState` | 30 | 10 | `rateLimited` |
| `init` (one call per page load is the norm; the SDK calls it once, whatever your game does) | 10 | 1 | `rateLimited` |
| `SDK.data` (it has its own one-per-second cap), `SDK.game.inviteLink` (built in the page) | – | – | – |

Local mode does not apply this table, so a loop that runs cleanly on `localhost` can still be limited in the portal; the SDK itself enforces the ad and banner cooldowns, the 250 ms friends interval and the room message rate everywhere, and the Preview tool shows the rest. A limited call is answered at once, with the code in the last column or silently dropped, and it never reaches the portal. The message is "Too many calls in a short time. Wait and retry." The next call goes through when the allowance has refilled, so wait a second before you retry and never retry in a tight loop.

The portal's servers also limit some calls per player and game, whatever the frame allows. `submitScore` is limited to 30 a minute (10 a minute on a board without an encryption key) and answers `rateLimited`. `SDK.achievements.unlock` is limited to 20 a minute and 1,000 a day, and to 10 unknown keys an hour; it resolves `{ ok: false, reason: "rate_limited" }`. See [leaderboards](https://docs.zokogames.com/sdk/leaderboards) and [achievements](https://docs.zokogames.com/sdk/achievements).

## Errors

Every failure is a plain object, never an `Error` instance:

```ts
interface SdkError {
  code: SdkErrorCode | (string & {}); // stable, switch on this; known codes autocomplete, any string is valid
  message: string;       // English, for logs
  containerId?: string;  // banner errors only: the container you passed
}
```

<!-- docs-sample: uses continueAsGuest -->
```js
try {
  await SDK.user.getUserToken();
} catch (e) {
  if (e.code === "userNotAuthenticated") continueAsGuest();
  else console.warn(e.code, e.message);
}
```

Since SDK 1.6.4 `code` is typed as `SdkErrorCode | (string & {})` (types only): editors autocomplete the known codes, and any other string still compiles. Compare `code` only. The `message` text is written for people, is not part of the contract and changed in SDK 1.6.3 (for example the old wording `disabled on this domain` is gone whenever a reason is known), so code that searches the text breaks on a release. An error is created fresh each time. Anything a host sends that is not a `{ code }` object (a plain `Error`, a string) is turned into one with code `other`.

Ad errors are different in one way: failures of the ad itself are delivered to your `adError` callback, not thrown. Invalid arguments, `sdkNotInitialized` and `sdkDisabled` still reject. See [video ads](https://docs.zokogames.com/sdk/ads).

### General codes

| Code | When |
| --- | --- |
| `sdkNotInitialized` | A member was used before `init()` resolved. The message tells you to `await SDK.init()` first. |
| `sdkDisabled` | The environment is `disabled`. Since SDK 1.6.3 the message names the reason (not framed by the portal and not on a local host; framed by another origin; no answer to the handshake; unsupported host protocol; the portal turned it off) and links the [local testing](https://docs.zokogames.com/getting-started/local-testing) page. |
| `invalidArgument` | A parameter has the wrong type or range. The message names it and says what was received (SDK 1.6.3: `got "interstitial"`, `got 150`, `got object`; strings are cut at 30 characters). |
| `timeout` | The portal did not answer within 10 seconds. `requestAd` waits up to 30 seconds for the ad to start (then `adError` gets `timeout`) and has no limit afterwards. `showAuthPrompt`, `showAccountLinkPrompt` and `store.buyItem` have no timeout because the player may take their time. |

### Module codes

| Module | Codes |
| --- | --- |
| Ad | `adsDisabled`, `unfilled`, `adblock`, `adCooldown`, `other` |
| Banner | `bannersDisabled`, `unfilled`, `missingId`, `notVisible`, `noAvailableSizes`, `notCreated`, `videoAdPlaying`, `invalidSize`, `bannerCooldown`, `maxRefreshReached`, `other` |
| User | `userNotAuthenticated`, `userAlreadySignedIn`, `userCancelled`, `showAuthPromptInProgress`, `showAccountLinkPromptInProgress`, `rateLimited`, `requestInProgress`, `unexpectedError` |
| Data | `dataLimitExceeded`, `dataModuleDisabled`, `other` |
| Room | `notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`, `invalidArgument`; meanings in [room data channel](https://docs.zokogames.com/sdk/game#room-data-channel) |
| Store | `catalogFetchFailed`, `inventoryFetchFailed`, `purchaseInitFailed`, `purchaseInProgress`, `purchaseCancelled`, `consumeItemFailed`, `itemNotConsumable`, `itemNotInInventory`, `insufficientItemQuantity`, `userNotAuthenticated`, `invalidArgument`, `requestInProgress`, `unexpectedError`, `other`; meanings in [in-game purchases](https://docs.zokogames.com/sdk/purchases#error-codes) |

In the module build, `ERROR_CODES` lists the same groups in code (`ERROR_CODES.ad`, `.banner`, `.user`, `.data`, `.store`, `.general`, `.room`). Anything the SDK cannot classify is reported as `other`. Write your handlers so an unknown code takes the safe path (resume the game, continue as a guest).

**Common mistakes.** The ones the upload validator, the Preview tool and the SDK itself report most often:

| Mistake | What you see | Fix |
| --- | --- | --- |
| A member is used before `await SDK.init()` has finished | Throws or rejects with `sdkNotInitialized` | Start your game code after `init()` resolves. Only `init()`, `SDK.environment` and `SDK.isQaTool` are safe before. |
| `init()` is wrapped in `try`/`catch` to detect a failure | The `catch` never runs | `init()` never rejects. Read `SDK.environment` after it resolves. |
| Errors are tested with `e instanceof Error` or `e.message` only | The test is false: SDK errors are plain objects | Switch on `e.code` and keep a default branch for unknown codes. |
| `SDK.data` is awaited or chained with `.then` | Works by accident, but the calls are synchronous and throw | Use `try`/`catch` around `setItem` and read values directly. |
| A call that returned `rateLimited`, `adCooldown`, `bannerCooldown` or `requestInProgress` is retried in a loop | The same code again, and more calls dropped | Wait at least a second, or until the player acts again. |
| The SDK script is missing, a copy of it is bundled, or its address is pinned | Validator codes `no_sdk` (warn), `sdk_bundled` (warn), `sdk_pinned` (info) | Load `https://sdk.zokogames.com/zokogames-sdk-v1.js`, see the versioning page. |
| The init call is hidden from the static scan (minified code, an engine wrapper) | Validator code `sdk_no_init` (info) | Check the Preview tool: if it shows `init`, nothing is wrong. |
| `SDK.isQaTool` is read before `init()` resolves | Always `false` | Read it after `await SDK.init()`. |

## Debugging

Add `?sdk_debug=true` to the URL to log every call and its result, in any environment. Without it the SDK writes one line in local mode saying so and, from SDK 1.6.2, three one-time notices per page: why the environment is `disabled`, the first call made before `init()` resolved, and the first cloud save that failed to sync. The first two name the cause and point to the local testing page. Combine it with the [Preview tool](https://www.zokogames.com/preview), try calls interactively in the [SDK playground](https://docs.zokogames.com/sdk/playground), and see [troubleshooting](https://docs.zokogames.com/guides/troubleshooting) for symptom-by-symptom fixes.

## Versions

The script URL carries the major version (`v1`). See [versioning and migration notes](https://docs.zokogames.com/sdk/versioning) for what stays compatible and what each release changed for game code. The release notes also appear in the docs changelog (Business, then Changelog). Each module page starts with a table of every member, what it resolves to, what it can fail with and the SDK version that added it, so you can check a member against the version you load.

## Next steps

- [Game module](https://docs.zokogames.com/sdk/game)
- [Video ads](https://docs.zokogames.com/sdk/ads)
- [SDK playground](https://docs.zokogames.com/sdk/playground)

---

Source: https://docs.zokogames.com/sdk/ads

# Video ads

**Purpose:** `SDK.ad` asks the portal to show a full-screen video ad and tells your game when it starts, finishes or fails, so you can pause and resume. Two types exist:

- **midgame**: shown at a natural break, such as between levels.
- **rewarded**: the player opts in and receives something when it finishes.

Today the portal fills both with its own house ads, because no ad network is connected yet, so ads earn no revenue for now (see [feature status](https://docs.zokogames.com/business/faq#feature-status)). Your integration works the same either way.

Ads are served for games in **full launch** whose developer has enabled ads, and never for kids' games. In basic launch, in a reviewer's QA frame and anywhere else ads are off, `requestAd` fails with `adsDisabled`; build your integration as if that can always happen. The Preview tool runs your build with ads switched on, so you can test the real ad flow before full launch. Only ads requested through the SDK are allowed. Read the [advertisement rules](https://docs.zokogames.com/requirements/advertisements) before you design placements, and the [monetisation guide](https://docs.zokogames.com/guides/ad-monetisation) for pacing.

## At a glance

Every member of `SDK.ad`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `requestAd(type: "midgame" \| "rewarded", callbacks?: AdCallbacks): Promise<void>` | Nothing, after `adFinished` or `adError` has run. | The promise rejects only with `invalidArgument`, `sdkNotInitialized` or `sdkDisabled`. Every ad failure goes to `adError`: `adsDisabled`, `unfilled`, `adblock`, `adCooldown`, `other`, `timeout`. | 1.0.0 |
| `hasAdblock(): Promise<boolean>` | `true` when a blocker is detected, otherwise `false`. | `sdkNotInitialized`, `sdkDisabled`, `timeout`. | 1.0.0 |

The type `AdCallbacks` (`adStarted`, `adFinished`, `adError`, all optional) and the type `AdType` are in the declaration file, see the declaration file described in the SDK introduction.

## Lifecycle

```text
requestAd(type, callbacks)
  -> (portal checks: ads on? connection? cooldown? gameplay started? ad blocker?)
       refused  -> adError(code)                           game keeps running, nothing to resume
       accepted -> adStarted   pause game + mute audio
                   -> adFinished | adError   resume game + audio -> gameplayStart()
  -> the promise resolves after adFinished or adError has run
```

Call `SDK.game.gameplayStop()` before you request an ad and `gameplayStart()` after it, so playtime is not counted while the ad is on screen.

## requestAd

```ts
requestAd(type: "midgame" | "rewarded", callbacks?: AdCallbacks): Promise<void>

interface AdCallbacks {
  adStarted?: () => void;
  adFinished?: () => void;
  adError?: (error: SdkError) => void;
}
```

The returned promise resolves **after** `adFinished` or `adError` has been called, never before. Exactly one of the two fires per request, and all three callbacks are optional. `adStarted` fires only when the ad really starts, so an ad refused up front calls only `adError`. After `adStarted`, `adFinished` or `adError` is always delivered when the ad ends (the player finishes or closes it, or the portal reports a failure), but nothing bounds how long that takes: the only limit in the SDK is the 30 seconds before the ad starts, so do not add a game-side timer that resumes play while the ad is still on screen. Once the ad has started there is no time limit, because the player may keep it open as long as they like; but if the portal neither answers nor starts the ad within 30 seconds, `adError` is called with `timeout`. It rejects (instead of calling `adError`) only for `invalidArgument` (the type is not exactly `"midgame"` or `"rewarded"`) and for `sdkNotInitialized` or `sdkDisabled`.

:::tabs
== Midgame
<!-- docs-sample: uses game, audio -->
```js
async function showMidgame() {
  await SDK.ad.requestAd("midgame", {
    adStarted: () => { game.pause(); audio.mute(); },
    adFinished: () => { audio.unmute(); game.resume(); },
    adError: (err) => { console.warn(err.code); audio.unmute(); game.resume(); },
  });
}
```
== Rewarded
<!-- docs-sample: uses rewardButton, game, audio, grantExtraLife, showMessage -->
```js
rewardButton.addEventListener("click", async () => {
  let earned = false;
  await SDK.ad.requestAd("rewarded", {
    adStarted: () => { game.pause(); audio.mute(); },
    adFinished: () => { earned = true; },
    adError: () => { earned = false; },
  });
  audio.unmute();
  game.resume();
  if (earned) grantExtraLife();
  else showMessage("No ad is available right now, try again later.");
});
```
:::

### Rules for callbacks

- **Pause and mute inside `adStarted`**, not when you call `requestAd`. The request may fail or take a moment; the player should not see a frozen game before the ad exists.
- **Resume in both `adFinished` and `adError`.** A game stuck paused after a failed ad is the most common reason for a failed QA.
- **Never give a reward in `adError`.** If the player closes a rewarded ad early, it ends with `adError`, so no reward is due; a skipped midgame ad counts as finished.
- Callbacks are wrapped, so an exception inside one does not break the SDK.

### One ad at a time

While a request is in progress a second `requestAd` does not start another ad; its `adError` callback receives `{ code: "other" }` and its promise resolves at once, while the first request carries on. Disable your trigger button while waiting.

**Arguments and ordering.** `callbacks` is an object, `null` or omitted: since SDK 1.6.1 `null` counts as no callbacks (on 1.6.0 and earlier, pass nothing rather than `null`). Since SDK 1.6.3 the console shows one warning per page (`[ZokoGames SDK] ad.requestAd: ... Pass { adStarted, adFinished, adError } as functions`) when the object cannot work: a bare function instead of an object, a misspelled name such as `onFinished`, or a value that is not a function. `undefined`, `null` and `{}` stay silent, and the call behaves exactly as before, so a misspelled callback is simply never called. If the object cannot be read at all (a revoked `Proxy`, a getter that throws), the request still settles and the promise resolves; on 1.6.2 and earlier it stayed pending for ever. Once `init()` has resolved, the type is checked first: `requestAd("banner")` rejects with `invalidArgument` (the message says what it got, such as `got "banner"`; compare the `code`, not the text), and so does `requestAd()`. Call `requestAd` only after `await SDK.init()`, otherwise it rejects with `sdkNotInitialized`; with the environment `"disabled"` it rejects with `sdkDisabled`, so check `SDK.environment` and skip the ad. The callbacks run in this order only: `adStarted` (when the ad appears), then `adFinished` or `adError`. A request that fails before the ad appears calls only `adError`, and the promise then resolves. If the portal answers neither way within 30 seconds, `adError` gets `timeout` and the game must resume as for any other error. Do not call `requestAd` while the game is mid-play: call `gameplayStop()` first, and `gameplayStart()` once the ad is over (the Preview tool flags a request made while playing).

## Ad-free members

A player with an ad-free membership or pass sees no midgame ads and no banners. For them `requestAd("midgame")` does not fail: `adStarted` and then `adFinished` fire at once with nothing on screen, so your resume code runs exactly as after a real ad. Rewarded ads still play, because the player asks for them. Banner requests fail with `bannersDisabled`. Never rely on an ad having been seen to unlock something for a midgame request.

## Error codes

| Code | Meaning | What to do |
| --- | --- | --- |
| `adsDisabled` | Ads are off for this game: basic launch, a kids' game, ads not enabled, the ad provider switched off, that ad type switched off by the portal, or the game runs inside a store app build. Inside the portal's Android app no ad is shown before the game either. | Continue without an ad, give no reward unless your design allows an alternative. |
| `unfilled` | The portal started no ad: nothing was available, or the player is offline. | Continue; try again later. |
| `adblock` | The portal detected an ad blocker and started no ad. `hasAdblock()` lets you check in advance. | Continue; see below. |
| `adCooldown` | A midgame ad was requested within the cooldown (three minutes by default) of the previous ad of either type, the portal's per-session or per-day ad limit was reached, or the game has not called `gameplayStart()` yet (see [Gameplay first](#gameplay-first)). | Continue; the break was too early. In the last case the message reads "Midgame ads are available after gameplay starts: call game.gameplayStart() first"; call `gameplayStart()` when play begins. |
| `other` | Anything else: a request already in progress, a rewarded ad the player closed early, or a failure inside the ad. | Continue. |

For a rewarded request the `adblock` error is also returned when the ad provider's script fails to load or times out on this page (a midgame request plays the portal's own ad instead). No reward is granted in that case.

When the player is a guest the codes are the same; ads do not depend on an account.

An invalid `type` argument rejects with `invalidArgument`, and a call before `init()` has resolved (or with the SDK disabled) rejects with `sdkNotInitialized` or `sdkDisabled`; none of these call `adError`.

## Cooldown

Midgame ads are limited to one every **180 seconds** by default (the portal can set a different value per game). The timer starts whenever any ad starts, so a midgame request right after a rewarded ad is declined with `adCooldown`. Request midgame ads at natural breaks and let the portal decline when it is too soon; do not build your own timer around exactly three minutes. Rewarded ads are player-initiated and are never declined for cooldown. The portal's optional per-session and per-day ad limits also apply to midgame ads only.

## Gameplay first {#gameplay-first}

A midgame ad is refused until your game has called `SDK.game.gameplayStart()` at least once in that game window. The refusal uses the code `adCooldown`, with its own message: "Midgame ads are available after gameplay starts: call game.gameplayStart() first". No ad starts and `adStarted` never runs, so only `adError` is called. Compare the `code`, not the message.

Call `gameplayStart()` when the player starts to play, before your first ad break. A game that never calls it still gets midgame ads: the portal allows them 30 seconds after play begins, counted from the moment the ad before the game has ended or been skipped. Reloading the game starts the wait again. Rewarded ads are not affected.

Since SDK 1.6.4 local mode applies the same rule: a midgame request before `gameplayStart()` fails with `adCooldown` and the same message, and a game that never calls it gets midgame ads after 30 seconds of visible page time. Rewarded ads are not gated. SDK 1.6.3 and earlier played the ad in local mode. The site and the [Preview tool](https://www.zokogames.com/preview) show the refusal as before.

## hasAdblock

```ts
hasAdblock(): Promise<boolean>
```

Resolves `true` when an adblocker is detected. It never rejects for a blocker, only for `sdkNotInitialized`, `sdkDisabled` or `timeout`. In a kids' game it resolves `false`, because no network ad code runs there.

<!-- docs-sample: uses rewardButton, showAlternativeReward -->
```js
if (await SDK.ad.hasAdblock()) {
  rewardButton.title = "Rewarded ads are unavailable while an ad blocker is active.";
  showAlternativeReward();
}
```

Players with an adblocker must be able to play the whole game. You may disable features that depend on rewarded ads, with a short notice, and must offer another way to get the same reward. Do not show pop-ups asking players to turn the blocker off.

## In local mode

In local mode an ad is a 3-second overlay; in the portal it is an ad screen with a countdown. Either way, the callbacks run in the same order. `adStarted` fires when it appears and `adFinished` when it closes. Use it to check your pause, mute and resume paths, then repeat in the [Preview tool](https://www.zokogames.com/preview), where real ad plumbing and failures occur.

| Situation in local mode | Result |
| --- | --- |
| Normal request | Overlay for 3 seconds, `adStarted`, `adFinished`. Rewarded ads cannot be closed early, so `adError` never follows a rewarded ad. |
| Second midgame request inside the cooldown | `adError` with `adCooldown`. |
| Midgame request before `gameplayStart()` | `adError` with `adCooldown` and the message "Midgame ads are available after gameplay starts: call game.gameplayStart() first", until `gameplayStart()` has been called or 30 seconds of visible page time have passed (SDK 1.6.4; earlier versions played the ad). Rewarded requests are not gated. See [Gameplay first](#gameplay-first). |
| Request while the overlay is up | `adError` with `other`. |
| `?ad_response=adsDisabled`, `unfilled`, `adblock` or `other` | The request fails with that code in `adError`. `ad_response=adblock` also makes `hasAdblock()` resolve `true`. |
| Offline, ad-free, kids | Not simulated; use the [Preview tool](https://www.zokogames.com/preview). |

Local mode also applies the midgame cooldown (180 seconds, counted from any ad); rewarded requests are never held back by it. A forced `ad_response` is checked before the cooldown. A misspelled value (`?ad_response=adblocked`) is ignored, so the ad plays normally; since SDK 1.6.3 the console prints one warning per page that names the switch and the accepted values.

**Common mistakes.** What the Preview checklist and QA reviewers flag most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| The game is paused or muted when `requestAd` is called | A frozen, silent game when the request fails or is refused | Pause and mute inside `adStarted` only. |
| Only `adFinished` resumes the game | The game stays paused after `adError` (a refused, blocked or timed-out ad) | Resume in both callbacks, or after the awaited promise. |
| A reward is granted in `adStarted` or `adError`, or after the await without a flag | Players are rewarded for an ad that failed or was closed early | Set a flag in `adFinished` only and grant the reward when it is set. |
| `requestAd` is called while `gameplayStart` is active | The Preview checklist item "ad breaks stop gameplay" fails, and playtime counts the ad | Call `gameplayStop()` before the request and `gameplayStart()` after it. |
| `gameplayStart()` is never called after an ad | The Preview checklist item "resume after an ad" warns | Call it in the resume path. |
| A midgame ad is requested before the game has called `gameplayStart()` | `adCooldown` with the message "Midgame ads are available after gameplay starts", and no ad | Call `gameplayStart()` when play begins, before the first break. Local mode shows it too since SDK 1.6.4. |
| A midgame ad is requested every few seconds or on a timer of your own | `adCooldown` for most requests | Ask only at natural breaks and treat `adCooldown` as "no ad now". |
| The reward button stays enabled while an ad is loading | A second request gets `adError` with `other` | Disable the button until the promise resolves. |
| A rewarded ad is required to progress | Players with a blocker, an offline player or an ad-free member are stuck | Check `hasAdblock()` and offer another way to get the same reward. |
| A rewarded ad is offered when `requestAd` is not possible (disabled SDK) | A rejected promise with `sdkDisabled` | Check `SDK.environment` first and wrap the call in `try`/`catch`. |

## Putting it together

<!-- docs-sample: uses game, audio -->
```js
async function onLevelComplete() {
  await SDK.game.gameplayStop();
  await SDK.ad.requestAd("midgame", {
    adStarted: () => { game.pause(); audio.mute(); },
    adFinished: () => { audio.unmute(); },
    adError: () => { audio.unmute(); },
  });
  game.resume();
  await SDK.game.gameplayStart();
}
```

## Next steps

- [Banners](https://docs.zokogames.com/sdk/banners)
- [Audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads)
- [Advertisement rules](https://docs.zokogames.com/requirements/advertisements)

---

Source: https://docs.zokogames.com/sdk/banners

# Banners

**Purpose:** `SDK.banner` places a small ad inside an element (a "container") that your page owns, and removes it again. Banners belong on screens that stay open for a while (menus, game-over and shop screens), never over the playfield. See the [advertisement rules](https://docs.zokogames.com/requirements/advertisements).

A container is any element with an `id`. It must be in the DOM, visible and at least partly on screen when you make the request.

## At a glance

Every member of `SDK.banner`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `requestBanner(options: { id: string; width: number; height: number }): Promise<void>` | Nothing, once the portal accepted the banner. | `invalidArgument`, `missingId`, `invalidSize`, `videoAdPlaying`, `notCreated`, `notVisible`, `bannerCooldown`, `maxRefreshReached`, `bannersDisabled`, `other`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. `invalidSize` also comes from the portal when the container sticks out over the top or left edge or its id is over 128 characters. Every code except `invalidArgument`, `missingId`, `sdkNotInitialized` and `sdkDisabled` carries `containerId`. | 1.0.0 |
| `requestResponsiveBanner(id: string): Promise<void>` | Nothing, once the portal accepted the banner. | `missingId`, `videoAdPlaying`, `notCreated`, `notVisible`, `noAvailableSizes`, `bannerCooldown`, `maxRefreshReached`, `bannersDisabled`, `invalidSize` (from the portal, see the limits), `other`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `clearBanner(id: string): Promise<void>` | Nothing, also when no banner is shown in that container. | `missingId`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `clearAllBanners(): Promise<void>` | Nothing. | `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |

The types `BannerOptions` (`id`, `width`, `height`) and `BannerRequest` are in the declaration file described in the SDK introduction.

## Lifecycle

```text
screen with a banner slot opens
  -> requestBanner / requestResponsiveBanner(id)     checks run in this order:
       id given -> size allowed (static only) -> no video ad playing -> container found and visible
       -> size fits (responsive only) -> refresh limits -> portal answers
  -> (banner stays while the container stays)
  -> clearBanner(id) / clearAllBanners()             when the player leaves the screen
```

A failed request leaves nothing on screen. Do not request a banner while a [video ad](https://docs.zokogames.com/sdk/ads) is on screen; wait for `adFinished` or `adError`.

## requestBanner

```ts
requestBanner(options: { id: string; width: number; height: number }): Promise<void>
```

Places a banner of an exact size, centred inside the container, and resolves with nothing once the portal has accepted it. `options` must be an object (`invalidArgument` otherwise). Allowed sizes:

| Static sizes (`width x height`) |
| --- |
| 728x90, 300x250, 320x50, 468x60, 320x100 |

```html
<div id="menu-banner" style="width:300px;height:250px"></div>
<script>
  SDK.banner.requestBanner({ id: "menu-banner", width: 300, height: 250 })
    .catch((e) => console.warn("banner:", e.code, e.containerId));
</script>
```

## requestResponsiveBanner

```ts
requestResponsiveBanner(id: string): Promise<void>
```

Measures the container and picks the largest size from this list that fits inside it:

| Responsive sizes |
| --- |
| 970x250, 970x90, 728x90, 468x60, 336x280, 300x600, 300x250, 250x250, 320x50, 160x600, 120x600 |

The banner is placed at the container's own position and size, so give the container explicit dimensions or a layout that resolves to a sensible box. If nothing fits you get `noAvailableSizes`.

```js
await SDK.banner.requestResponsiveBanner("sidebar");
```

It resolves with nothing. A non-string or empty `id` rejects with `missingId`.

## Clearing

```ts
clearBanner(id: string): Promise<void>
clearAllBanners(): Promise<void>
```

Remove banners when the player leaves the screen they sit on. `clearBanner` takes the container id (empty or non-string rejects with `missingId`); `clearAllBanners` takes nothing. Both resolve with nothing, and clearing an id that has no banner is harmless. Clearing does **not** reset the refresh timer or the refresh count: the limits below continue across clear and request cycles.

<!-- docs-sample: uses startLevel -->
```js
function leaveMenu() {
  SDK.banner.clearAllBanners();
  startLevel();
}
```

## Limits

- The same container can be requested again no sooner than **30 seconds** after its previous successful request, even if you cleared it in between. Earlier calls reject with `bannerCooldown`. Checked by the SDK before it asks the portal.
- A session may refresh banners at most **60 times** (a refresh is a request for a container that was already requested before). After that, `maxRefreshReached`.
- At most **3** banners can be live on the game page at once; this is the technical limit. The review rule is stricter: at most **two** banners on one screen (see the launch checklist). A request for a fourth container rejects with `maxRefreshReached` until you clear one; requesting a container that already shows a banner does not count as a new one. Checked by the portal.
- While a video ad is on screen banner requests reject with `videoAdPlaying`. Request the banner again after `adFinished`.
- The container `id` can be at most 128 characters, and the banner's top left corner must lie inside the game frame: a container that sticks out over the top or left edge of the page is answered by the portal with `invalidSize`, even when its size is allowed. A banner that is larger than the space left in the frame is cut to fit. Keep banner containers fully on screen.
- A request for a container that already shows a banner (not cleared) moves or resizes it. The SDK still counts it for the 30 second floor and for the 60 refreshes, so it is refused with `bannerCooldown` inside the first 30 seconds. Clear the banner and wait, or keep the container size fixed.
- The Preview checklist flags a banner requested while gameplay is active (call `gameplayStop()` first), a refresh inside 30 seconds, more than 60 refreshes and more than two banners on screen at once.

**Knowing whether banners are available.** There is no call that reports it up front. The first `requestBanner` or `requestResponsiveBanner` rejects with `bannersDisabled` when banners are not served (ads off for the game, an ad-free member, offline, a store app build). Keep the container collapsed (no reserved height) until the request resolves, and remove or keep it collapsed on `bannersDisabled` so the layout does not leave a hole.

## Error codes

Banner errors carry the `containerId` you passed, except `missingId` (there is none) and the general codes such as `invalidArgument`, `sdkNotInitialized` and `sdkDisabled`.

| Code | Meaning |
| --- | --- |
| `bannersDisabled` | Banners are not served: ads are off for this game (always the case in basic launch), banners are switched off, the player is an ad-free member, the player is offline, or the game runs inside a store app build. |
| `unfilled` | Listed for "no banner available"; the current portal does not send it. Handle it like any other error. |
| `missingId` | `id` is empty or not a string. |
| `notCreated` | No element with that `id` exists. |
| `notVisible` | The element has no size, is hidden (`display:none`, `visibility:hidden`, `opacity:0`) or is outside the viewport. |
| `noAvailableSizes` | Responsive request: the container is smaller than every supported size. |
| `invalidSize` | Static request: the size is not in the static list. Since SDK 1.6.3 the message lists the allowed sizes (`300x250 is not a supported banner size (allowed: ...)`). |
| `videoAdPlaying` | A video ad is playing. |
| `bannerCooldown` | Refresh interval below 30 seconds. |
| `maxRefreshReached` | One code for two different limits: the session refresh cap (60 refreshes) or three banners already live. The error `message` says which ("refresh limit for this session" for the cap), but that text is for logs and can change in any release: do not match on it. To branch, count the banners you have live yourself, and treat the rest as the session cap. |
| `other` | Anything else, including a transport failure. |

Errors from the portal that carry no container id get the id you passed. Because failures are plain objects, read `e.code` and `e.containerId` (see [errors](https://docs.zokogames.com/sdk/introduction#errors)).

Banners are never required for the game to work. On any error, keep the container empty or collapse it, and do not retry in a tight loop.

## In local mode, as a guest, offline, ad-blocked or ad-free

| Situation | What happens |
| --- | --- |
| Local mode | The banner is a dashed grey box labelled with its size and container id, appended to the container. The SDK-side checks (`missingId`, `notVisible`, `invalidSize`, `videoAdPlaying`, `bannerCooldown`, `maxRefreshReached`, `noAvailableSizes`) run too, but the box itself never fails to fill, `bannersDisabled` never happens and the limit of three live banners is not applied, so test error handling by temporarily hiding the container (`notVisible`) or passing a wrong size (`invalidSize`). |
| Basic launch | `bannersDisabled`: banners switch on only at full launch, together with ads. Build the handling now; the Preview tool runs your build with ads switched on, so real banners can be tested there. |
| Guest | Same as a signed-in player. |
| Offline | `bannersDisabled`. |
| Ad blocker | Banner requests are not refused for a blocker; the blocker may keep the ad itself from loading. Keep the container collapsible. |
| Ad-free member | `bannersDisabled`. |

**Common mistakes.** What the Preview checklist and the portal report most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| The container is created, resized or shown after the request | `notCreated` or `notVisible` | Request after the container is in the DOM, visible and measured (for example after the screen's first layout). |
| The container has `display:none`, zero height or `opacity:0` | `notVisible` | Give it a real size and show it before the request. |
| A banner is placed over the playfield or while the game is running | The Preview checklist item for banners fails ("banner during gameplay") and review rejects it | Banners belong on menu, shop and result screens. Call `gameplayStop()` first. |
| The same banner is requested again on a timer of 10 or 20 seconds | `bannerCooldown`, and after 60 refreshes `maxRefreshReached` | Refresh at most every 30 seconds, and only while the screen stays open. |
| Three or more containers are requested | A third request works, a fourth is `maxRefreshReached`; review allows two | Keep at most two banners on a screen and clear the others. |
| A size that is not on the static list (for example `300x300`) | `invalidSize` | Use a listed size, or `requestResponsiveBanner`. |
| Width and height are passed as strings or are missing | `invalidSize` | Pass numbers: `{ id, width: 300, height: 250 }`. |
| The layout keeps a gap for the banner when the request fails | An empty hole in the menu | Collapse or hide the container on `bannersDisabled` and every other error. |
| The request is made while a video ad plays | `videoAdPlaying` | Request after `adFinished` or `adError`. |
| Banners are never cleared when the screen closes | The banner stays over the next screen, and refreshes still count | Call `clearBanner(id)` or `clearAllBanners()` when the player leaves. |

## Putting it together

<!-- docs-sample: uses startLevel -->
```js
async function showMenuBanner() {
  try {
    await SDK.banner.requestResponsiveBanner("menu-banner");
  } catch (e) {
    if (e.code === "bannersDisabled" || e.code === "noAvailableSizes") {
      const box = document.getElementById("menu-banner");
      if (box) box.hidden = true;
    } else {
      console.warn("banner:", e.code, e.containerId);
    }
  }
}

function leaveMenu() {
  SDK.banner.clearAllBanners().catch(() => {});
  startLevel();
}
```

## Next steps

- [Advertisement rules](https://docs.zokogames.com/requirements/advertisements)
- [Ad monetisation guide](https://docs.zokogames.com/guides/ad-monetisation)

---

Source: https://docs.zokogames.com/sdk/game

# Game module

**Purpose:** `SDK.game` tells the portal what your game is doing (loading, playing, celebrating, in a room) and lets the portal tell your game about player preferences. Every method returns a promise except where noted. Errors that any call can raise (`sdkNotInitialized`, `sdkDisabled`, `timeout`) are listed in [errors](https://docs.zokogames.com/sdk/introduction#errors); the codes below are the ones specific to this module.

## At a glance

Every member of `SDK.game`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `gameplayStart(): Promise<void>` | Nothing. | `sdkNotInitialized`, `sdkDisabled`. A portal that does not answer in time only logs a console warning. | 1.0.0 |
| `gameplayStop(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `loadingStart(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `loadingStop(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `loadingProgress(percentage: number): Promise<void>` | Nothing, as soon as the value is queued. | `invalidArgument` (not a number from 0 to 100), `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `happytime(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `reportGameCompletedPercentage(percentage: number): Promise<void>` | Nothing. | `invalidArgument` (not a number from 0 to 100), `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `setGameContext(context: GameContext): Promise<void>` | Nothing. | `invalidArgument` (not a flat object of strings, finite numbers and booleans), `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `clearGameContext(): Promise<void>` | Nothing. | `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `readonly settings: GameSettings` | A copy of the current settings, at once. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `addSettingsChangeListener(fn: (settings: GameSettings) => void): () => void` | A function that removes this listener; calling it twice is harmless (returned nothing before SDK 1.6.4). | Throws `invalidArgument` (not a function), `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `removeSettingsChangeListener(fn: (settings: GameSettings) => void): void` | Nothing. | Throws `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `readonly isOffline: boolean` | `true` while the player has no connection. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.2.0 |
| `addOfflineListener(fn: (offline: boolean) => void): () => void` | A function that removes this listener; calling it twice is harmless (returned nothing before SDK 1.6.4). | Throws like `addSettingsChangeListener`. | 1.2.0 |
| `removeOfflineListener(fn: (offline: boolean) => void): void` | Nothing. | Throws like `removeSettingsChangeListener`. | 1.2.0 |
| `updateRoom(update: RoomUpdate): Promise<void>` | Nothing. | `invalidArgument` (see below), `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `leftRoom(): Promise<void>` | Nothing. | Same as `gameplayStart`. | 1.0.0 |
| `inviteLink(params: InviteParams): Promise<string>` | The link to share. | `invalidArgument` (not a flat object of strings), `unexpectedError` (kids mode), `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `readonly inviteParams: InviteParams \| null` | The invite parameters of this launch, or `null`. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `getInviteParam(key: string): string \| null` | One parameter, or `null`. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `addJoinRoomListener(fn: (params: InviteParams) => void): () => void` | A function that removes this listener; calling it twice is harmless (returned nothing before SDK 1.6.4). | Throws like `addSettingsChangeListener`. | 1.0.0 |
| `removeJoinRoomListener(fn: (params: InviteParams) => void): void` | Nothing. | Throws like `removeSettingsChangeListener`. | 1.0.0 |
| `readonly isInstantMultiplayer: boolean` | `true` for a "play together" launch. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `readonly room: RoomApi` | The room data channel (table below). | Its members throw or reject like the rest of the module. | 1.3.0 |
| `reportChat(report: ChatReport): Promise<void>` | Nothing. | `invalidArgument`, `rateLimited`, `unexpectedError`, `sdkNotInitialized`, `sdkDisabled`. | 1.4.0 |
| `onScreenshotRequest(handler: ScreenshotHandler): () => void` | A function that removes the handler. | Throws `invalidArgument` (not a function), `sdkNotInitialized`, `sdkDisabled`. | 1.4.0 |
| `showInviteButton(params: InviteParams, options?: { portalOnly?: boolean }): Promise<string>` | The invite link. | As `updateRoom` and `inviteLink`. With `portalOnly: true` the call does not use `updateRoom` (see below). | 1.1.0 (deprecated; `options` added in 1.7.0) |
| `hideInviteButton(options?: { portalOnly?: boolean }): Promise<void>` | Nothing. | As `updateRoom`; with `portalOnly: true` it cannot fail on the room. | 1.1.0 (deprecated; `options` added in 1.7.0) |
| `readonly isInstantJoin: boolean` | Same as `isInstantMultiplayer`. | Throws like `isInstantMultiplayer`. | 1.1.0 (deprecated) |

Since SDK 1.6.2: a read-only `gameId` string on the game module, the portal's id for this game as the portal sends it when the SDK starts (`"local-game"` in local mode). Like `isInstantMultiplayer` it throws `sdkNotInitialized` before `init()` resolves and `sdkDisabled` when the environment is `disabled`. It is not wrapped by the engine plugins yet.

Types: `GameApi`, `GameContext`, `ChatReport`, `GameSettings`, `InviteParams`, `RoomUpdate`, `RoomApi`, `ScreenshotHandler` and `ScreenshotSource` are in the declaration file described in the SDK introduction.

## Lifecycle

```text
init() resolves
  -> loadingStart()                 portal shows its loading bar
  -> loadingProgress(0..100)        optional, repeat
  -> loadingStop()                  loading bar removed, load time recorded
  -> gameplayStart()                first level is live (also removes the loading bar)
       ... gameplayStop() at pause / death / menu / shop ...
       ... gameplayStart() when play resumes ...
  ad:  gameplayStop() -> requestAd -> adStarted (pause + mute) -> adFinished | adError (resume) -> gameplayStart()
```

None of these calls is checked for order, so a wrong order never throws. The portal just records what you send.

## Gameplay events

```ts
gameplayStart(): Promise<void>
gameplayStop(): Promise<void>
```

Call `gameplayStart()` when the player is actively playing and `gameplayStop()` whenever that stops: pause menu, death or results screen, level select, a shop, or before an ad. The portal uses the pair to measure real playtime, which feeds your [basic launch metrics](https://docs.zokogames.com/guides/basic-launch-metrics).

<!-- docs-sample: uses game -->
```js
function resume() { game.running = true; SDK.game.gameplayStart(); }
function pause() { game.running = false; SDK.game.gameplayStop(); }
document.addEventListener("visibilitychange", () => { if (document.hidden) pause(); });
```

Rules of thumb:

- Do not call `gameplayStart` at page load. Call it when the first level is live.
- Do not call either one every frame. Repeated calls in the same state are harmless but noisy.
- Basic launch needs only `gameplayStart`. Full launch needs both, in the right places.
- `gameplayStart()` also removes the portal's loading bar if you never called `loadingStop()`.

Errors: only `sdkNotInitialized` and `sdkDisabled`. The call has no arguments and resolves with nothing. If the portal does not answer within 10 seconds (a busy or closing tab), the call still resolves and the SDK writes a warning to the console, so an unawaited call never becomes an unhandled rejection. `gameplayStart`, `gameplayStop`, `loadingStart`, `loadingStop`, `happytime` and `leftRoom` behave this way. Over the call limits (see the call limits in the SDK introduction: 10 in a burst and 5 a second for all but `leftRoom`, 30 and 10 for `leftRoom`) a call is dropped and still resolves.

## Loading

```ts
loadingStart(): Promise<void>
loadingStop(): Promise<void>
```

Optional. Call `loadingStart()` as the game begins loading assets and `loadingStop()` when it is ready to play. Between the two you may also report progress:

```ts
loadingProgress(percentage: number): Promise<void>
```

`percentage` is a number from 0 to 100; anything else (a string, `NaN`, 101) rejects with `invalidArgument`. The portal shows it as a progress bar, but only between `loadingStart` and `loadingStop`. Values are rounded to a whole number and coalesced: at most one message every 100 ms, with the latest value winning, so calling it every frame is fine. The returned promise resolves as soon as the value is queued, and a failure to deliver it is ignored. `loadingStart` resets the progress; `loadingStop` drops any value still waiting.

The portal records `loadingStop` so it can separate load time from play time, and the [Preview tool](https://www.zokogames.com/preview) ticks it off. See [first frame fast](https://docs.zokogames.com/guides/first-frame).

<!-- docs-sample: uses assets, loadAsset -->
```js
await SDK.game.loadingStart();
for (let i = 0; i < assets.length; i++) {
  await loadAsset(assets[i]);
  SDK.game.loadingProgress(((i + 1) / assets.length) * 100);
}
await SDK.game.loadingStop();
```

## Happy moments

```ts
happytime(): Promise<void>
```

Call it at moments of celebration: a boss defeated, a record broken, a level three-starred. The portal answers with a short confetti celebration over the game and records a `happytime` event. If today's daily puzzle list includes your game, a happy moment also counts as a win for the player's daily streak (once per game load, and ignored in the first two seconds after the game starts). Use it sparingly, a handful of times per session at most. Errors: only the general ones.

## Completion

```ts
reportGameCompletedPercentage(percentage: number): Promise<void>
```

Reports how far through the game the player is, from 0 to 100. A value outside that range, a non-number, or `NaN` rejects with `invalidArgument`. Send it when it changes meaningfully (after a level), not on every frame. The portal does not store the number itself. A value of 100 counts as a win for the daily streak in the same way as `happytime` (see above); lower values have no visible effect.

<!-- docs-sample: uses level, totalLevels -->
```js
await SDK.game.reportGameCompletedPercentage(Math.round((level / totalLevels) * 100));
```

## Game context

```ts
setGameContext(context: Record<string, string | number | boolean>): Promise<void>
clearGameContext(): Promise<void>
```

A flat bag of values describing what the player is doing (current mode, level, difficulty). Values must be strings, numbers or booleans; nesting, arrays or any other value type reject with `invalidArgument`. Each call replaces the previous context. Use `clearGameContext()` when the player returns to a menu. The portal attaches the current context to the report when the player sends feedback or reports a problem, so your support team can see where they were. It keeps at most 30 entries (the first 30 in object order), cuts keys to 60 characters and string values to 200 characters, skips an entry that would take keys and values over 4,000 characters in total, drops the keys `__proto__`, `constructor` and `prototype`, and does not show it anywhere else. `NaN`, `Infinity`, `null`, `undefined`, objects and arrays are not accepted: the SDK rejects the call with `invalidArgument`. Calls over the limit (30 in a burst, 10 a second) are dropped but the newest context is applied once the limit refills.

```js
await SDK.game.setGameContext({ mode: "time-trial", level: 7, hard: false });
```

## Portal settings

```ts
readonly settings: { disableChat: boolean; muteAudio: boolean; kidsMode?: boolean }
addSettingsChangeListener(fn: (settings: GameSettings) => void): () => void
removeSettingsChangeListener(fn: (settings: GameSettings) => void): void
```

The portal owns these player preferences. `settings` returns a copy of the current values (synchronous). Apply them at start and listen for changes.

<!-- docs-sample: uses audio, chatPanel -->
```js
function applySettings(s) {
  audio.setMuted(s.muteAudio);
  chatPanel.hidden = s.disableChat;
}
applySettings(SDK.game.settings);
SDK.game.addSettingsChangeListener(applySettings);
```

If your game has chat or user-generated text, honour `disableChat` fully. That is a [multiplayer](https://docs.zokogames.com/requirements/multiplayer) requirement. `addSettingsChangeListener` throws `invalidArgument` if the argument is not a function; `removeSettingsChangeListener` ignores a function that was never added. The portal sends a change event when the player toggles a setting while the game is open; the listener receives a fresh copy.

In local mode the starting values come from `?disableChat=true`, `?muteAudio=true` and `?kidsMode=true` on the page address (`kidsMode=true` also sets `disableChat`, as on the portal; without it `kidsMode` is `false`), and they do not change by themselves. To test a live change, dispatch the window event `zokogames:local-settings` with `detail` set to any of `{ disableChat, kidsMode, muteAudio }` as booleans (SDK 1.5.1): the SDK updates `settings` and calls your settings listeners (`kidsMode: true` also turns `disableChat` on). The [Preview tool](https://www.zokogames.com/preview) can also send changes.

### Kids mode

Available from SDK 1.5.0. The portal already sends the field on every game, and an older SDK build copies the whole settings object it receives, so on 1.4.1 `settings.kidsMode` is there at run time too, only missing from the type definitions. `settings.kidsMode` is `true` when the game runs in kids mode: the game has the kids flag, or the player is in kids mode (the portal's kids area, or kids mode switched on for the device). Otherwise it is `false`. In kids mode there is no chat, no rooms or invites, no sign-in prompt and no personalised ads, so hide any of those your game shows. The portal sets `disableChat` to `true` in exactly the same cases, so where `kidsMode` is missing (`undefined`, for example an older SDK in local mode) fall back to `disableChat`:

```js
const isKids = (s) => s.kidsMode ?? s.disableChat;
```

The portal sends no separate change event for kids mode: if kids mode is switched on while a game is open, the portal reloads the game, which then starts with `kidsMode: true`; switching it off applies the next time the game loads. Room calls in kids mode fail with `roomUnavailable`, and the platform's realtime servers refuse rooms for kids games as well. Everything else the portal switches off is listed in [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Offline state

```ts
readonly isOffline: boolean
addOfflineListener(fn: (offline: boolean) => void): () => void
removeOfflineListener(fn: (offline: boolean) => void): void
```

Added in SDK 1.2.0. `isOffline` is `true` while the player has no connection, including when the game was launched from the [offline library](https://docs.zokogames.com/guides/offline-play). The portal keeps it current, and listeners receive the new value only when it changes. On a portal that does not send the flag it stays `false`. In local mode it mirrors `navigator.onLine`, and `?offline=true` on the page URL pins it to `true`. `addOfflineListener` throws `invalidArgument` if the argument is not a function.

While offline the portal answers `requestAd` with `unfilled` straight away and `requestBanner` with `bannersDisabled`, so the game carries on without an ad.

<!-- docs-sample: uses leaderboardButton -->
```js
function showNetwork(offline) {
  leaderboardButton.hidden = offline;
}
showNetwork(SDK.game.isOffline);
SDK.game.addOfflineListener(showNetwork);
```

On older SDK versions use `navigator.onLine` with the `online` / `offline` window events instead; see [Making a game playable offline](https://docs.zokogames.com/guides/offline-play).

## Rooms and invites

For games that play together. Read the [multiplayer requirements](https://docs.zokogames.com/requirements/multiplayer) first.

```ts
readonly isInstantMultiplayer: boolean
readonly inviteParams: Record<string, string> | null
getInviteParam(key: string): string | null
updateRoom(update: { roomId?: string; isJoinable?: boolean; isPublic?: boolean; inviteParams?: Record<string, string> }): Promise<void>
leftRoom(): Promise<void>
inviteLink(params: Record<string, string>): Promise<string>
addJoinRoomListener(fn: (params: InviteParams) => void): () => void
removeJoinRoomListener(fn: (params: InviteParams) => void): void
```

- **`showInviteButton` / `hideInviteButton` and the invite button.** The old forms (no options) are the deprecated aliases of `updateRoom({ isJoinable: true, inviteParams })` and `updateRoom({ isJoinable: false })` and behave exactly as before: the portal's **Invite friends** button follows the room. From SDK 1.7.0, `showInviteButton(params, { portalOnly: true })` asks the portal to show its invite button and to put `params` in the link it shares, **without creating or changing a room**, and resolves the same link `inviteLink(params)` returns (same checks and limits on `params`, `invalidArgument` if it is not a flat object of strings). `hideInviteButton({ portalOnly: true })` hides the button again and leaves the room and its `isJoinable` alone, even in a game the portal lists as multiplayer. The ask lasts until the game asks again, until a later `updateRoom` that sets `isJoinable` hands the button back to the room, or until the game reloads. In kids mode the portal shows no invite button: `portalOnly` calls resolve nothing to show and `showInviteButton` rejects with `unexpectedError` like `inviteLink`. Without a signed-in player the button shares the link directly; rooms still need sign-in.
- **`isInstantMultiplayer`** is true when the portal page address has `instantJoin=true` (a "play together" entry) and the player should go straight into a lobby instead of a menu. `isInstantJoin` is the deprecated old name. `showInviteButton(params)` (equivalent to `updateRoom({ isJoinable: true, inviteParams: params })`, and it resolves the invite link) and `hideInviteButton()` (equivalent to `updateRoom({ isJoinable: false })`) are deprecated.
- **`inviteParams`** holds the query parameters of the portal game page the player opened, as strings: the portal's own keys (`roomId`, `instantJoin`, `ref`, `utm_*`) and the flat keys your game put in `updateRoom` or `inviteLink` (the docs use `room`), or `null` when none survive. Other parameters are not passed on. Because `ref` and `utm_*` also arrive on ordinary visits from campaigns, a non-null `inviteParams` does not mean an invite. To tell an invite from a plain launch, read a key your game set (`getInviteParam("room")`) or `roomId`, or check `isInstantMultiplayer` for a "play together" entry. The portal drops parameters that look like credentials (keys such as `token`, `code` or `state`, or token-shaped values) and values over 256 characters; see [what survives the page](https://docs.zokogames.com/guides/multiplayer-invites). Use `getInviteParam("room")` for a single value.
- **`updateRoom`** announces the room you are in. Call it when the player creates or joins a room and again when it changes (full, started). `isJoinable: false` stops the portal offering the invite. `inviteParams` is what a friend's join listener will receive. All values must be strings; `roomId` must be a string, `isJoinable` and `isPublic` booleans, and `update` an object, otherwise the call rejects with `invalidArgument`. `isJoinable` stays as it was if you omit it (a new room starts joinable). If you omit `roomId` the portal generates one; ids are limited to letters, digits, `_`, `.` and `-` (other characters become `_`, 64 characters at most), and the id is always added to `inviteParams` as `roomId`. Rooms and presence need a signed-in player: for guests the call succeeds but nothing is announced. From SDK 1.6.0 the host can also send `isPublic: true` so friends can join the room from their friends list without an invite; rooms are private by default, only the host's value counts, and in kids mode rooms always stay private. The portal accepts at most 16 invite parameters, with keys of 1 to 40 characters from letters, digits, `_`, `.` and `-` (but not `__proto__`, `constructor` or `prototype`) and values of up to 200 characters. A map that breaks any of these limits is ignored silently: the call does not reject, and the invite carries only `roomId` and any parameters from an earlier valid call. Keep parameters small, such as a room code or a level id, and test them in the Preview tool.
- **`leftRoom`** clears the room. Call it when the player leaves the lobby or match.
- **`inviteLink`** returns a promise of a link to the portal's game page (the address in the player's browser bar, `https://<portal>/game/<slug>`, not the game frame's own address) with your parameters added as query parameters. Any query string or hash on the current portal page is not copied; only your parameters are. `params` must be a flat object of strings (`invalidArgument` otherwise). Show it in a "copy invite link" button. Stay within the same limits as `updateRoom`: the link is built as given, but the page that opens it keeps a parameter only when its key has at most 64 characters from the same set and its value at most 256 characters (30 keys at most), and drops the others silently.
- **`addJoinRoomListener`** fires when the player is already in your game and accepts an invite; it also updates `inviteParams` to the new values. Parse the params and move them into the room. See the [friend invite flow](https://docs.zokogames.com/guides/multiplayer-invites#the-friend-invite-flow).

<!-- docs-sample: uses joinRoom, network, copyButton -->
```js
SDK.game.addJoinRoomListener((params) => joinRoom(params.room));

async function createRoom() {
  const room = await network.create();
  await SDK.game.updateRoom({ roomId: room.id, isJoinable: true, inviteParams: { room: room.id } });
  copyButton.onclick = async () => navigator.clipboard.writeText(await SDK.game.inviteLink({ room: room.id }));
}

if (SDK.game.inviteParams?.room) joinRoom(SDK.game.inviteParams.room);
```

## Room data channel

Added in SDK 1.3.0. `SDK.game.room` lets the players of one room exchange small messages and share a tiny state through the platform, so a multiplayer game does not need its own server for simple cases. It is a **game data channel, not a text chat**: it is not moderated or logged as chat, it has no history, and `settings.disableChat` does not switch it off (it only governs the text your game shows). Do not use it to carry free text between players; if you do, the [chat moderation rules](https://docs.zokogames.com/requirements/multiplayer#chat-and-user-content) apply to your game. For a step-by-step walkthrough with a lobby, turns and reconnects, see [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms). The channel exists while the player is in a room, that is after `updateRoom(...)` (or after joining from an invite) and until `leftRoom()`. It needs a signed-in player and a portal with realtime enabled; otherwise calls fail with `roomUnavailable`.

```ts
readonly room: {
  send(data: unknown, options?: { to?: string }): Promise<void>
  onMessage(cb: (m: { from: string; data: unknown; direct: boolean; seq: number; ts: number }) => void): () => void
  setState(patch: Record<string, unknown>): Promise<void>
  getState(): Record<string, unknown>
  onState(cb: (state: Record<string, unknown>, change: { keys: string[]; rev: number; by?: string }) => void): () => void
  members(): Array<{ id: string; username: string; profilePictureUrl: string }>
  onMembers(cb: (members: Array<{ id: string; username: string; profilePictureUrl: string }>) => void): () => void
  isHost(): boolean
  onHostChange(cb: (hostId: string | null, isHost: boolean) => void): () => void
  onError(cb: (error: { code: string; message: string }) => void): () => void
  // The same five listeners in the add/remove form used by the rest of the SDK:
  addMessageListener(cb: (m: RoomMessage) => void): () => void
  removeMessageListener(cb: (m: RoomMessage) => void): void
  addStateListener(cb: (state: Record<string, unknown>, change: RoomStateChange) => void): () => void
  removeStateListener(cb: (state: Record<string, unknown>, change: RoomStateChange) => void): void
  addLeftListener(cb: (event: { reason: "left" | "kicked" | "closed" | "disconnected"; roomId?: string }) => void): () => void
  removeLeftListener(cb: (event: { reason: "left" | "kicked" | "closed" | "disconnected"; roomId?: string }) => void): void
  addMembersListener(cb: (members: RoomMember[]) => void): () => void
  removeMembersListener(cb: (members: RoomMember[]) => void): void
  addHostChangeListener(cb: (hostId: string | null, isHost: boolean) => void): () => void
  removeHostChangeListener(cb: (hostId: string | null, isHost: boolean) => void): void
  addErrorListener(cb: (error: SdkError) => void): () => void
  removeErrorListener(cb: (error: SdkError) => void): void
  readonly selfId: string | null
}
```

- **`send(data, { to })`** relays any JSON value to every other member of the room, or only to the member whose `id` you pass as `to`. You never receive your own messages. It resolves when the portal accepted the call; delivery is best effort (no acknowledgement, no replay for a player who was disconnected). `data` must be JSON-serializable and at most **8 KB** once serialized, otherwise it rejects with `payloadTooLarge` (or `invalidArgument`).
- **`onMessage(cb)`** receives `{ from, data, direct, seq, ts }`. `from` is the sender's platform id and is **set by the platform, never by the sender**, so you can trust it for "who sent this". `seq` increases for every message in the room (gaps are possible, order by it) and `ts` is the server time in milliseconds. `direct` is true when it was sent to you alone. Every `on*` method returns a function that removes the listener. Each one also has an `add<Thing>Listener(cb)` / `remove<Thing>Listener(cb)` pair (`addMessageListener`, `addStateListener`, `addMembersListener`, `addHostChangeListener`, `addErrorListener`), the same convention as `addSettingsChangeListener` and `addJoinRoomListener`; pass the same function to `remove...` that you passed to `add...`. Both forms do the same thing, use whichever you prefer.
- **Shared state.** The room keeps a small key-value state, at most **64 KB** in total. Only the **host** can change it: `setState(patch)` merges the keys of `patch` into the state, and a `null` value removes a key. Keys are 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. The change is applied when the platform confirms it: read it from `getState()` or `onState`, not straight after `await setState(...)`. A player who joins, or reconnects, receives the full current state first. When your game page reloads while the portal still holds the player's room, the SDK picks the room up again at start-up: `members()`, `selfId` and `getState()` fill in shortly after `init()` resolves, without a new `updateRoom` call and without calling your `onMembers` or `onState` listeners for that first restore, so read them once after start-up instead of waiting for an event. A non-host that calls `setState` gets `notHost`; a patch that would push the state over 64 KB is refused with `stateTooLarge`. The state is deleted when the last player leaves.
- **Members and host.** `members()` lists the players in the room including yourself (`selfId` is your own id). The **first player to join is the host**. When the host leaves, the longest-standing remaining member becomes host and `onHostChange` fires on every client with the new host id (it also fires for the first assignment). The shared state survives a host change.
- **Errors.** A call can fail at once (it rejects) or later (the platform reports it through `onError`, for example `rateLimited`, `notHost` or `unknownMember`).

| Code | Meaning |
| --- | --- |
| `notInRoom` | The player is not in a room yet. Call `updateRoom` first. |
| `notHost` | Only the host can change the shared state. |
| `payloadTooLarge` | A message or patch is larger than 8 KB. |
| `stateTooLarge` | The shared state would exceed 64 KB. |
| `unknownMember` | `to` is not a member of the room (or is yourself). |
| `rateLimited` | More than 10 calls a second from the game (after a burst of 30), or more than 20 messages per second on the relay. The excess messages are dropped; **repeated** abuse (10 rejected messages within 10 seconds) closes the player's realtime connection, which then reconnects with a back-off and rejoins the room. |
| `roomUnavailable` | Guest, realtime is not enabled on this portal, or the account has no 13+ birthday (rooms never open in kids mode). |
| `invalidArgument` | A bad argument, such as data that cannot be serialized or an invalid state key. |

**Limits at a glance:** 8 KB per message or patch, 20 messages per second per player on the relay (a burst of 20 is allowed), 64 KB of shared state, and as many players as the lobby size you entered at upload (at most 100). The game page also limits how fast your code may call: `room.send` and `room.setState` each accept a burst of 30 calls and then 10 a second, and a call over that is rejected with `rateLimited` before it reaches the relay, so stay below 10 messages a second on average and batch small updates into one message. Nothing is stored after the room ends and message contents are not logged.

Every member of `SDK.game.room` (all since SDK 1.3.0). Members that read state are synchronous; all of them throw `sdkNotInitialized` or `sdkDisabled` as the rest of the module does.

| Member | Returns | Can fail with |
| --- | --- | --- |
| `send(data, options?)` | `Promise<void>`, when the portal accepted the call. | Rejects at once with `invalidArgument` (data not JSON, `undefined`, or `to` not a non-empty string), `payloadTooLarge`, `notInRoom`, `roomUnavailable`. Later, through `onError`: `unknownMember` (`to` is a string but not a member of the room, or is yourself), `rateLimited`. |
| `setState(patch)` | `Promise<void>`. The state changes when the platform confirms it. | Rejects at once with `invalidArgument` (empty patch, a bad key, or `__proto__`, `constructor`, `prototype` as a key), `payloadTooLarge` (patch over 8 KB), `notHost`, `notInRoom`, `roomUnavailable`. Later, through `onError`: `stateTooLarge`, `notHost`, `rateLimited`. |
| `getState()` | A copy of the shared state; `{}` outside a room. | Throws only the general codes. |
| `members()` | A copy of the member list, yourself included; `[]` outside a room. | Throws only the general codes. |
| `isHost()` | `true` when this player is the host. | Throws only the general codes. |
| `selfId` | This player's platform id, or `null` outside a room. | Throws only the general codes. |
| `onMessage(cb)`, `addMessageListener(cb)`, `removeMessageListener(cb)` | `on*` returns a function that removes the listener; since SDK 1.6.4 `add*` returns the same function (it returned nothing before), and `remove*` returns nothing. | Throws `invalidArgument` when `cb` is not a function. |
| `onState`, `onMembers`, `onHostChange`, `onError` and their `add...Listener` and `remove...Listener` forms | The same as for messages. | The same as for messages. |

Registering the same function twice with `add...Listener` registers it once. Callbacks receive copies, so changing them does not change the SDK's state.

A complete example (cursors, a host-owned round counter and a direct reply):

<!-- docs-sample: uses showRound, slowDown, pointer -->
```js
const SDK = window.ZokoGames.SDK;
await SDK.init();
const room = SDK.game.room;
const cursors = new Map(); // player id -> { x, y }
let round = 0;

await SDK.game.updateRoom({ roomId: "lobby-1", isJoinable: true }); // joining a room starts the channel

room.onMembers((members) => {
  for (const id of cursors.keys()) if (!members.some((m) => m.id === id)) cursors.delete(id);
});
room.onHostChange((hostId, me) => {
  if (me) room.setState({ round: round + 1 }).catch(console.warn); // the new host keeps the game going
});
room.onState((state) => { round = Number(state.round ?? 0); showRound(round); });
room.onMessage(({ from, data, direct }) => {
  const msg = /** @type {{ type: string, x?: number, y?: number }} */ (data); // whatever the sender sent
  if (msg.type === "cursor") cursors.set(from, { x: msg.x, y: msg.y });
  if (msg.type === "ping" && direct) room.send({ type: "pong" }, { to: from });
});
room.onError(({ code }) => {
  if (code === "rateLimited") slowDown(); // stay below 20 messages per second
});

setInterval(() => {
  // 5 sends per second stays well inside the 10 per second the portal accepts; the sender is added by the platform
  room.send({ type: "cursor", x: pointer.x, y: pointer.y }).catch(() => {});
}, 200);

if (room.isHost()) await room.setState({ round: 1, map: "forest" });
```

The module build exports the types `GameApi`, `GameContext`, `RoomApi`, `RoomMessage`, `RoomSendOptions`, `RoomStateChange`, `RoomMember`, `InviteParams`, `RoomUpdate` and `GameSettings`, and the code type `RoomErrorCode`.

**Kids mode.** `send` and `setState` reject with `roomUnavailable`, `updateRoom` and `leftRoom` resolve and announce nothing, `inviteLink` rejects with `unexpectedError`, and the room reads as empty; see [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode).

## Reporting chat

Added in SDK 1.4.0. If your game shows text from other players, give them a way to report it. `reportChat` sends one message to the portal's moderators:

<!-- docs-sample: uses member, lastLines -->
```js
await SDK.game.reportChat({
  reportedName: "Player42",          // 1 to 40 characters
  message: "the reported text",      // 1 to 500 characters
  reason: "abuse",                   // "abuse" | "spam" | "cheating" | "other"
  reportedUserId: member.id,         // optional: the platform id, for example a room member id
  roomId: "room-7",                  // optional, at most 64 characters
  context: lastLines,                // optional: [{ name, text }], the newest 10 lines are kept
});
```

The portal relays the call to `POST /api/sdk/chat-report`, which is same-origin only and takes the game from the portal frame, never from your data. Guests may report; each player can send 5 reports per 10 minutes and 30 per day, and an identical report within 10 minutes is accepted without a new row. In kids mode the report is accepted without recording who sent it.

| Error code | When |
| --- | --- |
| `invalidArgument` | A field is missing or out of range: a text that is empty or only spaces, a `reason` outside the four listed, a `reportedUserId` over 128 characters, a `context` that is not an array of `{ name, text }` lines. Checked in the SDK before anything is sent. |
| `rateLimited` | The player reported too often. |
| `unexpectedError` | The portal could not take the report, did not answer in time, or is too old to know the call. |

`reportChat` is not a replacement for your own filters; see the [chat rules](https://docs.zokogames.com/requirements/multiplayer#chat-and-user-content).

`reportedName` and `message` are supplied by your game and are shown to moderators as unverified, so send the text exactly as the player saw it. `reportedUserId` must be a real player id from the SDK (for example a room member id); an id the portal does not know is not stored. Per game the portal also allows 20 reports per 10 minutes and 100 per day from one network address, and 300 per hour and 2,000 per day in total; a report over a limit is refused with `rateLimited`. Format and bidirectional control characters are stripped from the text and the names.

## Feedback screenshot

Added in SDK 1.4.0. When a player opens the portal's feedback form, the portal may ask your game for an image of the current screen so the player can attach it. The SDK answers for you:

```js
const stop = SDK.game.onScreenshotRequest(async () => {
  // return a Blob, an HTMLCanvasElement, an image data URL, or null for "no image"
  return document.querySelector("canvas");
});
```

- The SDK scales the image so the long edge is at most **1280 px**, encodes JPEG at falling quality until it is at most **1.5 MB**, and answers within **3 seconds** (a slow or failing handler counts as no image). The portal checks the type and size again.
- One handler is active; a second call replaces it. The returned function removes it.
- **Without a handler** the SDK tries the largest visible `<canvas>` on the page. A tainted canvas yields no image. A WebGL canvas only works when it was created with `preserveDrawingBuffer: true` (otherwise it reads back blank, which counts as no image). If your engine cannot set that, register a handler that renders a frame first.
- **Unity WebGL needs a handler**: the canvas is not readable between frames. Capture at the end of the frame and pass the pixels on (helper below).
- Nothing is sent unless the player opens the form and chooses to attach the image.

Unity helper (WebGL): grab the frame in a coroutine, encode it, and hand the data URL to the page. Register the handler once from a `.jslib` or `Application.ExternalEval` that calls `SDK.game.onScreenshotRequest(() => window.__zokoShot ? window.__zokoShot() : null)`, where `__zokoShot` returns the last data URL the C# side stored:

```csharp
using System.Collections;
using System.Runtime.InteropServices;
using UnityEngine;

public class ZokoScreenshot : MonoBehaviour
{
    [DllImport("__Internal")] static extern void ZokoSetScreenshot(string dataUrl);

    // Call from a UI button or every few seconds while a menu is open; the SDK scales it down.
    public void Capture() => StartCoroutine(CaptureAtEndOfFrame());

    IEnumerator CaptureAtEndOfFrame()
    {
        yield return new WaitForEndOfFrame();
        var tex = ScreenCapture.CaptureScreenshotAsTexture();
        var jpg = tex.EncodeToJPG(75);
        Destroy(tex);
        ZokoSetScreenshot("data:image/jpeg;base64," + System.Convert.ToBase64String(jpg));
    }
}
```

<!-- docs-sample: fragment -->
```js
// ZokoScreenshot.jslib
mergeInto(LibraryManager.library, {
  ZokoSetScreenshot: function (ptr) { window.__zokoShot = UTF8ToString(ptr); },
});
```

The player chooses whether to attach the screenshot to a report. It is stored privately, shown only to the studio and the platform staff, and deleted after 180 days. It is never requested in kids mode. The portal accepts an image of at most 1.5 MB with each side between 16 and 4096 px and refuses anything else.

**Common mistakes.** The ones reviewers and the Preview checklist report most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| `gameplayStart()` is called at page load, or never | **First gameplayStart within 20 seconds** shows **Recommended** (it must come within 20 seconds of the frame loading), or **gameplayStart called** stays on **Waiting for you to play**, and playtime is wrong | Call it when the first level is live, and `gameplayStop()` at every pause, menu and before ads. |
| `gameplayStart()` is not called again after an ad or a pause | The Preview checklist warns "resume after an ad" and playtime stops counting | Call it in every resume path. |
| `loadingProgress` is called with `0` to `1` instead of `0` to `100` | A bar stuck near zero | Pass a percentage from 0 to 100. |
| `loadingStart()` is called after the game is already playable | A loading bar over a running game | Call it at the start of loading, and `loadingStop()` when it ends. |
| `setGameContext` gets a nested object or an array | `invalidArgument` | Use a flat object of strings, finite numbers and booleans. |
| `settings.disableChat` or `kidsMode` is read once at start | Chat stays on after the player turns it off | Apply `settings` at start and again in `addSettingsChangeListener`. |
| `inviteParams !== null` is used to detect an invite | True for ordinary visits from a campaign (`ref`, `utm_*`) | Read a key your game set, such as `getInviteParam("room")`. |
| `updateRoom` is given a nested object, a number, or more than 16 parameters | `invalidArgument`, or the whole map is silently ignored by the portal | Flat string values, at most 16 keys, keep each value short. |
| `room.send` runs on every frame | `rateLimited` and dropped messages | Send at most a few messages a second, and batch updates. |
| `room.setState` is called by every player | `notHost` for everyone but the host | Check `room.isHost()` and let the host own the shared state. |
| `room.send` is called before `updateRoom` | `notInRoom` | Call `updateRoom` first, and use the channel only while the player is in a room. |
| Chat text is shown but there is no way to report it | Review rejects unmoderated free text | Call `reportChat` from a "report" button on every message from another player. |
| `inviteParams` is modified in place | The SDK's own copy changes too | Treat it as read-only and copy it first. |

## In local mode

| Member | Local behaviour |
| --- | --- |
| `gameplayStart`, `gameplayStop`, `loadingStart`, `loadingProgress`, `loadingStop`, `reportGameCompletedPercentage`, `setGameContext`, `clearGameContext`, `leftRoom` | Resolve with nothing; the mock records nothing and draws no loading bar. Arguments are still validated. |
| `updateRoom` | Resolves with nothing and, for a signed-in mock player, joins the local room channel (below). |
| `room` | Tabs of the same origin that called `updateRoom` with the same `roomId` (default `local-room`, or the `roomId` of the page address) are connected through a `BroadcastChannel`: open the game in two tabs to test messages, targeting, the shared state and host migration without the portal. Each tab is its own member (`<user id>:<tab id>`) and the tab that joined first is the host; `seq` counts what that tab received. The 8 KB, 20 per second and 64 KB limits and the error codes are the same as on the portal. There is no lobby-size limit. |
| `reportChat` | Validates, logs the report to the console and resolves; nothing is sent. |
| `onScreenshotRequest` | The handler is kept. Test it by dispatching `new CustomEvent("zokogames:local-screenshot", { detail: { respond: console.log } })` on `window`; `respond` receives `{ dataUrl }` or `{ none: true }`. |
| `happytime` | Shows a yellow "Happy time!" toast for 1.5 seconds. |
| `settings` | From `?disableChat=`, `?muteAudio=` and `?kidsMode=` (which also turns `disableChat` on); changes only when the page dispatches `zokogames:local-settings` (SDK 1.5.1). |
| `isOffline` | Mirrors `navigator.onLine`; `?offline=true` pins it to `true`. The offline listeners fire on the browser's `online` and `offline` events, or when the page dispatches `zokogames:local-offline` with `detail: { offline: true }` (ignored under `?offline=true`). |
| `inviteParams` | `null` only when the page address has no query string at all. Otherwise it holds **every** query parameter, including mock switches such as `useLocalSdk` or `sdk_debug`; the real portal passes on only its own keys and your game's flat keys (see above). Read the keys you expect with `getInviteParam`, never test `inviteParams !== null` to detect an invite. |
| `isInstantMultiplayer` | `true` only with `?instantJoin=true` on the address. |
| `inviteLink` | Your own page address (the local page, not a portal address) with your parameters set as query strings. Unlike the portal, it keeps every query parameter already on the page address, so a link made on `?sdk_debug=true` carries that too. It resolves as a promise like the real call. |
| `showInviteButton(params, { portalOnly: true })` / `hideInviteButton({ portalOnly: true })` | Log the request to the console; there is no portal button to change. `showInviteButton` still resolves the local `inviteLink`. |
| `room.addLeftListener` | Fires when the page dispatches the window event `zokogames:local-leave-room` with `detail: { reason }` (`left`, `kicked`, `closed` or `disconnected`; anything else reads as `left`) while the local room is joined. The local room is left first, so `onMembers` listeners see an empty room. |
| `addJoinRoomListener` | Fires when the page dispatches the window event `zokogames:local-join-room` with a flat object of strings as `detail` (SDK 1.5.1), and then updates `inviteParams`. Test the full join path in the [Preview tool](https://www.zokogames.com/preview). |

## When the player is a guest, offline or ad-free

| Situation | Behaviour |
| --- | --- |
| Basic launch | Everything in this module works as in full launch. `gameplayStart` and `gameplayStop` are what the portal counts: plays and play time for the launch metrics come only from them (see the basic launch metrics guide). |
| Guest | Everything above works. Rooms and presence need a signed-in player: `updateRoom`, `leftRoom` and friend invites succeed but announce nothing, and `room.send` / `room.setState` fail with `roomUnavailable`. `inviteLink` works and the link can be shared by hand. |
| Offline | `isOffline` is `true`; ads are `unfilled` and banners `bannersDisabled`. Gameplay and loading calls still resolve. |
| Ad blocked or ad-free | No effect on this module. |

Full runnable example of the start-up order:

<!-- docs-sample: uses loadEverything, startFirstLevel -->
```js
await SDK.init();
await SDK.game.loadingStart();
await loadEverything();
await SDK.game.loadingStop();
startFirstLevel();
await SDK.game.gameplayStart();
```

## Next steps

- [User module](https://docs.zokogames.com/sdk/user)
- [Data (cloud save)](https://docs.zokogames.com/sdk/data)

---

Source: https://docs.zokogames.com/sdk/user

# User module

**Purpose:** `SDK.user` tells your game who is playing (a signed-in player or an anonymous guest), lets you ask a guest to sign in, and gives your own server a signed token to verify that identity. Your game must work for both kinds of player.

## At a glance

Every member of `SDK.user`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `getUser(): Promise<PortalUser \| null>` | The signed-in player, or `null` for a guest. | `timeout`, `sdkNotInitialized`, `sdkDisabled`. Never `userNotAuthenticated`. | 1.0.0 |
| `readonly systemInfo: SystemInfo` | The player's country, locale, device, OS, browser and app type, at once. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `readonly isUserAccountAvailable: boolean` | `false` when there are no portal accounts here (kids mode). | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `addAuthListener(fn: (user: PortalUser) => void): () => void` | A function that removes this listener; calling it twice is harmless (returned nothing before SDK 1.6.4). | Throws `invalidArgument` (not a function), `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `removeAuthListener(fn: (user: PortalUser) => void): void` | Nothing. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.0.0 |
| `listFriends(options: { page: number; size: number }): Promise<FriendsPage>` | One page of friends who also play this game. | `invalidArgument`, `requestInProgress`, `rateLimited`, `userNotAuthenticated`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `getUserToken(options?: { signingKeyType?: SigningKeyType }): Promise<string>` | A signed token (cached until a minute before it expires). | `invalidArgument`, `userNotAuthenticated`, `rateLimited`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `showAuthPrompt(): Promise<PortalUser>` | The player who signed in. | `userCancelled`, `userAlreadySignedIn`, `showAuthPromptInProgress`, `sdkNotInitialized`, `sdkDisabled`. `timeout` only if the portal does not say within 10 seconds who is signed in (the SDK asks first); the prompt itself has no timeout. | 1.0.0 |
| `showAccountLinkPrompt(): Promise<{ response: "yes" \| "no" }>` | The player's answer. | `userNotAuthenticated`, `showAccountLinkPromptInProgress`, `userCancelled`, `sdkNotInitialized`, `sdkDisabled`. No timeout. | 1.0.0 |
| `submitScore(options: { encryptedScore: string; score: number; delayed?: { encryptedScore: string; earnedAt: number } }): Promise<void>` | Nothing, also when nothing was recorded. | `invalidArgument`, `rateLimited`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 (`delayed`: 1.6.4) |
| `getXsollaUserToken(): Promise<string>` | The purchase token (same as `SDK.store.getPurchaseToken()`). | `userNotAuthenticated`, `rateLimited`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 (deprecated) |

Types in the declaration file described in the SDK introduction: `UserApi`, `PortalUser`, `Friend`, `FriendsPage`, `SystemInfo`, `SigningKeyType` and `LeaderboardEntry`.

## Lifecycle

```text
init() resolves
  -> getUser()                          null for a guest
  -> player presses "Sign in" -> showAuthPrompt() -> auth listener fires -> new PortalUser
  -> getUserToken()                     only for a signed-in player
  -> send the token to YOUR server -> server verifies it with the public keys -> trusted userId
```

Errors every call can raise (`sdkNotInitialized`, `sdkDisabled`, `timeout`, `invalidArgument`) are in [errors](https://docs.zokogames.com/sdk/introduction#errors). The tables below list the module-specific codes for each call.

## System information

```ts
readonly isUserAccountAvailable: boolean
readonly systemInfo: SystemInfo
```

`isUserAccountAvailable` is false when the game is embedded somewhere without portal accounts. Hide sign-in UI when it is. Both members are synchronous and throw `sdkNotInitialized` before `init()` resolves.

```ts
interface SystemInfo {
  countryCode: string;                       // "US"
  locale: string;                            // "en-US"
  device: { type: "desktop" | "tablet" | "mobile" };
  os: { name: string; version: string };
  browser: { name: string; version: string };
  applicationType: "web" | "pwa" | "google_play_store" | "apple_store";
}
```

In the portal these values describe the player's real browser; in local mode they are read from your browser's user-agent string (`countryCode` is always `"US"`, `applicationType` always `"web"`). Use `device.type` to decide on mobile controls, not `"ontouchstart" in window`, and `locale` to pick a language. See [control pitfalls](https://docs.zokogames.com/guides/input-controls).

## getUser

```ts
getUser(): Promise<PortalUser | null>

interface PortalUser {
  username: string;
  profilePictureUrl: string;
  __dangerousUserId: string;
}
```

Returns the signed-in player or `null` for a guest. It asks the portal each time, so it also picks up a sign-in that happened in the portal's own header. Errors: only the general ones (it never rejects with `userNotAuthenticated`: a guest is `null`). Over the call limit (30 in a burst, 10 a second) it resolves the previous answer again. The double-underscore name is deliberate: `__dangerousUserId` comes from the browser, so anyone can fake it. Use it for display and local state only, and never to decide whose save to load on your server. Server-side identity comes from the [token](#tokens).

Update stored usernames and avatars whenever you see them change.

## Friends

```ts
listFriends(options: { page: number; size: number }): Promise<FriendsPage>

interface FriendsPage { friends: Friend[]; page: number; size: number; hasMore: boolean; total: number }
interface Friend { id: string; username: string; profilePictureUrl: string }
```

`page` is an integer starting at 1 and `size` an integer from 1 to 50; anything else (including a missing options object) rejects with `invalidArgument`. Only one request may run at a time (`requestInProgress`) and calls closer than 250 ms apart fail with `rateLimited`; the portal can also answer `rateLimited` when you call too often overall. Guests get `userNotAuthenticated`. Any other failure is `unexpectedError`. `profilePictureUrl` is a full address you can put in an `<img>`.

<!-- docs-sample: uses render -->
```js
let page = 1, more = true;
while (more) {
  const res = await SDK.user.listFriends({ page, size: 20 });
  render(res.friends);
  more = res.hasMore;
  page++;
  await new Promise((r) => setTimeout(r, 300));
}
```

## Tokens

```ts
getUserToken(options?: { signingKeyType?: "IN_GAME_AUTH" | "IN_GAME_AUTH_LEGACY" }): Promise<string>
```

Returns a signed JWT (a token, a compact text string signed by the portal) that proves the player's identity to **your** server. It is valid for one hour. The SDK caches it and fetches a new one when less than a minute of life remains, so call it freely before each backend request (the cache is dropped when the player signs in). Without a signed-in player it rejects with `userNotAuthenticated`: let that player continue as a guest. The same code answers a signed-in player whose account has no confirmed 13+ birthday, and every call in kids mode or in a kids' game. A game cannot tell that player from a signed-out one, on purpose: `getUser()` also resolves `null` for both, so treat both as a guest and keep the game playable. Offering `showAuthPrompt` is right for both: for an account without a confirmed birthday it opens the sign-in flow as for a guest instead of rejecting with `userAlreadySignedIn`, and `addAuthListener` fires once the account is eligible. Other errors: `rateLimited` (the portal allows 60 token requests a minute per player), `unexpectedError` (for example a game that is not live and not yours to test), `invalidArgument` (a `signingKeyType` other than the two listed). Calls made while a token request is already running share its result.

The `signingKeyType` option is accepted so code ported from other portals keeps working, but ZokoGames signs every token the same way: with one RS256 key. `IN_GAME_AUTH` and `IN_GAME_AUTH_LEGACY` return equivalent tokens, so there is nothing to migrate and new games should omit the option. The SDK caches one token per `signingKeyType` value. The argument must be an object: passing the string `"IN_GAME_AUTH"` is ignored and the default key is used, and since SDK 1.6.3 the console prints one warning per page that names the type you passed (never the value). An object whose `signingKeyType` is anything but those two names rejects with `invalidArgument`.

The token is a JWT signed with **RS256**. Its header carries `alg: "RS256"`, `typ: "JWT"` and a `kid` that names the signing key. It carries these claims, plus `iat` (issue time), `exp` (`iat` plus 3,600 seconds), `iss` (`zokogames`), `aud` (your game id) and `sub` (the player id):

| Claim | Meaning |
| --- | --- |
| `userId` | Stable player id. Use it as the key of your own account record. |
| `gameId` | Your game's id. **Check it matches**, otherwise a token minted for another game could be replayed against yours. |
| `username` | Display name at the time of issue. |
| `profilePictureUrl` | Avatar URL at the time of issue. |

Times are in seconds and there is no `nbf`. `aud` is one string, not an array, and `sub` always equals `userId`. `userId` is a UUID (36 characters), the same in every game and equal to `__dangerousUserId` from `getUser()`. The game id is the UUID in your game's console address (`/developer/games/<id>`): it is set when the draft is created and stays the same after launch. From SDK 1.6.2 the game can read it as `SDK.game.gameId`; your server should still keep its own copy in its configuration.

### Verifying on your server

Never trust a token you did not verify, and never act on `getUser()` data sent from the browser. Fetch the public keys from the JWKS endpoint and verify the signature, the expiry, the issuer (`zokogames`) and the audience (`aud`, which must equal your game id). Every sample below does all four, pins `RS256`, and also compares the `gameId` claim (the same value as `aud`) and checks that `sub` equals `userId`. Where your game id comes from: the UUID in the game's console address (`/developer/games/<id>`), fixed when the draft is created and unchanged after launch. The same id is used to [encrypt scores](https://docs.zokogames.com/sdk/leaderboards#client-submission), and `userId` here is the id that goes into that encryption as well.

```text
https://www.zokogames.com/.well-known/jwks.json
```

The key set is a standard JWKS with RS256 signature keys (`use: "sig"`). The response is served with `cache-control: public, max-age=3600, stale-while-revalidate=86400` and open CORS, so an hour of caching is what we expect.

**Key rotation.** A token's `kid` names the key that signed it. When the signing key is replaced, new tokens carry the new `kid` and the JWKS lists it; tokens already issued (valid for one hour) keep verifying while their key is still listed. So: cache the set, and when a token arrives with a `kid` you do not have, refetch the set once (rate-limit that refetch, for example once a minute, so a forged `kid` cannot make you hammer the endpoint) and then fail if it is still unknown. `jose`, PyJWT's `PyJWKClient` and `keyfunc` do this for you; the C# sample refreshes hourly, so on an unknown `kid` clear its cache and verify once more. Do not hard-code a key in your server.

**Using the token on a WebSocket or in a long session.** A browser cannot set an `Authorization` header on a WebSocket, so send the token as the first message after the connection opens (a token in the address ends up in server logs) and close the connection if it does not verify within a few seconds. The token lives for one hour, so a connection that outlives it must send a fresh one from `getUserToken()` before it expires. A guest has no token: let a guest play with an id you create yourself, and ask the player to sign in before you link that id to a ZokoGames account. Your server needs to reach `https://www.zokogames.com` to read the keys; cache them as described above.

If your JWT library only takes a static key, fetch the same key as PEM from `https://www.zokogames.com/.well-known/public-key.json`. It returns `{ "publicKey": "-----BEGIN PUBLIC KEY-----…", "kid": "…", "alg": "RS256" }`. When a token's `kid` no longer matches the stored one, the key was rotated: fetch it again. Prefer the JWKS, which handles rotation for you.

:::tabs
== Node.js
<!-- docs-sample: fragment -->
```js
import { createRemoteJWKSet, jwtVerify } from "jose";

const GAME_ID = process.env.ZOKO_GAME_ID;
const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));

/** Returns { userId, username } for a valid token, or throws. */
export async function verifyZokoToken(raw) {
  const { payload } = await jwtVerify(raw, JWKS, {
    algorithms: ["RS256"],       // never accept anything else
    issuer: "zokogames",
    audience: GAME_ID,           // a token for another game fails here
    requiredClaims: ["exp", "iat", "aud"],
    clockTolerance: 5,           // seconds of clock drift
  });
  if (payload.gameId !== GAME_ID || payload.sub !== payload.userId) {
    throw new Error("malformed token");
  }
  return { userId: String(payload.userId), username: String(payload.username) };
}
```
== Python
```python
import os
import jwt  # PyJWT >= 2.8, with the "crypto" extra

jwks_client = jwt.PyJWKClient("https://www.zokogames.com/.well-known/jwks.json", cache_keys=True)
GAME_ID = os.environ["ZOKO_GAME_ID"]

def verify_zoko_token(token: str) -> dict:
    signing_key = jwks_client.get_signing_key_from_jwt(token)
    claims = jwt.decode(
        token,
        signing_key.key,
        algorithms=["RS256"],
        audience=GAME_ID,
        issuer="zokogames",
        options={"require": ["exp", "iat"]},
        leeway=5,
    )
    if claims.get("gameId") != GAME_ID or claims.get("sub") != claims.get("userId"):
        raise ValueError("token is for a different game")
    return claims
```
== C#
```csharp
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

public sealed class ZokoTokenVerifier
{
    private static readonly HttpClient Http = new();
    private JsonWebKeySet? _keys;
    private DateTime _fetched = DateTime.MinValue;

    public async Task<JwtSecurityToken> VerifyAsync(string token, string gameId)
    {
        if (_keys is null || DateTime.UtcNow - _fetched > TimeSpan.FromHours(1))
        {
            var json = await Http.GetStringAsync("https://www.zokogames.com/.well-known/jwks.json");
            _keys = new JsonWebKeySet(json);
            _fetched = DateTime.UtcNow;
        }

        var parameters = new TokenValidationParameters
        {
            ValidAlgorithms = new[] { SecurityAlgorithms.RsaSha256 }, // RS256 only
            IssuerSigningKeys = _keys.GetSigningKeys(),
            ValidateIssuer = true,
            ValidIssuer = "zokogames",
            ValidateAudience = true,
            ValidAudience = gameId, // the token's `aud` is your game id
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(5),
        };

        new JwtSecurityTokenHandler().ValidateToken(token, parameters, out var validated);
        var jwt = (JwtSecurityToken)validated;
        string? Claim(string type) => jwt.Claims.FirstOrDefault(c => c.Type == type)?.Value;
        if (Claim("gameId") != gameId || Claim("sub") != Claim("userId"))
            throw new SecurityTokenException("token is for a different game or malformed");
        return jwt;
    }
}
```
== Go
```go
package zoko

import (
	"errors"
	"os"
	"time"

	"github.com/MicahParks/keyfunc/v3"
	"github.com/golang-jwt/jwt/v5"
)

// NewDefault fetches the key set, caches it and refreshes it in the background.
var jwks, _ = keyfunc.NewDefault([]string{"https://www.zokogames.com/.well-known/jwks.json"})

func VerifyToken(raw string) (jwt.MapClaims, error) {
	claims := jwt.MapClaims{}
	_, err := jwt.ParseWithClaims(raw, claims, jwks.Keyfunc,
		jwt.WithValidMethods([]string{"RS256"}),
		jwt.WithExpirationRequired(),
		jwt.WithIssuer("zokogames"),
		jwt.WithAudience(os.Getenv("ZOKO_GAME_ID")),
		jwt.WithLeeway(5*time.Second),
	)
	if err != nil {
		return nil, err
	}
	if claims["gameId"] != os.Getenv("ZOKO_GAME_ID") {
		return nil, errors.New("token is for a different game")
	}
	return claims, nil
}
```
:::

Send the token with each request, for example `Authorization: Bearer <token>`:

<!-- docs-sample: uses saveGame -->
```js
const token = await SDK.user.getUserToken();
const res = await fetch("https://api.example.com/save", {
  method: "POST",
  headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
  body: JSON.stringify(saveGame),
});
```

> [!WARNING]
> Local mode issues an unsigned token (`alg: none`). A correct verifier rejects it. For local backend development, add a clearly separated test-only bypass that is impossible to enable in production. There is no signed test token and no test key: to run your verifier against a real signed token, sign in with an account of your studio and open the game's build preview in the console (the portal issues tokens for a game that is not live yet to its studio's members).

**Testing your verifier without a live player.** There is no signed test token and no shared test key, on purpose. Three ways, from cheapest:

1. Unit-test the checks themselves: generate your own RSA key pair in the test, sign tokens with it and give your verifier that public key instead of the JWKS. Cover a valid token, a wrong `aud`, a wrong `iss`, an expired `exp`, `alg: none`, a signature from another key, and `sub` different from `userId`.
2. Against the real keys: in the console open the game's build preview signed in as a member of your studio. Call `SDK.user.getUserToken()` there and send the token to your staging server; the portal issues real signed tokens for a game that is not live yet to its studio's members.
3. Locally: `?token_response=user1` issues an unsigned token that a correct verifier must reject; use it to test the rejection path.

In local mode the token has the claims `userId`, `gameId` (`"local-game"`), `username`, `profilePictureUrl`, `iat`, `exp` and `local: true`, but no `iss`, `aud` or `sub`, and its header says `alg: none`. You can steer it with `?token_response=`: `logged_out` rejects with `userNotAuthenticated`, `user1` or `user2` issue a token for that mock player, and `expired_token` issues one whose `exp` is already in the past, so you can test your backend's expiry path. Any other `token_response` value is ignored and the current mock player gets a token. Switch values are case-sensitive and a misspelled one is not an error: `?user_response=User1` or `?user_response=guest` simply starts the game as a guest, and a wrong `show_auth_prompt_response` or `link_account_response` is read as a cancel or as `yes`. Since SDK 1.6.3 the console prints one warning per page that names the wrong switch and the values it accepts.

## Sign-in prompt

```ts
showAuthPrompt(): Promise<PortalUser>
addAuthListener(fn: (user: PortalUser) => void): () => void
removeAuthListener(fn: (user: PortalUser) => void): void
```

Asks the player to sign in. The portal first shows a small invitation over the game ("Sign in" or "Not now"); choosing Sign in opens the portal's own sign-in dialog, and "Not now" rejects with `userCancelled`. Only call it in response to a player action, such as pressing a "Sign in to save your progress" button, never automatically at start. It resolves with the new user, or rejects:

| Code | Meaning |
| --- | --- |
| `userAlreadySignedIn` | Someone is already signed in. Check with `getUser()` first. |
| `showAuthPromptInProgress` | The invitation or the dialog is already open. |
| `userCancelled` | The player chose Not now or closed the dialog, or sign-in is not offered here (for example in a kids' game). Carry on as a guest. |

Before it opens anything, `showAuthPrompt` asks the portal who is signed in, so a stale answer from before a sign-out cannot give `userAlreadySignedIn`; that one question is the only step that can reject with `timeout` (10 seconds). The prompt itself has no timeout. `addAuthListener` throws `invalidArgument` if the argument is not a function; `removeAuthListener` ignores a function that was never added. The portal opens at most three prompts per page view and none for 60 seconds after the player chose Not now or closed the dialog; a call in either case rejects with `userCancelled` at once. In a kids' game the portal answers `userCancelled` at once. The auth listener also fires when the player signs in through the portal's own header while your game is open, so register one and update your UI there instead of relying only on the promise. The listener only ever receives a signed-in `PortalUser`, never `null`, and nothing is sent when the player signs out: signing out of the portal does not call it. If your game stays open across a sign-out, do not rely on the listener; call `getUser()` again when you need to know who is playing, and treat `null` as a guest.

<!-- docs-sample: uses hud, syncProgress, signInButton -->
```js
SDK.user.addAuthListener((user) => { hud.setName(user.username); syncProgress(); });

signInButton.onclick = async () => {
  try { await SDK.user.showAuthPrompt(); }
  catch (e) { if (e.code !== "userCancelled") console.warn(e.code); }
};
```

## Deprecated

`getXsollaUserToken(): Promise<string>` is a deprecated alias that returns the purchase token (the same value as `SDK.store.getPurchaseToken()`); use the new name instead (see [in-game purchases](https://docs.zokogames.com/sdk/purchases)). It fails with `userNotAuthenticated` for guests.

## Account linking

```ts
showAccountLinkPrompt(): Promise<{ response: "yes" | "no" }>
```

For games with their own accounts. Ask a signed-in player whether to link their ZokoGames identity to the game's existing account. Link the `userId` from the verified token on your server only when the response is `"yes"`, and prefer linking to fresh accounts over merging two accounts with progress. A player with no signed-in portal user (and every player in a kids' game) gets `userNotAuthenticated`, and a second call while the prompt is open rejects with `showAccountLinkPromptInProgress`. The same limits as for the sign-in prompt apply (three per page view, a 60-second pause after a "no"), and a call over them rejects with `userCancelled`. The call has no timeout because the player decides when to answer. See [account integration scenarios](https://docs.zokogames.com/requirements/accounts).

## Submitting scores

```ts
submitScore(options: { encryptedScore: string; score: number; delayed?: { encryptedScore: string; earnedAt: number } }): Promise<void>
```

Posts a leaderboard score from the client. It rejects with `invalidArgument` unless `encryptedScore` is a string and `score` is a finite number, and with `rateLimited` when the player submits too often. A guest does not get an error; see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission) for that and for the encryption scheme. The optional `delayed` copy keeps a score that was earned offline and sends it when the player is back online (SDK 1.6.4); how to seal it is in [Offline scores](https://docs.zokogames.com/sdk/leaderboards#offline-scores).

## In local mode, as a guest, offline or ad-free

| Member | Local mode | Guest | Offline |
| --- | --- | --- | --- |
| `isUserAccountAvailable` | `true`; `false` with `?user_account_available=false` (then the player is a guest) | `true` in the portal | `true` |
| `getUser` | A mock player: `?user_response=user1` (default) or `user2`; any other value (such as `logged_out`) means a guest | `null` | A saved game started offline uses the last signed-in player on this device |
| `listFriends` | 12 mock friends, paged | `userNotAuthenticated` | Needs the portal; fails with `unexpectedError` |
| `getUserToken` | Unsigned test token (see `token_response` above) | `userNotAuthenticated` | Needs the portal; fails with `unexpectedError` |
| `showAuthPrompt` | Signs in at once as `?show_auth_prompt_response=` (`user1` default, `user2`); any other value rejects with `userCancelled`; `userAlreadySignedIn` if already signed in | Shows the invitation, then opens the portal's sign-in dialog | Needs the portal; fails or never answers until back online |
| `showAccountLinkPrompt` | `?link_account_response=yes` (default) or `no`; `logged_out` or a guest gives `userNotAuthenticated` | `userNotAuthenticated` | Needs the portal; fails or never answers until back online |
| `submitScore` | Resolves, records nothing; SDK 1.6.3 logs one console line per call. Offline with a signed-in player and `delayed`, SDK 1.6.4 shows "Score saved offline" | Resolves without recording, and the score is not kept. When it would place in the top 10 of the current week's board, the portal invites the player to sign in, at most once per game per page view. Submit the score again after sign-in if it should count. | Resolves without recording. Offline, the score is not lost if you also pass `delayed`: a copy sealed at the end of the run with `earnedAt = Date.now()`, additional data `zoko-score-v3|<userId>|<gameId>|<earnedAt>` and plaintext `<score>|<earnedAt>`. The portal keeps it on the device for a signed-in player (keyed boards only, never in kids mode) and sends it when they are back online, within 72 hours. It counts for the all-time board only, not the weekly board. Without `delayed`, or on a portal older than SDK 1.6.4, an offline score is not queued. See [Offline scores](https://docs.zokogames.com/sdk/leaderboards#offline-scores). |
| Ad blocker / ad-free | No effect on this module | | |

In basic launch nothing in this module changes: a basic-launch game is live, so players can sign in, list friends and get tokens as in full launch.

**Common mistakes.** The ones reviewers and the Preview tool report most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| `getUserToken()` is called for a guest | `userNotAuthenticated` | Check `getUser()` first, or catch the code and continue as a guest. |
| `__dangerousUserId` or `username` is sent to your server as proof of identity | Anyone can fake it | Send the token from `getUserToken()` and verify it on the server, with the `iss`, `aud` and `gameId` checks. |
| The token is verified without checking `aud` or `gameId` | A token from another game is accepted | Check both, as in the samples. |
| A local-mode token (`alg: none`) reaches production verification | Correctly rejected | Use the test-only bypass for local work only. |
| `showAuthPrompt()` runs at start or on a timer | `userCancelled` after the first refusal, and none for 60 seconds | Call it from a button press ("Sign in to save"). |
| The `userCancelled` rejection is shown as an error | A scary message after "Not now" | Treat it as a normal answer and carry on as a guest. |
| `showAuthPrompt()` is called for a player who is already signed in | `userAlreadySignedIn` | Check `getUser()`, or just handle the code. |
| The game only uses the promise of `showAuthPrompt` | A sign-in from the portal header is missed | Register `addAuthListener` as well. |
| `listFriends` is called in a tight loop | `requestInProgress` or `rateLimited` | One request at a time, 250 ms or more apart, `size` 1 to 50. |
| `submitScore` is called every frame | `rateLimited` | Submit once per run. |
| Sign-in UI is shown in kids mode | `isUserAccountAvailable` is `false` and the prompt answers `userCancelled` | Hide it when `isUserAccountAvailable` is `false`. |
| `systemInfo` or `isUserAccountAvailable` is read before `init()` | `sdkNotInitialized` | Read them after `await SDK.init()`. |

Full runnable example:

<!-- docs-sample: uses hud -->
```js
await SDK.init();

let user = await SDK.user.getUser();
SDK.user.addAuthListener((u) => { user = u; hud.setName(u.username); });

async function loadProfile() {
  if (!user) return null; // guest: play without a profile
  try {
    const token = await SDK.user.getUserToken();
    const res = await fetch("https://api.example.com/profile", {
      headers: { authorization: `Bearer ${token}` },
    });
    return res.json();
  } catch (e) {
    if (e.code === "userNotAuthenticated") return null;
    throw e;
  }
}
```

**Kids mode.** `init` reports no user and `isUserAccountAvailable` is `false`, `getUser` resolves `null`, `getUserToken`, `listFriends` and `showAccountLinkPrompt` reject with `userNotAuthenticated`, and `showAuthPrompt` rejects with `userCancelled`. Branch on `isUserAccountAvailable`, not on the codes; the full list is in [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode).

## Next steps

- [Leaderboards](https://docs.zokogames.com/sdk/leaderboards)
- [Player accounts and your backend](https://docs.zokogames.com/guides/player-accounts)

---

Source: https://docs.zokogames.com/sdk/data

# Data (cloud save)

**Purpose:** `SDK.data` stores a small key/value save in the portal so progress follows the player across devices and survives cleared browser storage. The API deliberately mirrors `localStorage`:

```ts
getItem(key: string): string | null
setItem(key: string, value: string): void
removeItem(key: string): void
clear(): void
```

Each call coerces its arguments with `String()`, so `setItem("level", 3)` stores `"3"`. `getItem` returns `null` for a key that was never set. Setting a key to the value it already has does nothing (no upload). `removeItem` of a missing key and `clear()` on an empty save do nothing either.

All four are **synchronous**. The whole save is loaded when `init()` resolves, so reads never wait. Writes update memory immediately and sync to the portal in the background.

<!-- docs-sample: uses stars -->
```js
await SDK.init();

const level = Number(SDK.data.getItem("level") ?? "1");

function onLevelComplete(next) {
  SDK.data.setItem("level", String(next));
  SDK.data.setItem("stars", JSON.stringify(stars));
}
```

Values are strings. Store structured state with `JSON.stringify` and parse defensively.

## At a glance

Every member of `SDK.data`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Returns | Can fail with | Since |
| --- | --- | --- | --- |
| `getItem(key: string): string \| null` | The saved string, or `null` for a key that was never set. Synchronous. | Throws `dataModuleDisabled`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `setItem(key: string, value: string): void` | Nothing. Memory changes at once; the upload follows in the background. | Throws `dataLimitExceeded` (nothing is written), `dataModuleDisabled`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `removeItem(key: string): void` | Nothing. | Throws `dataModuleDisabled`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `clear(): void` | Nothing. | Throws `dataModuleDisabled`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `mirrorLocalStorage(options?: MirrorLocalStorageOptions): () => void` | A function that stops mirroring. Does nothing when the SDK is `disabled`. | Throws `dataModuleDisabled`, `sdkNotInitialized`. | 1.4.0 |
| `mirrorIndexedDB(options?: MirrorIndexedDBOptions): Promise<() => void>` | A promise that resolves, after any restore, with a function that stops mirroring. Resolves with a no-op function when the SDK is `disabled` or the browser has no IndexedDB. | Rejects with `dataModuleDisabled`, `sdkNotInitialized`, `invalidArgument` (no `databases` given and the browser cannot list them). | 1.7.0 |

`MirrorLocalStorageOptions` is `{ keys?: string[] | RegExp; prefix?: string; onError?: (error: SdkError) => void }`. The type `DataApi` is in the declaration file described in the SDK introduction. Mirroring keeps its own bookkeeping in the reserved cloud key `__zoko_ls_mirror_ts`, which counts toward the 1 MiB save limit; do not use that key yourself.

## Lifecycle

```text
init() resolves                 whole save already in memory
  -> getItem(...)               read, no waiting
  -> setItem / removeItem / clear   memory changes at once, upload scheduled
       1 s of quiet  OR  30 s since the first unsent change  OR  page hidden / closed  -> upload
       upload fails -> data stays in memory, retried after 2 s, 4 s, ... up to 60 s, or sooner with the next write
```

## How syncing works

- Writes are **debounced by one second**: several `setItem` calls in a burst become one upload.
- If writes keep arriving, an upload still goes out at least every 30 seconds.
- Pending writes are sent immediately when the page is hidden or closed (`visibilitychange` to hidden, `pagehide`).
- If an upload fails, the data is kept in memory and retried on its own after 2, 4, 8 seconds and so on up to 60 seconds, and sooner with the next write or when the page is hidden. The failure is **not surfaced to your game**: `setItem` has already returned, no promise rejects and no event fires (there is no flush call to wait on either). The SDK only logs `data sync failed` to the console. A game cannot tell that a background upload is failing, so treat the cloud save as best effort and keep playing from memory.
- While the player is offline the portal keeps the changes on the device and uploads them when the connection returns (for a signed-in player).

Guests and signed-in players both get a save, but it lives in different places:

- **Signed-in players:** the save is stored on the portal's servers and follows the account across devices and browsers.
- **Guests:** the save is kept in the browser's `localStorage` of the portal page, which the portal writes for your game when the SDK syncs. It is not your game's own `localStorage`: the game frame runs on its own origin and has its own, separate storage, which the SDK never reads or writes. A guest's save survives reloads and later visits in the same browser, but not a cleared browser, a private window or another device; the portal may offer to sign in so the save is not lost.
- **When a guest signs in while playing,** their save is uploaded if the account has no save for your game yet. If the account already has a different save, the portal asks the player which copy to keep: until they answer, your game keeps the guest's data and its writes stay on the device, and choosing the account's copy reloads your game (see [Guests and signing in](https://docs.zokogames.com/guides/cloud-saves#guests-and-signing-in)). Plan for both outcomes: never assume the data you loaded at start is still the data in the store.
- **After a sign-out or a switch to another account,** the portal restarts your game. Until it does, `setItem`, `removeItem` and `clear` behave as usual but the change is not stored. A signed-in player's changes that had not been uploaded when they signed out are uploaded, not replaced by the older cloud save, when the same player signs in again.
- **Kids mode:** saves stay on the device and are never uploaded. `SDK.data` works as for a guest: `getItem` returns what your game saved on this device in kids mode, never anything from a signed-in parent's account. A kids-mode save belongs to no account, so it is never merged into an account's cloud save, and it is not adopted or uploaded when kids mode ends and an adult is signed in. Changes that could not be uploaded (offline, a failed upload, a closed tab) are remembered on the device for that player alone and are offered again the next time the same player is signed in; see [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode).
- **Two copies of the SDK in one game frame** (for example an engine plugin and a script tag, or your game reloading its own document) share one load: the second `init()` gets the same save as the first. If the player signed in since the frame started, the second copy waits briefly for the portal to finish the sign-in comparison; if the frame was started for a different player, its `init()` is refused and that copy stays `"disabled"` until the game is reloaded.
- **While the player deletes the cloud save** (**Delete cloud save** in the game page menu), uploads stop, and an `init()` that arrives meanwhile is refused: that SDK copy stays `"disabled"`. When the delete succeeds the game restarts from an empty save, in this tab and in the player's other tabs; if it fails, the player is offered a reload.
- **A deleted cloud save is not brought back:** when the player deleted the cloud save from another tab or device, an upload written against that save is refused (HTTP 409 `save_gone`) and the SDK reports a generic save failure, so keep playing with the local copy and do not retry the upload in a loop.
- **After a player deletes a game's cloud save,** the portal remembers the deletion for 90 days. A device that still holds the old progress does not upload it silently: the player is asked whether to keep that device's progress or delete it there too, and until they answer nothing is uploaded and the game keeps running on its local copy. After 90 days an old device saves as normal. The game needs no code for this: the `SDK.data` calls behave as usual, and a write the portal holds back is not an error (nothing throws and no event fires).

## Limit

The whole save, serialised as JSON, must not grow past **1,048,576 bytes (1 MiB)**. The size is measured on the whole save as one JSON object of key/value strings, in UTF-8 bytes. The limit is on the whole save, not on a key: there is no separate per-key limit, so one value may use almost all of it, and every key's name, quotes and separators count too. Ten keys of 100 KiB each are over the limit, and so is one key of 1 MiB. A `setItem` that would exceed it throws `dataLimitExceeded` and changes nothing; that is the only limit error your code sees, and it is raised at write time, never by a later background upload.

The portal also checks a few things the SDK does not: a key name of more than 256 characters, or a key or value that contains the character U+0000, makes the portal refuse the whole upload, and the top-level key names `constructor` and `prototype` are dropped. One account holds at most 25 MiB of cloud saves across all games; when it is full, progress stays on the device. None of these is reported to your game, so keep key names short and plain.

<!-- docs-sample: uses bigString -->
```js
try {
  SDK.data.setItem("replay", bigString);
} catch (e) {
  if (e.code === "dataLimitExceeded") SDK.data.removeItem("replay");
}
```

Keep saves compact: store ids and numbers, not whole world snapshots.

## Errors

| Code | Thrown by | Meaning |
| --- | --- | --- |
| `dataLimitExceeded` | `setItem` | The write would push the save over 1 MiB. Nothing was written. |
| `dataModuleDisabled` | all four methods | The data module is not enabled for this game. In the console open the game's **Technical** step, turn on **Uses the SDK data module** and save. The game reads the setting when it starts. |
| `sdkNotInitialized`, `sdkDisabled` | all four methods | See [errors](https://docs.zokogames.com/sdk/introduction#errors). |

`removeItem` and `clear` never throw `dataLimitExceeded`. The code `other` is part of the data code list but the SDK does not raise it for these calls.

Because these methods are synchronous they **throw** rather than reject. `dataModuleDisabled` is thrown by every method, including `getItem`.

**Ordering.** Every method needs `init()` to have resolved: before that, and in the `"disabled"` environment, it throws `sdkNotInitialized` or `sdkDisabled`, so read the save only after `await SDK.init()`. When the game is not allowed to use cloud saves (`dataModuleDisabled`) fall back to your own in-memory state. Writes made in the first moments after a sign-in or a sign-out are covered above.

**Common mistakes.** The ones the Preview checklist and QA report most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| A save is written on every frame or every click | Many uploads that are only coalesced, not avoided | Write when the state changes meaningfully (a level, a purchase) and let the SDK debounce. |
| One big JSON snapshot of the whole world is stored | `dataLimitExceeded` at 1 MiB, and a Preview check fails when the save reaches 1,048,576 bytes | Store ids and numbers; keep replays and assets on your own storage. |
| `setItem` is not wrapped in `try`/`catch` | An uncaught `dataLimitExceeded` stops the game loop | Catch it and drop the least useful key. |
| `SDK.data.setItem("level", 3)` is read back as a number | `getItem` returns `"3"` | Parse: `Number(SDK.data.getItem("level") ?? "1")`. |
| The game keeps using `localStorage` and `SDK.data` for the same keys | Two saves that drift apart | Pick one, or use `mirrorLocalStorage` for a ported game. |
| `mirrorLocalStorage` is called after the game has read its saves | The game starts from the old local values | Call it right after `init()` and before the first read. |
| `mirrorIndexedDB()` is not awaited before the engine starts | The engine reads the old local files | `await` it, then start the engine. |
| `localStorage.level = 3` is used while mirroring | The write is not seen | Use `localStorage.setItem`. |
| A failed upload is expected to reject or fire an event | Nothing is reported; only a console message | Treat the cloud save as best effort and keep playing from memory. |
| Local mode is used to test `dataModuleDisabled` | It cannot happen locally (always enabled) | Catch `dataModuleDisabled` anyway, and test the real setting in the Preview tool. |

## When to use something else

- Progress that must be shared between your own services, or tied to purchases, belongs on your server with the [verified token](https://docs.zokogames.com/sdk/user#tokens).
- Large assets and replays belong on your own storage.
- Anything you cannot afford to lose should also be stored in a way you can recover. Treat cloud save as convenient, not as a database.

## In local mode, as a guest, offline or ad-free

| Situation | Behaviour |
| --- | --- |
| Local mode | The save lives in `localStorage` under the key `zoko-sdk-data` and is always enabled, so `dataModuleDisabled` cannot be tested locally. Delete that key (or use an incognito window) to simulate a new player. The 1 MiB limit and the debounce are the same. |
| Basic launch | No difference: the save works as in full launch, as long as **Uses the SDK data module** is on. |
| Signed-in player | Save stored on the portal and merged as described above. |
| Guest | Save kept in the browser for the portal; the portal may offer to sign in so the save is not lost. |
| Offline | Reads and writes work from memory and the device copy; upload resumes online. |
| Ad blocker / ad-free | No effect. |

## Mirroring `localStorage` (ported games)

Added in SDK 1.4.0. A game that already saves with `localStorage` can get cloud saves without code changes. Call this once right after `init()`, before the game reads its saves:

```js
await SDK.init();
const stop = SDK.data.mirrorLocalStorage({ prefix: "mygame_" }); // or { keys: ["save", "settings"] } or { keys: /^slot\d$/ }
```

Nothing is mirrored unless you call it. With no `keys` and no `prefix` every key is mirrored (a key matches when it is in `keys`, matches the expression, or starts with `prefix`). The function it returns stops mirroring.

- **Writes:** `localStorage.setItem`, `removeItem` and `clear` on the page's own `localStorage` are copied into the cloud save under the same key, 2 seconds after the last write (at most every 10 seconds under steady writes, and at once when the page is hidden or closed). `sessionStorage` is never touched. Assigning `localStorage.key = value` or `localStorage["key"] = value` bypasses the methods and is not seen; use `setItem`.
- **Restore on call:** the SDK keeps one timestamp per key (a reserved key, `__zoko_ls_mirror_ts`, in both places; do not use that name). For each key the newer side wins, and a deletion counts as a write. A key only one side has is copied to the other. On equal timestamps nothing changes.
- **Quota:** the cloud save is still limited to 1 MiB. A key that does not fit stays in `localStorage` only and is reported through `onError(error)` with code `dataLimitExceeded` (default: `console.error`); other keys keep syncing.
- Does nothing when the SDK is `disabled`; throws `dataModuleDisabled` when cloud saves are off for the game and `sdkNotInitialized` before `init()` resolves. Mirrored keys share the cloud save with `setItem`, so a key written by both is overwritten by whichever wrote last.

## Mirroring IndexedDB (Unity, Godot, GameMaker)

Added in SDK 1.7.0. Engines that save into IndexedDB (Unity's `/idbfs`, Godot's user file system, GameMaker) get cloud saves without code changes. Opt-in, like `mirrorLocalStorage`. **Await it before the engine starts**: the restore happens inside the promise, and an engine that reads its files before the promise resolves sees the old local data and may overwrite the cloud copy with it.

<!-- docs-sample: uses startEngine -->
```js
await SDK.init();
const stop = await SDK.data.mirrorIndexedDB({ databases: ["/idbfs/mygame"] });
startEngine(); // only now
```

Options (`MirrorIndexedDBOptions`): `databases` (names to mirror; default: every database `indexedDB.databases()` lists except engine asset caches such as `UnityCache`, and required when the browser cannot list databases), `maxBytes` (a lower cap; never above the 1 MiB save limit), `debounceMs` (default 2000), `pollMs` (default 5000) and `onError(error)` (default `console.error`). Pass `databases` whenever you know the names: it is faster and keeps big asset caches out.

- **Storage:** the snapshot is one reserved cloud key, `__zoko_idb_mirror`, a versioned JSON string with each database's version, object stores (key path, auto-increment, indexes) and records. Binary values (`ArrayBuffer`, typed arrays, `Blob`) are base64, dates and `Map`/`Set`/`bigint` are tagged. Binary grows by about a third, and the whole snapshot counts toward the same 1 MiB save limit as everything else in `SDK.data`; do not use that key yourself.
- **Limit:** a snapshot that would not fit is **never truncated**. That cycle is skipped, IndexedDB and the last cloud copy stay as they are, and `onError` gets `dataLimitExceeded` once (until a cycle fits again). A value the encoding cannot carry (a function, a cyclic object) is reported the same way.
- **Restore:** when the cloud copy is newer than this device's last sync, it is written back into IndexedDB: stores in the snapshot are replaced, and databases and stores that are **not** in the snapshot are never deleted or touched. A missing database is created at the snapshot's version; an existing one is only upgraded to a higher snapshot version, and a store whose key path differs is skipped and reported. An empty local database never replaces cloud data. On equal timestamps nothing changes. Restore stops waiting after 10 seconds so the game still starts.
- **Changes:** IndexedDB has no change event, so the SDK polls while the page is visible (counts every 5 s, a full read about every 15 s) and checks again when the page is hidden or closed. A change is uploaded after it has been stable for 2 seconds (at most every 10 seconds under steady writes). A save made in the last moments before the tab closes can be lost, because IndexedDB reads are asynchronous.
- **Not mirrored:** Cache Storage, OPFS and cookies.

## Migrating from `localStorage`

```js
const migrated = SDK.data.getItem("migrated") === "1";
if (!migrated) {
  for (const key of ["level", "stars", "coins"]) {
    const v = localStorage.getItem(key);
    if (v !== null) SDK.data.setItem(key, v);
  }
  SDK.data.setItem("migrated", "1");
}
```

## Next steps

- [Cloud saves in practice](https://docs.zokogames.com/guides/cloud-saves)
- [Leaderboards](https://docs.zokogames.com/sdk/leaderboards)

---

Source: https://docs.zokogames.com/sdk/leaderboards

# Leaderboards

**Purpose:** this page explains how players are ranked each week and how your game or your server submits scores. Leaderboards are enabled per game in the developer console. Players are ranked inside a weekly season, and the best of each season earns trophies on their profile.

## Concepts

Configure these in the console, on your game's **Leaderboard** tab.

| Setting | Meaning |
| --- | --- |
| Score label | How scores are described to players: `XP`, `KDA`, `POINTS` (shown as Points) or `MINUTES` (shown as Minutes). |
| Sorting | `DESC` (bigger is better) or `ASC` (smaller is better, for times). |
| Min and max value | Scores outside the range are rejected. Default 0 to 999,999,999; the console accepts any value from -1,000,000,000,000 to 1,000,000,000,000, and the minimum may not exceed the maximum. On an incremental board the range applies to each submitted amount, not to the running total. |
| Cooldown | Minimum seconds between submissions from the same player (counted from their last update), from `0` (none) to `86400`. Enforced atomically, so parallel submissions cannot slip past it. A score sent inside the cooldown is dropped, not queued: your game sends it again after the cooldown if it still wants it. |
| Incremental | When on, each submitted score is **added** to the player's season total, and must be greater than zero. When off, the player keeps their better score for the season; a worse score is accepted but changes nothing. |
| Player guide | Free text (up to 600 characters) shown with the board that explains how to score. |
| Encryption key | A 32-byte key (base64) used to encrypt client submissions. Shown once when you generate or rotate it. |
| API key | For server submissions, starts with `zlb_`. Shown once; we store only a hash. |

A **season** is one ISO week (for example `2026-W47`). Seasons roll over on Monday at 09:00 UTC. When a season closes, ranks 1, 2 and 3 receive gold, silver and bronze trophies, and further top-1 %, top-5 % and top-10 % trophies are awarded once at least 10 players took part. Players with the same score share a rank.

Only signed-in players appear on a leaderboard. Guests cannot submit. Players choose who sees them on leaderboards in their account settings: everyone (`public`, the default), accepted friends only (`friends`), or nobody (`hidden`). A player who is not shown to a viewer is left out of that viewer's board, and the ranks of everyone else are counted without them, so there are no gaps. Scores are still recorded for a hidden player, and they always see their own row. The leaderboard responses the player-facing panel uses (`/api/sdk/leaderboard/<gameId>` and `/api/leaderboard/<gameId>`) carry `privacyDisabled: true` for a signed-in player who chose `hidden` (otherwise `false`), so your game can explain why they are not listed to others. The field is additive; ignore it if you do not need it.

**Changing the rules later.** Saving applies the new rules to the next submission only; scores already on the board are not rewritten. Flipping **Sorting** re-ranks the existing scores by the new rule, flipping **Incremental** changes how the next submissions combine with what is already stored, and a narrower min and max does not remove old scores. After changing sorting or incremental on a board that has scores, use **Reset scores** on the Leaderboard tab to start the week clean. **Reset this week** deletes the running week's scores, **Reset all weeks** deletes every week's; either way players lose those scores from the board and from their own best scores, trophies already awarded stay, and the studio's webhook `leaderboard.reset` fires. Turning **Leaderboard enabled** off hides the board and refuses new scores (`no_leaderboard`) but deletes nothing. **Rotating the encryption key** makes every shipped build that still has the old key drop its scores silently, for all players, until a build with the new key is live; a build update is reviewed before players get it, so rotate only when that build is ready.

A game made for children has no leaderboard: `submitScore` still resolves and records nothing (a `delayed` copy is not kept either), and the server API answers `403` with `kids-game`.

## Lifecycle

```text
run ends in the game
  -> user = await SDK.user.getUser()           null for a guest: skip the submission
  -> encryptedScore = encrypt(score, key, userId, gameId)
  -> await SDK.user.submitScore({ encryptedScore, score })
  -> portal checks the board rules -> accepted -> rank toast for the player
```

## Client submission

```ts
SDK.user.submitScore(options: { encryptedScore: string; score: number; delayed?: { encryptedScore: string; earnedAt: number } }): Promise<void>
```

`encryptedScore` proves the number came from your game: it is the score encrypted with your board's encryption key. When the board has a key, **only the encrypted value counts**; the plain `score` is ignored. Keys are opt-in: a new board has no key until you press **Generate** next to **Encryption key** on the game's **Leaderboard** tab. A board with no key accepts the plain `score` (and `encryptedScore` may be an empty string); that path is limited to 10 submissions a minute per player and can be forged by anyone with the browser's developer tools, so only the range, cooldown and rate limits protect it. Generate the key before you ship if the scores matter: on a game that is already live, the first key makes the board ignore the plain scores of the build players have now, for every player, until a build that encrypts with it is live (a build update is reviewed before players get it), so the console asks you to confirm before it makes one.

The scheme is AES-256-GCM, and the payload is bound to the player, the game and the moment it was made:

1. Build the plaintext `"<score>|<unix milliseconds now>"`, for example `"4210|1767225600000"`. The score may be negative or have up to 6 decimals, with at most 15 integer digits.
2. Generate a random 12-byte IV. It doubles as a one-time nonce, so use a fresh one for every submission.
3. Encrypt the UTF-8 bytes with the game's 32-byte key and the additional authenticated data `zoko-score-v1|<userId>|<gameId>`. The tag (16 bytes) is appended to the ciphertext.
   - `<userId>` is `getUser().__dangerousUserId`. It is the same value as the `userId` claim (and `sub`) of the player's [token](https://docs.zokogames.com/sdk/user#tokens): one UUID per account, identical in every game. It is not the opaque `userId` that the rankings endpoint returns.
   - `<gameId>` is your game's id: the UUID in your console address (`/developer/games/<id>`). It is set when the draft is created and stays the same after launch, and it is the `aud` and `gameId` claim of the tokens. From SDK 1.6.2 the game can read it as `SDK.game.gameId`; on earlier versions put it in your build as a constant (`GAME_ID` in the sample).
4. Send `base64(iv || ciphertext || tag)`.

In the sample below, `GAME_KEY` is the key the console showed once when you generated it (the console and the step-by-step guide call it `KEY`).

The portal rejects a payload made for another player or game, one older than 2 minutes (or from the future), and one it has already seen. Encrypt at the moment of submission; do not store or retry old payloads.

<!-- docs-sample: uses GAME_KEY, GAME_ID -->
```js
async function encryptScore(score, keyBase64, userId, gameId) {
  const raw = Uint8Array.from(atob(keyBase64), (c) => c.charCodeAt(0));
  const key = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt"]);
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const data = new TextEncoder().encode(`${score}|${Date.now()}`);
  const additionalData = new TextEncoder().encode(`zoko-score-v1|${userId}|${gameId}`);
  const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData }, key, data));
  const out = new Uint8Array(iv.length + sealed.length);
  out.set(iv, 0);
  out.set(sealed, iv.length);
  return btoa(String.fromCharCode(...out));
}

async function finishRun(score) {
  const user = await SDK.user.getUser();
  if (!user) return;
  const encryptedScore = await encryptScore(score, GAME_KEY, user.__dangerousUserId, GAME_ID);
  await SDK.user.submitScore({ encryptedScore, score });
}
```

> [!WARNING]
> Anti-cheat, honestly: every score a browser sends can be forged. Anything shipped in the browser can be read by a determined player, including the key, and a board without a key accepts the plain number outright. The encryption, the min and max range, the cooldown and the rate limits stop casual tampering, not a motivated cheater. If your game has real competitive stakes, calculate the score on your own server and submit it with the API key through the [server API](#server-api) below; that is the only path the portal can treat as trustworthy. Scores are accepted only for games that are live; a game in review or preview records nothing.

`submitScore` rejects with `invalidArgument` when `options` is not an object, `encryptedScore` is not a string, or `score` is not a finite number. Otherwise it resolves with nothing; `rateLimited` is the only portal error. It also throws `sdkNotInitialized` or `sdkDisabled` as described in [errors](https://docs.zokogames.com/sdk/introduction#errors). `delayed` is optional and never makes the call reject: a malformed one is dropped by the portal and the normal score still goes through, and neither the SDK nor local mode checks `earnedAt` or the token. See [Offline scores](#offline-scores).

To test the encryption without a live player, use local mode (it validates the call and records nothing) and decrypt your own payload in a unit test with the same key, IV and additional data; for a real accepted score, play a build in basic launch signed in with an account of your studio and look under **Entries this week** on the Leaderboard tab.

A submission that cannot be read (wrong key, malformed payload) or that breaks a board rule (range, cooldown) is dropped by the portal without telling the game why, so a cheater learns nothing; the call itself still resolves. A player who is not signed in does not get an error either: the call resolves without recording anything, and when the score would reach the top 10 of the current week's board the portal invites the player to sign in, at most once per game per page view; a run that does not place does not use up that invitation. Submissions are limited to 30 per minute per player and game; beyond that the call rejects with `rateLimited`. When a score is accepted the portal shows the player's rank.

**When `submitScore` rejects with `rateLimited`.** This is the one refusal the game is told about. The portal refused the call before it read the score, so nothing was recorded and the payload was not used up. The run is still yours to send. The retry rule:

1. **Keep the run, not the payload.** A payload older than 2 minutes is refused, so encrypt the kept score again for every attempt, with a fresh IV and the current time.
2. **Wait about a minute before the first retry.** The limit counts the last 60 seconds (10 without an encryption key). Then back off, for example 60, 120 and 240 seconds, and give up after about 5 attempts or when the player leaves. Never retry in a loop.
3. **Send one score for the backlog, not every run that piled up.** On a highest-first board keep the best run, on a lowest-first (`ASC`) board the lowest, on an incremental board add the amounts into one submission (it must stay within the max).
4. **A weekly score is not back-dated.** A retry that goes through after Monday 09:00 UTC counts for the new week, not for the week the run was played in.
5. **Retry only `rateLimited`.** Every other outcome resolves normally and the game is not told whether it counted. A score dropped by the cooldown can be sent again after the cooldown; one outside the min and max is never accepted, so do not resend it.

On the server API the same refusal is HTTP `429` `rate-limited` with a `Retry-After` header: wait that many seconds and resend the same body, since nothing in it was recorded.

### Offline scores {#offline-scores}

A run that ends while the player is offline cannot reach the board. Pass `delayed` next to the normal score to keep it:

```text
delayed?: { encryptedScore: string; earnedAt: number }
```

Offline, the score is not lost if you also pass `delayed`: a copy sealed at the end of the run with `earnedAt = Date.now()`, additional data `zoko-score-v3|<userId>|<gameId>|<earnedAt>` and plaintext `<score>|<earnedAt>`. The portal keeps it on the device for a signed-in player (keyed boards only, never in kids mode) and sends it when they are back online, within 72 hours. It counts for the all-time board only, not the weekly board. Without `delayed`, or on a portal older than SDK 1.6.4, an offline score is not queued.

- `earnedAt` is the moment the run ended, in Unix milliseconds (13 digits). Use the same number in the additional data, in the plaintext and in the field.
- `encryptedScore` inside `delayed` is the sealed copy as text, at most 256 characters. Seal it like the normal payload (AES-256-GCM, a fresh 12-byte IV, `base64(iv || ciphertext || tag)`); only the additional data and the plaintext differ.
- Nothing changes for the normal `encryptedScore`: send it as before. `delayed` is an extra field, and there is no new call.
- A malformed `delayed` is dropped by the portal, and the normal score still goes through. Neither the SDK nor local mode validates `earnedAt` or the token, so a wrong value is silent.
- Nothing is kept for a guest, on a board without an encryption key or in kids mode. A portal older than SDK 1.6.4 ignores `delayed`.

<!-- docs-sample: uses GAME_KEY, GAME_ID, encryptScore -->
```js
async function encryptDelayedScore(score, keyBase64, userId, gameId, earnedAt) {
  const raw = Uint8Array.from(atob(keyBase64), (c) => c.charCodeAt(0));
  const key = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt"]);
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const data = new TextEncoder().encode(`${score}|${earnedAt}`);
  const additionalData = new TextEncoder().encode(`zoko-score-v3|${userId}|${gameId}|${earnedAt}`);
  const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData }, key, data));
  const out = new Uint8Array(iv.length + sealed.length);
  out.set(iv, 0);
  out.set(sealed, iv.length);
  return btoa(String.fromCharCode(...out));
}

async function finishRun(score) {
  const user = await SDK.user.getUser();
  if (!user) return;
  const earnedAt = Date.now();
  const encryptedScore = await encryptScore(score, GAME_KEY, user.__dangerousUserId, GAME_ID);
  const delayed = {
    encryptedScore: await encryptDelayedScore(score, GAME_KEY, user.__dangerousUserId, GAME_ID, earnedAt),
    earnedAt,
  };
  await SDK.user.submitScore({ encryptedScore, score, delayed });
}
```

### In local mode, as a guest, offline or ad-free

| Situation | What `submitScore` does |
| --- | --- |
| Local mode | Validates its arguments, then resolves without recording anything and without a rank toast. Since SDK 1.6.3 every call also writes one console line (`Local mode: score <n> not sent (nothing is stored; real leaderboards run in the portal)`), so you can see the call happened. Offline (`?offline=true`), with a signed-in player and `delayed`, it shows "Score saved offline" (SDK 1.6.4). Test the encryption in your own code and the ranking in the [Preview tool](https://www.zokogames.com/preview). |
| Basic launch | Scores are recorded: a basic-launch game is live. Only a game that is not live yet (draft, in review, preview) records nothing. |
| Guest | Resolves without recording, and the score is not kept. When it would place in the top 10 of the current week's board, the portal invites the player to sign in, at most once per game per page view. Submit the score again after sign-in if it should count. |
| Offline | Resolves without recording. Offline, the score is not lost if you also pass `delayed`: a copy sealed at the end of the run with `earnedAt = Date.now()`, additional data `zoko-score-v3|<userId>|<gameId>|<earnedAt>` and plaintext `<score>|<earnedAt>`. The portal keeps it on the device for a signed-in player (keyed boards only, never in kids mode) and sends it when they are back online, within 72 hours. It counts for the all-time board only, not the weekly board. Without `delayed`, or on a portal older than SDK 1.6.4, an offline score is not queued. On a game with a leaderboard (never in kids mode), the offline notice over the game tells the player: **Scores are not saved while you're offline.** See [Offline scores](#offline-scores). |
| Ad blocker or ad-free member | No effect. |

**Common mistakes.** The ones QA and support see most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| The score is encrypted at level load and sent later, or an old payload is retried | The portal drops it silently: it only accepts a payload under 2 minutes old that it has not seen | Encrypt at the moment of submission with a fresh IV. |
| `userId` in the encryption's additional data is not the player's id from `getUser()`, or `gameId` is wrong | The payload is dropped without an error | Use `zoko-score-v1\|<userId>\|<gameId>` with the values from `getUser().__dangerousUserId` and your game id. |
| The board has a key but `encryptedScore` is empty | The plain score is ignored and nothing is recorded | Always send the encrypted value for a board with a key. |
| A score is submitted after every action | `rateLimited` (30 a minute, 10 without a key) | Submit once per run. If it already happened, keep the best run and re-send it after about a minute, encrypted again (see the retry rule under Client submission). |
| The result of `submitScore` is read as "accepted" | It resolves even when the score was dropped, ignored or the player is a guest | Do not show "new high score" from the promise. Read the rankings endpoint to show the rank. |
| Guests are expected to appear on the board | Nothing is recorded; the portal may invite them to sign in | Ask the player to sign in, then submit again. |
| Scores that matter are only checked in the browser | Anyone can forge them | Calculate on your server and use the server API. |
| The ranking `userId` is used as an account id | It does not match any token | Use it as a list key only, and `isYou` to find the player's row. |
| Test scores are left on the live board | Fake rows in the ranking | Use **Reset scores** before launch. |
| `delayed` is sealed with the normal payload's data, or its `earnedAt` differs between the field, the additional data and the plaintext, or it is in seconds | The portal drops the copy without an error; the normal score still goes through, and the offline score is lost | Seal it with `zoko-score-v3\|<userId>\|<gameId>\|<earnedAt>` and the plaintext `<score>\|<earnedAt>`, with one `earnedAt` in milliseconds. |

## Server API

For authoritative scores. Authenticate with your API key and send up to 100 scores per request (a request body over 100 KB is refused). `userId` is the `userId` claim from a [verified token](https://docs.zokogames.com/sdk/user#tokens). Each key may make 1,000 requests per minute. A missing or unknown key spends a separate budget of 30 a minute per address and then answers `429`; a valid key from that address is still served. A very high total request rate from one address (far above the per-key limit) also answers `429` with `Retry-After`.

```http
POST https://www.zokogames.com/api/v1/leaderboard/scores
X-API-Key: <your game's api key>
Content-Type: application/json

{ "scores": [ { "userId": "0b9c2e1a-8f2c-4d7e-9a11-2f6f3c1d4b55", "score": 4210 }, { "userId": "5e1d77a0-1a77-4c0b-8b3e-9d2c6a7f1e08", "score": 3987 } ] }
```

Send the request from your server. Examples:

:::tabs
== Node.js
<!-- docs-sample: uses process, batch -->
```js
const res = await fetch("https://www.zokogames.com/api/v1/leaderboard/scores", {
  method: "POST",
  headers: { "x-api-key": process.env.ZOKO_LEADERBOARD_KEY, "content-type": "application/json" },
  body: JSON.stringify({ scores: batch }),
});
const { ok, results } = await res.json();
```
== Python
```python
import os, requests

res = requests.post(
    "https://www.zokogames.com/api/v1/leaderboard/scores",
    headers={"X-API-Key": os.environ["ZOKO_LEADERBOARD_KEY"]},
    json={"scores": [{"userId": user_id, "score": 4210}]},
    timeout=10,
)
data = res.json()
```
== Go
```go
body, _ := json.Marshal(map[string]any{
	"scores": []map[string]any{{"userId": userID, "score": 4210}},
})
req, _ := http.NewRequest("POST", "https://www.zokogames.com/api/v1/leaderboard/scores", bytes.NewReader(body))
req.Header.Set("X-API-Key", os.Getenv("ZOKO_LEADERBOARD_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
```
== C#
```csharp
using var http = new HttpClient();
using var req = new HttpRequestMessage(HttpMethod.Post, "https://www.zokogames.com/api/v1/leaderboard/scores");
req.Headers.Add("X-API-Key", Environment.GetEnvironmentVariable("ZOKO_LEADERBOARD_KEY"));
req.Content = JsonContent.Create(new { scores = new[] { new { userId, score = 4210 } } });
var resp = await http.SendAsync(req);
var json = await resp.Content.ReadAsStringAsync();
```
== curl
```bash
curl -X POST https://www.zokogames.com/api/v1/leaderboard/scores \
  -H "X-API-Key: $ZOKO_LEADERBOARD_KEY" -H "Content-Type: application/json" \
  -d '{"scores":[{"userId":"0b9c2e1a-8f2c-4d7e-9a11-2f6f3c1d4b55","score":4210}]}'
```
:::

Keep the API key on your server only. The same min, max, sorting, cooldown and incremental rules apply as for the client path. Each score is checked on its own, so one bad entry does not stop the others. The response has one result per submitted score, in order:

Unlike the client path, the server API does not check the game's status: while the board is enabled and the key is valid, scores are recorded even for a game that is still a draft or in review. Use **Reset scores** on the game's **Leaderboard** tab to clear test scores before launch.

```json
{
  "ok": true,
  "results": [
    { "index": 0, "userId": "0b9c2e1a-8f2c-4d7e-9a11-2f6f3c1d4b55", "ok": true, "score": 4210, "rank": 12 },
    { "index": 1, "userId": "5e1d77a0-1a77-4c0b-8b3e-9d2c6a7f1e08", "ok": false, "error": "validation" }
  ]
}
```

Per-score `error` values:

| Error | Meaning |
| --- | --- |
| `no-active-season` | The leaderboard is disabled for this game. |
| `user-not-found` | The `userId` is unknown or the player is banned. |
| `banned` | An administrator has barred this player from leaderboards. |
| `validation` | The entry is malformed, outside the min and max range, or inside the cooldown. |
| `internal-server-error` | Retry later. |

The whole request fails instead (with no per-score results and `{ "ok": false, "error": ... }`) in these cases:

| HTTP status | `error` |
| --- | --- |
| 400 | `invalid-body` (not `{ scores: [...] }`), `empty` |
| 401 | `invalid-api-key` (missing, unknown or revoked) |
| 403 | `kids-game` (the game is made for children and has no leaderboard), `developer-suspended` (the studio is suspended; its server keys are refused like its API tokens) |
| 405 | `method-not-allowed` (any method other than `POST` or `OPTIONS`; the `Allow` header lists them) |
| 404 | `leaderboard-not-found` |
| 413 | `too-many-items` (more than 100), `payload-too-large` |
| 429 | `rate-limited` (a `retry-after` header says when to retry). Requests with a missing or unknown key get the same answer once their address has sent 30 of them in the last minute; a valid key from that address is not affected. |

Each score item is `{ "userId": string, "score": number }`.

### Errors of the server API

Every failure body is `{ "ok": false, "error": "<code>", "message": "<what happened>", "hint": "<how to fix it>" }`. Branch on `error` and the HTTP status; `message` and `hint` are for humans and their wording may change. The same `message` and `hint` fields are on every failed per-score result. The codes are the two tables above; causes and fixes:

| `error` | Status | Cause | Fix |
| --- | --- | --- | --- |
| `invalid-api-key` | 401 | The `X-API-Key` header is missing, has a typo, or the key was rotated or revoked. | Copy the current server API key (starts with `zlb_`) from the game's Leaderboard tab; after a rotation the old one stops working at once. |
| `invalid-body` | 400 | The body is not JSON, or has no `scores` array. | Send `Content-Type: application/json` and `{ "scores": [ ... ] }`. |
| `empty` | 400 | `scores` has no items. | Do not send empty batches. |
| `too-many-items` | 413 | More than 100 scores. | Send batches of at most 100. |
| `payload-too-large` | 413 | Body over 100 KB. | Send smaller batches. |
| `leaderboard-not-found` | 404 | The key's game has no leaderboard row. | Enable the leaderboard and save the rules on the Leaderboard tab, then generate a new key. |
| `kids-game` | 403 | The game is made for children. | Do not submit; a kids game has no board. |
| `developer-suspended` | 403 | The studio is suspended. | Contact support through the console. |
| `rate-limited` | 429 | Over the per-key or per-address limit. | Wait for the `Retry-After` seconds, then retry; batch instead of sending one score per request. |
| `method-not-allowed` | 405 | Not a `POST`. | Use `POST`. |

Per-score errors: `no-active-season` (turn on **Leaderboard enabled** and save the rules), `user-not-found` (use the `userId` claim of a verified token, not a ranking `userId` or a name), `banned` (nothing to fix; do not retry), `validation` (send `{ userId, score }`, keep the score in the min and max range, wait out the cooldown, and on an incremental board send an amount above zero) and `internal-server-error` (retry that entry later).

> [!NOTE]
> Generate and rotate the encryption key and the server API key on the game's **Leaderboard** tab (or the **Leaderboard keys** page in the console's left menu). A new key is shown once, with a button that copies it as code; leaving the page before you press **I have saved it** loses it, and rotating is the way to get a new one. Generating, rotating or revoking a key asks for a second step: a passkey or an authenticator app on your player account. Without one the console changes nothing and says so, and you add one in your account's security settings first. Rotating the encryption key breaks any shipped build that still uses the old one, and revoking the server API key makes your server's requests fail with `401` at once.

## Reading rankings

Public rankings for a game are available without a key:

```http
GET https://www.zokogames.com/api/leaderboard/<gameId>?scope=global&limit=10&season=2026-W47
```

`scope` is `global`, `country` or `friends` (friends needs a signed-in session and answers 401 otherwise). `limit` is 1 to 100 (default 10) and `season` (format `YYYY-Www`) defaults to the current one. The answer includes the season, when it ends, the sorting, the entries (`rank`, `userId`, `username`, `avatarUrl`, `countryCode`, `score`, `isYou`), the total, and the signed-in viewer's own row (`me`) and nearest neighbours. The game must be live and have the leaderboard enabled. Errors use the body `{ "error": "<code>" }`: `404` `game_not_found` (no live game with that id), `404` `no_leaderboard` (the leaderboard is off), `400` `invalid_request` (a malformed game id, `scope`, `limit` or `season`) and `401` `unauthenticated` (`scope=friends` without a session). A game made for children answers `200` with no entries and an `unavailable` field.

### Errors of the rankings read

The status codes are as above; the body is `{ "error": "<code>", "message": "<what happened>", "hint": "<how to fix it>" }` (the `401` also carries the usual season fields).

| Status | `error` | Cause | Fix |
| --- | --- | --- | --- |
| 400 | `invalid_request` | The game id is not a valid id, or `scope`, `limit` or `season` is malformed. | Use the game's UUID, `scope` of `global`, `country` or `friends`, `limit` 1 to 100 and a season like `2026-W47`. |
| 404 | `game_not_found` | No live game has this id. A draft, a game in review or a mistyped id looks the same. | Use the id from `/developer/games/<id>` and read the board once the game is live. |
| 404 | `no_leaderboard` | The game is live but **Leaderboard enabled** is off. | Turn it on and save the rules on the Leaderboard tab. |
| 401 | `unauthenticated` | `scope=friends` without a signed-in session. | Use `global` or `country` from a server, or call from the player's browser with credentials. |

**Player ids in rankings.** In every ranking row (`entries`, `me` and `neighbours`), `userId` is an opaque id for that player in this game only: the same player always gets the same id in the same game, and a different id in every other game. It is not the player's account id (the `userId` in the [player token](https://docs.zokogames.com/sdk/user#tokens)), it cannot be turned back into one, and no other API accepts it, so use it only as a list key. To highlight the player's own row, use `isYou`: it is `true` on the signed-in caller's row and `false` on every other row, and always `false` for guests. Show `username` as the player's name. Never store the ranking `userId` as an account identifier or link accounts with it; use the `userId` from a verified token for that. `isYou` is part of the JSON response. The SDK has no leaderboard read call, so fetch the endpoint yourself; since SDK 1.5.0 its type declarations include `LeaderboardEntry`, a type only, which describes one row (`isYou` and this `userId` included).

## Design tips

- Submit once per run, at the end, not every frame.
- For time-based games use `ASC` with `MINUTES`.
- Show the player's own rank, not just the top ten.
- Do not make the leaderboard the only reason to play; the weekly reset is a feature for new players too.

## Next steps

- [Leaderboards step by step](https://docs.zokogames.com/guides/leaderboard-setup)
- [Achievements](https://docs.zokogames.com/sdk/achievements)

---

Source: https://docs.zokogames.com/sdk/analytics

# Analytics

**Purpose:** this page says what the portal measures for you, and documents the SDK calls for reporting a purchase (`trackOrder`) and for your own events (`track`).

Playtime, sessions, retention, ad impressions and conversion are measured by the portal automatically. You do not instrument them and there is no SDK call for them. The [gameplay events](https://docs.zokogames.com/sdk/game#gameplay-events) are what make those numbers accurate.

The analytics module has two methods. `trackOrder` reports a purchase:

```ts
trackOrder(provider: string, order: unknown): Promise<void>
```

`provider` is a non-empty string (up to 64 characters) naming the payment provider, and `order` is that provider's order object (any value that serialises to at most 16 KiB). Both are sent to the portal. The call resolves with nothing. An empty or non-string provider, or an oversized order, rejects with `invalidArgument`; more than 20 reports a minute from one game session rejects with `rateLimited`; the general `sdkNotInitialized` and `sdkDisabled` apply too (see [errors](https://docs.zokogames.com/sdk/introduction#errors)). The portal counts each accepted call as one anonymous order event for the game (no visitor id, and a daily cap per player and game); the order object itself is not stored, because provider orders carry personal data. In local mode the call is accepted and does nothing. Purchases made through `SDK.store` are already recorded by the portal, so do not call `trackOrder` for them.

The counted orders appear, per day, under **In-game orders** in your game's analytics in the developer console, and as the `orders` field of the [game stats API](https://docs.zokogames.com/guides/developer-api) (`/games/{id}/stats` and `/games/{id}/stats/daily`). They are self-reported by your game, so they are never ZokoGames revenue or part of a payout.

```js
async function onProviderPurchase(order) {
  try {
    await SDK.analytics.trackOrder("provider-name", order);
  } catch (e) {
    console.warn("trackOrder failed:", e.code);
  }
}
```

## At a glance

Every member of `SDK.analytics`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `trackOrder(provider: string, order: unknown): Promise<void>` | Nothing, when the portal accepted the report (also in kids mode, where nothing is counted). | `invalidArgument` (empty or non-string `provider`, a provider over 64 characters, an order that cannot be copied or is over 16 KiB), `rateLimited` (more than 20 reports a minute), `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.0.0 |
| `track(name: string, params?: Record<string, string \| number \| boolean>): void` | Nothing, always. It is fire-and-forget and never throws or rejects. | Nothing reaches the game: an invalid or over-limit call is dropped silently. | 1.7.0 |

The type `AnalyticsApi` is in the declaration file described in the SDK introduction. The module has no other member and no events.

## Custom events: `track`

```js
SDK.analytics.track("level_done", { level: 3, mode: "hard", won: true });
```

`track` records one event of your own. It returns nothing, so there is nothing to `await` or catch. Limits, checked by the SDK and again by the portal; a call that breaks any of them is dropped without an error:

- `name` matches `^[a-z][a-z0-9_]{0,39}$` (lower case, digits and underscores, starting with a letter, at most 40 characters).
- `params` is optional, has at most 10 entries, and each key matches the same pattern.
- A string value is at most 100 characters, a number must be finite (no `NaN`, no infinity), and a boolean is allowed. Nested objects and arrays are not.
- At most 60 calls a minute from one game session; the rest are dropped.

Custom events are counted only when the player has allowed analytics cookies, and never in kids mode or in a kids game. They are kept apart from the portal's own events (a separate `game_custom` kind), so a name can never collide with one. At present the portal counts that the event happened; the name and parameters stay in the browser and are not stored or shown in the developer console. In local mode the call is accepted and does nothing. Do not put personal data in an event.

**Common mistakes.**

| Mistake | Result | Fix |
| --- | --- | --- |
| `trackOrder` is called for a purchase made through `SDK.store` | The order is counted twice | Do not: the portal already records store purchases. |
| The whole provider response with card or personal data is passed as `order` | The portal does not store it, but a large object is refused | Pass only the order object, under 16 KiB, with no data you would not want in logs. |
| The call is made for every click or in a loop | `rateLimited` after 20 reports a minute | Report once per completed order. |
| The result is used as a revenue figure | The numbers are self-reported and never revenue | Use your payment provider's own records for money. |
| `await SDK.analytics.trackOrder(...)` blocks the purchase flow | A slow or offline portal delays the game by up to 10 seconds | Do not await it in the flow that delivers the item, and catch the error. |

## In local mode, as a guest, offline or ad-free

| Situation | Behaviour |
| --- | --- |
| Local mode | Argument check only: the SDK itself rejects only an empty or non-string `provider`. The call resolves and nothing is sent anywhere, so the 64-character provider limit, the 16 KiB order limit and the 20-a-minute limit are enforced by the portal only and cannot fail locally. |
| Guest | Same as a signed-in player. |
| Offline | Needs the portal like any call; it rejects with `timeout` if the portal does not answer within 10 seconds. |
| Ad blocker / ad-free | No effect. |

This call is only meaningful for games that have in-game purchases enabled, which is currently by invitation. See [in-game purchases](https://docs.zokogames.com/sdk/purchases).

## Your own analytics

You may add your own analytics tools, as long as they respect these limits:

- No third-party advertising or tracking SDKs that profile players.
- If you collect personal data beyond what the portal provides, show a clear privacy notice and link to your policy.
- Do not slow the first frame; load analytics scripts after `gameplayStart`.

## Next steps

- [In-game purchases](https://docs.zokogames.com/sdk/purchases)
- [Analytics and metrics reference](https://docs.zokogames.com/guides/analytics-metrics)

---

Source: https://docs.zokogames.com/sdk/purchases

# In-game purchases

**Purpose:** the store module (`SDK.store`) lets a signed-in player buy items from inside your game. A game is the whole product you uploaded; an item here is one product you sell inside it. You define products in the developer console, the portal shows its own checkout dialog, and the purchased items land in the player's inventory, where your game reads and consumes them.

> [!IMPORTANT]
> **Real money is not available yet** (status: in testing, no real money yet; see [feature status](https://docs.zokogames.com/business/faq#feature-status)). Real-money sales are switched off on the portal for now (the payment provider is integrated, but the portal team has not switched real money on), so every purchase today is a **test purchase** in sandbox mode: no money moves and players see a "Test purchase" badge. Build and test your whole flow now; the code does not change when real payments are switched on. See [provider not connected](#provider-not-connected).

## At a glance

Every member of `SDK.store`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `readonly isAvailable: boolean` | `true` when this game can sell items here. Synchronous. | Throws `sdkNotInitialized` or `sdkDisabled`. | 1.1.0 |
| `getCatalogItems(options?: StorePageOptions): Promise<StoreItem[]>` | One page of active products. | `invalidArgument`, `requestInProgress`, `catalogFetchFailed`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `getPlayerInventory(options?: StorePageOptions): Promise<InventoryItem[]>` | One page of what the signed-in player owns. | `invalidArgument`, `requestInProgress`, `userNotAuthenticated`, `inventoryFetchFailed`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `buyItem(itemId: string): Promise<{ itemId: string }>` | `{ itemId }` once the order is paid. No timeout. | `invalidArgument`, `purchaseInProgress`, `userNotAuthenticated`, `purchaseInitFailed`, `purchaseCancelled`, `unexpectedError`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `consumeItem(sku: string, quantity: number): Promise<void>` | Nothing, when the units were removed. | `invalidArgument`, `requestInProgress`, `userNotAuthenticated`, `itemNotInInventory`, `itemNotConsumable`, `insufficientItemQuantity`, `consumeItemFailed`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `setSandbox(sandbox: boolean): void` | Nothing. | Throws `invalidArgument` (not a boolean), `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |
| `getPurchaseToken(): Promise<string>` | A signed RS256 token listing the player's items and orders. Not cached. | `userNotAuthenticated`, `rateLimited`, `unexpectedError`, `timeout`, `sdkNotInitialized`, `sdkDisabled`. | 1.1.0 |

`StorePageOptions` is `{ limit?: number; offset?: number }`. The types `StoreApi`, `StoreItem` and `InventoryItem` are in the declaration file described in the SDK introduction.

## How it works

1. You enable the store and add products in the console.
2. Your game checks `SDK.store.isAvailable`, lists the catalogue with `getCatalogItems()` and starts a purchase with `buyItem(sku)`.
3. The portal opens a checkout dialog over the game, charges the payment provider and fulfils the order.
4. Your game reads `getPlayerInventory()`, grants what the player bought and calls `consumeItem()` for consumables it has used up.
5. For anything that matters (progress on your own backend, items worth real value) your server verifies a signed [purchase token](#verifying-a-purchase-on-your-server) instead of trusting the browser.

Purchases need a signed-in player, because an order must belong to an account. Guests can browse the catalogue but get `userNotAuthenticated` for everything else. See the [user module](https://docs.zokogames.com/sdk/user#sign-in-prompt) for `showAuthPrompt`.

## Lifecycle

```text
init() resolves
  -> SDK.store.isAvailable?  no -> hide every purchase button
  -> (optional) setSandbox(true) before the first store call
  -> getCatalogItems()            shop list, works for guests
  -> getPlayerInventory()         signed-in players only
  -> player presses buy -> buyItem(sku)     checkout dialog; resolves when paid
  -> getPlayerInventory()         refresh, grant the effect
  -> consumeItem(sku, qty)        consumables only, after the effect is granted
  -> (your server) getPurchaseToken() -> verify -> grant once per order id
```

## Enable the store and sandbox mode

Open your game in the developer console and go to the **Store** page. Owners and admins can change it; other roles see it read only.

| Setting | Meaning |
| --- | --- |
| **Store enabled** | Master switch for your game. When on **and** at least one product is active, `SDK.store.isAvailable` is `true`. |
| **Payment mode** | **Sandbox (test purchases)** settles orders instantly without money. **Real money** is selectable only once the portal switches real-money sales on, which is not the case yet; until then the console shows "Payment provider not connected" and saving it fails with "Real-money mode needs a connected payment provider" (code `providerNotConnected`). |

The store is off by default for a new game, and the portal can also switch purchases off for every game at once; the page then shows "Disabled by the portal" and keeps your settings.

A game marked **Made for children** never sells: the Store page says so instead of "Selling to players", players are refused and `SDK.store.isAvailable` is `false`. Your products are kept if you untick the box later.

Players can buy only in a game that is live. Members of your studio can test earlier, in preview, using the same store.

> [!NOTE]
> `isAvailable` is read once when the game starts. If you enable the store or add your first product while the game is open, reload the game.

The **In-game purchases** badge on your game's cards and game page does not come from this page or from SDK calls. It follows **Contains in-game purchases** under **Video and multiplayer extras** on the **Technical** step, which you tick yourself whenever players can spend real money in the game; when the game has store products and the box is not ticked, the console suggests ticking it. A game made for children never shows the badge, and the box cannot be ticked for it. On a card the badge appears only when the card shows no other badge.

## Create products

On the **Store** page choose **New product**.

| Field | Rules |
| --- | --- |
| **Sku** | 1 to 64 characters: lowercase letters, digits, `.`, `-`, `_`, starting with a letter or digit. This is the id your game uses in `buyItem` and `consumeItem`; pass it exactly as saved, in lowercase (the console lowercases capitals you type, your game's code does not). Unique per game. After saving, the product's row in the table has a copy button that puts `await SDK.store.buyItem("your-sku");` on your clipboard. |
| **Name** | English name required (80 characters). Add translations with a locale code such as `de` or `pt-BR`. Players see the closest match to their language, then English. |
| **Description** | Optional, 500 characters per language. |
| **Type** | **Consumable** or **Durable**, see [below](#consumables-and-durables). |
| **Price and currency** | A price above zero, entered as a normal amount such as `1.99`. Currencies: USD, EUR, GBP, CAD, AUD, BRL, MXN, PLN, SEK, NOK, DKK, CHF, TRY, INR, JPY and KRW. JPY and KRW have no decimals. |
| **Units per purchase** | 1 to 100,000. How many units one purchase adds to the inventory. A durable item is always 1. |
| **Image URL** | Optional `https` image shown in the checkout and returned as `imageUrl`. |
| **Order** | 0 to 9,999. Items are listed by this number, then by sku. |
| **Active** | Inactive products are hidden from the catalogue and cannot be bought. Players keep what they already own. |

A game can list up to 200 products; the Products table shows how many you use and **New product** is disabled at the limit. Subscriptions do not exist. Once a product has any order, its sku cannot change and it cannot be deleted: deactivate it instead.

**Editing and deleting products.**

Only the studio's owners and admins can create, edit, activate, deactivate or delete products; other roles see the table read only. Every change is written to the studio's audit trail. There is no bulk import or export of products: add them one at a time in the console (the **Orders** table has its own CSV export).

- **Checks.** The form validates when you press **Save product** and puts the cursor on the first field to fix; the server checks again. Capitals in a sku are lowercased when saving. For JPY, KRW and portal coins the price is a whole number.
- **The sku is the product's id.** Your game's `buyItem` and `consumeItem` calls and every order and inventory row use it. It can be changed only while the product has no orders. After the first order, to retire a sku you deactivate it and add a new product.
- **Other fields can be edited at any time.** Names, description, image, order and active apply at once to the catalogue. Orders already placed keep the amount they were charged. Players keep every unit they own.
- **Changing the type of a product that has been sold changes how the units already owned behave** (a durable cannot be consumed with `consumeItem`; a consumable can be bought again). Add a new product instead of changing the type of one that has sold.
- **Deactivate or delete.** Deactivating hides the product from `getCatalogItems()` and a `buyItem` for it fails; owned units stay in inventories and `consumeItem` still works on them. Deleting is possible only for a product with no orders, and cannot be undone. A deleted sku behaves like one that never existed (`itemNotInInventory`, or a failed `buyItem`).

## Consumables and durables

| | Consumable | Durable |
| --- | --- | --- |
| Examples | Coins, gems, extra lives. | Remove ads, a character, a level pack. |
| Can be bought again | Yes, quantities add up. | No. A second purchase fails with a message that the player already owns it. |
| `consumeItem` | Allowed. | Fails with `itemNotConsumable`. |
| Inventory `quantity` | Total units owned. | `1`. |

## SDK reference

The module is `SDK.store`. Each call returns a promise and rejects with an error whose `code` is one of the [error codes](#error-codes).

```ts
readonly isAvailable: boolean
getCatalogItems(options?: { limit?: number; offset?: number }): Promise<StoreItem[]>
getPlayerInventory(options?: { limit?: number; offset?: number }): Promise<InventoryItem[]>
buyItem(itemId: string): Promise<{ itemId: string }>
consumeItem(sku: string, quantity: number): Promise<void>
setSandbox(sandbox: boolean): void

interface StoreItem {
  sku: string;
  name: string;
  description: string;
  imageUrl: string;            // "" when the product has no image
  consumable: boolean;
  price: { amount: number; currency: string } | null;   // amount in major units, e.g. 1.99
}

interface InventoryItem {
  sku: string;
  name: string;
  description: string;
  imageUrl: string;
  quantity: number | null;
}
```

`price` is `null` when the item has no price for this player, so check it before you read `amount`. `quantity` is `null` when the provider does not count the item; the portal's own store always returns a number.

Paging: `limit` is a whole number from 1 to 50 (default 50) and `offset` a whole number of 0 or more (default 0). Anything else (including `options` that is not an object) rejects with `invalidArgument`. Names and descriptions come back in the player's language when you provided a translation.

### isAvailable

`true` when the store is enabled for this game, has at least one active product and the page can show the checkout. It does not say whether the player is signed in. Hide every purchase button when it is `false`, and always check it before calling the other methods.

### getCatalogItems

Lists active products, ordered as set in the console. It works for guests. Only one catalogue request may run at a time; a second one rejects with `requestInProgress`.

<!-- docs-sample: uses shop -->
```js
if (SDK.store.isAvailable) {
  const items = await SDK.store.getCatalogItems();
  for (const i of items) {
    const price = i.price ? `${i.price.amount} ${i.price.currency}` : "";
    shop.add(i.sku, i.name, price, i.consumable);
  }
}
```

### getPlayerInventory

Lists what the signed-in player owns, totalled per sku (empty stacks are left out). Guests get `userNotAuthenticated`. One request at a time (`requestInProgress`). Read it at start and after every purchase.

### buyItem

Starts a purchase for one sku (a non-empty string, `invalidArgument` otherwise) and opens the [checkout dialog](#the-checkout-dialog). It resolves with `{ itemId }` (the sku you passed) once the order is paid and the items are in the inventory, and rejects otherwise. There is no timeout while the player decides. Only one purchase can run at a time (`purchaseInProgress`).

<!-- docs-sample: uses refreshInventory, showMessage -->
```js
async function buy(sku) {
  try {
    await SDK.store.buyItem(sku);
    await refreshInventory();
  } catch (e) {
    if (e.code === "purchaseCancelled") return;          // the player closed the dialog
    if (e.code === "userNotAuthenticated") return SDK.user.showAuthPrompt().catch(() => {});
    showMessage("The purchase did not go through.");
  }
}
```

### consumeItem

Removes `quantity` units (a whole number of 1 or more; `invalidArgument` for a non-integer, zero or a negative; the `sku` must be a non-empty string) of a consumable from the inventory, oldest purchase first. It is all or nothing: if the player owns fewer units than asked, nothing is removed.

<!-- docs-sample: uses wallet -->
```js
await SDK.store.consumeItem("coins-100", 1);
wallet.add(100);
```

Call it **after** you have granted the effect, or grant and consume in a way you can recover from if the page closes between the two. Consuming makes the units unavailable to every later `getPlayerInventory` and token.

### setSandbox

```ts
setSandbox(sandbox: boolean): void
```

Routes later store calls to the sandbox ledger (test payments) when `true`. It is synchronous and throws `invalidArgument` unless the argument is a boolean. The default is `false`, meaning real money. While the store's payment mode in the console is **Sandbox**, which is the only possible mode today, every call is sandbox whatever you pass. Once real money exists, only members of your studio may use `setSandbox(true)` on a live store; anyone else gets an error, so players cannot take items for free. Call it once before your first store call, for example when your own debug flag is on.

### The purchase token

```ts
SDK.store.getPurchaseToken(): Promise<string>
```

Returns a signed token that lists the player's items, for your server to verify. `SDK.user.getXsollaUserToken()` still works as a deprecated alias that returns the same token, so existing code keeps running; use `getPurchaseToken()` in new code. Use `userNotAuthenticated` to detect guests. The token follows the `sandbox` value of the most recent catalogue, inventory, buy or consume call (`setSandbox` itself sends nothing until one of those runs, so call `setSandbox` before the first store call and not just before the token). It is not cached: call it when you need a fresh one. See the next section.

## Verifying a purchase on your server

The browser can be tampered with. If a purchase unlocks anything on your own backend, send it the purchase token and verify it there.

The token is an RS256 JWT, valid for one hour, signed with the same key set as the [player token](https://docs.zokogames.com/sdk/user#tokens). Fetch the keys from:

```text
https://www.zokogames.com/.well-known/jwks.json
```

Check the signature and expiry, then check these:

| Claim | Value |
| --- | --- |
| `iss` | Always `zokogames:store`. A player token has a different issuer, so one can never pass as the other. **Reject anything else.** |
| `aud` | Your game's id. Reject a token for another game. |
| `typ` | `purchase`. |
| `sub` and `userId` | The player's stable id, the same one as in the [player token](https://docs.zokogames.com/sdk/user#tokens). |
| `gameId` | Your game's id, again. |
| `sandbox` | `true` when the token reflects test purchases. **Never grant real value for `true`.** |
| `items` | The inventory: `[{ "sku": "coins-100", "quantity": 3 }]`. |
| `orders` | The player's 20 most recent settled orders, newest first: `{ id, sku, quantity, status, amountMinor, currency, fulfilledAt }`. `status` is `fulfilled` or `consumed`; `amountMinor` is in the currency's smallest unit; `fulfilledAt` is Unix seconds. |

```js
const token = await SDK.store.getPurchaseToken();
await fetch("https://api.example.com/purchases/sync", {
  method: "POST",
  headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
});
```

:::tabs
== Node.js
<!-- docs-sample: fragment -->
```js
import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));
const GAME_ID = process.env.ZOKO_GAME_ID;

export async function verifyPurchaseToken(token) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: "zokogames:store",
    audience: GAME_ID,
    clockTolerance: 5,
  });
  if (payload.typ !== "purchase") throw new Error("not a purchase token");
  return payload; // userId, sandbox, items, orders
}
```
== Python
```python
import os
import jwt  # PyJWT >= 2.8, with the "crypto" extra

jwks_client = jwt.PyJWKClient("https://www.zokogames.com/.well-known/jwks.json", cache_keys=True)
GAME_ID = os.environ["ZOKO_GAME_ID"]

def verify_purchase_token(token: str) -> dict:
    signing_key = jwks_client.get_signing_key_from_jwt(token)
    claims = jwt.decode(
        token,
        signing_key.key,
        algorithms=["RS256"],
        issuer="zokogames:store",
        audience=GAME_ID,
        options={"require": ["exp", "iat", "iss", "aud"]},
        leeway=5,
    )
    if claims.get("typ") != "purchase":
        raise ValueError("not a purchase token")
    return claims
```
== C#
```csharp
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

public sealed class ZokoPurchaseVerifier
{
    private static readonly HttpClient Http = new();
    private JsonWebKeySet? _keys;
    private DateTime _fetched = DateTime.MinValue;

    public async Task<JwtSecurityToken> VerifyAsync(string token, string gameId)
    {
        if (_keys is null || DateTime.UtcNow - _fetched > TimeSpan.FromHours(1))
        {
            var json = await Http.GetStringAsync("https://www.zokogames.com/.well-known/jwks.json");
            _keys = new JsonWebKeySet(json);
            _fetched = DateTime.UtcNow;
        }

        var parameters = new TokenValidationParameters
        {
            IssuerSigningKeys = _keys.GetSigningKeys(),
            ValidateIssuer = true,
            ValidIssuer = "zokogames:store",
            ValidateAudience = true,
            ValidAudience = gameId,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(5),
        };

        new JwtSecurityTokenHandler().ValidateToken(token, parameters, out var validated);
        var jwt = (JwtSecurityToken)validated;
        if (jwt.Claims.FirstOrDefault(c => c.Type == "typ")?.Value != "purchase")
            throw new SecurityTokenException("not a purchase token");
        return jwt;
    }
}
```
== Go
```go
package zoko

import (
	"errors"
	"os"
	"time"

	"github.com/MicahParks/keyfunc/v3"
	"github.com/golang-jwt/jwt/v5"
)

var jwks, _ = keyfunc.NewDefault([]string{"https://www.zokogames.com/.well-known/jwks.json"})

func VerifyPurchaseToken(raw string) (jwt.MapClaims, error) {
	claims := jwt.MapClaims{}
	_, err := jwt.ParseWithClaims(raw, claims, jwks.Keyfunc,
		jwt.WithValidMethods([]string{"RS256"}),
		jwt.WithExpirationRequired(),
		jwt.WithIssuer("zokogames:store"),
		jwt.WithAudience(os.Getenv("ZOKO_GAME_ID")),
		jwt.WithLeeway(5*time.Second),
	)
	if err != nil {
		return nil, err
	}
	if claims["typ"] != "purchase" {
		return nil, errors.New("not a purchase token")
	}
	return claims, nil
}
```
:::

### Granting exactly once

Treat the order `id` in `orders` as your idempotency key. Keep a table of order ids you have already granted, and grant an order only when its id is new. Then the same token (or an overlapping one) can be sent as often as you like, after a crash, a retry or a second device, and nothing is granted twice. Portal side, a purchase is just as safe: a retried payment for the same order never charges or grants twice, and the SDK's checkout retries use a fresh order only after the previous one failed.

Use `items` for "what does the player own right now" (durable unlocks, current stock) and `orders` for "what happened" (granting a delivery once). Only the 20 newest settled orders are listed, so sync often enough that an order is seen before 20 newer ones push it out.

> [!WARNING]
> There are no fulfilment webhooks for purchases. Fulfilment is pull-based: your server learns about a purchase from the token the player's game sends it.

## The checkout dialog

`buyItem` opens the portal's own dialog on top of the game, so you never handle payment details.

1. **Confirm purchase** shows the item, its price and **Buy for {price}**, with **Cancel**. In sandbox it carries a **Test purchase** badge and the note that no money is charged, plus a **Simulate a declined payment** link for rehearsing a failure.
2. **Processing** while the order is paid and fulfilled.
3. **Purchase complete** says the item was added to the player's items. The promise resolves at this point; the player dismisses the dialog with **Continue**, so refresh your UI immediately and expect the dialog to still be on screen for a moment.
4. **Purchase failed** says nothing was charged and offers **Try again** (creates a new order) and **Close**.

Escape, the backdrop, **Cancel** and **Close** reject `buyItem` with `purchaseCancelled`. The dialog needs the portal page around your game: when a game runs somewhere without it, `buyItem` rejects with `purchaseInitFailed` ("Checkout is not available on this page") and `isAvailable` is `false`.

## Refunds in sandbox

In the console, **Store > Orders** lists every order with its status (`created`, `paid`, `fulfilled`, `consumed`, `refunded`, `failed`), mode, player, amount and date. You can filter by status, mode, sku and dates, and export CSV. Choose **Refund** on a **test** order to mark it refunded and remove whatever is left of its items from the player's inventory. Units the player already consumed are not restored. Refunded orders also drop out of the token's `orders` list, so they stop counting on your server the next time you sync. Real-money orders cannot be refunded from the console.

## Testing locally

Open your game on `localhost` (or with `useLocalSdk=true`) and the SDK runs in [local mode](https://docs.zokogames.com/getting-started/local-testing). The store is always available there and is a mock held in memory, so nothing you do is saved between page loads:

- The catalogue is fixed: `local-coins-100` (consumable, 0.99 USD), `local-gems-50` (consumable, 2.99 USD) and `local-no-ads` (durable, 4.99 USD). Your own skus do not exist in local mode.
- The inventory starts with 3 `local-coins-100` and 1 `local-no-ads`.
- `buyItem` succeeds at once with a toast, no dialog. Buying an owned durable fails with `purchaseInitFailed`.
- `consumeItem` enforces the same rules, with `itemNotInInventory`, `itemNotConsumable` and `insufficientItemQuantity`.
- The purchase token is a fake string, not a JWT. Your verifier will correctly reject it, so for local backend work add a test-only bypass that cannot be enabled in production.

**To test a purchase without money, with your real skus and the real dialog**, use the game's Preview in the console. The steps:

1. On the **Store** page, switch **Store enabled** on and keep **Payment mode** on **Sandbox (test purchases)**.
2. Create a product and leave **Active** ticked. The page's top line changes to "On, in sandbox mode" when this is right.
3. Open the game from the **Open this game in Preview** link on the Store page (the game's **Preview** tab, the same tool as the [Preview tool](https://www.zokogames.com/preview)), signed in with a studio account. Reload the game after changing the store settings, because `isAvailable` is read once at start.
4. Call `SDK.store.buyItem("your-sku")`. The checkout dialog carries the **Test purchase** badge; use **Simulate a declined payment** to rehearse a failure.
5. Open **Store > Orders**. The test order shows **Sandbox** next to its status, and **Refund** removes what is left of its items. Your own test orders never count as sales.

## Provider not connected

"Payment provider not connected" is shown in the console while real-money sales are switched off on the portal, which is the case today: the payment provider is integrated, but **real money cannot be charged** until the portal team switches it on. Until then:

- the payment mode is locked to sandbox;
- every order, whoever places it, is a test order shown with the "Test purchase" badge;
- test items are not worth anything and tokens carry `sandbox: true`.

We will announce the change in the [changelog](https://docs.zokogames.com/business/changelog). Real-money sales will also need an agreement with us; see [revenue share](https://docs.zokogames.com/business/revenue-share). Do not add your own payment links, donation buttons or external checkouts to a game ([quality guidelines](https://docs.zokogames.com/requirements/quality)).

**Common mistakes.** The ones QA and the Preview tool report most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| Purchase buttons are shown without checking `SDK.store.isAvailable` | Every call fails (`catalogFetchFailed`, `purchaseInitFailed`) | Hide the shop when it is `false`, and in kids mode and the Android app it always is. |
| `getPlayerInventory`, `buyItem` or `consumeItem` is called for a guest | `userNotAuthenticated` | Offer `SDK.user.showAuthPrompt()` when a guest presses buy. |
| The reward is granted from the result of `buyItem` only | Lost on a closed page, forged by a modified client | Refresh `getPlayerInventory()` and, for anything that matters, verify the purchase token on your server. |
| `purchaseCancelled` is shown as a failure | An error message after the player pressed Cancel | Return quietly on `purchaseCancelled`. |
| A second `buyItem` is started while the dialog is open | `purchaseInProgress` | Disable buy buttons until the promise settles. |
| `consumeItem` is called before the effect is granted | A lost item if the page closes in between | Grant first, or grant and consume in a way you can recover from. |
| A durable item is consumed or bought twice | `itemNotConsumable`, or a "you already own it" failure | Check `consumable` in the catalogue and `quantity` in the inventory. |
| The `sandbox` token is trusted on the server | Free items for test purchases | Reject a token whose `sandbox` claim is `true` for real value. |
| `price` is read without a check | A `TypeError` when it is `null` | Test `item.price` before reading `amount`. |
| Two catalogue or inventory requests run at once | `requestInProgress` | Wait for the first to finish. |
| Local-mode skus are shipped | `itemNotInInventory`, `purchaseInitFailed` on the portal | Local mode has its own fixed catalogue; use your real skus in the Preview tool. |

## Errors per call

| Call | Codes it can reject with (besides the [general ones](https://docs.zokogames.com/sdk/introduction#errors)) |
| --- | --- |
| `getCatalogItems` | `invalidArgument`, `requestInProgress`, `catalogFetchFailed`, `unexpectedError` |
| `getPlayerInventory` | `invalidArgument`, `requestInProgress`, `userNotAuthenticated`, `inventoryFetchFailed`, `unexpectedError` |
| `buyItem` | `invalidArgument`, `purchaseInProgress`, `userNotAuthenticated`, `purchaseInitFailed`, `purchaseCancelled`, `unexpectedError` |
| `consumeItem` | `invalidArgument`, `requestInProgress`, `userNotAuthenticated`, `itemNotInInventory`, `itemNotConsumable`, `insufficientItemQuantity`, `consumeItemFailed`, `unexpectedError` |
| `getPurchaseToken` | `userNotAuthenticated`, `rateLimited`, `unexpectedError` |
| `setSandbox` (throws) | `invalidArgument` |

## When the player is a guest, offline or ad-free

| Situation | Behaviour |
| --- | --- |
| Guest | `getCatalogItems` works. Inventory, `buyItem`, `consumeItem` and `getPurchaseToken` fail with `userNotAuthenticated`. Offer `SDK.user.showAuthPrompt()` when the guest presses buy. |
| Offline | The store needs the portal; calls fail with the failure code of that call. Hide the shop while `SDK.game.isOffline` is `true`. |
| Ad blocker or ad-free member | No effect on purchases. |
| Basic launch | Players can buy in any live game, basic launch included, when the store is on and a product is active (sandbox mode only today). |
| Local mode | A fixed mock store; see [testing locally](#testing-locally). |
| Inside the Android app | Purchases are off. `SDK.store.isAvailable` is `false`, as for a game without a store: `getCatalogItems` rejects with `catalogFetchFailed`; for a signed-in player `getPlayerInventory` rejects with `inventoryFetchFailed`, `buyItem` with `purchaseInitFailed`, `consumeItem` with `consumeItemFailed` and `getPurchaseToken` with `unexpectedError`; guests get `userNotAuthenticated`. The portal also refuses real-money payments from the app with `purchaseInitFailed`. Your game is not told why: check `isAvailable` and hide every shop button. |

**Kids mode.** `SDK.store.isAvailable` is `false`, `getCatalogItems` rejects with `catalogFetchFailed`, and `getPlayerInventory`, `buyItem`, `consumeItem` and `getPurchaseToken` reject with `userNotAuthenticated`. Check `isAvailable` instead of the codes; see [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode).

## Error codes

| Code | When |
| --- | --- |
| `userNotAuthenticated` | The player is a guest (inventory, buy, consume, token). |
| `invalidArgument` | A wrong argument: empty sku, `limit` outside 1 to 50, a non-integer `quantity` and so on. |
| `catalogFetchFailed` | The catalogue could not be loaded, or the store is not enabled. |
| `inventoryFetchFailed` | The inventory could not be loaded. |
| `purchaseInitFailed` | The order could not be created or paid: unknown or inactive sku, durable already owned, payment declined, no checkout on this page, store off. The message for an unknown sku and for an inactive one is the same, `No item with sku "...".`, so when you see it check that the sku is typed exactly as in the console (lowercase) and that the product is **Active**. |
| `purchaseInProgress` | Another `buyItem` is still running. |
| `purchaseCancelled` | The player closed the dialog, or the order was cancelled. |
| `consumeItemFailed` | The consume call failed or the store is off. |
| `itemNotConsumable` | The sku is a durable. |
| `itemNotInInventory` | The player owns none of that sku, or the sku does not exist. |
| `insufficientItemQuantity` | The player owns fewer units than `quantity`. |
| `requestInProgress` | The same kind of request is already running. |
| `unexpectedError` | Anything else, including a failed token request. |
| `other` | Something the SDK could not classify, for example an answer from the portal that was not an error object. Treat it like `unexpectedError`. |

The general codes `sdkNotInitialized`, `sdkDisabled` and `timeout` apply too. Calls are rate limited: a call over the game page's [call limits](https://docs.zokogames.com/sdk/introduction#call-limits) fails with `requestInProgress`, and a call the store server limits per player fails with the failure code of that call.

## FAQ

**Can I sell real items today?** No. Only sandbox purchases work, see [provider not connected](#provider-not-connected).

**Why is `isAvailable` false?** The store is off in the console, no product is active, the portal switched purchases off, or the game runs without portal checkout (for example a local page that does not use local mode). Inside the portal's Android app it is always `false`.

**Do guests see the shop?** They can read the catalogue. Ask them to sign in with `showAuthPrompt` when they press buy.

**Do sandbox and real purchases share an inventory?** No. They are separate ledgers; test items never become real ones.

**What happens if the player closes the tab mid-purchase?** An unpaid order is abandoned and nothing is charged. If it was paid, the items are in the inventory at the next start.

**Can I price in several currencies?** One price and currency per product.

**Can I give items for free?** Not through the store. Grant free rewards in your own game state.

**Are there fulfilment webhooks?** No. Verify the [purchase token](#verifying-a-purchase-on-your-server). The studio [webhooks](https://docs.zokogames.com/guides/webhooks) cover builds and reviews, not purchases.

## Next steps

- [Analytics](https://docs.zokogames.com/sdk/analytics)
- [Webhooks](https://docs.zokogames.com/guides/webhooks)

---

Source: https://docs.zokogames.com/sdk/versioning

# Versioning and migration notes

**Purpose:** this page explains how SDK versions are numbered, what never changes inside the `v1` line, and what to check when you move between releases. Here "version" always means a version of the SDK; the files you upload for a game are called a build.

## The script URL is the contract

```text
https://sdk.zokogames.com/zokogames-sdk-v1.js
```

That URL is the **latest** alias of the 1.x line: it is cached for about an hour at most and always points at the newest 1.x release. To lock a build to one release, use the immutable, versioned URL instead:

```text
https://sdk.zokogames.com/1.7.0/zokogames-sdk-v1.js
```

A versioned file never changes once published. Pinning means you do not receive fixes until you change the number, so most games should use the latest alias.

The `v1` in the file name is the major version. Inside a major version the SDK stays **backwards compatible**: methods, argument shapes, return values and error codes you already use keep working. The current release is **1.7.0** and the exact number is exported as `SDK_VERSION` by the module build and set as `window.ZokoGames.SDK_VERSION` by the script tag (the SDK also sends the number to the portal during the handshake).

What may change inside `v1` without notice:

- New methods, new optional arguments and new fields on returned objects.
- New error codes. Always keep a default branch in `switch (e.code)` that takes the safe path.
- Calls the portal accepts but barely uses today (`reportGameCompletedPercentage` and `setGameContext` have only small effects, see [game](https://docs.zokogames.com/sdk/game#completion)) start doing more.
- Bug fixes and stricter validation of arguments that were already documented as invalid.

What requires a new major version (`v2`) and a long overlap:

- Removing or renaming a method, argument or documented error code.
- Changing the meaning of an existing return value.
- Changing the wire protocol in a way old SDK builds cannot answer.

The portal checks the protocol version during `init()`. A game built against `v1` keeps working while `v1` is served.

## Do not self-host an old copy

Load the script from the URL above rather than copying it into your build, so fixes reach your players. If you must bundle a copy (an offline build), keep the `ZokoGames` global name so the upload validator still recognises the SDK, and update the copy whenever the [changelog](https://docs.zokogames.com/business/changelog) lists a release.

## Migration notes

The newest release is listed first, and the docs changelog (Business, then Changelog) lists every release.

### 1.7.0

Additive: game code written for 1.6.4 needs no change, and no name, global, error code or return value changes. New: `SDK.analytics.track(name, params?)` (custom events, fire-and-forget), `SDK.data.mirrorIndexedDB(options?)` (cloud saves for Unity, Godot and GameMaker, which save into IndexedDB; await it before the engine starts), `SDK.game.room.addLeftListener` / `removeLeftListener` (the portal ended your room membership: `left`, `kicked`, `closed` or `disconnected`) and an optional second argument `{ portalOnly: true }` on `showInviteButton` / `hideInviteButton` (the portal's invite button without a room). A portal older than 1.7.0 drops the new calls; check for them before use if you pin an older script. The script grew from about 57.7 KB to about 71 KB minified.

### 1.6.4

Additive: game code written for 1.6.3 needs no change, and no name, global, error code or return value changes. `SDK.user.submitScore` accepts an optional `delayed: { encryptedScore, earnedAt }`: a second copy of the score, sealed at the end of the run with `earnedAt = Date.now()`, that the portal keeps on the device for a signed-in player (boards with an encryption key only, never in kids mode, never for guests) and sends when they are back online, within 72 hours. It counts for the all-time board only, not the weekly board. There is no new message kind; a malformed `delayed` is dropped and the normal score still goes through, and a portal older than 1.6.4 ignores it. Neither the SDK nor local mode checks `earnedAt` or the token. Local mode changed in two ways you will see when you test: it refuses a midgame ad with `adCooldown` until the game has called `gameplayStart()` (or 30 seconds of visible page time have passed; rewarded ads are not gated), and it shows "Score saved offline" for an offline signed-in `submitScore` with `delayed`. Three small additions: every `add<Thing>Listener` method now returns a function that removes that listener, `window.ZokoGames.SDK_VERSION` holds the version string, and `SdkError.code` autocompletes the known codes in editors (any other string stays valid). The engine plugins need no update and do not pass `delayed`. Pinned: `https://sdk.zokogames.com/1.7.0/zokogames-sdk-v1.js`.

### 1.6.3

Messages only: game code written for 1.6.2 needs no change, and no name, global, type, error code, return value or timing changes. The `sdkDisabled` message says why the SDK is disabled and links the local testing page; the one-time "Disabled" console line adds a hint to use `?useLocalSdk=true` when local mode is the way out. `invalidArgument` messages say what was received, and the banner `invalidSize` message lists the allowed sizes. New one-time console warnings that never throw: callbacks passed to `ad.requestAd` that can never run, a non-object passed to `user.getUserToken`, and a misspelled local scenario switch value. Local mode logs each `user.submitScore` call. If your code compares the text of an error `message`, compare the `code` instead: codes are stable, messages are not. One fix: `ad.requestAd` now resolves when the callbacks object cannot be read (for example a revoked `Proxy`); before, such a request stayed pending for ever. Pinned: `https://sdk.zokogames.com/1.6.3/zokogames-sdk-v1.js`.

### 1.6.2

Additive: game code written for 1.6.1 needs no change, and no name, global or message format changes. `SDK.game.gameId` is a new read-only string with the portal's id for your game (`"local-game"` in local mode); like the other game properties it throws `sdkNotInitialized` before `init()` resolves and `sdkDisabled` when the environment is `disabled`. The SDK writes one-time console notices (once per page each): an info line saying why the environment is `disabled`, an info line the first time a member is used before `init()` resolved, and a warning the first time a cloud save fails to sync (the save is kept locally and retried). A parent page on a host with a reserved label at any depth, such as `x.g-<slug>.zokogames.com`, no longer counts as the portal. Two fixes: an ad request that already ended (timeout, error or finished) ignores later host events, so a late `adStarted` no longer keeps banners refused with `videoAdPlaying`; and `showAuthPrompt()` asks the portal who is signed in (one extra `user.getUser` call) instead of trusting the cached player, so it opens the sign-in dialog after a sign-out in the portal instead of rejecting with `userAlreadySignedIn`. The engine plugins need no update and do not wrap `gameId` yet. Pinned: `https://sdk.zokogames.com/1.6.2/zokogames-sdk-v1.js`.

### 1.6.1

Security hardening: game code written for 1.6.0 needs no change, and no name, global or message format changes. The SDK accepts the handshake answer only from a ZokoGames page (`https` on `zokogames.com` or a subdomain, except the game hosts `g-<slug>` and the preview runner), from a local host when the game itself also runs on a local host, or from the game's own origin. Any other answer counts as no answer (`local` when local mode applies, otherwise `disabled`), so a site that frames your game can no longer pose as the portal. One trailing dot on a host name is ignored. `SDK.ad.requestAd(type, null)` no longer throws, and the descriptions of the banner error codes `missingId` and `notCreated`, which had been swapped, are correct now. The engine plugins need no update. Pinned: `https://sdk.zokogames.com/1.6.1/zokogames-sdk-v1.js`.

### 1.6.0

Additive: game code written for 1.5 needs no change. The room host can call `SDK.game.updateRoom({ isPublic: true })` so friends can join the room from their friends list; rooms are private by default, a guest's value is ignored, and in kids mode rooms always stay private. A value that is not a boolean rejects with `invalidArgument`; an older portal ignores the field. The engine wrappers move to 1.6.0 as well (Construct 3 action **Set room public**, Unity `ZokoRoomUpdate.IsPublic`). See [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms). Pinned: `https://sdk.zokogames.com/1.6.0/zokogames-sdk-v1.js`.

### 1.5.1

Additive, and only for testing: nothing changes outside local mode, and game code written for 1.5.0 needs no change. Local mode now fires `settingsChange`, `joinRoom` and `offlineChange` when the page dispatches the `zokogames:local-settings`, `zokogames:local-join-room` and `zokogames:local-offline` window events, so you can test those listeners without the portal (see [simulating portal events](https://docs.zokogames.com/getting-started/local-testing#simulating-portal-events)). The engine wrappers stay at 1.5.0. Pinned: `https://sdk.zokogames.com/1.5.1/zokogames-sdk-v1.js`.

### 1.5.0

Additive: nothing breaks and game code written for 1.4 needs no change. `SDK.game.settings.kidsMode` (an optional boolean) is now typed and is also in the settings listener's payload; where it is `undefined` (an older portal), fall back to `disableChat`. Local mode reads `?kidsMode=true`, and the [Preview tool](https://www.zokogames.com/preview) can send a kids-mode settings change. The type declarations add `LeaderboardEntry`, one row of the [leaderboard](https://docs.zokogames.com/sdk/leaderboards) JSON endpoints with `isYou` and the opaque per-game `userId`: a type only, the SDK has no leaderboard read call. The engine wrappers 1.5.0 expose `kidsMode` as well (see each [engine page](https://docs.zokogames.com/engines/overview)). See [kids mode](https://docs.zokogames.com/sdk/game#kids-mode). Pinned: `https://sdk.zokogames.com/1.5.0/zokogames-sdk-v1.js`.

### 1.4.1 (fix)

Nothing breaks and no action is needed: 1.4.1 only fixes robustness problems, and every name, argument and error code stays the same. What you may notice:

- **Start-up in the portal:** when the page that embeds your game is the portal (zokogames.com), the SDK now waits up to 15 s for the portal to answer `init()` instead of giving up after 1.5 s, so a slow connection no longer leaves the game `disabled` for the whole session. On any other page the wait stays 1.5 s.
- **Calls you do not await:** `gameplayStart`, `gameplayStop`, `happytime`, `loadingStart`, `loadingStop` and `leftRoom` resolve with a console warning when the portal does not answer in time, so they no longer cause an unhandled promise rejection. They still reject with `sdkNotInitialized` or `sdkDisabled`.
- **Cloud saves:** `data.setItem` is faster on large saves (the 1 MB limit is unchanged). A failed sync is retried on its own after 2 s, 4 s and so on, at most 60 s apart. Values in a save that are not strings are read back as strings, as in `localStorage`, and `mirrorLocalStorage` handles a key named `__proto__`.
- **Player tokens:** `getUserToken` keeps one token per `signingKeyType`, so a request for `IN_GAME_AUTH_LEGACY` never receives the default token, and a sign-in during a request no longer keeps the previous player's token.
- **Stricter arguments:** an argument that cannot be copied to the portal (a function, a DOM node) rejects with `invalidArgument` instead of `other`; `setGameContext` refuses `NaN` and `Infinity` with `invalidArgument`; `banner.requestBanner` refuses sizes given as strings (`"300"`) with `invalidSize`; `getInviteParam("constructor")` returns `null`.
- **Reloads:** a late portal answer meant for the previous page load can no longer settle a call made after the game frame reloads.
- **Compatibility shim:** an `adError` callback that throws, or a callback that is not a function, no longer rejects the promise `requestAd` returns.

The script grows by about 2 KB (51.7 KB, 18.3 KB gzip), and the module build declares `"sideEffects": false`. Pinned: `https://sdk.zokogames.com/1.4.1/zokogames-sdk-v1.js`.

### 1.3 to 1.4

Nothing breaks. New: `SDK.game.reportChat(...)` (report a chat message), `SDK.game.onScreenshotRequest(handler)` (an image for the feedback form) and `SDK.data.mirrorLocalStorage(options)` (opt-in cloud save for games that use `localStorage`); see [reporting chat](https://docs.zokogames.com/sdk/game#reporting-chat), [feedback screenshot](https://docs.zokogames.com/sdk/game#feedback-screenshot) and [mirroring localStorage](https://docs.zokogames.com/sdk/data#mirroring-localstorage-ported-games). All three need SDK 1.4.0. On a portal that does not know `reportChat` the call rejects with `unexpectedError`; without a screenshot handler the portal simply gets no image from older SDKs. The script grows by about 9 KB. Game code written for 1.3 needs no change.

### 1.2 to 1.3

Nothing breaks. New: `SDK.game.room`, a data channel for the players of one room (see [room data channel](https://docs.zokogames.com/sdk/game#room-data-channel)), with the error codes `notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember` and `roomUnavailable` (grouped as `ERROR_CODES.room`, with the type `RoomErrorCode`; `rateLimited` is also reported there). It needs SDK 1.3.0 on a portal that has the channel; on an older portal `room.send` fails with `unexpectedError`, so check for the error and fall back to your own server if you must support both. Game code written for 1.2 needs no change.

### 1.1 to 1.2

Nothing breaks. New: `SDK.game.isOffline`, `addOfflineListener` and `removeOfflineListener`, described under [offline state](https://docs.zokogames.com/sdk/game#offline-state), and `SDK.achievements` (`unlock`, `list`, `onUnlock`; see [achievements](https://docs.zokogames.com/sdk/achievements)). On a portal that does not know the achievement calls, `unlock` resolves `{ ok: false, reason: "error" }`. On a portal that does not send the flag, `isOffline` stays `false`. In local mode it mirrors `navigator.onLine` and `?offline=true` pins it. Game code written for 1.1 needs no change.

### 1.1.1 (fix)

The 30 second banner refresh floor and the per-session refresh cap now also hold when you clear a banner and request the same container again (the [banner limits](https://docs.zokogames.com/sdk/banners#limits)). Local mode reads `instantJoin=true` and every other query parameter of the page address as invite parameters.

### 1.0 to 1.1

Nothing breaks: 1.1 only adds. Upgrade by using the latest URL (or by changing the number in a pinned URL). The one name to act on:

- **`store.getPurchaseToken()` is the name to use for the purchase token; `user.getXsollaUserToken()` is a deprecated alias for it.** Both names arrived together in 1.1.0; 1.0 had no purchase token call. Both return `Promise<string>`, a signed token your server verifies, and both fail with `userNotAuthenticated` for guests. The old name still works, so existing code keeps running, but new code and edits should call the new name:

```js
// 1.1.0: deprecated alias, kept for ported code
const legacyToken = await SDK.user.getXsollaUserToken();
// 1.1.0: the name to use
const token = await SDK.store.getPurchaseToken();
```

  Check `SDK.store.isAvailable` before relying on purchases. See [in-game purchases](https://docs.zokogames.com/sdk/purchases) for what to do with the token.
- **New in 1.1:** the `SDK.store` module (`isAvailable`, `getCatalogItems`, `getPlayerInventory`, `buyItem`, `consumeItem`, `setSandbox`, `getPurchaseToken`) with its [error codes](https://docs.zokogames.com/sdk/introduction#errors); `SDK.game.loadingProgress(0..100)`; `ad_response` for local-mode ad failures; the exported `ERROR_CODES` table.
- **Changed behaviour:** `getUserToken({ signingKeyType })` now sends the key type to the portal and caches one token per key type (every token is still signed RS256 by the same key set). `submitScore` accepts an empty `encryptedScore` for boards that have no encryption key.
- **Deprecated, still working:** `game.showInviteButton(params)` and `game.hideInviteButton()` (use `updateRoom({ isJoinable, inviteParams })`), `game.isInstantJoin` (use `isInstantMultiplayer`), `user.getXsollaUserToken()`.

### 1.0.0 (first release)

There is nothing to migrate from earlier ZokoGames versions. If you come from another portal's SDK, use the [migration guide](https://docs.zokogames.com/guides/migrating). The points that bite most often:

- Errors are plain `{ code, message }` objects, not `Error` instances. Use `e.code`, not `e instanceof Error`.
- `init()` never rejects. Check `SDK.environment` instead of catching.
- `SDK.data` methods are synchronous and throw, they do not return promises.
- `getUserToken` accepts `signingKeyType` for ported code but signs every token the same way (RS256, one key set). From 1.1 the argument is passed to the portal and cached per key type.
- `__dangerousUserId` is for display only. Identify players on your server through the verified token.
- 1.0 has no client store or purchase API; it arrived in 1.1. See [in-game purchases](https://docs.zokogames.com/sdk/purchases).

### Compatibility shim

`zokogames-compat-v1.js` is an optional script for porting a game written against another portal's SDK shape. Download it from `https://www.zokogames.com/sdk/zokogames-compat-v1.js`, put it in your build zip and load it after the ZokoGames SDK and set `data-global` to the global your game already reads. It translates the old names and error spellings to the ones on this page. New games should call `SDK` directly. See the [migration guide](https://docs.zokogames.com/guides/migrating).

### Engine wrappers

Wrappers share one browser bridge with the JavaScript SDK. When you update a wrapper, re-export your web build and re-test in the [Preview tool](https://www.zokogames.com/preview). Wrapper-specific changes are listed on each engine page and in the changelog.

## In local mode, and for guests, offline, ad-blocked and ad-free players

The version does not change these behaviours, which are listed on each module page. The only version-specific rules are that `isOffline` needs SDK 1.2.0 on a portal that sends the flag that `game.room` needs SDK 1.3.0, and that `reportChat`, `onScreenshotRequest` and `mirrorLocalStorage` need SDK 1.4.0.

## Checking the version at run time

The version is not a property of `SDK`. Read it from the module build, which is not published on npm at present (`import { SDK_VERSION } from "@zoko/sdk"`) or from the pinned script URL you load; the script-tag global exposes only `ZokoGames.SDK`.

## How to upgrade safely

1. Read the [changelog](https://docs.zokogames.com/business/changelog) for the release.
2. Run the game with `?sdk_debug=true` and look for new warnings.
3. Check error handling still takes the safe path for unknown codes.
4. Test in local mode, then in the Preview tool, then in a build preview from the console.
5. Ship the update. See [updating a live game](https://docs.zokogames.com/getting-started/updating-a-game).

## Next steps

- [Changelog](https://docs.zokogames.com/business/changelog)
- [Migrating from another portal's SDK](https://docs.zokogames.com/guides/migrating)

---

Source: https://docs.zokogames.com/sdk/playground

# SDK playground

**Purpose:** try every kind of SDK call without writing a game, and see exactly what comes back.

The playground runs the real ZokoGames SDK on this page in **local mode**. It answers from the in-page mock, so ads are a three-second overlay, banners are dashed boxes, users and friends are fake and cloud save lives in your browser. Press a button to run a call, read its code, and see the result or error object in the log.

Use it to learn the shapes of the calls and errors. It does not show the portal's real behaviour (real ad failures, per-game ad and banner settings, guests on the live portal); for that load your own game in the [Preview tool](https://www.zokogames.com/preview).

> [!NOTE]
> The page adds `useLocalSdk=true` to its address so the SDK allows local mode on this host. The scenario selectors below reload the page with the matching [query switch](https://docs.zokogames.com/getting-started/environments).

What it can and cannot show:

| Situation | In the playground |
| --- | --- |
| Local mode | Always. The environment is `"local"`. |
| Guest | Set the scenario switch `user_response` to `logged_out`, then press the sign-in call. |
| Token and sign-in outcomes | Scenario switches `token_response` and `show_auth_prompt_response` (see [local testing](https://docs.zokogames.com/getting-started/local-testing)). |
| Ad blocked | There is no switch here. Add `ad_response=adblock` to the page address by hand; `hasAdblock()` then returns `true`. |
| Calls covered | Ads, banners, game, user, data, analytics and a group of calls that fail on purpose. The store, achievements, rooms (`game.room`), offline state and leaderboards are not in the list; use your own game in the [Preview tool](https://www.zokogames.com/preview) or local mode. |
| Offline, ad-free, real checkout | Not simulated here; use the [Preview tool](https://www.zokogames.com/preview). |

## Try it

## Next steps

- [Introduction, init and errors](https://docs.zokogames.com/sdk/introduction)
- [Testing with local mode and the Preview tool](https://docs.zokogames.com/getting-started/local-testing)

---

Source: https://docs.zokogames.com/sdk/achievements

# Achievements

**Purpose:** `SDK.achievements` lets your game award achievements that you define in the developer console. Players see a toast when they unlock one, and a list of unlocked and locked achievements on your game's page. Unlocking is idempotent, so you can call it every time the condition is met without keeping your own state.

## At a glance

Every member of `SDK.achievements`, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

| Signature | Resolves to | Can fail with | Since |
| --- | --- | --- | --- |
| `unlock(key: string): Promise<AchievementUnlockResult>` | `{ ok: true, unlocked, achievement }` or `{ ok: false, reason }`. | Rejects only with `invalidArgument` (a key that does not match `^[a-z0-9_-]{1,40}$`), `sdkNotInitialized`, `sdkDisabled`. Every other failure, a timeout included, resolves with `reason: "error"`. | 1.2.0 |
| `list(): Promise<AchievementInfo[]>` | Every achievement of the game in display order, with the player's state. | `timeout`, `sdkNotInitialized`, `sdkDisabled`. Over the call limit it resolves the previous list (`[]` before the first). | 1.2.0 |
| `onUnlock(fn: (achievement: AchievementInfo) => void): () => void` | A function that removes the listener. | Throws `invalidArgument` (not a function), `sdkNotInitialized`, `sdkDisabled`. | 1.2.0 |

The types `AchievementsApi`, `AchievementInfo` (the `Achievement` shape below), `AchievementUnlockResult` and `AchievementUnlockFailure` are in the declaration file described in the SDK introduction.

## Concepts

Define achievements on your game's **Achievements** tab in the console. A game can have up to 100.

| Field | Meaning |
| --- | --- |
| Key | What your game passes to `unlock()`. 1 to 40 characters from `a-z`, `0-9`, `-` and `_` (`^[a-z0-9_-]{1,40}$`). Unique per game and fixed once created. |
| Name | Up to 60 characters. Shown in the toast and on the game page. |
| Description | Up to 200 characters. |
| Icon URL | Optional `https` link to a square image. |
| Points | A whole number from 0 to 100. Shown with each achievement and summed on the game page. |
| Hidden | When on, players see a mask (no name, description or icon) until they unlock it. |
| Order | Display order on the game page, lowest first. |

**Create, edit and delete in the console.**

Open your game in the developer console and choose **Achievements**. **Add achievement** opens the form; **Edit** and **Delete** are on each row. Only the studio's owners and admins can change achievements; other roles see the list read only. Each change is written to the studio's audit trail.

- **Limit and checks.** A game holds at most 100. The key is checked as you type, and the name, icon link and points when you save; a refused save keeps the form open with the reason.
- **The key cannot change.** Your game's `unlock()` calls and the stored unlocks both refer to it. To rename a key, delete the achievement and add a new one: players lose their unlocks of the old key, and the new key starts empty for everyone.
- **Editing is live.** Name, description, icon, points, hidden and order apply to the game page and to the next `list()` call at once; a game that is already open keeps the list it loaded until it calls `list()` again. Points are counted from the current value, so changing them changes the totals players already have, on the game page and on their profile.
- **Deleting removes every player's unlock of it**, from the game page and from profiles, and cannot be undone. After that `unlock("that-key")` resolves `reason: "not_found"`. If you only want to stop awarding it, remove the `unlock` call from your game and keep the achievement.
- **Icons** are links, not uploads: host a square image over `https` yourself. The portal does not copy it, so an icon breaks if you move or delete the file.
- **Order.** Lowest number first on the game page; equal numbers are ordered by key. There is no drag and drop, and no bulk import or export: set the numbers in the form.

Achievements are recorded per signed-in player and per game. Guests cannot unlock achievements; the call resolves with `reason: "guest"` and nothing is recorded. The same happens in a kids' game: `list()` resolves with an empty array and `unlock()` with `reason: "guest"`.

## API

```ts
SDK.achievements.unlock(key: string): Promise<
  | { ok: true; unlocked: boolean; achievement: Achievement }
  | { ok: false; reason: "guest" | "not_found" | "not_live" | "rate_limited" | "error" }
>
SDK.achievements.list(): Promise<Achievement[]>
SDK.achievements.onUnlock(fn: (achievement: Achievement) => void): () => void

interface Achievement {
  key: string;
  name: string;
  description: string;
  iconUrl: string | null;
  points: number;
  hidden: boolean;
  unlocked: boolean;
  unlockedAt: string | null; // ISO 8601
}
```

```js
await SDK.init();

SDK.achievements.onUnlock((a) => console.log("Unlocked", a.name));

async function onBossDefeated() {
  const r = await SDK.achievements.unlock("first-boss");
  if (r.ok && r.unlocked) {
    // Earned just now. The portal already showed its toast.
  } else if (!r.ok && r.reason === "guest") {
    // Optional: invite the player to sign in with SDK.user.showAuthPrompt().
  }
}

const all = await SDK.achievements.list();
const done = all.filter((a) => a.unlocked).length;
```

### unlock

Resolves instead of throwing for every expected outcome, so you never need a `try` around it for guests or typos.

| Result | Meaning |
| --- | --- |
| `{ ok: true, unlocked: true }` | The player earned it with this call. The portal shows a toast and `onUnlock` listeners run. |
| `{ ok: true, unlocked: false }` | The player already had it. Nothing changes and the original unlock time is kept. |
| `{ ok: false, reason: "guest" }` | Nobody is signed in, or the player is in kids mode. Nothing is recorded. A signed-in player also gets `guest` when the portal has switched achievements off for the game. |
| `{ ok: false, reason: "not_found" }` | The game has no achievement with that key. |
| `{ ok: false, reason: "not_live" }` | The game is not published. Preview and QA runs never record unlocks, so they cannot affect real player stats. |
| `{ ok: false, reason: "rate_limited" }` | A limit per player and game was reached: more than 20 unlock calls in a minute, more than 1,000 in a day, or more than 10 unknown keys in an hour (the portal answers 429). |
| `{ ok: false, reason: "error" }` | The portal could not be reached or failed. Try again later. |

**Retrying.** Unlocking is idempotent, so any failure that recorded nothing (`rate_limited`, `error`) is safe to send again, and a second try for an achievement the player already has answers `unlocked: false`. For `rate_limited`, keep the key, wait about a minute and call `unlock` once more; do not retry in a loop. When the limit was the 10 unknown keys an hour, waiting does not help: the key is not defined in the console, so create it first (`not_found` is the same mistake before the limit is reached). `not_live`, `guest` and `not_found` are not retried: the game, the player or the key has to change first.

`unlock` rejects with `invalidArgument` only when `key` does not match `^[a-z0-9_-]{1,40}$`. It also throws `sdkNotInitialized` or `sdkDisabled` as described in [errors](https://docs.zokogames.com/sdk/introduction#errors). Repeated calls for a key the SDK already knows is unlocked (from an earlier `unlock`, a `list()` or an `onUnlock` event in this session) answer immediately with `{ ok: true, unlocked: false }` and no network request, and so does a second call for the same key while the first is still running (when that first call fails, the second one resolves the same failure). The SDK forgets what it knows when a different player signs in. Over the call limit (30 in a burst, 10 a second) the call resolves `reason: "rate_limited"`.

### list

Returns every achievement of the game in display order with the signed-in player's state. Guests get the definitions with `unlocked: false`. A hidden achievement that is still locked is masked: `name` and `description` are empty, `iconUrl` is `null`, `points` is `0` and `key` is a placeholder (`hidden-1`, `hidden-2`, by position in the list), so the real key is not revealed. Do not look a locked hidden achievement up by its key in `list()`; call `unlock("your-real-key")` as usual, and once it is unlocked the real key, name and points appear.

### onUnlock

Runs `fn` whenever the player earns an achievement, whichever call earned it. It returns a function that removes the listener. Use it to play your own sound or animation; the portal toast is always shown.

## Local mode and previews

| Situation | What happens |
| --- | --- |
| Local mode | Any valid key unlocks once per page load for the simulated player, with a toast and an `onUnlock` event. There are no console definitions locally, so `name` equals the key and `points` is 0, and `list()` returns only the keys unlocked so far. A guest (`?user_response=logged_out`) gets `reason: "guest"`. |
| Basic launch | Unlocks are recorded, as the game is live. |
| Preview tool and QA | Unlocks are refused with `not_live` and nothing is recorded. |
| Offline | Needs the portal; resolves `reason: "error"`. |

**Common mistakes.** The ones QA and the Preview tool report most often:

| Mistake | Result | Fix |
| --- | --- | --- |
| A key with capital letters, spaces or more than 40 characters (`"First Boss"`) | `invalidArgument` | Use lowercase letters, digits, `-` and `_`: `"first-boss"`. |
| `try`/`catch` is the only handling | Failures arrive as a result, not an exception | Read `r.ok` and `r.reason`. |
| A key that is not defined in the console | `reason: "not_found"` | Create the achievement on the **Achievements** tab first, with exactly that key. |
| Unlocks are tested in the Preview tool and nothing is saved | `reason: "not_live"` | Unlocks are recorded only for a live game; use local mode to test the code path. |
| Guests are told they unlocked something | `reason: "guest"` and nothing recorded | Show the achievement only when `r.ok` is `true`, and offer sign-in. |
| The game draws its own "Unlocked!" for `r.unlocked === false` | A repeat toast for an old achievement | Show your own animation only when `unlocked` is `true`, or from `onUnlock`. |
| Local-mode names and points are used in the UI | `name` equals the key and `points` is 0 | Use `list()` on the portal for the real definitions. |
| `unlock` is called every frame while a condition holds | `rate_limited` after the 20 a minute limit | Call it once when the condition first becomes true. |

## Engines

The engine plugins expose the same three members: see the coverage table in each engine's page, for example [Unity](https://docs.zokogames.com/engines/unity) and [Phaser](https://docs.zokogames.com/engines/phaser).

## Next steps

- [Leaderboards](https://docs.zokogames.com/sdk/leaderboards)
- [Game module](https://docs.zokogames.com/sdk/game)

---

Source: https://docs.zokogames.com/engines/overview

# Engines overview

Every engine page documents the same SDK. The wrappers are thin: they load the JavaScript SDK in the web export and translate calls, so behaviour, limits and [error codes](https://docs.zokogames.com/sdk/introduction#errors) are identical to the [JavaScript reference](https://docs.zokogames.com/sdk/introduction) (SDK 1.7.0, script `https://sdk.zokogames.com/zokogames-sdk-v1.js`). Unfamiliar words are explained in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Decision table

| Engine | Page | Plugin folder (`packages/sdk-engines/`) | Mechanism | Verified |
| --- | --- | --- | --- | --- |
| Unity (WebGL) | [Unity](https://docs.zokogames.com/engines/unity) | `unity/` | UPM package `com.zokogames.sdk`, `.jslib` bridge, WebGL template | Run in Unity 6 (6000.3) in a full WebGL game; Unity 2021.3 to 2023 only compiled with a real C# compiler against stubs of the Unity API |
| Phaser 3 and 4 | [Phaser](https://docs.zokogames.com/engines/phaser) | `phaser/` | Global plugin `ZokoPlugin`, typed client, scene mixin | Run in a real browser against Phaser 3.90.0 and 4.2.1 |
| Godot 4 | [Godot](https://docs.zokogames.com/engines/godot) | `godot/` | Addon `zokogames` with autoload `ZokoGames`, custom HTML shell | Godot 4.3, 4.7.2 and 3.6.3 Web exports run in a browser (headless Chrome, local mode); not yet run against the live portal |
| Construct 3 | [Construct 3](https://docs.zokogames.com/engines/construct-3) | `construct3/` | SDK v2 addon `zokogames.c3addon` (actions, conditions, expressions) | Addon installed in the Construct 3 r506.4 editor and an exported build run |
| GameMaker | [GameMaker](https://docs.zokogames.com/engines/gamemaker) | `gamemaker/` | Extension `zokogames.js` (HTML5) plus `zokogames_sim.gml` | Extension JavaScript run in a real browser against the SDK; not built in the GameMaker IDE |
| Cocos Creator 3 | [Cocos](https://docs.zokogames.com/engines/cocos) | `cocos/` | TypeScript module `ZokoSDK` in `assets/zokogames/` | Run in the real Cocos Creator 3.8.8 editor command-line build (web-desktop and web-mobile), in a browser; the editor Preview mode not used |
| Defold | [Defold](https://docs.zokogames.com/engines/defold) | `defold/` | Lua library `zokogames` with a small native extension | Defold 1.14.1: native extension built by the build server and run in a browser |
| PlayCanvas 2.x | [PlayCanvas](https://docs.zokogames.com/engines/playcanvas) | `playcanvas/` | App helper `ZokoPlayCanvas`, typed client, ESM and classic Editor scripts | Run in a real browser against playcanvas 2.24.2; the Editor app itself not driven |
| Wonderland Engine 1.x | [Wonderland](https://docs.zokogames.com/engines/wonderland) | `wonderland/` | TypeScript package `ZokoSDK` and `zoko-sdk` component | Type-checked against the official @wonderlandengine/api 1.6.1 declarations; not run in the editor |
| GDevelop 5 | [GDevelop](https://docs.zokogames.com/engines/gdevelop) | `gdevelop/` | Events extension `ZokoGames.json` (actions, conditions, expressions; automatic pause/mute during ads) | Export from GDevelop 5.6.287 run in a real browser; editor UI not driven |
| Plain HTML5, Three.js, PixiJS, Babylon.js | [Plain HTML5 and libraries](https://docs.zokogames.com/engines/html5-libraries) | none: the JavaScript SDK directly | The JavaScript SDK | Tested part: the JavaScript SDK itself |

> [!NOTE]
> **Status: available now** (see [feature status](https://docs.zokogames.com/business/faq#feature-status)). Every plugin is published (the version is on its page and in `engines.json`), and each was verified as far as free tools allow (details on each engine page): Unity ran in the Unity 6 editor (2026-11-21); on 2026-11-23 the Godot 4.3, 4.7.2 and Godot 3.6.3 Web exports, Defold 1.14.1 (native extension built by the build server), Cocos Creator 3.8.8 command-line web builds, Phaser 3.90.0 and 4.2.1, PlayCanvas 2.24.2 and a GDevelop 5.6.287 export all ran in a real browser, and the Construct 3 r506.4 addon was installed in the editor and an exported build ran. GameMaker's extension JavaScript was run in a browser against the SDK but not built in the IDE, and Wonderland was type-checked against @wonderlandengine/api 1.6.1 but not run in the editor. Also tested are the JavaScript SDK, the shared bridge core, the TypeScript client, the simulator and the packaging tools (unit tests in `packages/sdk-engines/tests`), and a coverage check that every one of the 97 JavaScript SDK members and exports exists in every wrapper. Expect small fixes on first import and send them to [support](https://docs.zokogames.com/business/support) with the engine version.

### Getting the plugin

Each plugin is the folder named above in the repository. The packager (`pnpm --filter @zoko/sdk-engines package`) writes one zip per engine, `dist/zokogames-<engine>-<version>.zip` (the Construct 3 zip contains the installable `zokogames.c3addon`), and a `dist/manifest.json` with sizes and checksums. The web app serves the same zips without the version in the name: `/sdk-engines/<engine>.zip` (`unity`, `godot`, `godot3`, `construct3`, `gamemaker`, `cocos`, `defold`, `phaser`), linked from each engine page. The starter kits are downloadable from [starter kits](https://docs.zokogames.com/getting-started/starter-kits).

Each engine page links the versioned file `/sdk-engines/zokogames-<id>-<version>.zip` (ids `unity`, `godot`, `godot3`, `construct3`, `gamemaker`, `cocos`, `defold`, `phaser`, `playcanvas`, `wonderland`, `gdevelop`; each page names the current version), and `/sdk-engines/<id>.zip` is always the latest version. [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS) lists the SHA-256 checksum of every file, and [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json) is a machine-readable index with each engine's id, version, file name, size and checksum.

## Which path

| You are | Your path |
| --- | --- |
| **A solo developer with a finished Phaser or vanilla JavaScript game** | Add the SDK script tag, wrap your existing ad, save and score calls, test on `localhost`, upload. Phaser: [Phaser](https://docs.zokogames.com/engines/phaser) (plugin or plain SDK). Anything else in the browser: [plain HTML5 and libraries](https://docs.zokogames.com/engines/html5-libraries). Start from the `html5-minimal` or `phaser` [starter kit](https://docs.zokogames.com/getting-started/starter-kits) if it saves time. No engine install, no editor. |
| **A Unity WebGL studio** | [Unity](https://docs.zokogames.com/engines/unity): install the package and WebGL template, call `ZokoSDK.InitAsync()`, set Brotli or Gzip compression (the game origin serves `.br` and `.gz` correctly), keep Decompression Fallback off, threads off, upload. Plan for the initial-download budget and iOS (off by default). |
| **A Godot or Construct hobbyist** | [Godot](https://docs.zokogames.com/engines/godot) (enable the addon, set the custom HTML shell, threads off) or [Construct 3](https://docs.zokogames.com/engines/construct-3) (install the addon, add **Initialize**, use the event sheet). Both need no scripting beyond the examples. Test in the editor first, then on `localhost`. |
| **GameMaker, Cocos or Defold** | The matching page; the shape is the same: install, init once, wrap ads with pause and resume on finish and error. |

Whatever your engine, the minimum for a good launch is the same list, and every page gives the code for it: init, gameplay start and stop, a midgame and a rewarded ad that resume on finish and on error, save and load through the data module, a leaderboard score, and a game that also runs when the SDK is `disabled`.

## Naming rules

The JavaScript API is the source of truth. Other languages follow a mechanical mapping.

| JavaScript | C# (Unity) | GDScript (Godot) | GML (GameMaker) |
| --- | --- | --- | --- |
| `SDK.init()` | `ZokoSDK.Init(cb)` or `InitAsync()` | `ZokoGames.init_async()` | `zoko_init()` |
| `SDK.ad.requestAd(type, cb)` | `ZokoSDK.Ad.RequestAd(type, ...)` | `ZokoGames.request_ad_async(type)` | `zoko_ad_request_ad(type)` |
| `SDK.game.gameplayStart()` | `ZokoSDK.Game.GameplayStart()` | `ZokoGames.gameplay_start()` | `zoko_game_gameplay_start()` |
| `SDK.user.getUserToken()` | `ZokoSDK.User.GetUserToken(cb)` | `ZokoGames.get_user_token_async()` | `zoko_user_get_user_token("")` |
| `SDK.data.setItem(k, v)` | `ZokoSDK.Data.SetItem(k, v)` | `ZokoGames.data_set_item(k, v)` | `zoko_data_set_item(k, v)` |

- Modules become `Ad`, `Banner`, `Game`, `User`, `Data`, `Store`, `Analytics` in C# and `ad`, `banner`, `game`, `user`, `data`, `store`, `analytics` in Lua and TypeScript (Cocos `ZokoSDK.game`, Defold `zoko.game`). GDScript and GML flatten the modules into the method name. Phaser's plugin calls the SDK `game` module `gameApi`, because `this.game` is Phaser's own object.
- Promises become callbacks (Unity, Defold, GameMaker through the Async - Social event), signals (Godot) or awaitable calls (Godot `_async`, Unity `...Async`, Cocos and Phaser promises). Construct uses tagged actions.
- Error objects keep `code` and `message`; C# exposes them as `Code` and `Message`.

## Properties of all wrappers

- **Simulators.** In the editor and in non-web players a simulator answers instead of the browser (Unity, Godot, GameMaker, Cocos, Defold), so you can run the game without uploading it. It mimics ads, users, friends, cloud save and a test store, and has settings to force an ad failure or an adblocker. Phaser, Construct 3 and the plain HTML5 libraries run in a browser, so on `localhost` the SDK's own [local mode](https://docs.zokogames.com/getting-started/local-testing) does the same job. **No simulator enforces the three-minute midgame cooldown (`adCooldown`)** that the portal and the SDK's local mode enforce, so test ad handling in a web build as well.
- **Disabled is normal.** If the SDK is `disabled` (for example the game opened outside the portal and not on `localhost`), calls fail with `sdkDisabled` and your game must still run. Check `IsAvailable` or the equivalent before calling.
- **Shared core.** The browser side of the Unity, Godot, GameMaker, Construct 3 and Defold wrappers is generated from one bridge (`shared/zoko-core.js`); the Cocos and Phaser wrappers share one TypeScript client. A fix applies everywhere, and the coverage check reports drift.
- **No leaderboard encryption helper.** `submitScore(encryptedScore, score)` is available in every engine, but no wrapper builds the encrypted payload. A board with an encryption key counts only that payload, so on a keyed board encrypt in your own code ([leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), compute scores on your server with the server API, or use a board without a key (empty `encryptedScore`). Browser-side games (Phaser, plain HTML5, Cocos) can use the page's Web Crypto directly. The wrappers do not pass the SDK 1.6.4 `delayed` copy either, so an offline score from an engine build is not queued; a web build can call `SDK.user.submitScore` itself to send it.

## Web export checklist (all engines)

- Export for the web (WebGL, HTML5), not as a desktop or mobile app. Zip the export folder **contents** so `index.html` is at the archive root, with relative paths only.
- The page that hosts the engine must load `https://sdk.zokogames.com/zokogames-sdk-v1.js` before the engine boots. Provided: the Unity WebGL template, the Godot custom shell and the Cocos snippet (you install them); the Construct 3 addon and the Defold library inject the script themselves; the Phaser plugin injects it when missing; GameMaker needs the tag added by hand. The upload validator looks for the URL in your files, so add the tag even where a wrapper can inject it.
- Keep the initial download small, see [first frame fast](https://docs.zokogames.com/guides/first-frame). Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile), estimated from **uncompressed** sizes.
- Test in the [Preview tool](https://www.zokogames.com/preview) and on `localhost` first.

### What the game origin serves

Games are served from `https://g-<slug>.zokogames.com/<buildId>/` by a Cloudflare Worker (`workers/game-origin`) in front of the storage bucket. Facts that decide your export settings:

| Behaviour | Detail |
| --- | --- |
| Pre-compressed files | A file whose name ends in `.br` or `.gz` is served with `Content-Encoding: br` or `gzip`, the stored bytes untouched, and a `Content-Type` taken from the inner extension (`game.wasm.br` is `application/wasm`). Only an engine that requests exactly those names can use this: **Unity** (Build files with Brotli or Gzip). Godot, Construct, GameMaker, Cocos, Defold and Phaser request plain names, so ship plain files. |
| Not supported | Legacy `.unityweb` files get no content encoding (`unity_unityweb`); mixing `.br` and `.gz`, or leaving some Build files uncompressed, warns (`unity_mixed_compression`, `unity_compression_mismatch`); a `.gz` file that is not gzip data is rejected (`bad_precompressed`). |
| Plain files | Served as stored. The portal documents no compression in transit for them, so keep them small. |
| Caching | Files under the build id are immutable (one year); HTML documents revalidate after 60 seconds. |
| Threads | The portal sends no `Cross-Origin-Embedder-Policy`, so the frame is not cross-origin isolated and `SharedArrayBuffer` is unavailable: turn off thread support in Unity, Godot and Defold exports. |
| Range requests | Passed through (206), so streaming media works. |
| Frame | The game runs in an iframe with `allow` for autoplay, fullscreen, gamepad, clipboard-write, motion sensors and others (camera and microphone only when staff grant them for one game), and a `sandbox` that allows scripts, same-origin, forms, pointer lock, orientation lock, modals, downloads and presentation. Popups only when enabled for the game. |
| Fullscreen | Use the fullscreen button in the portal's frame bar. A game's own fullscreen call is permitted but fullscreens only the game's canvas, so do not build a competing button. |
| Audio | Browsers suspend WebAudio until a first click, tap or key press, in every engine. Start music from a "tap to play" screen, not at boot. |

## Next

- Pick your engine in the table above and follow its install steps.
- Test with the [local mode and the Preview tool](https://docs.zokogames.com/getting-started/local-testing).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Already shipping this game on other web game portals? [Bring your game](https://docs.zokogames.com/porting/overview) lists the export settings and calls to change.

---

Source: https://docs.zokogames.com/engines/phaser

# Phaser

Phaser games run in the browser, so you have two ways in. Use the **ZokoGames Phaser plugin** (`packages/sdk-engines/phaser`), which pauses the game loop and the sound around ads for you, or call the [JavaScript SDK](https://docs.zokogames.com/sdk/introduction) directly. Both use the same calls, limits and [error codes](https://docs.zokogames.com/sdk/introduction#errors). Jargon such as "midgame" and "rewarded" is explained in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (1.7.1): run in a real browser against Phaser 3.90.0 and 4.2.1 (2026-11-23). Send the Phaser version and the exact error to [support](https://docs.zokogames.com/business/support) if the first import fails. The JavaScript SDK underneath is the tested part. Release 1.7.1 (script-load timeout) was re-run on 2026-11-23, in a browser and on production.

## Install

Download the Phaser plugin: [/sdk-engines/zokogames-phaser-1.7.1.zip](https://www.zokogames.com/sdk-engines/zokogames-phaser-1.7.1.zip) (the same files as the folder in the repository).

[/sdk-engines/phaser.zip](https://www.zokogames.com/sdk-engines/phaser.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

Pick the route that matches your game.

| You have | Do this |
| --- | --- |
| A finished Phaser game (JavaScript or TypeScript) | Copy the plugin sources into your project and register the plugin (below), or skip the plugin and use the [plain SDK](#without-the-plugin). |
| A new game | Start from the `phaser` [starter kit](https://docs.zokogames.com/getting-started/starter-kits). It already has the plugin under `src/zoko/`, four scenes and an `npm run package` script. |

The plugin is plain TypeScript in `packages/sdk-engines/phaser/src/`: `ZokoPlugin.ts`, `ZokoClient.ts`, `ZokoAdFlow.ts`, `ZokoLoadingBridge.ts`, `ZokoSceneMixin.ts`, `types.ts` and an `index.ts` that re-exports them. Copy the folder (for example to `src/zokogames-phaser/`) and import from it. The starter kit holds the same files, formatted, in `src/zoko/` and has no `index.ts`, so import `./zoko/ZokoPlugin` there. The peer dependency is `phaser ^3.80.0`; the starter kit itself pins Phaser 4.2 and is type-checked and built against it.

You do not have to add a script tag: when `window.ZokoGames` is missing, the plugin injects `https://sdk.zokogames.com/zokogames-sdk-v1.js` itself (pass `loadScript: false` to turn that off). A script tag in `index.html` is still better, because the upload validator looks for the SDK URL (see [build validation](https://docs.zokogames.com/requirements/build-validation)):

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
```

## A working game loop with the plugin

This is one file that covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score. Every portal call is wrapped so the game also runs when the SDK is `disabled` (see [local mode](#test-locally)).

```ts
import Phaser from "phaser";
import { ZokoPlugin } from "./zokogames-phaser/ZokoPlugin";

// SDK calls must never break the game: swallow errors, return a fallback.
async function safe<T>(fn: () => Promise<T> | T, fallback: T): Promise<T> {
  try { return await fn(); } catch { return fallback; }
}

class Boot extends Phaser.Scene {
  constructor() { super("Boot"); }
  async create() {
    const z = this.zoko;                                   // available because of `mapping: "zoko"`
    await safe(() => z.ready(), null);                     // loads the script if missing, then SDK.init()
    const live = (() => { try { return z.sdk.environment !== "disabled"; } catch { return false; } })();
    this.registry.set("live", live);
    if (live) {
      await safe(() => z.sdk.game.loadingStart(), undefined);
      this.registry.set("best", Number(z.sdk.data.getItem("best") ?? "0") || 0);   // load: synchronous
      await safe(() => z.sdk.game.loadingStop(), undefined);
    }
    this.scene.start("Play");
  }
}

class Play extends Phaser.Scene {
  private score = 0;
  constructor() { super("Play"); }

  create() {
    const z = this.zoko;
    const live = this.registry.get("live") as boolean;
    const start = () => { if (live) void safe(() => z.sdk.game.gameplayStart(), undefined); };
    const stop = () => { if (live) void safe(() => z.sdk.game.gameplayStop(), undefined); };
    start();                                               // input is live now, not at page load
    this.game.events.on("hidden", stop);
    this.game.events.on("visible", start);
    this.events.once("shutdown", () => {
      this.game.events.off("hidden", stop);
      this.game.events.off("visible", start);
      stop();
    });
    // ... spawn targets, call this.finish() when the round ends
  }

  async finish() {
    const z = this.zoko;
    const live = this.registry.get("live") as boolean;
    if (!live) { this.scene.start("Play"); return; }
    await safe(() => z.sdk.game.gameplayStop(), undefined);

    // Save. Writes are batched and sent about a second later; reads are synchronous.
    if (this.score > (this.registry.get("best") as number)) {
      this.registry.set("best", this.score);
      try { z.sdk.data.setItem("best", String(this.score)); } catch { /* dataLimitExceeded */ }
    }
    // Leaderboard (needs a signed-in player and the board enabled in the console).
    await safe(async () => {
      const user = await z.sdk.user.getUser();
      if (!user) return;
      const encryptedScore = await encryptScore(this.score, BOARD_KEY, user.__dangerousUserId, GAME_ID);
      await z.sdk.user.submitScore({ encryptedScore, score: this.score });
    }, undefined);

    // Midgame ad at a natural break. Pauses sound and the loop from adStarted until adFinished OR adError.
    const { finished, error } = await z.requestAd("midgame");
    if (!finished) console.warn("no ad:", error?.code);   // adCooldown, unfilled, adblock ... the game just carries on
    this.scene.start("Play");
  }

  async watchForBonus() {                                   // call from a button press
    const { finished } = await this.zoko.requestAd("rewarded");
    if (finished) this.score += 10;                         // reward only after adFinished
  }
}

new Phaser.Game({
  type: Phaser.AUTO,
  parent: "game",
  scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, width: 1280, height: 720 },
  plugins: { global: [{ key: "ZokoPlugin", plugin: ZokoPlugin, start: true, mapping: "zoko", data: { syncMute: true } }] },
  scene: [Boot, Play],
});
```

`encryptScore`, `BOARD_KEY` and `GAME_ID` come from the [leaderboards page](https://docs.zokogames.com/sdk/leaderboards#client-submission), which has the AES-GCM helper and explains why a board without an encryption key accepts `encryptedScore: ""` with the plain `score`. Only signed-in players are ranked, and a submission that breaks a board rule is dropped silently while the call still resolves.

### What the plugin gives you

| Member | Behaviour (verified in `ZokoPlugin.ts` and `ZokoAdFlow.ts`) |
| --- | --- |
| `ready()` | Loads the SDK script if `window.ZokoGames` is missing, then runs `SDK.init()`. Rejects with `{ code: "sdkNotLoaded" }` when the script cannot load. Safe to call repeatedly. When the environment is not `disabled` it also registers settings and offline listeners and applies `muteAudio` to `game.sound.mute` (option `syncMute`, default `true`). |
| `requestAd("midgame" \| "rewarded")` | On `adStarted` it pauses all sound, mutes, and calls `game.loop.sleep()`. On `adFinished`, on `adError`, and when the request itself throws, it wakes the loop, restores mute (the portal's `muteAudio` or what it was before) and resumes sound. Resolves `{ finished, error? }` and never rejects for ad problems. |
| `version` | The JavaScript SDK release the plugin was written against (`SDK_VERSION`). |
| `isAdPlaying` | `true` while an ad is on screen. |
| `events` | Emits `adStarted`, `adFinished`, `adError(error)`, `settingsChange(settings)` and `offlineChange(offline)`. |
| `sdk` | The raw SDK. Throws `sdkNotInitialized` before `ready()` resolved. |
| `ad`, `banner`, `user`, `data`, `store`, `analytics`, `gameApi`, `environment`, `isQaTool`, `client` | The typed client. `gameApi` is the SDK `game` module (`this.game` is Phaser's own object). `client` is the underlying `ZokoClient`, which also has `achievements` (`this.zoko.client.achievements.list()`, `unlock(key)`, `onUnlock(cb)`; see [achievements](https://docs.zokogames.com/sdk/achievements)). |
| `trackLoading(this.load)` | Reports a loader to the portal: `loadingStart` on `start`, `loadingProgress` (0 to 100) on `progress`, `loadingStop` on `complete`. Returns a function that detaches the listeners. |
| `rectFromGameBounds(x, y, w, h)` | Converts a rectangle in game coordinates (the configured game width and height) to the normalised canvas rectangle the banner calls use. |
| `requestBannerAt(id, x, y, w, h, size?)` | Positions a DOM container over a rectangle in game coordinates and requests a banner there; without `size` it requests the largest responsive size that fits. |

The plugin file also exports `runAdFlow`, `bindLoadingProgress`, `withZoko` and `ZOKO_SDK_SCRIPT_URL`, and `ZokoClient` can be used on its own in unit tests (it needs no Phaser). `this.zoko` is also available through `class X extends withZoko(Phaser.Scene)` when the plugin key is `ZokoPlugin`.

## Without the plugin

If you do not want a plugin, call the SDK yourself. Initialise before you create the `Phaser.Game`, and write the ad helper so it resumes on both outcomes.

```js
const SDK = window.ZokoGames?.SDK;
let live = false;

async function main() {
  if (SDK) { await SDK.init(); live = SDK.environment !== "disabled"; }   // init never rejects
  const game = new Phaser.Game({
    type: Phaser.AUTO,
    parent: "game",
    scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH, width: 1280, height: 720 },
    scene: [Boot, Play],
  });
  if (live) {
    const apply = (s) => { game.sound.mute = s.muteAudio; };
    apply(SDK.game.settings);
    SDK.game.addSettingsChangeListener(apply);
  }
}

function showAd(game, type) {
  if (!live) return Promise.resolve(false);
  let paused = false;
  const pause = () => { if (paused) return; paused = true; game.sound.pauseAll(); game.sound.mute = true; game.loop.sleep(); };
  const resume = () => {
    if (!paused) return; paused = false;
    game.loop.wake();
    game.sound.mute = SDK.game.settings.muteAudio;
    game.sound.resumeAll();
  };
  return new Promise((done) => {
    SDK.ad.requestAd(type, {
      adStarted: pause,
      adFinished: () => { resume(); done(true); },
      adError: () => { resume(); done(false); },
    }).catch(() => { resume(); done(false); });          // throws (for example sdkDisabled) instead of calling adError
  });
}
main();
```

Pausing one scene with `scene.pause()` is not enough: tweens, timers on other scenes and the sound manager keep running. `game.loop.sleep()` stops the whole game step. `requestAd` resolves only after `adFinished` or `adError` has been delivered, so `await showAd(...)` is a safe place to resume game logic.

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `SDK.game.settings.kidsMode` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `disableChat`, which the portal sets to true in the same cases. To test it, add `?kidsMode=true` to the page address in local mode. See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Banners

Banner containers are DOM elements next to the canvas, not game objects. Request them on menu screens only and clear them before play.

```html
<div id="game"></div>
<div id="menu-banner" style="width:728px;height:90px;margin:8px auto"></div>
```

```js
SDK.banner.requestBanner({ id: "menu-banner", width: 728, height: 90 }).catch(() => {});
this.events.once("shutdown", () => SDK.banner.clearAllBanners());
```

With the plugin, `await this.zoko.requestBannerAt("hud", 20, 20, 300, 250, "300x250")` creates the container for you over that rectangle of the canvas. Banners are refused while a video ad plays (`videoAdPlaying`) and a container can refresh only every 30 seconds (`bannerCooldown`).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

The plugin has no room helpers of its own; use the SDK's `game.room` through `this.zoko.gameApi.room`. It is `undefined` on an SDK older than 1.3.0, so check it first. Methods: `send(data, { to })`, `setState(patch)`, `getState()`, `members()`, `isHost()`, `selfId`, and `onMessage`, `onState`, `onMembers`, `onHostChange`, `onError`, each returning an unsubscribe function. On `localhost` the SDK's local mode makes two browser tabs in the same room id behave like two players.

```ts
async startMatch() {
  await this.zoko.ready();
  await this.zoko.gameApi.updateRoom({ roomId: "match-1", isJoinable: true });
  const room = this.zoko.gameApi.room;
  if (!room) return;
  room.onMessage((m) => this.placeMark((m.data as { cell: number }).cell));
  room.onHostChange((_hostId, isHost) => { if (isHost) void room.setState({ turn: "X" }); });
}

onCellClicked(cell: number) { void this.zoko.gameApi.room?.send({ cell, mark: "X" }); }
```

## Purchases

```ts
const store = this.zoko.sdk.store;
if (store.isAvailable) {
  try {
    const items = await store.getCatalogItems({ limit: 20 });
    await store.buyItem(items[0].sku);
    const token = await store.getPurchaseToken();            // send to your server and verify there
  } catch (e) {
    if ((e as { code?: string }).code === "purchaseCancelled") return;
  }
}
```

Check `isAvailable` before showing any purchase UI and verify ownership on your server. See [in-game purchases](https://docs.zokogames.com/sdk/purchases). On `localhost` the SDK's local mode serves a test store.

## Export settings that matter on the web

- **Bundle with relative paths.** Vite: `base: "./"`. Root-absolute paths (starting with a slash) break under the game's own origin and raise the `absolute_path` warning. See [technical requirements](https://docs.zokogames.com/requirements/technical#relative-paths-only).
- **Do not pre-compress.** Phaser, unlike Unity, asks for plain file names. A file ending in `.br` or `.gz` is served with `Content-Encoding`, but your page would still request the plain name, so ship plain files. The game origin does serve a `.br` or `.gz` suffix with the matching `Content-Encoding` and caches game files for a year under the build id. Whether plain files are compressed in transit is not documented or guaranteed by the portal, and the initial-download estimate uses uncompressed sizes, so keep the files small.
- **Size.** Pack textures into atlases and keep audio at modest bitrates. Load later levels after the first scene instead of in `preload`. The upload limits are 1,500 files, 250 MB unpacked and about 50 MB initial download (20 MB for mobile); see [first frame fast](https://docs.zokogames.com/guides/first-frame).
- **Canvas sizing.** The frame size changes with fullscreen and rotation. `Phaser.Scale.FIT` with `autoCenter: CENTER_BOTH` keeps the game legible at every [required resolution](https://docs.zokogames.com/requirements/gameplay). The starter kit uses 800 by 450.
- **Audio unlock.** Browsers block sound until the first pointer or key event. Phaser's sound manager handles the unlock itself; start music from a button press or after the sound manager's `unlocked` event, not unconditionally in `create()`. Ads and `syncMute` do not replace this.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar: it fullscreens the whole frame, including the portal's controls. The frame carries `allow="fullscreen"`, so `this.scale.startFullscreen()` is permitted, but it fullscreens only your canvas; do not add a competing button.
- **Memory.** There is no threading or `SharedArrayBuffer` in the portal frame (the portal does not send cross-origin isolation headers), which Phaser does not need.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: `zoko.gameApi.reportChat(report)`, `zoko.gameApi.onScreenshotRequest(handler)` and `zoko.data.mirrorLocalStorage({ prefix: "save_" })`. `ready()` registers a default screenshot provider built on `renderer.snapshot`; pass `screenshots: false` to the plugin config to skip it. The mirror only covers `localStorage`. The simulator accepts all three.

## Test locally

Phaser always runs in a browser, so there is no editor simulator. Serve the game from `localhost` (the starter kit does it with `npm run dev`, port 5173) and the SDK starts in its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second overlay stands in for each ad, banners are dashed boxes, two fake players exist, and cloud saves go to `localStorage`. Two things trip people up:

- A second midgame request within three minutes of the last ad fails with `adCooldown`. That is the real rule, so your game must handle it.
- `submitScore` is accepted and does nothing visible in local mode, and the local token is unsigned.

Add `?sdk_debug=true` to log every call, `?ad_response=unfilled` to force ad failure, and `?user_response=logged_out` to test the guest path. Then open the [Preview tool](https://www.zokogames.com/preview), enter your local address and watch the requirements checklist tick.

## API

### `init`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `init` | `await this.zoko.ready()` |
| `environment` | `this.zoko.environment` |
| `isQaTool` | `this.zoko.isQaTool` |

### `ad.*`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `ad.requestAd` | `this.zoko.requestAd(type)` (pausing) or `this.zoko.ad.requestAd(type, callbacks)` |
| `ad.requestAd.adStarted` | `callbacks.adStarted` of `this.zoko.ad.requestAd(type, callbacks)`; `this.zoko.requestAd(type)` pauses for you |
| `ad.requestAd.adFinished` | `callbacks.adFinished`; `requestAd` resolves `{ finished: true }` |
| `ad.requestAd.adError` | `callbacks.adError(error)`; `requestAd` resolves `{ finished: false, error }` |
| `ad.hasAdblock` | `this.zoko.ad.hasAdblock`() |

### `banner.*`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `banner.requestBanner` | `this.zoko.banner.requestBanner({ id, width, height })` |
| `banner.requestResponsiveBanner` | `this.zoko.banner.requestResponsiveBanner`() |
| `banner.clearBanner` | `this.zoko.banner.clearBanner`() |
| `banner.clearAllBanners` | `this.zoko.banner.clearAllBanners`() |

### `game.*`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `game.settings` | `this.zoko.gameApi.settings` |
| `game.addSettingsChangeListener` | `this.zoko.gameApi.addSettingsChangeListener(fn)` / `this.zoko.events.on("settingsChange", fn)` |
| `game.removeSettingsChangeListener` | `this.zoko.gameApi.removeSettingsChangeListener`() |
| `game.gameplayStart` | `this.zoko.gameApi.gameplayStart`() |
| `game.gameplayStop` | `this.zoko.gameApi.gameplayStop`() |
| `game.loadingStart` | `this.zoko.gameApi.loadingStart()` |
| `game.loadingStop` | `this.zoko.gameApi.loadingStop`() |
| `game.loadingProgress` | `this.zoko.gameApi.loadingProgress(percentage)` |
| `game.happytime` | `this.zoko.gameApi.happytime`() |
| `game.reportGameCompletedPercentage` | `this.zoko.gameApi.reportGameCompletedPercentage`() |
| `game.reportChat` | `zoko.gameApi.reportChat(report)` |
| `game.onScreenshotRequest` | `zoko.gameApi.onScreenshotRequest(handler)` / `zoko.useDefaultScreenshot()` |
| `game.setGameContext` | `this.zoko.gameApi.setGameContext`() |
| `game.clearGameContext` | `this.zoko.gameApi.clearGameContext`() |
| `game.isInstantMultiplayer` | `this.zoko.gameApi.isInstantMultiplayer` |
| `game.isInstantJoin` | `this.zoko.gameApi.isInstantJoin` |
| `game.isOffline` | `this.zoko.gameApi.isOffline` |
| `game.addOfflineListener` | `this.zoko.gameApi.addOfflineListener(fn)` / `this.zoko.events.on("offlineChange", fn)` |
| `game.removeOfflineListener` | `this.zoko.gameApi.removeOfflineListener(fn)` |
| `game.updateRoom` | `this.zoko.gameApi.updateRoom`() |
| `game.leftRoom` | `this.zoko.gameApi.leftRoom`() |
| `game.addJoinRoomListener` | `this.zoko.gameApi.addJoinRoomListener`() |
| `game.removeJoinRoomListener` | `this.zoko.gameApi.removeJoinRoomListener`() |
| `game.inviteParams` | `this.zoko.gameApi.inviteParams` |
| `game.inviteLink` | `this.zoko.gameApi.inviteLink`() |
| `game.getInviteParam` | `this.zoko.gameApi.getInviteParam`() |
| `game.showInviteButton` | `this.zoko.gameApi.showInviteButton(params)` |
| `game.hideInviteButton` | `this.zoko.gameApi.hideInviteButton()` |
| `game.room` | `this.zoko.gameApi.room` |
| `game.room.send` | `this.zoko.gameApi.room.send(data, { to })` |
| `game.room.onMessage` | `this.zoko.gameApi.room.onMessage(cb)` |
| `game.room.addMessageListener` | `this.zoko.gameApi.room.addMessageListener(cb)` |
| `game.room.removeMessageListener` | `this.zoko.gameApi.room.removeMessageListener(cb)` |
| `game.room.setState` | `this.zoko.gameApi.room.setState(patch)` |
| `game.room.getState` | `this.zoko.gameApi.room.getState()` |
| `game.room.onState` | `this.zoko.gameApi.room.onState(cb)` |
| `game.room.addStateListener` | `this.zoko.gameApi.room.addStateListener(cb)` |
| `game.room.removeStateListener` | `this.zoko.gameApi.room.removeStateListener(cb)` |
| `game.room.members` | `this.zoko.gameApi.room.members()` |
| `game.room.onMembers` | `this.zoko.gameApi.room.onMembers(cb)` |
| `game.room.addMembersListener` | `this.zoko.gameApi.room.addMembersListener(cb)` |
| `game.room.removeMembersListener` | `this.zoko.gameApi.room.removeMembersListener(cb)` |
| `game.room.isHost` | `this.zoko.gameApi.room.isHost()` |
| `game.room.onHostChange` | `this.zoko.gameApi.room.onHostChange(cb)` |
| `game.room.addHostChangeListener` | `this.zoko.gameApi.room.addHostChangeListener(cb)` |
| `game.room.removeHostChangeListener` | `this.zoko.gameApi.room.removeHostChangeListener(cb)` |
| `game.room.selfId` | `this.zoko.gameApi.room.selfId` |
| `game.room.onError` | `this.zoko.gameApi.room.onError(cb)` |
| `game.room.addLeftListener` | `this.zoko.gameApi.room.addLeftListener(cb)` |
| `game.room.removeLeftListener` | `this.zoko.gameApi.room.removeLeftListener(cb)` |
| `game.room.addErrorListener` | `this.zoko.gameApi.room.addErrorListener(cb)` |
| `game.room.removeErrorListener` | `this.zoko.gameApi.room.removeErrorListener(cb)` |

### `user.*`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `user.isUserAccountAvailable` | `this.zoko.user.isUserAccountAvailable` |
| `user.systemInfo` | `this.zoko.user.systemInfo` |
| `user.getUser` | `this.zoko.user.getUser`() |
| `user.listFriends` | `this.zoko.user.listFriends`() |
| `user.getUserToken` | `this.zoko.user.getUserToken`() |
| `user.showAuthPrompt` | `this.zoko.user.showAuthPrompt`() |
| `user.addAuthListener` | `this.zoko.user.addAuthListener`() |
| `user.removeAuthListener` | `this.zoko.user.removeAuthListener`() |
| `user.showAccountLinkPrompt` | `this.zoko.user.showAccountLinkPrompt`() |
| `user.submitScore` | `this.zoko.user.submitScore`() |
| `user.getXsollaUserToken` | `this.zoko.user.getXsollaUserToken()` |

### `data.*`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `data.getItem` | `this.zoko.data.getItem(key)` |
| `data.setItem` | `this.zoko.data.setItem(key, value)` |
| `data.removeItem` | `this.zoko.data.removeItem`() |
| `data.clear` | `this.zoko.data.clear`() |
| `data.mirrorLocalStorage` | `zoko.data.mirrorLocalStorage(options)` |

### `store.*`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `store.isAvailable` | `this.zoko.store.isAvailable` |
| `store.getCatalogItems` | `this.zoko.store.getCatalogItems({ limit, offset })` |
| `store.getPlayerInventory` | `this.zoko.store.getPlayerInventory({ limit, offset })` |
| `store.buyItem` | `this.zoko.store.buyItem(itemId)` |
| `store.consumeItem` | `this.zoko.store.consumeItem`() |
| `store.getPurchaseToken` | `this.zoko.store.getPurchaseToken()` |
| `store.setSandbox` | `this.zoko.store.setSandbox`() |

### `achievements.*`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `achievements.list` | `this.zoko.achievements.list()` |
| `achievements.unlock` | `this.zoko.achievements.unlock(key)` |
| `achievements.onUnlock` | `this.zoko.achievements.onUnlock(fn)` |

### `analytics.*`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `analytics.trackOrder` | `this.zoko.analytics.trackOrder`() |
| `analytics.track` | `this.zoko.analytics.track(name, params)` |

### `constants`

<!-- search: headings-only -->

| JavaScript | Phaser |
| --- | --- |
| `ERROR_CODES` | `ZOKO_ERROR_CODES.<module>` |
| `SDK_VERSION` | `this.zoko.version` |

## Known pitfalls

<!-- search: headings-only -->

- **`trackLoading` before `ready()`.** The plugin's loading bridge calls the SDK from the loader's `start` event. If `ready()` has not resolved by then, that call fails with `sdkNotInitialized` (a rejected promise; it no longer throws inside the event handler) and the loading is not reported. Call `await this.zoko.ready()` in a boot scene first, then call `trackLoading(this.load)` in the `init()` of the next scene that loads assets.
- **`sdkNotLoaded`.** The script was blocked or offline and `loadScript` is off or failed. Your game should still start; the starter kit shows the pattern.
- **Calls on a disabled SDK throw `sdkDisabled`.** Check `sdk.environment !== "disabled"` first, as above, or an unhandled rejection reaches your console.
- **Sound stays muted after an ad.** Something else changed `sound.mute` during the ad. The plugin restores the portal's `muteAudio` value, or the value it saw at `adStarted`.
- **`this.zoko` is undefined.** Register the plugin with `mapping: "zoko"`, or extend `withZoko(Phaser.Scene)` and keep the key `ZokoPlugin`.
- **Banner in the wrong place.** `requestBannerAt` converts game coordinates using the configured game size; check your Scale Manager mode.
- **Reward granted twice.** Grant on `finished === true` only, never on the button press.

## Next

- Plain JavaScript with another renderer: [Plain HTML5, Three.js and PixiJS](https://docs.zokogames.com/engines/html5-libraries).
- All engines at a glance: [engines overview](https://docs.zokogames.com/engines/overview).
- Upload: zip the build output with `index.html` at the archive root (`npm run package` in the starter kit does this), then follow the [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/engines/html5-libraries

# Plain HTML5, Three.js and PixiJS

Rendering libraries need no wrapper and there is no plugin folder for them in `packages/sdk-engines`: the browser SDK (`window.ZokoGames.SDK`) is already the integration. What you add is a few lines that connect it to your render loop and audio. The same pattern works for Three.js, PixiJS, Babylon.js, p5.js, Kaboom and a bare `<canvas>`. For Phaser use the [Phaser page](https://docs.zokogames.com/engines/phaser), which has a plugin. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Which path

| You have | Start from |
| --- | --- |
| A finished game in plain JavaScript, no build step | The `html5-minimal` [starter kit](https://docs.zokogames.com/getting-started/starter-kits): one `index.html`, every SDK call commented. Copy the calls you need. |
| A bundled TypeScript game (Vite, Webpack, esbuild) | The `html5-vite-ts` starter kit: `src/zoko-sdk.d.ts` (types for `window.ZokoGames.SDK`) and `src/zoko.ts` (a safe wrapper). |
| Three.js, PixiJS, Babylon.js or similar | This page: the adapter, then the tab for your library. |

## 1. Load the SDK first

Put the script before your bundle so `window.ZokoGames` exists when your code runs. Keep the exact URL: the upload validator looks for it, and a bundled copy is flagged (`sdk_bundled`).

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script type="module" src="./main.js"></script>
```

With a bundler, set the public base to a relative path (`base: "./"` in Vite) so every asset URL is relative. See [technical requirements](https://docs.zokogames.com/requirements/technical#relative-paths-only).

## 2. A small adapter

Wrap the SDK once so the game also runs when the SDK is missing or `disabled`, and so one failing call never breaks a frame. `SDK.init()` never rejects; when the environment is `disabled`, every other call throws `sdkDisabled`, which the adapter swallows.

```js
const SDK = window.ZokoGames?.SDK;           // undefined when the script was blocked
let online = false;

export async function startPlatform() {
  if (!SDK) return;
  await SDK.init();
  online = SDK.environment !== "disabled";   // "local", "zokogames" or "disabled"
}

export function call(fn, fallback = null) {
  if (!online) return Promise.resolve(fallback);
  return Promise.resolve().then(fn).catch((e) => { console.warn("sdk", e.code); return fallback; });
}
```

## 3. A complete working example (plain canvas)

This covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, a leaderboard score, settings and audio unlock. Library-specific pause code follows in section 4.

```js
let running = false, inAd = false;
let audioCtx;                                   // created on the first input (audio unlock)

function setMuted(m) { if (m) audioCtx?.suspend(); else audioCtx?.resume(); }   // the portal's mute, applied to your audio

function unlockAudio() {
  audioCtx ??= new AudioContext();
  setMuted(online && SDK.game.settings.muteAudio);   // resumes the context unless the portal has muted the game
  removeEventListener("pointerdown", unlockAudio);
  removeEventListener("keydown", unlockAudio);
}
addEventListener("pointerdown", unlockAudio);   // browsers keep audio suspended until a gesture
addEventListener("keydown", unlockAudio);

// Pause on adStarted; resume on adFinished AND adError. Resolves true only when the ad finished.
function showAd(type) {
  if (!online) return Promise.resolve(false);
  let finished = false;
  let wasRunning = false;
  const pause = () => { inAd = true; wasRunning = running; running = false; audioCtx?.suspend(); };
  const resume = () => {
    if (!inAd) return;
    inAd = false; running = wasRunning;   // a midgame ad at game over must not restart the loop
    if (!SDK.game.settings.muteAudio) audioCtx?.resume();
  };
  return SDK.ad.requestAd(type, {
    adStarted: pause,
    adFinished: () => { finished = true; resume(); },
    adError: (e) => { console.log("no ad:", e.code); resume(); },   // adCooldown, unfilled, adblock ...
  }).then(() => finished, () => { resume(); return false; });       // throws (for example sdkDisabled) instead of adError
}

async function boot() {
  await startPlatform();
  if (online) {
    await call(() => SDK.game.loadingStart());
    state.best = Number(SDK.data.getItem("best") ?? "0") || 0;      // load: synchronous after init
    await loadAssets();
    await call(() => SDK.game.loadingStop());
    SDK.game.addSettingsChangeListener((s) => { if (!inAd) setMuted(s.muteAudio); });   // an ad in progress keeps the sound off
  } else {
    await loadAssets();
  }
  showMenu();
}

function startRound() {                          // the player takes control: now, not at page load
  running = true;
  call(() => SDK.game.gameplayStart());
}

async function endRound(score) {
  running = false;
  call(() => SDK.game.gameplayStop());
  if (score > state.best) {                      // save
    state.best = score;
    try { if (online) SDK.data.setItem("best", String(score)); } catch (e) { console.warn(e.code); }  // dataLimitExceeded
  }
  await submitScore(score);                      // leaderboard
  await showAd("midgame");                       // natural break; then show the results screen
  showResults(score);
}

async function onRewardButton() {
  if (await showAd("rewarded")) grantReward();   // reward only after adFinished
}

addEventListener("visibilitychange", () => {     // a hidden tab is not play time
  if (document.hidden && running) call(() => SDK.game.gameplayStop());
  else if (!document.hidden && running) call(() => SDK.game.gameplayStart());
});
```

The leaderboard call. Only signed-in players are ranked; a score that breaks a board rule is dropped silently while the call still resolves. The `encryptScore` helper is on the [leaderboards page](https://docs.zokogames.com/sdk/leaderboards#client-submission); without an encryption key on the board, pass an empty string.

```js
async function submitScore(score) {
  const user = await call(() => SDK.user.getUser());
  if (!user) return;                             // guests are not ranked
  const encryptedScore = BOARD_KEY
    ? await encryptScore(score, BOARD_KEY, user.__dangerousUserId, GAME_ID)   // fresh payload per submit
    : "";
  await call(() => SDK.user.submitScore({ encryptedScore, score }));
}
```

## 4. Pause, mute and resume by library

<!-- search: headings-only -->

Pause what you own: the render loop, your clock, physics and audio. The loop must keep running only if it is a cheap "paused" screen. The `showAd` helper above works for any library once `pause` and `resume` call your library's own switches.

:::tabs
== Three.js
```js
import * as THREE from "three";

const renderer = new THREE.WebGLRenderer({ canvas });
const timer = new THREE.Timer();                // THREE.Clock is deprecated since r183 and logs a warning
let paused = false;

renderer.setAnimationLoop(() => {
  if (paused) return;
  timer.update();
  const dt = Math.min(timer.getDelta(), 0.1);   // clamp so a long pause does not teleport anything
  world.update(dt);
  renderer.render(scene, camera);
});

function setLibMuted(m) { listener.setMasterVolume(m ? 0 : 1); }
function setPaused(p) {
  paused = p;
  if (!p) timer.reset();                        // drop the time spent paused
  setLibMuted(p || (online && SDK.game.settings.muteAudio)); // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).
```
== PixiJS
```js
import { Application } from "pixi.js";
import { sound } from "@pixi/sound";            // PixiJS's audio library; it has its own AudioContext

const app = new Application();
await app.init({ resizeTo: window, resolution: Math.min(devicePixelRatio, 2), autoDensity: true });
document.body.append(app.canvas);

function setLibMuted(m) { if (m) sound.muteAll(); else sound.unmuteAll(); }
function setPaused(p) {
  app.ticker[p ? "stop" : "start"]();
  if (p) sound.pauseAll(); else sound.resumeAll();
  setLibMuted(p || (online && SDK.game.settings.muteAudio)); // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).
```
== Babylon.js
```js
import { Engine, Scene, CreateAudioEngineAsync } from "@babylonjs/core";

const engine = new Engine(canvas, true);
const scene = new Scene(engine);
const audio = await CreateAudioEngineAsync();   // the audio engine unlocks itself on the first input
let paused = false;

// Keep the loop registered while paused: Babylon measures frame time inside it, so a stopped loop
// would hand the scene one huge delta on resume (animations and physics jump).
engine.runRenderLoop(() => { if (!paused) scene.render(); });

function setLibMuted(m) { audio.volume = m ? 0 : 1; }
function setPaused(p) {
  paused = p;
  if (p) audio.pauseAsync(); else audio.resumeAsync();
  setLibMuted(p || (online && SDK.game.settings.muteAudio));   // keep the portal's mute
}
// In showAd: call setPaused(true) in pause and setPaused(false) in resume. In setMuted (section 3): add setLibMuted(m).
```
== Plain canvas
```js
let last = 0;
function frame(t) {
  if (running) {
    update(Math.min((t - last) / 1000, 0.1));
    draw();
  }
  last = t;
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
// showAd above already flips `running` and suspends the AudioContext.
```
:::

## Multiplayer, achievements and purchases

These need no adapter. Call `SDK.game.room` (the room data channel, SDK 1.3.0; `undefined` on older SDKs), `SDK.achievements` and `SDK.store` directly, behind the same `call` helper. See the [game module](https://docs.zokogames.com/sdk/game#room-data-channel), [achievements](https://docs.zokogames.com/sdk/achievements) and [in-game purchases](https://docs.zokogames.com/sdk/purchases).

## 5. Sizing

The game lives in a frame of unknown size that changes with fullscreen and rotation. Size the canvas from the window, not from constants:

```js
function resize() {
  const mobile = online && SDK.user.systemInfo.device.type === "mobile";
  const dpr = Math.min(window.devicePixelRatio, mobile ? 1 : 2);
  renderer.setPixelRatio(dpr);              // Three.js; PixiJS uses the `resolution` option
  renderer.setSize(innerWidth, innerHeight, false);
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
}
addEventListener("resize", resize);
resize();
```

Read `SDK.user.systemInfo` only after `init()` and only when the SDK is not disabled (it throws otherwise). Capping `devicePixelRatio` at 1 on phones avoids running out of memory; details are in [optimisation tips](https://docs.zokogames.com/guides/optimisation) and the [mobile guide](https://docs.zokogames.com/guides/mobile).

## Export settings that matter on the web

- **Relative paths only**, and `index.html` at the archive root.
- **Ship plain files.** Your page requests plain names, so do not rename assets to `.br` or `.gz`. The game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but it works only for requests of those exact names. The initial-download estimate uses uncompressed sizes: minify, tree-shake, and use WebP or Basis/KTX2 textures. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile). See [first frame fast](https://docs.zokogames.com/guides/first-frame).
- **Audio unlock.** Create or resume your `AudioContext` from a pointer or key event, as above; resume it again after an ad, and honour `SDK.game.settings.muteAudio`.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so `canvas.requestFullscreen()` works from an input event, but it fullscreens only your canvas; do not add a competing button.
- **Memory.** Dispose textures and geometry when a level unloads (`texture.dispose()` in Three.js, `destroy()` in PixiJS). No threads or `SharedArrayBuffer` are available in the portal frame (it sends no cross-origin isolation headers), so avoid libraries that require them.

## Test locally

Serve the folder from `localhost` (any static server, for example `npx http-server . -p 8080`). The SDK then starts in its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second overlay for each ad, fake players, a `localStorage` cloud save, a test store. Things to try:

- `?sdk_debug=true` logs every call; `?ad_response=unfilled` forces ad failure; `?user_response=logged_out` tests the guest path.
- A second midgame ad within three minutes fails with `adCooldown`: the real rule, so your game must handle it.
- `submitScore` is accepted and does nothing visible; the local token is unsigned.
- Open the game from `file://` or another host without `?useLocalSdk=true` to see the `disabled` path: the game must still play.

Then open the [Preview tool](https://www.zokogames.com/preview), enter your local address, and watch the requirements checklist tick.

## Checklist for library games

<!-- search: headings-only -->

- [ ] SDK script loaded before the game script and every path relative.
- [ ] Game runs when `SDK` is `undefined` or `SDK.environment` is `"disabled"`.
- [ ] Render loop, clock and audio pause on `adStarted` and resume on both `adFinished` and `adError`.
- [ ] Rewards granted only after `adFinished`.
- [ ] Time deltas are clamped so a long pause does not teleport anything.
- [ ] `SDK.game.settings.muteAudio` is applied at start and on change.
- [ ] `gameplayStart` at first player control, `gameplayStop` at game over, pause and tab hidden.
- [ ] Canvas resizes with the window and caps `devicePixelRatio`.
- [ ] Textures and geometry are disposed when a level unloads.
- [ ] Tested in the [Preview tool](https://www.zokogames.com/preview).

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/engines/unity

# Unity

The Unity package `com.zokogames.sdk` (Unity 2021.3 or newer, WebGL builds) wraps the JavaScript SDK in one static class, `ZokoGames.ZokoSDK`. Every asynchronous method has a callback form and an `...Async` form returning a `Task`. Cloud save (`Data`), `Store.IsAvailable`, `Store.SetSandbox`, `Game.Settings` and `Game.InviteParams` are synchronous. Terms such as "midgame ad" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (plugin 1.7.0, run on 2026-11-23): built and run with Unity 6000.3.28f1. The published package compiles with no warnings, and a WebGL build ran in local mode and on the production portal (console Preview), passing all 12 areas. Store purchases, two-player rooms, the sign-in prompt, kids mode, offline and mobile browsers are not tested yet. Unity 2021.3 to 2023 are only compiled with a real C# compiler against stubs of the Unity API. If something fails on import, send the Unity version and the exact error to [support](https://docs.zokogames.com/business/support).

## Install

Download the Unity plugin: [/sdk-engines/zokogames-unity-1.7.0.zip](https://www.zokogames.com/sdk-engines/zokogames-unity-1.7.0.zip) (the same files as the folder in the repository).

[/sdk-engines/unity.zip](https://www.zokogames.com/sdk-engines/unity.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. **Window > Package Manager > Add package from disk**, then choose `package.json` from the plugin folder (`packages/sdk-engines/unity/package.json`, or the same file inside the unzipped packager output, see the [overview](https://docs.zokogames.com/engines/overview#getting-the-plugin)). Copying the folder into your project's `Packages/` folder (an embedded package) also works. From 1.6.1 every file ships with its `.meta` file, so the package should also import from your own git repository or a tarball, which Unity treats as read-only (not yet tried in an editor). The package depends on `com.unity.ugui`, which new Unity projects already include.
2. Run **ZokoGames > Install WebGL Template**. It copies the template to `Assets/WebGLTemplates/ZokoGames` and sets Player Settings to `PROJECT:ZokoGames`. The template loads `https://sdk.zokogames.com/zokogames-sdk-v1.js` before the Unity loader, reports the engine download to the portal's loading bar (`loadingStart`, `loadingProgress`, `loadingStop`) and keeps the canvas id `unity-canvas`. With your own template, add the script tag to `<head>` before the Unity loader and keep that canvas id.
3. Optional: **ZokoGames > Create Simulator Settings** creates `Assets/Resources/ZokoSDKSettings.asset` to tune the editor simulator.
4. Optional: import the **Demo** sample from the Package Manager (`ZokoDemo.cs` touches every module with one key per module; `ZokoStoreExample.cs` is a purchase flow: catalogue, buy, consume, inventory, error codes).

The bridge is `Plugins/WebGL/ZokoSDK.jslib`. It calls the JavaScript SDK and answers a hidden `ZokoSDKBridge` GameObject through `SendMessage`, so leave the `.jslib` in `Plugins/WebGL/` and do not rename that GameObject.

## Which path

| You are | Do this |
| --- | --- |
| A WebGL studio with a shipping game | Install the package and template, call `InitAsync` first, wrap your existing ad, save and score calls in `ZokoSDK`, set Brotli, upload. |
| Starting a game for the portal | Same, and keep the first scene under the [initial download limit](https://docs.zokogames.com/guides/first-frame); load the rest with Addressables. |

## A working boot script

One MonoBehaviour that covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score. Put it in your first scene.

```csharp
using UnityEngine;
using ZokoGames;

public class ZokoBoot : MonoBehaviour
{
    float _savedTimeScale = 1f;
    bool _adPaused;

    async void Start()
    {
        try { await ZokoSDK.InitAsync(); }                 // throws ZokoException when the SDK script is missing
        catch (ZokoException e) { Debug.LogWarning("ZokoGames init failed: " + e.Code); }

        // Environment is "local", "zokogames" or "disabled"; IsSimulated is true in the editor.
        Debug.Log("ZokoGames: " + ZokoSDK.Environment + (ZokoSDK.IsSimulated ? " (simulated)" : ""));
        if (!ZokoSDK.IsAvailable) { StartGame(); return; }  // the game must run without the portal

        // Audio needs no code: the SDK applies the portal's mute (Ad.FollowPortalMute) and mutes during ads (Ad.MuteAudioDuringAds).

        int level = ZokoSDK.Data.GetInt("level", 1);        // load: synchronous, after Init only
        StartGame();
    }

    // Call when the player takes control, and when play stops (pause menu, game over, level end).
    public void OnPlayStart() { if (ZokoSDK.IsAvailable) ZokoSDK.Game.GameplayStart(); }
    public void OnPlayStop()  { if (ZokoSDK.IsAvailable) ZokoSDK.Game.GameplayStop(); }

    // Pause on adStarted, resume on adFinished AND adError. RequestAdAsync never throws.
    public async void ShowMidgame() { await ShowAd(ZokoAdType.Midgame); }

    public async void OnRewardButton()
    {
        bool finished = await ShowAd(ZokoAdType.Rewarded);
        if (finished) GrantReward();                        // reward only after adFinished
    }

    async System.Threading.Tasks.Task<bool> ShowAd(ZokoAdType type)
    {
        if (!ZokoSDK.IsAvailable) return false;
        ZokoError error = await ZokoSDK.Ad.RequestAdAsync(type, adStarted: PauseForAd);
        ResumeAfterAd();                                    // runs for finished, unfilled, adCooldown, adblock ...
        if (error != null) Debug.Log("no ad: " + error.Code);
        return error == null;
    }

    void PauseForAd()
    {
        if (_adPaused) return;
        _adPaused = true;
        _savedTimeScale = Time.timeScale;
        Time.timeScale = 0f;
    }

    void ResumeAfterAd()
    {
        if (!_adPaused) return;
        _adPaused = false;
        Time.timeScale = _savedTimeScale;
    }

    // Save: synchronous against a preloaded copy; uploads are batched.
    public void SaveProgress(int level)
    {
        ZokoSDK.Data.SetInt("level", level);
        if (ZokoSDK.Data.LastError != null) Debug.LogWarning(ZokoSDK.Data.LastError.Code); // e.g. dataLimitExceeded
    }

    // Leaderboard: needs a signed-in player and the board enabled in the console.
    public void SubmitScore(double score)
    {
        ZokoSDK.User.GetUser((user, err) =>
        {
            if (err != null || user == null) return;        // guests are not ranked
            ZokoSDK.User.SubmitScore("", score, e => { if (e != null) Debug.Log(e.Code); });
        });
    }

    void StartGame() { }
    void GrantReward() { }
}
```

You do not write audio code for the portal. The SDK mutes `AudioListener` while an ad plays and restores it afterwards (`ZokoSDK.Ad.MuteAudioDuringAds`), and applies the portal's mute setting to `AudioListener.pause` after init and on every change (`ZokoSDK.Ad.FollowPortalMute`); both are on by default. Set `FollowPortalMute` to `false` before `Init` if you want to handle `Game.SettingsChanged` yourself. Pausing the game itself (`Time.timeScale` above) stays your job.

About the leaderboard line: `SubmitScore(encryptedScore, score)` sends whatever string you give it. A board **with** an encryption key counts only a correctly encrypted payload (see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), and no engine wrapper ships an encryption helper, so the empty string above works only for a board **without** a key (the plain score is then validated against the board rules). For a keyed board, either encrypt in C# yourself (AES-256-GCM with the additional data `zoko-score-v1|<userId>|<gameId>`, where `ZokoUser.UserId` holds the player id; check that your Unity version has an AES-GCM implementation that works in WebGL) or compute scores on your own server and use the server API.

## Initialise and state

| Member | Meaning |
| --- | --- |
| `ZokoSDK.Init(cb)` / `InitAsync()` | Once, first. Safe to call repeatedly. Other calls before it finishes fail with `sdkNotInitialized`; if the call itself fails (for example `sdkNotLoaded`) the SDK stays uninitialised. |
| `ZokoSDK.IsInitialized` | `Init` completed. |
| `ZokoSDK.IsAvailable` | Initialised and not `disabled`. |
| `ZokoSDK.Environment` | `"local"`, `"zokogames"` or `"disabled"`. |
| `ZokoSDK.IsQaTool` | Running in the QA tool. |
| `ZokoSDK.Version` | The JavaScript SDK release the wrapper was written against. The published package (1.7.0) reports `"1.7.0"`. Plugin versions are separate from the SDK version, and the plugins are repacked at the next plugin release. |
| `ZokoSDK.IsSimulated` | The editor or native simulator is answering (the build is not a WebGL player). |

## Mapping

<!-- search: headings-only -->

| Module | JavaScript | Unity |
| --- | --- | --- |
| Ad | `ad.requestAd(type, cbs)` | `Ad.RequestAd(ZokoAdType.Midgame, adStarted, adFinished, adError)` or `Ad.RequestAdAsync(type, adStarted)` |
| Ad | `ad.hasAdblock()` | `Ad.HasAdblock(cb)` / `Ad.HasAdblockAsync()` |
| Banner | `banner.requestBanner({id,width,height})` | `Banner.RequestBanner(id, w, h, screenRect, done)` or the `ZokoBanner` component |
| Banner | `banner.requestResponsiveBanner(id)` | `Banner.RequestResponsiveBanner(id, screenRect, done)` |
| Banner | `clearBanner`, `clearAllBanners` | `Banner.ClearBanner(id)`, `Banner.ClearAllBanners()` |
| Game | `game.gameplayStart/Stop` | `Game.GameplayStart()`, `Game.GameplayStop()` |
| Game | `loadingStart/Stop`, `loadingProgress(0..100)`, `happytime` | `Game.LoadingStart()`, `Game.LoadingStop()`, `Game.LoadingProgress(percentage)`, `Game.Happytime()` |
| Game | `reportGameCompletedPercentage` | `Game.ReportGameCompletedPercentage(float)` |
| Game | `setGameContext`, `clearGameContext` | `Game.SetGameContext(IDictionary<string, object>)`, `Game.ClearGameContext()` |
| Game | `settings`, listener | `Game.Settings`, event `Game.SettingsChanged` |
| Game | `isOffline`, offline listeners | `Game.IsOffline`, event `Game.OfflineChanged` (`Action<bool>`) |
| Game | rooms and invites | `Game.UpdateRoom(ZokoRoomUpdate)`, `Game.LeftRoom()`, `Game.InviteLink(params, cb)`, `Game.ShowInviteButton(params, cb)`, `Game.HideInviteButton()`, `Game.InviteParams`, `Game.GetInviteParam(key)`, `Game.IsInstantMultiplayer` (alias `IsInstantJoin`), event `Game.JoinRoom` |
| User | `getUser` | `User.GetUser(cb)` / `User.GetUserAsync()` |
| User | `listFriends({page,size})` | `User.ListFriends(page, size, cb)` |
| User | `getUserToken` | `User.GetUserToken(cb, ZokoSigningKeyType)` |
| User | `showAuthPrompt`, listener | `User.ShowAuthPrompt(cb)`, event `User.AuthChanged` |
| User | `showAccountLinkPrompt` | `User.ShowAccountLinkPrompt(cb)` (calls back `true` for yes) |
| User | `systemInfo`, `isUserAccountAvailable` | `User.SystemInfo`, `User.IsUserAccountAvailable` |
| User | `submitScore` | `User.SubmitScore(encryptedScore, score, done)` / `SubmitScoreAsync` |
| Data | `getItem` ... `clear` | `Data.GetItem/SetItem/RemoveItem/Clear`, plus `GetString/SetString/GetInt/SetInt/GetFloat/SetFloat/HasKey/DeleteKey/DeleteAll` |
| Store | `store.isAvailable`, `getCatalogItems`, `getPlayerInventory` | `Store.IsAvailable`, `Store.GetCatalogItemsAsync(limit, offset)`, `Store.GetPlayerInventoryAsync(limit, offset)` |
| Store | `buyItem`, `consumeItem`, `setSandbox` | `Store.BuyItemAsync(sku)`, `Store.ConsumeItemAsync(sku, qty)`, `Store.SetSandbox(bool)` |
| Store | `getPurchaseToken` (`user.getXsollaUserToken` is the deprecated name) | `Store.GetPurchaseTokenAsync()` |
| Errors | `ERROR_CODES` | `ZokoErrorCodes.Store.PurchaseCancelled` etc.; `ZokoError.Is(code)` |
| Achievements | `achievements.list()`, `achievements.unlock(key)`, `onUnlock` | `Achievements.List(cb)`, `Achievements.Unlock(key, cb)` (or `...Async`), event `Achievements.OnUnlock`; see [achievements](https://docs.zokogames.com/sdk/achievements) |
| Analytics | `trackOrder(provider, order)` | `Analytics.TrackOrder(provider, order, done)` |
| Analytics | `track(name, params)` (1.7.0) | `Analytics.Track(name, params, done)` |

Errors arrive as `ZokoError` (`Code`, `Message`, `ContainerId`). The `...Async` methods throw `ZokoException` (`Error`, `Code`). `RequestAdAsync` never throws: it returns `null` when the ad finished and the error otherwise.

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `ZokoSDK.Game.Settings.KidsMode` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `ZokoSDK.Game.Settings.DisableChat`, which the portal sets to true in the same cases. To test it, switch on `ZokoSDKSettings.kidsMode` in the simulator (it also turns chat off, as the portal does). See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

`ZokoSDK.Game.Room` carries it. Pass a `Dictionary`, a `List`, a string, a number or a bool, a JSON string (`SendJson`) or a `[Serializable]` object (`SendTyped<T>`, which uses `JsonUtility`). Events are raised on the main thread. In the editor and in non-WebGL players the simulator is one room with one member that receives its own messages and state changes, so a single instance can run the flow.

| JavaScript | Unity |
| --- | --- |
| `room.send(data, { to })` | `Game.Room.Send(data, done)`, `SendTo(memberId, data, done)`, `SendJson(json, to, done)`, `SendTyped<T>(obj, to, done)`, `SendAsync(data, to)` |
| `room.onMessage(cb)` | event `Game.Room.MessageReceived` (`ZokoRoomMessage`: `From`, `Direct`, `Seq`, `Ts`, `Data`, `Json`, `As<T>()`) |
| `room.setState(patch)` | `Game.Room.SetState(patch, done)`, `SetState(key, value, done)`, `SetStateJson(json, done)`, `SetStateAsync(patch)` |
| `room.getState()`, `room.onState(cb)` | `Game.Room.State`, `GetState(key)`, `GetState<T>()`, `GetStateJson()`; event `StateChanged(state, ZokoRoomStateChange)` |
| `room.members()`, `room.onMembers(cb)` | `Game.Room.Members` (`ZokoRoomMember`: `Id`, `Username`, `ProfilePictureUrl`); event `MembersChanged` |
| `room.isHost()`, `room.onHostChange(cb)`, `room.selfId` | `Game.Room.IsHost`; event `HostChanged(hostId, isHost)`; `Game.Room.SelfId` |
| `room.addLeftListener(cb)` (1.7.0) | event `Game.Room.Left(reason, roomId)` |
| `room.onError(cb)` | event `Game.Room.Error` (`ZokoError`); codes in `ZokoErrorCodes.Room` |

```csharp
[System.Serializable] class Move { public int cell; public string mark; }

async void StartMatch()
{
    await ZokoSDK.InitAsync();
    ZokoSDK.Game.Room.MessageReceived += m => Board.Place(m.As<Move>());
    ZokoSDK.Game.Room.HostChanged += (hostId, isHost) => { if (isHost) ZokoSDK.Game.Room.SetState("turn", "X"); };
    ZokoSDK.Game.Room.Error += e => Debug.LogWarning("room: " + e);
    await ZokoSDK.Game.UpdateRoomAsync(new ZokoRoomUpdate { RoomId = "match-1", IsJoinable = true });
}

void OnCellClicked(int cell) => ZokoSDK.Game.Room.SendTyped(new Move { cell = cell, mark = "X" });
```

## Banners

Add **Add Component > ZokoGames > Zoko Banner** to a UI `RectTransform`. Set `containerId`, choose a `size` (`Responsive`, `S728x90`, `S300x250`, `S320x50`, `S468x60` or `S320x100`) and leave `requestOnEnable` on. The component reports its on-screen rectangle to the portal, which draws the banner over the canvas; disabling the object clears the banner. Request banners on menu screens, never in play.

```csharp
ZokoSDK.Banner.RequestResponsiveBanner("menu", GetComponent<ZokoBanner>().GetScreenRect(), err =>
{
    if (err != null) Debug.Log(err.Code);
});
```

## Purchases

```csharp
if (ZokoSDK.Store.IsAvailable)
{
    try
    {
        var catalog = await ZokoSDK.Store.GetCatalogItemsAsync(limit: 20);
        string bought = await ZokoSDK.Store.BuyItemAsync(catalog[0].Sku);
        string token = await ZokoSDK.Store.GetPurchaseTokenAsync();   // send to your server and verify there
    }
    catch (ZokoException e) when (e.Error.Is(ZokoErrorCodes.Store.PurchaseCancelled)) { }
}
```

Verify ownership on your server (see [in-game purchases](https://docs.zokogames.com/sdk/purchases)). The sample `ZokoStoreExample` is the full flow.

## Addressables and custom builds

Keep the first scene small and load the rest after the player can act. Addressables work on the portal under three rules.

1. **Ship the content inside the build.** Set the Addressables **Build Path** to a folder under `StreamingAssets` (for example `Assets/StreamingAssets/aa`, which is the default "local" group) and the **Load Path** to `{UnityEngine.AddressableAssets.Addressables.RuntimePath}`. The bundles then travel in the zip and are served from the same build folder, with relative paths. Do not point the remote load path at another host: the validator reports external hosts (`external_url`, `origin_unknown`) and a game that needs one cannot be saved for [offline play](https://docs.zokogames.com/guides/offline-play).
2. **Count the files.** Every bundle is a file in the 1,500 file budget and counts toward 250 MB. Group assets by scene or level, not one bundle per asset, and keep bundle names to ASCII with consistent letter case (the host is case sensitive, see [relative paths](https://docs.zokogames.com/requirements/technical#relative-paths-only)).
3. **Load after the first frame.** Call `Game.LoadingStart()` and `LoadingProgress(p)` from your own loading screen while `Addressables.LoadSceneAsync` runs, then `LoadingStop()` when the player can act. Only the first scene counts toward the [initial download](https://docs.zokogames.com/guides/first-frame).

A custom WebGL template works if it keeps the canvas id `unity-canvas` and loads `https://sdk.zokogames.com/zokogames-sdk-v1.js` before the Unity loader (see Install). Copy the ZokoGames template and edit it rather than starting from the default one. A custom build script (for example a CI job calling `BuildPipeline.BuildPlayer`) only has to set the same options as the table below and write the result to a folder you zip with `index.html` at the archive root.

## Common issues

<!-- search: headings-only -->

| Symptom | Cause and fix |
| --- | --- |
| Blank canvas, console shows `SharedArrayBuffer is not defined` | A multithreaded build. Turn WebGL threading off and rebuild (see **Threading** in the table below). |
| Loader stops at "Unable to parse Build/....framework.js.br" | A `.br` file served without `Content-Encoding`, usually a local static server. Test on `localhost` with a server that sends the header, or build with compression Disabled for local tests. On the portal the header is set for you. |
| 404 for a file that exists on your disk | Letter case differs from the reference (`case_mismatch`). Names are case sensitive on the host. |
| Works in the Editor, `sdkNotLoaded` in the build | The WebGL template is not ZokoGames. Run **ZokoGames > Install WebGL Template** and rebuild. |
| Save data lost between sessions | You wrote to `PlayerPrefs` only. In a WebGL player it lives in the browser's IndexedDB for that origin. Mirror the keys into cloud save with `ZokoSDK.Data.PushPlayerPrefs` and restore them with `PullPlayerPrefs` right after `InitAsync`. |
| Copy button does nothing | Browsers allow copying only from a click or tap handler. Call `ZokoSDK.CopyToClipboard(text)` there, not from `Update()` or after an `await`. |
| Out-of-memory crash on phones | The initial memory is too large or one texture or bundle is huge. Lower the initial memory, compress textures (ASTC), load content in pieces with Addressables. |

## PlayerPrefs mirror and clipboard

`PlayerPrefs` cannot tell the type of a key, so you list the keys and their types once:

```csharp
static readonly Dictionary<string, ZokoPrefType> Keys = new Dictionary<string, ZokoPrefType>
{
    { "playerName", ZokoPrefType.String },
    { "level", ZokoPrefType.Int },
    { "volume", ZokoPrefType.Float },
};

// After InitAsync: bring cloud save into PlayerPrefs (a key already there is kept; pass true to let cloud save win).
ZokoSDK.Data.PullPlayerPrefs(Keys);

// When the player saves or a level ends: copy PlayerPrefs into cloud save.
ZokoSDK.Data.PushPlayerPrefs(Keys);

// From a click handler: copy an invite code.
bool copied = ZokoSDK.CopyToClipboard(inviteCode);
```

Both calls skip keys that do not exist and return how many keys they moved. They respect the 1 MB cloud save limit like every other `Data` call (check `ZokoSDK.Data.LastError`).

## WebGL export settings that matter

<!-- search: headings-only -->

| Setting | What to choose, and why |
| --- | --- |
| Player Settings > Publishing Settings > **Compression Format** | **Brotli** or **Gzip**. Unity then writes `.br` or `.gz` files. The game origin gives any `.br` or `.gz` file the matching `Content-Encoding` header, so the browser decodes it and the Unity loader needs no JavaScript decompression. Use one format for the whole build. |
| **Decompression Fallback** | Leave **off**. It is for hosts that cannot set `Content-Encoding`; the portal can, and the fallback makes the loader larger and slower. |
| Compression **Disabled** | Works, but the download is larger. |
| Legacy `.unityweb` files | Avoid them. They get no `Content-Encoding`, so the loader unpacks them in JavaScript and the game starts slower (validator warning `unity_unityweb`). Mixing `.br` and `.gz` or leaving some Build files uncompressed also warns (`unity_mixed_compression`, `unity_compression_mismatch`). |
| Resolution and Presentation > **WebGL Template** | **ZokoGames**. The canvas fills the frame (CSS 100 percent), so use a Canvas Scaler set to **Scale With Screen Size**, not a fixed pixel size. |
| Other Settings | Managed Stripping Level High, Strip Engine Code on, IL2CPP "Faster (smaller) builds", ASTC for mobile or DXT textures. Avoid unused packages and large StreamingAssets. |
| **Memory** | The portal frame limits what a phone can allocate. Keep the initial memory small and let it grow; load big content through Addressables after the first scene. Unity games are off on iOS by default (tick **Tested and works well on iOS** in the console only after testing, see [mobile](https://docs.zokogames.com/guides/mobile)). |
| **Threading** | Off. Game pages are served without COOP/COEP headers, so the page is not cross-origin isolated and `SharedArrayBuffer` is unavailable; a threaded WebAssembly build cannot run. Disable multithreading (WebGL threading, and native C/C++ threads in plugins). A threaded build shows `SharedArrayBuffer is not defined` or a blank canvas. |
| Download budget | 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile). The estimate uses the uncompressed size, so compression does not rescue an oversized build. |

Other export notes:

- **Audio unlock.** Browsers keep WebAudio suspended until the first click, tap or key press. Unity resumes it on the first input, so show a "tap to play" screen before music instead of starting audio in `Start()`.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar: it fullscreens the whole frame (the portal keeps its own bar and handles phone orientation). The frame carries `allow="fullscreen"`, so `Screen.fullScreen = true` is permitted, but it fullscreens the game's own canvas and the portal cannot restore its layout the same way; do not add a competing button.
- **Single thread.** Never use `Task.Wait()` or `.Result` on WebGL: it deadlocks. `await` and the callback forms are fine.
- **Loading.** The template already reports the engine download. For your own first scene call `Game.LoadingStart()`, `LoadingProgress(p)` and `LoadingStop()` when the player can act.

Upload: build for WebGL, zip the **contents** of the build folder so `index.html` is at the archive root, and upload it in the developer console. Run the [Preview tool](https://www.zokogames.com/preview) first.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0 the wrapper binds three more calls.

```csharp
ZokoSDK.Game.ReportChat(new ZokoChatReport { ReportedName = "Trixie", Message = "buy gold", Reason = ZokoChatReportReason.Spam, RoomId = roomId }, err => { });
ZokoSDK.Game.SetScreenshotProvider(() => MyCamera.RenderToTexture()); // optional; a default end-of-frame capture is registered at init
ZokoSDK.Data.MirrorLocalStorage(prefix: "save_");                      // only for JavaScript-side localStorage
```

`ReportChat` sends one message to the portal's moderators (name 1 to 40 characters, message 1 to 500); it fails with `invalidArgument`, `rateLimited` or `unexpectedError`. The screenshot provider returns a `Texture2D` (or null for no picture) when the portal's feedback form asks; the wrapper encodes it as JPG and answers within the SDK's 3 second limit. Unity `PlayerPrefs` on WebGL live in IndexedDB, not `localStorage`, so the mirror never sees them: use `Data.PushPlayerPrefs` for those. In the editor all three calls run against the simulator.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`ZokoAdType.Midgame`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with the error code `adCooldown` (your `RequestAdAsync` returns it) until your game has called `ZokoSDK.Game.GameplayStart()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `ZokoSDK.Game.GameplayStart()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **In the Editor and in any non-WebGL player** the built-in simulator answers (`ZokoSDK.IsSimulated` is true), so Play mode works. Tune it in `ZokoSDKSettings`: simulate a disabled SDK, ad behaviour (Fill, NoFill, Error), ad duration (default 1.5 seconds), an adblocker, a logged-out player, friend count, mute and chat, offline, and store availability. Simulated cloud save lives in `PlayerPrefs` under `zoko-sdk-sim-data`; **ZokoGames > Clear Simulated Cloud Save** wipes it. Calls always answer asynchronously, like the browser.
- **Difference to remember.** The simulator does not enforce the three-minute midgame cooldown that the portal and the browser's local mode enforce (`adCooldown`), and it only logs banner requests. Test both in a web build.
- **A WebGL build on `localhost`.** Serve the build folder from a local web server on `localhost`; the SDK then runs its own [local mode](https://docs.zokogames.com/getting-started/local-testing) (a three-second overlay per ad, fake players, `localStorage` saves, a test store, `?sdk_debug=true`, `?ad_response=unfilled`). Brotli builds only load over HTTPS or `localhost`, because browsers accept `Content-Encoding: br` only in a secure context, and a plain static server must also send that header for `.br` files. If yours does not, build with compression Disabled for local tests.
- **Then the real thing.** Open the [Preview tool](https://www.zokogames.com/preview) with your local address, and run the uploaded build in the console's build preview.

## Known pitfalls

<!-- search: headings-only -->

- **Game stops while an ad plays or the tab is in the background.** Set `Application.runInBackground = true`. The SDK pauses `AudioListener` during ads and restores it afterwards (`ZokoSDK.Ad.MuteAudioDuringAds`).
- **`sdkNotLoaded` or "ZokoGames is undefined".** The page has no SDK script tag. Use the ZokoGames template or add the tag before the Unity loader.
- **`.jslib` ignored.** It must stay in `Plugins/WebGL/` and the build target must be WebGL.
- **Every call fails with `sdkNotInitialized`.** Wait for `Init` to finish; a failed `Init` leaves the SDK uninitialised.
- **Game stays paused or silent after an ad.** Resume on `adError` as well as `adFinished`: unfilled ads, `adCooldown` and ad blockers all end in `adError`. `RequestAdAsync` returns in every case, so the code after `await` is the safe place.
- **`Task` never completes.** The call was awaited off the main thread.
- **Banner empty in the Editor.** The simulator only logs banner requests.
- **`UserId` is not proof of identity.** `ZokoUser.UserId` is the raw id from the client; verify the [token](https://docs.zokogames.com/sdk/user#tokens) on your server.
- **Do not block the main thread** waiting for callbacks.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/engines/godot

# Godot

The `zokogames` addon (`packages/sdk-engines/godot/addons/zokogames`) targets **Godot 4** Web exports (the addon loads in Godot 4.0 or newer, but a build that runs on the portal needs **Godot 4.3 or newer**, see Thread Support below; Godot 3 has its own addon with the same API, see [Godot 3](#godot-3) below). It registers one autoload, `ZokoGames`, that talks to the JavaScript SDK through a small bridge (`window.ZokoBridge`) defined in the export's HTML shell. Outside a browser (in the editor, or a desktop run) a built-in simulator answers instead, so the same code runs everywhere. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (1.7.0): run in the official Godot 4.3 and 4.7.2 editors and as Web exports in a real browser (2026-11-23). The addon imports with no errors or warnings, enabling the plugin registers the autoload, every public method and signal behaves as documented in simulator mode, and the Web export (4.3, Thread Support off) contains the bridge. Godot 4.0 to 4.2 were not run. Send the Godot version and the exact error to [support](https://docs.zokogames.com/business/support) if the first import fails.

## Install

Download the Godot plugin: [/sdk-engines/zokogames-godot-1.7.0.zip](https://www.zokogames.com/sdk-engines/zokogames-godot-1.7.0.zip) (the same files as the folder in the repository).

[/sdk-engines/godot.zip](https://www.zokogames.com/sdk-engines/godot.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. Copy `addons/zokogames` into your project's `res://addons/` folder. It holds `plugin.cfg`, `plugin.gd`, `zokogames.gd` (the autoload), `zoko_banner.gd` and `export/zokogames_shell.html`.
2. **Project > Project Settings > Plugins**: enable **ZokoGames**. This registers the autoload `ZokoGames` (`res://addons/zokogames/zokogames.gd`) and the `zokogames/simulator/*` settings.
3. **Project > Export**: add a **Web** preset and set **Custom HTML Shell** to `res://addons/zokogames/export/zokogames_shell.html`. The shell loads `https://sdk.zokogames.com/zokogames-sdk-v1.js` before the engine, creates `window.ZokoBridge`, and reports the engine download to the portal's loading bar. With your own shell, add the script tag to `<head>` and copy the bridge block from the supplied one.
4. `await ZokoGames.init_async()` once at startup, before any other call.
5. Optional: add a `ZokoBanner` node (`zoko_banner.gd`) over the space you can spare for a banner. The `examples/` folder next to the addon has `zoko_demo.gd` (keys A, R, G, H, U, F, T, S, B) and `zoko_store.gd`.

> [!IMPORTANT]
> Without the custom shell `window.ZokoBridge` does not exist. The addon logs a warning and falls back to the simulator, so the game runs but uses no real ads, users or saves.

## Godot 3

Godot 3.x (3.5 and 3.6 LTS are the targets, 3.3 and 3.4 should work) has its own addon with the same public API as the Godot 4 one: the same autoload `ZokoGames`, the same method names and the same signals, so a project can move between them. Download it: [/sdk-engines/zokogames-godot3-1.7.1.zip](https://www.zokogames.com/sdk-engines/zokogames-godot3-1.7.1.zip). It is written in GDScript 1 and calls the SDK through the `JavaScript` singleton.

> [!NOTE]
> Status (1.7.1): run in the official Godot 3.6.3 editor and as an HTML5 Web export in a real browser (2026-11-23). The addon imports with no errors or warnings (warnings treated as errors), enabling the plugin registers the autoload, every public method and signal behaves as documented in simulator mode, and the HTML5 export contains the bridge. Version 1.7.1 fixed the simulator rejecting an empty encrypted score. Godot 3.3 to 3.5 are not verified. Send the Godot version and the exact error to [support](https://docs.zokogames.com/business/support) if the first import fails.

Install:

1. Copy `addons/zokogames` from the download into your project's `res://addons/` folder and enable **ZokoGames** under **Project > Project Settings > Plugins**. This registers the autoload `ZokoGames`.
2. **Project > Export**: add an **HTML5** preset and set **Custom HTML Shell** to `res://addons/zokogames/export/zokogames_shell.html`. It loads the same SDK script as the Godot 4 shell. Leave GDNative off, and use the **Adaptive** canvas resize policy.
3. Start with `yield(ZokoGames.init_async(), "completed")`.

What differs from the Godot 4 addon:

| Godot 4 | Godot 3 |
| --- | --- |
| `await ZokoGames.get_user_async()` | `yield(ZokoGames.get_user_async(), "completed")`, which returns the same Dictionary |
| `callback: Callable` | `callback`: a `FuncRef`, `funcref(self, "_on_done")` |
| `ZokoGames.ad_started.connect(f)` | `ZokoGames.connect("ad_started", self, "_on_ad_started")` |
| The addon pauses the tree and mutes the Master bus while an ad plays, restores both, and applies the portal's mute setting to Master (`pause_game_during_ads`, `mute_audio_during_ads`, `follow_portal_mute`, all `true` by default) | The same properties and defaults |
| `JavaScriptBridge` | `JavaScript` |

On Godot 4 the Godot 3 addon refuses to start (`init()` fails with `unsupportedEngine`). The full table and the export settings are in the addon README.

## Which path

| You are | Do this |
| --- | --- |
| A Godot hobbyist with a finished game | Copy the addon, enable it, set the shell, add the snippet below, export with threads off, upload. |
| A hobbyist starting out | Same, and test every call in the editor first: the simulator needs no browser. |

## A working script

Put this in a script on a node in your first scene (or in your own autoload). It covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score.

```gdscript
extends Node

func _ready() -> void:
	var res := await ZokoGames.init_async()
	if not res.ok:
		push_warning("ZokoGames unavailable: %s" % res.error.code)
	# The addon pauses the tree and mutes Master during an ad, and follows the portal's mute setting
	# (pause_game_during_ads, mute_audio_during_ads, follow_portal_mute): no ad or mute handlers needed.
	var level := int(ZokoGames.data_get_item("level", "1"))     # load: synchronous Strings
	start_game(level)

# Call when the player takes control, and when play stops.
func on_play_start() -> void:
	if ZokoGames.is_available():
		ZokoGames.gameplay_start()
func on_play_stop() -> void:
	if ZokoGames.is_available():
		ZokoGames.gameplay_stop()

func show_midgame() -> void:
	var res := await ZokoGames.request_ad_async("midgame")     # completes after the ad is over
	if not res.ok:
		print("no ad: ", res.error.code)                       # adCooldown, unfilled, adblock ...

func on_reward_button() -> void:
	var res := await ZokoGames.request_ad_async("rewarded")
	if res.ok:
		grant_reward()                                         # reward only after the ad finished

func save_progress(level: int) -> void:
	var r := ZokoGames.data_set_item("level", str(level))      # synchronous, uploaded in the background
	if not r.ok:
		push_warning(r.error.code)                             # for example dataLimitExceeded

func submit_score(score: float) -> void:
	var user := await ZokoGames.get_user_async()
	if not user.ok or user.result == null:
		return                                                 # guests are not ranked
	var r := await ZokoGames.submit_score_async("", score)     # "" works only on a board WITHOUT an encryption key
	if not r.ok:
		print(r.error.code)

func start_game(_level: int) -> void: pass
func grant_reward() -> void: pass
```

The addon pauses the tree from `ad_started` until `ad_finished` or `ad_error`, mutes the Master bus meanwhile, and applies the portal's mute setting to Master after init and on every change (`pause_game_during_ads`, `mute_audio_during_ads` and `follow_portal_mute` on the `ZokoGames` autoload, all `true`; set one to `false` to handle that part yourself). The autoload runs with `PROCESS_MODE_ALWAYS`, so its signals still arrive while the tree is paused; nodes of your own that must react during an ad need the **Always** process mode.

About the leaderboard: a board **with** an encryption key counts only a correctly encrypted payload ([leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), and no engine wrapper ships an encryption helper, so `""` works only for a board without a key. For a keyed board, encrypt yourself (AES-256-GCM, additional data `zoko-score-v1|<userId>|<gameId>`; the player id is `user.result.__dangerousUserId` from `get_user_async`) or compute the score on your server and use the server API.

## How calls work

<!-- search: headings-only -->

GDScript names are snake_case. Every method that talks to the portal comes in two forms:

| Form | Example | Use it for |
| --- | --- | --- |
| Callback | `ZokoGames.get_user(callback)` | Fire-and-forget calls. The `Callable` is optional and last, except in `store_get_catalog_items(callback, limit, offset)` and `store_get_player_inventory(callback, limit, offset)`, where it comes first, and in `get_user_token(signing_key_type, callback)`. |
| Awaitable | `await ZokoGames.get_user_async()` | Straight-line code. The name ends in `_async`. |

Both deliver a Dictionary, `{ "ok": true, "result": <value> }` or `{ "ok": false, "error": { "code": "...", "message": "..." } }` (`request_ad` takes a Dictionary of callables instead). All methods live directly on the autoload; there are no `ad.`, `game.` or `user.` sub-objects.

| JavaScript | GDScript |
| --- | --- |
| `SDK.init()` | `await ZokoGames.init_async()` or `ZokoGames.init(callback)`; signal `initialized(ok)` |
| `SDK.environment` | `ZokoGames.environment` (`"local"`, `"zokogames"` or `"disabled"`), `ZokoGames.is_available()`, `ZokoGames.is_simulated`, `ZokoGames.is_qa_tool`, `ZokoGames.VERSION` |
| `SDK.ad.requestAd(type, cbs)` | `ZokoGames.request_ad(type, {"ad_started": f, "ad_finished": f, "ad_error": f})` or `await ZokoGames.request_ad_async(type)` |
| `SDK.ad.hasAdblock()` | `ZokoGames.has_adblock(callback)` or `await ZokoGames.has_adblock_async()` |
| `SDK.banner.requestBanner(...)` | `await ZokoGames.request_banner_async(id, width, height, window_rect)` |
| `SDK.banner.requestResponsiveBanner(id)` | `await ZokoGames.request_responsive_banner_async(id, window_rect)` |
| `SDK.banner.clearBanner(id)` / `clearAllBanners()` | `ZokoGames.clear_banner(id)` / `ZokoGames.clear_all_banners()` |
| `SDK.game.gameplayStart()` / `gameplayStop()` | `ZokoGames.gameplay_start()` / `ZokoGames.gameplay_stop()` |
| `SDK.game.loadingStart()` / `loadingStop()` / `loadingProgress(n)` | `ZokoGames.loading_start()` / `loading_stop()` / `loading_progress(n)` |
| `SDK.game.happytime()` | `ZokoGames.happytime()` |
| `SDK.game.reportGameCompletedPercentage(n)` | `ZokoGames.report_game_completed_percentage(n)` |
| `SDK.game.setGameContext(obj)` / `clearGameContext()` | `ZokoGames.set_game_context(dict)` / `ZokoGames.clear_game_context()` |
| `SDK.game.updateRoom(u)` / `leftRoom()` | `ZokoGames.update_room(dict)` / `ZokoGames.left_room()` |
| `SDK.game.inviteLink(p)` / `getInviteParam(k)` | `await ZokoGames.invite_link_async(dict)` / `ZokoGames.get_invite_param(key)` |
| `SDK.game.showInviteButton(p)` / `hideInviteButton()` | `await ZokoGames.show_invite_button_async(dict)` / `ZokoGames.hide_invite_button()` |
| `SDK.game.settings` | `ZokoGames.settings` (`disableChat`, `muteAudio`), signal `settings_changed` |
| `SDK.game.isOffline`, offline listener | `ZokoGames.is_offline`, signal `offline_changed(offline)` |
| `SDK.game.isInstantMultiplayer` / `inviteParams` | `ZokoGames.is_instant_multiplayer` (alias `is_instant_join`) / `ZokoGames.invite_params`, signal `join_room(params)` |
| `SDK.user.isUserAccountAvailable` / `systemInfo` | `ZokoGames.is_user_account_available` / `ZokoGames.system_info` |
| `SDK.user.getUser()` | `await ZokoGames.get_user_async()` |
| `SDK.user.getUserToken(opts)` | `await ZokoGames.get_user_token_async(signing_key_type)` |
| `SDK.user.showAuthPrompt()` | `await ZokoGames.show_auth_prompt_async()`, signal `auth_changed(user)` |
| `SDK.user.showAccountLinkPrompt()` | `await ZokoGames.show_account_link_prompt_async()` |
| `SDK.user.listFriends(opts)` | `await ZokoGames.list_friends_async(page, size)` |
| `SDK.user.submitScore(opts)` | `await ZokoGames.submit_score_async(encrypted_score, score)` |
| `SDK.data.getItem(k)` / `setItem(k, v)` | `ZokoGames.data_get_item(key, default)` / `ZokoGames.data_set_item(key, value)`; also `data_has_key`, `data_remove_item`, `data_clear` (all synchronous) |
| `SDK.store.*` | `store_get_catalog_items_async`, `store_get_player_inventory_async`, `store_buy_item_async(item_id)`, `store_consume_item_async(sku, qty)`, `store_get_purchase_token_async()`, `is_store_available`, `store_set_sandbox(bool)` (synchronous); signals `purchase_completed(item_id)`, `purchase_failed(error)` |
| `SDK.achievements.list()` / `unlock(key)` / `onUnlock` | `await ZokoGames.achievements_list_async()` / `achievements_unlock_async(key)`, signal `achievement_unlocked(achievement)`; see [achievements](https://docs.zokogames.com/sdk/achievements) |
| `SDK.analytics.trackOrder(p, o)` | `await ZokoGames.track_order_async(provider, order)` |
| `SDK.analytics.track(name, params)` (1.7.0) | `ZokoGames.track(name, params)` / `track_async(name, params)` |

Signals on the autoload: `initialized`, `ad_started`, `ad_finished`, `ad_error(error)`, `auth_changed`, `settings_changed`, `offline_changed`, `join_room`, `purchase_completed`, `purchase_failed`. Error codes are in `ZokoGames.ERROR_CODES` (a Dictionary keyed by module, for example `ZokoGames.ERROR_CODES.ad`); `ZokoGames.has_error_code(res, "purchaseCancelled")` tests a result.

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `ZokoGames.settings.get("kidsMode", false)` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `ZokoGames.settings.disableChat`, which the portal sets to true in the same cases. To test it, switch on `zokogames/simulator/kids_mode` in the simulator (it also turns chat off, as the portal does). See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

The autoload carries it as `room_*` methods and signals. Payloads cross the bridge as JSON: use Dictionary, Array, String, numbers, bool and null (numbers come back as `float`). Outside a browser the simulator is one room with one member that receives its own messages and state changes.

| JavaScript | Godot |
| --- | --- |
| `room.send(data, { to })` | `ZokoGames.room_send(data, to, cb)` / `room_send_async(data, to)` / `room_send_to(member_id, data, cb)` |
| `room.onMessage(cb)` | signal `room_message(message)` (`from`, `data`, `direct`, `seq`, `ts`) |
| `room.setState(patch)` | `room_set_state(patch, cb)` / `room_set_state_async(patch)` (a `null` value removes the key) |
| `room.getState()`, `room.onState(cb)` | `room_get_state()`, `room_get_state_value(key, default)`; signal `room_state(state, change)` |
| `room.members()`, `room.onMembers(cb)` | `room_get_members()`; signal `room_members(members)` |
| `room.isHost()`, `room.onHostChange(cb)`, `room.selfId` | `room_is_host()`; signal `room_host_changed(host_id, is_host)`; `room_self_id()` |
| `room.addLeftListener(cb)` (1.7.0) | signal `room_left(reason, room_id)` |
| `room.onError(cb)` | signal `room_error(error)` |

```gdscript
func _ready() -> void:
	await ZokoGames.init_async()
	ZokoGames.room_message.connect(func(m: Dictionary) -> void: print(m.from, " played ", m.data))
	ZokoGames.room_host_changed.connect(_on_host_changed)
	await ZokoGames.update_room_async({"roomId": "match-1", "isJoinable": true})

func _on_host_changed(_host_id: String, is_host: bool) -> void:
	if is_host:
		ZokoGames.room_set_state({"turn": "X"})

func play_cell(cell: int) -> void:
	await ZokoGames.room_send_async({"cell": cell, "mark": "X"})
```

## Banners

Banner rectangles are in window pixels. Drop a `ZokoBanner` node (a `Control`) where the banner should go; it reports its on-screen rectangle (accounting for stretch mode), requests on `_ready`, and clears itself when it leaves the tree.

| Property | Meaning |
| --- | --- |
| `container_id` | Banner id, default `zoko-banner`. |
| `size_mode` | `responsive` (largest size that fits) or one of `728x90`, `300x250`, `320x50`, `468x60`, `320x100`. |
| `request_on_ready` | Request automatically in `_ready`. |
| `show_simulator_placeholder` | Draw a placeholder rectangle while the simulator answers. |

By hand: `await ZokoGames.request_responsive_banner_async("menu", $BannerSlot.get_global_rect())`. Request banners on menu screens only.

## Purchases

```gdscript
func buy_first_item() -> void:
	if not ZokoGames.is_store_available:
		return
	var catalog := await ZokoGames.store_get_catalog_items_async()
	if not catalog.ok or catalog.result.is_empty():
		return
	var bought := await ZokoGames.store_buy_item_async(catalog.result[0].sku)
	if ZokoGames.has_error_code(bought, "purchaseCancelled"):
		return
	var token := await ZokoGames.store_get_purchase_token_async()   # send to your server and verify there
```

Verify ownership on your server (see [in-game purchases](https://docs.zokogames.com/sdk/purchases)). `examples/zoko_store.gd` is the full flow.

## Web export settings that matter

<!-- search: headings-only -->

- **Custom HTML Shell**: `res://addons/zokogames/export/zokogames_shell.html`, as above. Canvas sizing is done by the shell (the canvas fills the frame, `width` and `height` 100 percent), so use a **Stretch Mode** of `canvas_items` with aspect `expand` or `keep` in Project Settings > Display > Window > Stretch.
- **Thread Support: off.** Threaded exports need `SharedArrayBuffer`, which needs cross-origin isolation (COOP and COEP headers). Game pages are served without them, so a threaded build cannot start (symptom: `SharedArrayBuffer is not defined` or a blank canvas). Use the single-threaded web export: in Godot 4.3 and later untick **Thread Support** in the Web preset. Godot 4.0 to 4.2 have no such option (their web exports always use `SharedArrayBuffer`), so they cannot run on the portal; export from 4.3 or newer. Extensions Support: off unless you need it.
- **File names.** Export to a file named `index.html` (type that name in the export path): the portal needs `index.html` at the archive root, and the export names its other files after it: `index.js`, `index.wasm`, `index.pck` and the audio worklet scripts. Do **not** rename them to `.br` or `.gz`: the engine requests the plain names. The game origin serves a file ending in `.br` or `.gz` with the matching `Content-Encoding` header, but it does that by suffix, so it only helps an engine that asks for exactly those names (Unity does; Godot does not). The portal does not document transfer compression of plain files, and the initial-download estimate uses uncompressed sizes: keep the `.wasm` and `.pck` small.
- **Texture compression.** In the export preset enable VRAM compression for both desktop (S3TC/BPTC) and mobile (ETC2/ASTC) so every browser has a format.
- **Size.** Use a custom export template with unused modules disabled and keep the `.pck` small. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile). Export With Debug: off.
- **Memory.** Mobile browsers have a small heap; avoid loading every level's textures up front, and stream with `ResourceLoader.load_threaded_request` after the first scene (thread-pool loading still works in a non-threaded export). Cap resolution on phones, see [mobile](https://docs.zokogames.com/guides/mobile).
- **Audio unlock.** Browsers keep audio suspended until the first click or key press. Godot starts its audio after the first input; show a "click to play" screen and start music from that input, not in `_ready`.
- **Fullscreen.** Use the fullscreen button in the portal's frame bar, which fullscreens the whole frame. The frame is allowed to go fullscreen, so `DisplayServer.window_set_mode(DisplayServer.WINDOW_MODE_FULLSCREEN)` works, but it fullscreens your canvas only; do not add a competing button.
- **Loading.** The shell already reports the engine download and calls `loadingStop` when the engine has started. For a longer in-game loading screen call `ZokoGames.loading_start()`, `loading_progress(percent)` and `loading_stop()` yourself.

Upload: **Project > Export > Web > Export Project**, zip the folder contents so `index.html` is at the archive root, upload it in the developer console, and run the [Preview tool](https://www.zokogames.com/preview) first.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`request_ad("midgame")`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with `ad_error` with `adCooldown` until your game has called `ZokoGames.gameplay_start()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `ZokoGames.gameplay_start()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **In the editor or a desktop run** `ZokoGames.is_simulated` is true. Tune the simulator under **Project Settings > zokogames/simulator**: `ad_behaviour` (`fill`, `no_fill`, `error`), `ad_duration_seconds` (default 1.5), `adblock`, `disabled`, `account_available`, `logged_in`, `username`, `user_id`, `friend_count`, `mute_audio`, `disable_chat`, `offline`, `store_available` and `verbose`. Cloud save is in `user://zoko_sim_data.json`, the simulated inventory in `user://zoko_sim_inventory.json`.
- **Difference to remember.** The simulator does not enforce the three-minute midgame cooldown (`adCooldown`) that the portal and the browser's local mode do.
- **A Web export on `localhost`.** Serve the export folder from a local web server on `localhost` (opening `index.html` from disk does not work for WebAssembly). The bridge exists, so `is_simulated` is false and the JavaScript SDK runs its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second ad overlay, fake players, `localStorage` saves, `?sdk_debug=true`, `?ad_response=unfilled`.
- **Then** open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## Known pitfalls

<!-- search: headings-only -->

- **`sdkNotLoaded`.** The page has no SDK script tag; use the custom shell.
- **`ZokoGames` autoload missing.** The plugin is not enabled.
- **Calls fail with `sdkNotInitialized`.** `await ZokoGames.init_async()` first.
- **Works in the editor, not in the browser.** Open the browser console and check that `window.ZokoBridge` exists (the shell defines it).
- **Game stays paused after an ad.** Resume on `ad_error` as well as `ad_finished`. Do not use `CONNECT_ONE_SHOT` on `ad_started`: when an ad fails (`unfilled`, `adCooldown`, `adblock`), `ad_started` never fires and the one-shot connection stays armed for the next ad.
- **Banners never show.** The `ZokoBanner` node needs a size and must be visible.
- **Threaded export will not start.** Turn Thread Support off.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: `ZokoGames.report_chat({"reportedName": "Trixie", "message": "buy gold", "reason": "spam"}, callback)` (or `report_chat_async`), `ZokoGames.set_screenshot_provider(callable)` (a viewport capture after `frame_post_draw` is registered by default) and `ZokoGames.mirror_local_storage({"prefix": "save_"})` with the `mirror_error` signal. Godot's own `user://` files live in IndexedDB, not `localStorage`, so the mirror does not see them; save those with `data_set_item`. The editor simulator accepts all three. Godot 3 has the same functions in its addon.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/engines/construct-3

# Construct 3

The **ZokoGames** addon (`zokogames.c3addon`, plugin id `zokogames`, SDK v2, single global object) lives in `packages/sdk-engines/construct3`. All SDK work runs on the page's main thread in a DOM-side script (`c3runtime/domside.js`), so it works with Construct's worker mode; the runtime exchanges plain results with it. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (1.7.2): the addon was installed in the Construct 3 r506.4 editor, and exports made by the editor pass the production check (12 areas, with 1.7.1). Seven further exports covering non-worker mode, rooms with two players, store errors, settings, mute and offline events, request blocking and behaviour before Initialize ran locally on 2026-11-23; version 1.7.2 fixes the room values after Update room. If the addon fails to load, send the Construct version and the exact error to [support](https://docs.zokogames.com/business/support).

## Install

Download the Construct 3 plugin: [/sdk-engines/zokogames-construct3-1.7.2.zip](https://www.zokogames.com/sdk-engines/zokogames-construct3-1.7.2.zip). It holds the installable `zokogames.c3addon` (built from the `construct3` folder in the repository), the README and the changelog.

[/sdk-engines/construct3.zip](https://www.zokogames.com/sdk-engines/construct3.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. Unzip the download and install **`zokogames.c3addon`** (not the zip) through **Menu > View > Addon Manager > Install new addon**. If you build from the repository, `pnpm --filter @zoko/sdk-engines package` writes `zokogames-construct3-<version>.zip` with the same file (see the [overview](https://docs.zokogames.com/engines/overview#getting-the-plugin)).
2. Restart Construct 3, then **Insert new object > ZokoGames**. It is a single global object, so one is enough. The addon uses Addon SDK v2 and needs Construct 3 r397 or newer.
3. Run the **Initialize** action at the start of the first layout. The DOM-side script loads `https://sdk.zokogames.com/zokogames-sdk-v1.js` itself when the page does not have it, so you do not edit any export file.
4. Export as an HTML5 website and upload the zip.

## Which path

| You are | Do this |
| --- | --- |
| A Construct hobbyist with a finished game | Install the addon, add **Initialize**, the ad events below, export as HTML5 website, upload. No scripting needed. |
| Comfortable with scripting | The same SDK is reachable from a script when worker mode is off (see [Scripting](#scripting)). |

## Tags, results and errors

<!-- search: headings-only -->

Every asynchronous action takes a **Tag**. When the call ends, **On request completed** (with that tag) or **On request failed** (with that tag) triggers; **On any request failed** triggers for every failure. Use one tag per request in flight. Every action is asynchronous, so **System: Wait for previous actions to complete** placed after it waits until the call has ended.

| Expression | Contents |
| --- | --- |
| `ResultString` | The last result when it is text: a token, an invite link, a saved item. |
| `ResultNumber` | The last result as a number (booleans are 1 and 0; **Check ad blocker** reads `ResultNumber`, 1 means blocked). |
| `ResultJSON` | The last result as JSON (the friends page, the account link answer). |
| `ErrorCode`, `ErrorMessage`, `ErrorContainerId` | Details of the last failure. `ErrorContainerId` is set for banner errors. |

## A working event sheet

The sheet below covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score. Use a global variable `Coins`, `Best` and `RewardPending`.

```
System: On start of layout (first layout)
    -> ZokoGames: Initialize (tag "init")

ZokoGames: On request completed ("init")
    -> ZokoGames: Get saved item (tag "load", key "best")           // load; saves are asynchronous in worker mode
ZokoGames: On request completed ("load")
    + ZokoGames: has saved item "best"  (compare HasSavedItem("best") = 1)
    -> Set Best to int(SavedItem("best"))
ZokoGames: On request failed ("init")                               // SDK missing or blocked: just start
    -> Go to layout "Menu"
ZokoGames: On request completed ("load")  or  On request failed ("load")
    -> Go to layout "Menu"                                          // a failed load (data module off) must not block the game

// Ads: pause on start, resume on finish AND error. Never pause in the action itself.
ZokoGames: On ad started
    -> System: Set time scale 0 ; Audio: Set silent
ZokoGames: On ad finished
    -> System: Set time scale 1 ; Audio: Set not silent
    + System: Compare variable RewardPending = 1
    -> Add 10 to Coins ; Set RewardPending to 0
ZokoGames: On ad error
    -> System: Set time scale 1 ; Audio: Set not silent ; Set RewardPending to 0

// Loading: the portal's loading bar ends here (once, when the menu can be used)
Menu layout: On start of layout
    + ZokoGames: Is available
    -> ZokoGames: Loading stop (tag "ls")

// Gameplay start/stop
Game layout: On start of layout (player can act)
    + ZokoGames: Is available
    -> ZokoGames: Gameplay start (tag "gs")
Game over (or pause menu opened)
    + ZokoGames: Is available
    -> ZokoGames: Gameplay stop (tag "gx")

// Midgame ad at a natural break (e.g. on the game-over screen)
Game over screen: On start of layout
    + ZokoGames: Is available
    -> ZokoGames: Request ad (type midgame, tag "mid")

// Rewarded ad
Reward button: On clicked
    + ZokoGames: Is available
    -> Set RewardPending to 1 ; ZokoGames: Request ad (type rewarded, tag "rew")

// Save
Round ends and Score > Best
    -> Set Best to Score ; ZokoGames: Set saved item (tag "save", key "best", value str(Best))

// Leaderboard (signed-in players only; board enabled in the console)
Round ends
    + ZokoGames: Is available
    -> ZokoGames: Submit score (tag "score", encrypted "", score Score)

// Mute setting
ZokoGames: On settings changed
    + ZokoGames: Is mute requested
    -> Audio: Set silent
ZokoGames: On settings changed
    + Else
    -> Audio: Set not silent
```

Two traps are built into this sheet on purpose:

- **On request completed ("rew") is not "ad finished".** When an ad is unfilled, blocked or in cooldown, the SDK delivers **On ad error** and the action still completes, so grant rewards in **On ad finished** only. When the SDK is disabled, the action fails (**On request failed**) and neither ad event fires, so never leave the game paused in the action's own event.
- **`Submit score` with an empty `encrypted` value** works only on a board without an encryption key (the plain score is validated against the board rules). A keyed board counts only a correctly encrypted payload ([leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), and the addon has no encryption helper: compute the score on your server and use the server API, or leave the board keyless for a casual game. A player who is not signed in is not ranked.

### Purchases

```
ZokoGames: On request completed ("init") + ZokoGames: Is store available
    -> Shop button: Set visible ; ZokoGames: Get catalogue items (limit 50, offset 0, tag "cat")
ZokoGames: On request completed ("cat")
    -> loop 0..StoreItemCount-1: row with StoreItemName(loopindex), StoreItemPrice(loopindex), StoreItemCurrency(loopindex)
Buy button: On clicked
    -> ZokoGames: Buy item (StoreItemSku(selected), tag "buy")
ZokoGames: On request completed ("buy")
    -> grant PurchasedItemId ; ZokoGames: Get purchase token (tag "tok")      // then send PurchaseToken to your server
ZokoGames: On request failed ("buy") + Last error is "purchaseCancelled"     -> (nothing)
ZokoGames: On request failed ("buy") + Last error is "userNotAuthenticated"  -> ZokoGames: Show login prompt (tag "login")
```

Verify ownership on your server (see [in-game purchases](https://docs.zokogames.com/sdk/purchases)). `StoreItemPrice` is -1 when there is none and `InventoryQuantity` is -1 when not counted.

## Actions

<!-- search: headings-only -->

| Group | Actions |
| --- | --- |
| Start-up | **Initialize** |
| Ads | **Request ad** (midgame or rewarded), **Check ad blocker** |
| Banners | **Request banner** (id, size 728x90, 300x250, 320x50, 468x60 or 320x100, x, y, w, h), **Request responsive banner** (id, x, y, w, h), **Clear banner**, **Clear all banners** |
| Game | **Gameplay start**, **Gameplay stop**, **Loading start**, **Loading stop**, **Report loading progress** (0 to 100), **Happytime**, **Report completed percentage**, **Set game context** (JSON), **Clear game context** |
| Multiplayer | **Update room**, **Set room public**, **Left room**, **Create invite link**, **Show invite button** and **Hide invite button** (deprecated) |
| User | **Get user**, **List friends**, **Get user token**, **Show login prompt**, **Show account link prompt**, **Submit score** |
| Store | **Get catalogue items**, **Get player inventory**, **Buy item**, **Consume item**, **Set sandbox**, **Get purchase token**, **Get payment provider user token** (deprecated) |
| Cloud save | **Get saved item**, **Set saved item**, **Remove saved item**, **Clear saved data** |
| Achievements | **Unlock achievement** (key), **List achievements** |
| Analytics | **Track order**, **Track event** (name, params JSON; SDK 1.7.0) |

Banner rectangles are in canvas CSS pixels with the origin at the top left; the addon converts them into fractions of the canvas. Request banners on menu layouts only.

## Conditions

<!-- search: headings-only -->

- Status: **Is initialized**, **Is available** (false when the SDK is disabled), **Is QA tool**.
- Requests: **On request completed**, **On request failed**, **On any request failed**, **Last error is** (code).
- Ads: **On ad started**, **On ad finished**, **On ad error**, **Is ad playing**.
- Settings: **On settings changed**, **Is mute requested**, **Is chat disabled**.
- Offline: **On offline changed**, **Is offline**, and the expression `IsOffline` (1 or 0). Before 1.6.1 that expression failed in the event sheet; update the addon if you use it.
- Multiplayer: **Is instant multiplayer**, **On join room**.
- Achievements: **On achievement unlocked**.
- Account: **On auth changed**, **Is logged in**, **Is account available**.
- Store: **Is store available**.

**Kids mode.** Since version 1.5.0 the wrapper exposes it: **Is kids mode** (`KidsMode`) is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring **Is chat disabled**, which the portal sets to true in the same cases. To test it, add `?kidsMode=true` to the page address in local mode. See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Expressions

<!-- search: headings-only -->

`Environment`, `SdkVersion`, `MuteAudio`, `DisableChat`, `IsOffline`, `InviteParam(key)`, `InviteParamsJSON`, `UserName`, `UserPictureUrl`, `UserId` (never trust it on a server; verify the token), `UserToken`, `FriendCount`, `FriendsTotal`, `FriendsHasMore`, `FriendName(i)`, `FriendId(i)`, `FriendPictureUrl(i)`, `Locale`, `CountryCode`, `DeviceType`, `SavedItem(key)`, `HasSavedItem(key)`, `ErrorCodes(module)` (comma separated codes for `ad`, `banner`, `user`, `data`, `store`, `room` or `general`), `ResultJSON`, `ResultString`, `ResultNumber`, `ErrorCode`, `ErrorMessage`, `ErrorContainerId`, and store expressions `StoreItemCount`, `StoreItemSku(i)`, `StoreItemName(i)`, `StoreItemDescription(i)`, `StoreItemImageUrl(i)`, `StoreItemPrice(i)`, `StoreItemCurrency(i)`, `StoreItemConsumable(i)`, `InventoryCount`, `InventorySku(i)`, `InventoryName(i)`, `InventoryDescription(i)`, `InventoryImageUrl(i)`, `InventoryQuantity(i)`, `PurchasedItemId`, `PurchaseToken`, `XsollaUserToken` (deprecated name for the purchase token), and the achievement expressions `AchievementCount`, `AchievementKeyAt(i)`, `AchievementNameAt(i)`, `AchievementDescriptionAt(i)`, `AchievementPointsAt(i)`, `AchievementUnlockedAt(i)`, `AchievementIsUnlockedAt(i)` (1 or 0), `LastUnlockReason`, `LastAchievementKey`, `LastAchievementName` and `LastAchievementPoints`. Run **List achievements** before the `...At(i)` expressions; **Unlock achievement** fills the `LastAchievement...` ones. For guests and unknown keys the action still completes, and `LastUnlockReason` is `guest`, `not_found`, `not_live`, `rate_limited` or `error`; `AchievementUnlockedAt(i)` is empty while the achievement is locked. See [achievements](https://docs.zokogames.com/sdk/achievements).

## Scripting

You can call the SDK from a script, but only when **Use worker** is off in Project Properties: with a worker the runtime has no `window`, so `globalThis.ZokoGames` does not exist in the script. Run scripts only after **Initialize** has completed.

```js
// Script event, after the "init" request completed. Needs Use worker = No.
const SDK = globalThis.ZokoGames.SDK;
const user = await SDK.user.getUser();
runtime.globalVars.PlayerName = user ? user.username : "guest";
```

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

The **Room** category carries it. Message and value parameters accept text or numbers: valid JSON (`{"x":1}`, `5`, `true`) is sent as that JSON value, anything else as plain text. The room state, member list, host and your own id are cached from the room events, so the expressions work in worker mode. On `localhost` the SDK's local mode makes two browser tabs that join the same room id behave like two players.

| Kind | ACEs |
| --- | --- |
| Actions | **Send room message** (tag, data), **Send room message to member** (tag, member id, data), **Set room state key** (tag, key, value; host only), **Remove room state key** (tag, key; host only) |
| Triggers | **On room message**, **On room state changed**, **On room members changed**, **On room host changed**, **On room left** (SDK 1.7.0; expressions `RoomLeftReason`, `RoomLeftRoomId`), **On room error** |
| Condition | **Is room host** |
| Message expressions | `RoomMessageData`, `RoomMessageFrom`, `RoomMessageDirect`, `RoomMessageSeq`, `RoomMessageValue(key)` |
| State expressions | `RoomStateJSON`, `RoomStateValue(key)`, `RoomStateChangedKeys`, `RoomStateChangedBy`, `RoomStateRev` |
| Member expressions | `RoomMemberCount`, `RoomMemberIdAt(i)`, `RoomMemberNameAt(i)`, `RoomMemberPictureUrlAt(i)`, `RoomHostId`, `RoomSelfId` |
| Error expressions | `RoomErrorCode`, `RoomErrorMessage` (for the room error trigger; request failures still use **On request failed**) |

```
ZokoGames: On room host changed
  + ZokoGames: Is room host        -> ZokoGames: Set room state key (key "turn", value "X", tag "turn")
Board: On cell clicked             -> ZokoGames: Send room message ("{""cell"":" & Cell & "}", tag "move")
ZokoGames: On room message         -> Board: Place cell ZokoGames.RoomMessageValue("cell")
ZokoGames: On room state changed   -> Text: Set text to ZokoGames.RoomStateValue("turn")
```

## Export settings that matter on the web

- **Export as HTML5 website** and zip the export folder **contents** so `index.html` is at the archive root.
- **Offline support: No** (it adds a service worker; the validator warns `service_worker` because it can clash with the portal's own offline handling). **Use worker: Yes** is supported. **Minify script: Simple or Advanced**.
- **No pre-compression.** Construct does not write `.br` or `.gz`; upload the export as is. The game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but Construct requests plain names, so renamed files would break. The initial-download estimate uses uncompressed sizes: compress images (WebP) and audio (Opus or AAC), and put large media in a second layout loaded once the first is interactive. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile); see [first frame fast](https://docs.zokogames.com/guides/first-frame).
- **Canvas sizing.** The frame size changes with fullscreen and rotation. Set the project's fullscreen scaling (Project Properties > Fullscreen mode) to a letterbox or scale-outer mode so the layout fits every [required resolution](https://docs.zokogames.com/requirements/gameplay).
- **Audio unlock.** Browsers keep audio suspended until the first click or tap. Start music from a "tap to play" button on the first layout, not on start of layout.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so Construct's **Request fullscreen** works from an input event, but it fullscreens only your canvas; do not add a competing button.
- **Memory.** Large projects load every layout's data up front. Split rarely used layouts and keep sprite sheets small, especially for mobile.
- **Loading.** In a loader layout run **Loading start** once, **Report loading progress** (`loadingprogress * 100`) each tick, and **Loading stop** when the first game layout starts.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: the action **Report chat message** (name, message, reason, optional user id, room id and context JSON), the actions **Set screenshot provider** and **Answer screenshot** with the condition **On screenshot requested**, and **Mirror localStorage to cloud save** with the condition **On mirror error**. By default the runtime canvas answers the portal's screenshot request. The Local storage object keeps its data in IndexedDB, so the mirror does not copy it; use the Data actions for those saves. The editor preview uses the simulator.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (**Request ad** with type `midgame`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with **On ad error** with `adCooldown` until your game has called the **Gameplay start** action or 30 seconds of visible page time have passed. On the portal the first midgame ad needs the **Gameplay start** action first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

There is no separate simulator. When the page's host is `localhost`, `127.0.0.1` or a `*.localhost` name, the JavaScript SDK runs its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second overlay for each ad, a fake player, a `localStorage` cloud save and a three-item test store, so the same events fire as on the portal. On any other host the environment is `disabled`, and **Is available** is false.

- If your preview URL is not a localhost address (for example a preview served from the editor's own web host or over the local network), add `?useLocalSdk=true` to the preview URL, or export the project and serve the folder with a local web server.
- A second midgame request within three minutes fails with `adCooldown` (fires **On ad error**): the real rule, so your event sheet must cope.
- Useful switches: `?sdk_debug=true`, `?ad_response=unfilled`, `?user_response=logged_out`.
- Then open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## Known pitfalls

<!-- search: headings-only -->

- **Addon will not install.** Install `zokogames.c3addon`, not the zip.
- **A condition never fires.** The tag in **On request completed** must equal the tag passed to the action, and only one request per tag should be in flight.
- **Actions run but nothing happens.** Run **Initialize** first and wait for its completion.
- **`sdkNotLoaded`.** Offline or the SDK host is blocked; the preview needs internet access to load the script.
- **Game stays paused or silent.** Resume in **On ad error** as well as **On ad finished**.
- **Banner in the wrong place.** Rectangles are canvas CSS pixels, origin top-left.
- **Saved item is empty right after a load.** Reads are asynchronous: wait for the tag's **On request completed** before reading `SavedItem`.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/engines/gamemaker

# GameMaker

The wrapper (`packages/sdk-engines/gamemaker`) has two files. `zokogames.js` is an extension file for the **HTML5** target and talks to the browser SDK. `zokogames_sim.gml` is GML code for every other target (Windows, macOS, Linux and so on); it defines the same `zoko_*` functions and answers through the same **Async - Social** event layout, so a game runs unchanged in the IDE. The simulator needs GameMaker 2023.1 or newer (it uses `call_later`). A third file, `gml/examples.gml`, is a copy-and-paste controller. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (1.7.0): the JavaScript extension runs in a real browser against the SDK, and the function list is checked against `zokogames.js` and `zokogames_sim.gml` (names, argument counts, and which functions return a request id). Not built or run in the GameMaker IDE, so how the IDE reads the extension is not verified. Send the IDE and runtime versions and the exact error to [support](https://docs.zokogames.com/business/support) if the first import fails. The JavaScript SDK underneath is the tested part.
>
> Supported export target: HTML5 only. The GX.games (WebAssembly) export is not supported: its runner has no `GMS_API`, so Async - Social events are not delivered.

## Install

Download the GameMaker plugin: [/sdk-engines/zokogames-gamemaker-1.7.0.zip](https://www.zokogames.com/sdk-engines/zokogames-gamemaker-1.7.0.zip) (the same files as the folder in the repository).

[/sdk-engines/gamemaker.zip](https://www.zokogames.com/sdk-engines/gamemaker.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. In the IDE create an **Extension** resource named `ZokoGames`. Add `zokogames.js` and tick **HTML5** only. Add `zokogames_sim.gml` and tick every platform **except** HTML5. The simulator is written in the GML extension format of the manual (one `#define` section per function), so the IDE lists its functions, including internal `__zoko_*` helpers you can leave alone. In the file properties of `zokogames_sim.gml` set **Init Function** to `__zoko_sim_init`, so `global.zoko_sim_config` exists before your first Create event.
2. Declare every function from the [function list](#functions) in the extension, one entry each. GameMaker needs each function declared, with the argument count shown; use return type **double** for ids, numbers and flags and **string** for text and JSON; arguments are **double** for numbers and **string** for ids, keys and JSON. The names are exactly those in `zokogames.js` and `zokogames_sim.gml`. The README in the download has the full table of functions to declare, with their arguments and return values; before 1.6.1 it missed 14 functions and gave the wrong return value for 14 others, so declare from the 1.6.1 table.
3. HTML5 only: load `https://sdk.zokogames.com/zokogames-sdk-v1.js` before the runner starts. The simplest way is the extension's own code injection: open the extension, choose **HTML5** under Platform Settings and add `<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>` under the `GM_HTML5_PostStyle` tag (it lands inside `<head>`). Alternatively copy the runtime's template `index.html`, add the tag, include it as an Included File and select it in the HTML5 game options. Without it every call fails with `sdkNotLoaded`.
4. Create a **persistent** controller object and paste `gml/examples.gml` into its Create and Async - Social events, or use the controller below. Call `zoko_init()` once, from that object.

## Which path

| You are | Do this |
| --- | --- |
| A GameMaker hobbyist with a finished game | Add the extension, paste the controller below, call `zoko_ad_request_ad` at natural breaks, export HTML5, upload. |
| Starting out | Develop on Windows or macOS with the simulator first, then test the HTML5 export on `localhost`. |

## How calls work

<!-- search: headings-only -->

- **Asynchronous** functions return a request id (a real number) at once. The result arrives later in the **Async - Social** event, never while the calling function is still running, so `async_load` stays valid in the event that made the call.
- **Synchronous** functions (state, settings and cloud save) return a value directly. Booleans are `1` or `0`; structured values are JSON strings, so wrap them in `json_parse`.

Every Async - Social event from the wrapper has `async_load[? "type"] == "zoko"`. Switch on `async_load[? "event"]`:

| Event | When | Fields |
| --- | --- | --- |
| `response` | An asynchronous call finished | `request_id`, `method`, `ok` (1 or 0), `result` (JSON text), `error_code`, `error_message` |
| `ad_started` | The ad began: pause and mute | `request_id` of the `zoko_ad_request_ad` call |
| `ad_finished` | The ad ended: resume | `request_id` |
| `ad_error` | The ad failed: resume | `request_id`, `error_code`, `error_message` |
| `settings_changed` | The portal changed mute or chat | `result` (JSON of `{ disableChat, muteAudio }`) |
| `offline_changed` | The player went offline or came back | `result` (`true` or `false`) |
| `auth_changed` | A player logged in | `result` (JSON of the user) |
| `join_room` | The player joined through an invite | `result` (JSON of the invite parameters) |
| `achievement_unlocked` | An achievement unlocked | `result` (JSON of the achievement) |
| `room_message`, `room_state`, `room_members`, `room_host_changed`, `room_left` (1.7.0), `room_error` | Room data channel, see [below](#room-data-channel) | `result` (JSON) |

`request_id` is 0 for events not tied to one call. Because `result` is JSON text, a string result such as a token is quoted JSON: pass it through `json_parse`.

## A working controller

One persistent object that covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score.

```gml
// ---- Create event (persistent object) ----
global.zoko_live = false;            // true when the SDK answered and is not disabled
global.in_ad = false;
global.reward_request = -1;          // request id of the rewarded ad in flight
global.best = 0;
zoko_init_request = zoko_init();
zoko_user_request = -1;

// ---- Async - Social event ----
if (async_load[? "type"] != "zoko") exit;
var _rid = async_load[? "request_id"];

switch (async_load[? "event"]) {
    case "response":
        var _ok = async_load[? "ok"] == 1;
        if (_rid == zoko_init_request) {
            global.zoko_live = _ok && zoko_environment() != "disabled";
            if (global.zoko_live) {
                audio_master_gain(json_parse(zoko_game_get_settings()).muteAudio ? 0 : 1);
                if (zoko_data_has_key("best")) global.best = real(zoko_data_get_item("best"));   // load: synchronous
                zoko_game_loading_stop();                // ends the portal's loading bar: the game can be played now
            }
            room_goto_next();                       // start the game whether or not the SDK is there
        } else if (_rid == zoko_user_request && _ok) {
            var _user = json_parse(async_load[? "result"]);
            // Leaderboard: only a signed-in player is ranked. "" is accepted only by a board WITHOUT an encryption key.
            if (_user != undefined) zoko_user_submit_score("", global.pending_score);
        } else if (!_ok) {
            show_debug_message(async_load[? "error_code"] + ": " + async_load[? "error_message"]);
        }
        break;

    // Pause on ad_started, resume on ad_finished AND ad_error.
    case "ad_started":
        global.in_ad = true;
        audio_pause_all();
        break;
    case "ad_finished":
        global.in_ad = false;
        audio_resume_all();
        if (_rid == global.reward_request) { global.coins += 50; global.reward_request = -1; }   // reward only here
        break;
    case "ad_error":
        global.in_ad = false;
        audio_resume_all();
        if (_rid == global.reward_request) global.reward_request = -1;
        show_debug_message("no ad: " + async_load[? "error_code"]);   // adCooldown, unfilled, adblock ...
        break;

    case "settings_changed":
        audio_master_gain(json_parse(async_load[? "result"]).muteAudio ? 0 : 1);
        break;
}
```

```gml
// ---- Anywhere in the game ----
// The player takes control / play stops:
if (global.zoko_live) zoko_game_gameplay_start();
if (global.zoko_live) zoko_game_gameplay_stop();

// Midgame ad at a natural break (game over, level end):
if (global.zoko_live) zoko_ad_request_ad("midgame");

// Rewarded ad from a button:
if (global.zoko_live) global.reward_request = zoko_ad_request_ad("rewarded");

// Save (synchronous, returns 1 or 0):
if (score > global.best) {
    global.best = score;
    if (global.zoko_live && !zoko_data_set_item("best", string(score))) show_debug_message(zoko_data_get_last_error());
}

// Leaderboard: ask for the user first; the controller's response branch submits.
global.pending_score = score;
if (global.zoko_live) zoko_user_request = zoko_user_get_user();
```

Game logic must not run while `global.in_ad` is true: check it at the top of your Step events (GameMaker has no automatic pause here). Two behaviours follow from the code in `zokogames.js`:

- A failed ad (unfilled, blocked, in cooldown) sends `ad_error` and then a `response` with `ok` 1 for the same request id. A request that cannot start at all (SDK disabled or not initialised) sends only a `response` with `ok` 0 and **no** `ad_error`, which is why the controller above never pauses before `ad_started`.
- The rewarded ad is tied to the request id returned by `zoko_ad_request_ad`; comparing `request_id` in `ad_finished` keeps a midgame ad from granting a reward.

About the leaderboard: a board **with** an encryption key counts only a correctly encrypted payload ([leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), and the wrapper has no encryption helper, so `""` works only for a board without a key. Otherwise compute scores on your server and use the server API. The player id for encryption is the `__dangerousUserId` field of the user JSON.

## Functions

<!-- search: headings-only -->

Declare these in the extension. The README of the wrapper has the same list with argument counts.

| JavaScript | GML |
| --- | --- |
| `SDK.init()` | `zoko_init()` (event `response`, method `init`; `result` is a JSON snapshot) |
| `SDK.environment` | `zoko_environment()`, `zoko_is_initialized()`, `zoko_is_qa_tool()`, `zoko_version()` |
| `SDK.ad.requestAd(type)` | `zoko_ad_request_ad("midgame")` or `"rewarded"` |
| `SDK.ad.hasAdblock()` | `zoko_ad_has_adblock()` (`result` is `true` or `false`) |
| `SDK.banner.requestBanner(...)` | `zoko_banner_request_banner(id, width, height, x, y, w, h, area_w, area_h)` |
| `SDK.banner.requestResponsiveBanner(id)` | `zoko_banner_request_responsive_banner(id, x, y, w, h, area_w, area_h)` |
| `clearBanner`, `clearAllBanners` | `zoko_banner_clear_banner(id)`, `zoko_banner_clear_all_banners()` |
| `SDK.game.gameplayStart()` / `gameplayStop()` | `zoko_game_gameplay_start()`, `zoko_game_gameplay_stop()` |
| `loadingStart`, `loadingStop`, `loadingProgress(n)` | `zoko_game_loading_start()`, `zoko_game_loading_stop()`, `zoko_game_loading_progress(n)` |
| `SDK.game.happytime()` | `zoko_game_happytime()` |
| `reportGameCompletedPercentage(n)` | `zoko_game_report_game_completed_percentage(n)` |
| `setGameContext(obj)`, `clearGameContext()` | `zoko_game_set_game_context(json)`, `zoko_game_clear_game_context()` |
| `updateRoom(u)`, `leftRoom()` | `zoko_game_update_room(json)`, `zoko_game_left_room()` |
| `inviteLink(p)` | `zoko_game_invite_link(json)` |
| `SDK.game.settings` | `zoko_game_get_settings()` (JSON text) |
| `isOffline`, `addOfflineListener` | `zoko_game_is_offline()` (1 or 0), event `offline_changed` |
| `isInstantMultiplayer` | `zoko_game_is_instant_multiplayer()` |
| `inviteParams`, `getInviteParam(k)` | `zoko_game_get_invite_params()` (JSON), `zoko_game_get_invite_param(key)` |
| `SDK.user.isUserAccountAvailable` | `zoko_user_is_account_available()` |
| `SDK.user.systemInfo` | `zoko_user_get_system_info()` (JSON text) |
| `SDK.user.getUser()` | `zoko_user_get_user()` (`result` is `null` when signed out) |
| `SDK.user.listFriends(opts)` | `zoko_user_list_friends(page, size)` |
| `SDK.user.getUserToken(opts)` | `zoko_user_get_user_token(signing_key_type)` (`""`, `"IN_GAME_AUTH"` or `"IN_GAME_AUTH_LEGACY"`) |
| `showAuthPrompt`, `showAccountLinkPrompt` | `zoko_user_show_auth_prompt()`, `zoko_user_show_account_link_prompt()` (`result` is `{"response":"yes"}` or `{"response":"no"}`) |
| `SDK.user.submitScore(opts)` | `zoko_user_submit_score(encrypted_score, score)` |
| `SDK.data.getItem(k)` | `zoko_data_get_item(key)` (`""` when missing), `zoko_data_has_key(key)` |
| `setItem`, `removeItem`, `clear` | `zoko_data_set_item(key, value)`, `zoko_data_remove_item(key)`, `zoko_data_clear()`; each returns 1 or 0, and `zoko_data_get_last_error()` returns the error JSON |
| `SDK.store.*` | `zoko_store_is_available()`, `zoko_store_get_catalog_items(limit, offset)`, `zoko_store_get_player_inventory(limit, offset)`, `zoko_store_buy_item(sku)`, `zoko_store_consume_item(sku, qty)`, `zoko_store_set_sandbox(bool)`, `zoko_store_get_purchase_token()` |
| `SDK.achievements.list()` / `unlock(key)` / `onUnlock` | `zoko_achievements_list()`, `zoko_achievements_unlock(key)`, social event `achievement_unlocked`; see [achievements](https://docs.zokogames.com/sdk/achievements) |
| `SDK.analytics.trackOrder(p, o)` | `zoko_analytics_track_order(provider, order_json)` |
| `SDK.analytics.track(name, params)` (1.7.0) | `zoko_analytics_track(name, params_json)` |
| `ERROR_CODES` | `zoko_error_codes("store")` (comma separated; also `ad`, `banner`, `user`, `data`, `room`, `general`; empty text for an unknown module) |

Deprecated aliases also exist: `zoko_game_is_instant_join`, `zoko_game_show_invite_button`, `zoko_game_hide_invite_button`, `zoko_user_get_xsolla_user_token`.

Banner rectangles are in pixels of the area described by `area_w` and `area_h` (pass `0` for the browser window size). Request banners on menu rooms only: `zoko_banner_request_banner("menu", 300, 250, x, y, 300, 250, room_width, room_height)`, and `zoko_banner_clear_all_banners()` when leaving.

### Purchases

```gml
// Create
if (zoko_store_is_available()) shop_buy = zoko_store_buy_item("gems_100");

// Async - Social, event "response"
if (async_load[? "request_id"] == shop_buy) {
    if (async_load[? "ok"] == 1) {
        show_debug_message("paid: " + json_parse(async_load[? "result"]).itemId);   // verify on your server
        zoko_store_get_purchase_token();                                            // the token arrives as a response
    } else if (async_load[? "error_code"] == "purchaseCancelled") {
        show_debug_message("closed the checkout");
    } else if (async_load[? "error_code"] == "userNotAuthenticated") {
        zoko_user_show_auth_prompt();
    }
}
```

Check `zoko_store_is_available()` before any purchase UI and verify ownership on your server ([in-game purchases](https://docs.zokogames.com/sdk/purchases)).

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `zoko_game_is_kids_mode() == 1` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `disableChat`, which the portal sets to true in the same cases. To test it, switch on `kids_mode` in the simulator (it also turns chat off, as the portal does). See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

Declare seven more functions in the extension: `zoko_room_send(data_json)`, `zoko_room_send_to(member_id, data_json)`, `zoko_room_set_state(patch_json)`, `zoko_room_get_state()`, `zoko_room_get_members()`, `zoko_room_is_host()` and `zoko_room_self_id()`. The first three return a request id and answer with a `response` event; incoming data arrives as the social events `room_message`, `room_state`, `room_members`, `room_host_changed` and `room_error`, each with `result` as JSON text. On non-HTML5 targets the simulator is one room with one member that receives its own messages and state changes.

```gml
// Async - Social
switch (async_load[? "event"]) {
    case "room_message":
        var _m = json_parse(async_load[? "result"]);      // { from, data, direct, seq, ts }
        board_place(_m.data.cell, _m.data.mark);
        break;
    case "room_state":
        global.turn = json_parse(async_load[? "result"]).state.turn;
        break;
    case "room_left":
        // result: { reason: "left" | "kicked" | "closed" | "disconnected", roomId }
        break;
    case "room_host_changed":
        if (json_parse(async_load[? "result"]).isHost) zoko_room_set_state(json_stringify({ turn: "X" }));
        break;
}

// on a click
zoko_room_send(json_stringify({ cell: 4, mark: "X" }));
```

## HTML5 export settings that matter

<!-- search: headings-only -->

- **Export** HTML5 to a clean output folder, then zip its **contents** so `index.html` is at the archive root.
- **No pre-compression.** GameMaker writes plain files; upload them as is. The game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but GameMaker requests plain names, so renamed files would break. The initial-download estimate uses uncompressed sizes. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile).
- **Canvas sizing.** The frame size changes with fullscreen and rotation. In the HTML5 options use "Keep aspect ratio" or "Full scale" so the game fits every [required resolution](https://docs.zokogames.com/requirements/gameplay).
- **Textures and audio.** Use texture groups so only the first room's textures are in the initial download; use OGG audio and stream music.
- **Loading.** If you report loading yourself, turn the built-in loading bar off and call `zoko_game_loading_start()` at the start of the loading room, `zoko_game_loading_progress(p)` a few times per second (each call produces a `response` event, so not every step), and `zoko_game_loading_stop()` when the player can act.
- **Audio unlock.** Browsers keep audio suspended until the first click or key press. Show a "click to play" room before music.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so `window_set_fullscreen(true)` can work from an input event, but it fullscreens only your canvas; do not add a competing button.
- **Single thread.** The HTML5 target is single-threaded; keep Step events cheap while ads show, and keep memory modest for mobile browsers.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: `zoko_game_report_chat(report_json)`, `zoko_game_set_screenshot_provider(enabled)` with `zoko_game_answer_screenshot(url)`, and `zoko_data_mirror_local_storage(options_json)` (stopped with `zoko_data_stop_mirror_local_storage()`). The canvas can only be read right after a frame is drawn, so call `zoko_game_screenshot_tick()` in the Post Draw event; a pending request is answered there (the social event is `screenshot_requested`, with a 1.5 second fallback). The mirror only sees `localStorage`; where your GameMaker runtime saves depends on its version, so test it. Failures arrive as the social event `mirror_error`. Non-HTML5 targets use the GML simulator.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`zoko_ad_request_ad("midgame")`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with `ad_error` with `adCooldown` until your game has called `zoko_game_gameplay_start()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `zoko_game_gameplay_start()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **On a non-HTML5 target** the simulator answers one tick later with the same Social events. Edit `global.zoko_sim_config` before `zoko_init()`: `disabled`, `account_available`, `logged_in`, `username`, `user_id`, `friend_count`, `ad_behaviour` (`"fill"`, `"no_fill"` or `"error"`), `ad_duration` (seconds, default 1.5), `adblock`, `offline`, `mute_audio`, `disable_chat`, `store_available`, `verbose`. The simulated store has three items and an in-memory inventory; cloud save is in memory only.
- **Difference to remember.** The simulator does not enforce the three-minute midgame cooldown (`adCooldown`) that the portal and the browser's local mode do.
- **On an HTML5 export served from `localhost`** the browser SDK runs its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second ad overlay, fake players, `localStorage` saves, `?sdk_debug=true`, `?ad_response=unfilled`. A page opened from disk or served from another host is `disabled` unless you add `?useLocalSdk=true`.
- **Then** open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## Known pitfalls

<!-- search: headings-only -->

- **`sdkNotLoaded` in the `response`.** The HTML5 page has no SDK script tag.
- **Functions undefined on HTML5.** `zokogames.js` is not ticked for the HTML5 platform.
- **Functions undefined on Windows, macOS or Linux.** `zokogames_sim.gml` is not included for those platforms.
- **No events arrive.** The controller must be persistent, handle **Async - Social**, and filter on `async_load[? "type"] == "zoko"`.
- **`call_later` not found.** Update GameMaker to 2023.1 or newer.
- **`(no GMS_API)` in the console.** The game runs on the GX.games (WebAssembly) export, which is not supported. Export for HTML5.
- **Game stays paused or silent after an ad.** Resume on `ad_error` as well as `ad_finished`.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/engines/cocos

# Cocos

The Cocos package (`packages/sdk-engines/cocos`) is a promise-based TypeScript wrapper over `window.ZokoGames.SDK` for **Cocos Creator 3.x**. Names match the JavaScript SDK one to one (`ZokoSDK.game.gameplayStart()`). In the Creator editor, in native builds, or when the SDK script cannot be loaded in a browser, a built-in simulator answers so the game keeps running. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (1.7.1): the module and the example type-check in TypeScript strict mode against the official engine declarations of Cocos Creator 3.8.8 (`@cocos/creator-types`), and command-line web builds (web-desktop and web-mobile) of Cocos Creator 3.8.8 ran in a real browser (2026-11-23); the editor Preview mode was not used. Send the Creator version and the exact error to [support](https://docs.zokogames.com/business/support) if the first import fails. The JavaScript SDK underneath is the tested part. Release 1.7.1 only adds a script-load timeout and is covered by unit tests; it was re-run in the engine and on production on 2026-11-23 (12 areas).

## Install

Download the Cocos Creator plugin: [/sdk-engines/zokogames-cocos-1.7.1.zip](https://www.zokogames.com/sdk-engines/zokogames-cocos-1.7.1.zip) (the same files as the folder in the repository).

[/sdk-engines/cocos.zip](https://www.zokogames.com/sdk-engines/cocos.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. Copy `assets/zokogames/` (`ZokoSDK.ts`, `ZokoClient.ts`, `ZokoTypes.ts`, `ZokoSimulator.ts`, and `examples/ZokoStoreExample.ts`) into your project's `assets/` folder.
2. Paste the contents of `build-templates/zokogames-sdk-snippet.html` (one script tag for `https://sdk.zokogames.com/zokogames-sdk-v1.js`) into the `<head>` of your build templates, `build-templates/web-desktop/index.ejs` and `build-templates/web-mobile/index.ejs`, before the engine starts. Creator renders `index.ejs` files in `build-templates/<platform>/` instead of its default page; if your project has none yet, generate the default ones first as described on the "Custom Project Build Template" page of the Creator manual, then add the tag. A plain `index.html` in that folder would be copied over the rendered page and goes stale when Creator updates its template, so edit `index.ejs`. If the tag is missing, the module injects the script on the first `init()`, but the upload validator looks for the tag, so add it.
3. `import ZokoSDK from "./zokogames/ZokoSDK";` (a named `{ ZokoSDK }` import also works) and call `await ZokoSDK.init()` once at startup.

## Which path

| You are | Do this |
| --- | --- |
| A Cocos hobbyist or small team with a web build | Copy the folder, paste the snippet, wrap ad and save calls as below, build Web Mobile, upload. |
| Writing plain TypeScript tests | Use `ZokoClient.ts` (no engine imports) instead of `ZokoSDK.ts`, which imports `cc`. |

## A working component

One component in your first scene covering init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score.

```ts
import { _decorator, Component, game } from "cc";
import ZokoSDK from "./zokogames/ZokoSDK";
const { ccclass } = _decorator;

@ccclass("ZokoBoot")
export class ZokoBoot extends Component {
  private live = false;
  private adActive = false;

  async start() {
    try { await ZokoSDK.init(); } catch (e) { console.warn("ZokoGames init failed", e); }
    this.live = ZokoSDK.isAvailable;                       // initialised and not "disabled"
    if (!this.live) return this.beginGame();               // the game must run without the portal

    ZokoSDK.game.addSettingsChangeListener((s) => this.applyMute(s.muteAudio));
    this.applyMute(ZokoSDK.game.settings.muteAudio);
    const best = Number(ZokoSDK.data.getItem("best") ?? "0") || 0;   // load: synchronous
    this.beginGame(best);
  }

  // Wrap every ad call. game.pause() stops the main loop; resume in a finally so both outcomes resume.
  async showAd(type: "midgame" | "rewarded"): Promise<boolean> {
    if (!this.live) return false;
    let finished = false;
    try {
      await ZokoSDK.ad.requestAd(type, {
        adStarted: () => { this.adActive = true; game.pause(); },
        adFinished: () => { finished = true; },
        adError: (e) => console.log("no ad:", e.code),       // adCooldown, unfilled, adblock ...
      });
    } catch (e) {
      console.warn("ad call failed", e);                    // for example sdkDisabled
    } finally {
      if (this.adActive) { this.adActive = false; game.resume(); }
    }
    return finished;
  }

  async onRewardClicked() { if (await this.showAd("rewarded")) this.grantReward(); }   // reward only when finished
  async onRoundEnded(score: number) {
    this.onPlayStop();
    this.save(score);
    await this.submitScore(score);
    await this.showAd("midgame");                           // natural break
  }

  onPlayStart() { if (this.live) void ZokoSDK.game.gameplayStart().catch(() => {}); }
  onPlayStop()  { if (this.live) void ZokoSDK.game.gameplayStop().catch(() => {}); }

  save(score: number) {
    if (!this.live) return;
    try { ZokoSDK.data.setItem("best", String(score)); }     // synchronous; uploaded in the background
    catch (e) { console.warn((e as { code?: string }).code); } // dataLimitExceeded
  }

  async submitScore(score: number) {
    if (!this.live) return;
    try {
      const user = await ZokoSDK.user.getUser();
      if (!user) return;                                     // guests are not ranked
      // "" works only on a board WITHOUT an encryption key; see leaderboards for the encrypted form.
      await ZokoSDK.user.submitScore({ encryptedScore: "", score });
    } catch (e) { console.warn((e as { code?: string }).code); }
  }

  private applyMute(mute: boolean) { if (!this.adActive) { /* set your audio master volume: mute ? 0 : 1 */ } }
  private beginGame(_best = 0) {
    if (this.live) void ZokoSDK.game.loadingStop().catch(() => {});   // ends the portal's loading bar
    this.onPlayStart();
  }
  private grantReward() { /* ... */ }
}
```

On a web build the Cocos TypeScript runs in the page, where the Web Crypto API exists, so a keyed leaderboard is practical here: use the `encryptScore` function from the [leaderboards page](https://docs.zokogames.com/sdk/leaderboards#client-submission), passing `user.__dangerousUserId` and your game id, and send its result as `encryptedScore`. Keep in mind that a key shipped in the browser can be read; for real stakes compute scores on your server.

## State and simulator

<!-- search: headings-only -->

| Member | Meaning |
| --- | --- |
| `ZokoSDK.init()` | Once, first; safe to call twice. Does not reject for a missing script: the simulator takes over (see pitfalls). |
| `ZokoSDK.isInitialized`, `isAvailable`, `isSimulated`, `isSupportedPlatform` | Initialised; initialised and not disabled; the simulator is answering; running in a browser build. |
| `ZokoSDK.environment` | `"local"`, `"zokogames"` or `"disabled"`. |
| `ZokoSDK.isQaTool` | Running in the QA tool. |

`ZokoSDK.configureSimulator(options)` tunes the simulator; call it before `init()`. Options: `disabled`, `accountAvailable`, `loggedIn`, `username`, `userId`, `friendCount`, `adBehaviour` (`"fill"`, `"no_fill"` or `"error"`), `adDurationMs` (default 1500), `adblock`, `muteAudio`, `disableChat`, `kidsMode`, `instantMultiplayer`, `offline`, `storeAvailable`, `verbose`.

## Mapping

<!-- search: headings-only -->

Names are identical to JavaScript; calls return promises (the `data` calls are synchronous). Errors are plain `{ code, message }` objects.

| JavaScript | Cocos (TypeScript) |
| --- | --- |
| `SDK.init()` | `await ZokoSDK.init()` |
| `SDK.ad.hasAdblock()` | `await ZokoSDK.ad.hasAdblock()` |
| `SDK.ad.requestAd(type, cbs)` | `await ZokoSDK.ad.requestAd(type, { adStarted, adFinished, adError })`; resolves after the ad ended, and rejects (for example `sdkDisabled`) without calling `adError` when the call cannot start |
| `SDK.banner.requestBanner(...)` | `ZokoSDK.banner.requestBanner(...)` (needs a DOM container) or `ZokoSDK.banner.requestBannerForNode(id, node, size?)` |
| `SDK.banner.requestResponsiveBanner(id)`, `clearBanner(id)`, `clearAllBanners()` | `ZokoSDK.banner.requestResponsiveBanner(id)`, `ZokoSDK.banner.clearBanner(id)`, `ZokoSDK.banner.clearAllBanners()` |
| `SDK.game.*`, `SDK.user.*`, `SDK.data.*`, `SDK.store.*`, `SDK.analytics.*` | The same names (`game.loadingProgress`, `game.isOffline` with `addOfflineListener` / `removeOfflineListener`, invite params, `store.getPurchaseToken` included) |
| `SDK.achievements.*` | `ZokoSDK.achievements.list()`, `unlock(key)`, `onUnlock(cb)` (returns an unsubscribe function); see [achievements](https://docs.zokogames.com/sdk/achievements) |
| `ERROR_CODES` | `ZOKO_ERROR_CODES.store`, `.ad`, `.banner`, `.user`, `.data`, `.room`, `.general` |

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `ZokoSDK.game.settings.kidsMode` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `disableChat`, which the portal sets to true in the same cases. To test it, switch on `kidsMode` in the simulator (it also turns chat off, as the portal does). See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

`ZokoSDK.game.room` passes straight through to the JavaScript `SDK.game.room`. It is `undefined` when the portal's SDK is older than 1.3.0 and in the built-in simulator, which has no room channel, so check it before use and test rooms in a web build. The methods are `send(data, { to })`, `setState(patch)`, `getState()`, `members()`, `isHost()` and `selfId`, with `onMessage`, `onState`, `onMembers`, `onHostChange` and `onError` (each returns an unsubscribe function) or the `add...Listener` and `remove...Listener` pairs.

```ts
async startMatch() {
  await ZokoSDK.init();
  await ZokoSDK.game.updateRoom({ roomId: "match-1", isJoinable: true });
  const room = ZokoSDK.game.room;
  if (!room) return;                                   // simulator or an older SDK
  room.onMessage((m) => {
    const move = m.data as { cell: number; mark: string };   // data is typed unknown
    this.placeMark(move.cell, move.mark);
  });
  room.onHostChange((_hostId, isHost) => { if (isHost) void room.setState({ turn: "X" }); });
  room.onError((e) => console.warn("room:", e.code));
}

onCellClicked(cell: number) { void ZokoSDK.game.room?.send({ cell, mark: "X" }); }
```

## Banners

Banners are drawn in the page, not in the canvas. Add a UI node with a `UITransform` where the banner should sit and let the module place a container over it. Request banners on menu scenes only.

```ts
await ZokoSDK.banner.requestBannerForNode("menu-banner", this.bannerSlot);            // largest size that fits
await ZokoSDK.banner.requestBannerForNode("menu-banner", this.bannerSlot, "300x250"); // a static size
await ZokoSDK.banner.clearBanner("menu-banner");
```

`ZokoSDK.rectOfNode(node)` returns the node's normalised rectangle for `ZokoSDK.banner.requestBannerForRect(id, rect, size?)`. A node without a `UITransform` fails with `invalidArgument`.

## Purchases

```ts
if (ZokoSDK.store.isAvailable) {
  try {
    const items = await ZokoSDK.store.getCatalogItems({ limit: 20 });
    const { itemId } = await ZokoSDK.store.buyItem(items[0].sku);
    const token = await ZokoSDK.store.getPurchaseToken();      // send to your server and verify there
  } catch (e) {
    if ((e as { code?: string }).code === "purchaseCancelled") return;
  }
}
```

Verify ownership on your server ([in-game purchases](https://docs.zokogames.com/sdk/purchases)). `examples/ZokoStoreExample.ts` is a ready component.

## Web export settings that matter

- **Build target:** **Web Mobile** or **Web Desktop**. Leave **Remote server address** empty: everything must ship in the zip, with relative paths.
- **No pre-compression.** Cocos does not write `.br` or `.gz`; upload the build as is. The game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but Cocos requests plain names, so renamed files would break. The initial-download estimate uses uncompressed sizes. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile).
- **Size.** Use **Auto Atlas**, compressed texture formats (ETC2 or ASTC for mobile) and OGG or MP3 audio at modest bitrates. Split rarely used content into **Asset Bundles** loaded after the first scene. Disable unused engine modules in Project Settings > Feature Cropping. Remote bundles count toward the initial download only when fetched before the first frame.
- **Canvas sizing.** The frame size changes with fullscreen and rotation. Set a design resolution and a resolution policy (Fixed Height or Show All) so the game fits every [required resolution](https://docs.zokogames.com/requirements/gameplay); `requestBannerForNode` assumes the canvas fills the page for exact placement.
- **Audio unlock.** Browsers keep audio suspended until the first tap or click. Start music from a "tap to play" screen, not in `start()`.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so Cocos' own fullscreen call works from an input event, but it fullscreens only your canvas; do not add a competing button.
- **Memory.** Mobile browsers have small heaps; release unused bundles and avoid loading every scene's textures up front.
- **Loading.** Call `ZokoSDK.game.loadingStart()` before `director.preloadScene(name, (done, total) => void ZokoSDK.game.loadingProgress((done / total) * 100))`, and `loadingStop()` when the first scene runs.

Upload: build, zip the build folder **contents** so `index.html` is at the archive root, upload it in the developer console, and run the [Preview tool](https://www.zokogames.com/preview) first.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: `sdk.game.reportChat(report)`, `sdk.game.onScreenshotRequest(handler)` and `sdk.data.mirrorLocalStorage({ prefix: "save_" })` (returns a stop function). `init()` registers a default provider that reads the game canvas at `Director.EVENT_AFTER_DRAW`; turn it off with `sdk.useDefaultScreenshots(false)` before `init()`. Cocos `sys.localStorage` is the browser `localStorage` on web, so it can be mirrored. The editor simulator validates the same limits.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`ZokoSDK.ad.requestAd("midgame", ...)`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with `adError` with `adCooldown` until your game has called `ZokoSDK.game.gameplayStart()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `ZokoSDK.game.gameplayStart()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **In the Creator editor and in native builds** `ZokoSDK.isSimulated` is true. The simulator keeps cloud save in `localStorage` when available.
- **Difference to remember.** The simulator does not enforce the three-minute midgame cooldown (`adCooldown`) that the portal and the browser's local mode do.
- **A web preview or build on `localhost`** uses the real JavaScript SDK's [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second ad overlay, fake players, `localStorage` saves, `?sdk_debug=true`, `?ad_response=unfilled`. On another host without the portal around it, the environment is `disabled`, so calls reject with `sdkDisabled`; add `?useLocalSdk=true` to test.
- **Then** open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## Known pitfalls

<!-- search: headings-only -->

- **`sdkNotLoaded`.** The SDK script did not load (offline, blocked, or the build template snippet is missing).
- **`sdkNotInitialized`.** `await ZokoSDK.init()` first.
- **"Cannot find module `cc`".** You are running the file outside Creator; use `ZokoClient.ts` in plain TypeScript tests.
- **The simulator answers when the script is blocked.** In a browser, if `sdk.zokogames.com` is unreachable (offline, an extension), `init()` falls back to the simulator instead of failing, so fake ads and a fake player appear. In production that is harmless, but do not read it as proof the real SDK works; check `ZokoSDK.isSimulated` and `environment` in your test builds.
- **Banner node errors.** The node needs a `UITransform` and the canvas should fill the page.
- **Game stays paused after an ad.** Resume in a `finally`, as above.
- **Native builds.** Only the simulator exists; the real SDK is a web feature.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/engines/defold

# Defold

The `zokogames` library (`packages/sdk-engines/defold`) is a Lua API plus a small native extension (`zokogames/ext.manifest`, `zokogames/src/zokogames_ext.cpp` and `zokogames/lib/web/lib_zokogames.js`, compiled by Defold's build server when you bundle). It evaluates a JavaScript bridge with `html5.run()` and loads the ZokoGames SDK script for you. With the extension built in, the browser SDK pushes results straight into Lua (`zokogames.is_native` is `true`); if the extension is not part of your bundle, the module polls the bridge every 50 ms instead. Outside HTML5 (the editor, desktop builds) a Lua simulator answers. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (1.7.0): built for the web with Defold's official build tool, bob 1.14.1, with the native extension built by Defold's build server; the library resolved as a dependency and the bundle ran every call in a real browser (2026-11-23). Other Defold versions were not tried. Send the Defold version and the exact error or build-server log to [support](https://docs.zokogames.com/business/support) if the first import fails.

## Install

Download the Defold plugin: [/sdk-engines/zokogames-defold-1.7.0.zip](https://www.zokogames.com/sdk-engines/zokogames-defold-1.7.0.zip) (the same files as the folder in the repository).

[/sdk-engines/defold.zip](https://www.zokogames.com/sdk-engines/defold.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. Add the library to your project. It is a Defold library project (`game.project` has `[library] include_dirs = zokogames`). Either copy the `zokogames` folder into your project, or host the archive and add it as a dependency, then run **Project > Fetch Libraries**:

```ini
[project]
dependencies#0 = <URL of your zokogames library archive>
```

2. Require the module and call `init` once from a script's `init` function:

```lua
local zoko = require "zokogames.zokogames"
```

3. Bundle for HTML5 with native extensions enabled (the default). The module injects `https://sdk.zokogames.com/zokogames-sdk-v1.js` itself on the first `init`, so no HTML change is needed to run. But the upload validator reads your files statically, and the injected URL lives inside the bridge code, so it can raise `no_sdk` ("the SDK script is not referenced"), and a build without the SDK cannot go to full launch (see [build validation](https://docs.zokogames.com/requirements/build-validation)). To be safe, use a custom HTML5 template: copy Defold's default `/builtins/manifests/web/engine_template.html` into your project, point the **.html Shell** setting at it (`htmlfile` in the `[html5]` section of `game.project`) and add `<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>` to its `<head>`; the module then finds the SDK already loaded.

The module also ships `bridge_js.lua` (the embedded bridge source, regenerated with `tools/embed-defold-bridge.mjs` after editing `zokogames/web/zokogames_bridge.js`) and `examples/store.script`.

## Which path

| You are | Do this |
| --- | --- |
| A Defold hobbyist with a finished game | Copy the folder, add the script below to a bootstrap object, bundle HTML5, upload. |
| Cautious about native extensions | Bundle without them; the module falls back to polling (up to 50 ms latency). |

## A working script

Attach this to a game object in your bootstrap collection. It covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score.

```lua
local zoko = require "zokogames.zokogames"

local function set_paused(p)
	msg.post("@system:", "set_time_step", { factor = p and 0 or 1, mode = 0 })   -- sound: zoko.mute_audio_during_ads
end

function init(self)
	self.in_ad = false
	zoko.init(function(err)
		if err then print("ZokoGames:", err.code) end         -- the game must still run
		if zoko.is_available() then                          -- initialised and not "disabled"
			set_paused(false)                                -- portal mute: zoko.follow_portal_mute
			self.best = tonumber(zoko.data.get_item("best")) or 0   -- load: synchronous, nil when missing
			zoko.game.loading_stop()                         -- ends the portal's loading bar: the game can be played now
		end
		msg.post("#", "start_game")
	end)
end

-- Ads: pause on started, resume on finished AND error. Never pause before `started`.
local function show_ad(self, ad_type, on_reward)
	if not zoko.is_available() then return end
	local function resume()
		if not self.in_ad then return end
		self.in_ad = false
		set_paused(false)
	end
	zoko.ad.request_ad(ad_type, {
		started = function() self.in_ad = true; set_paused(true) end,
		finished = function() resume(); if on_reward then on_reward() end end,   -- reward only here
		error = function(e) resume(); print("no ad:", e.code) end,              -- adCooldown, unfilled, adblock ...
	})
end

function on_message(self, message_id, message, sender)
	if message_id == hash("start_game") then
		if zoko.is_available() then zoko.game.gameplay_start() end             -- player has control
	elseif message_id == hash("round_over") then
		if zoko.is_available() then zoko.game.gameplay_stop() end
		local score = message.score
		if score > (self.best or 0) then
			self.best = score
			local ok, e = zoko.data.set_item("best", score)                   -- numbers are converted to strings
			if not ok then print(e.code) end                                   -- for example dataLimitExceeded
		end
		zoko.user.get_user(function(err, user)
			-- "" works only on a board WITHOUT an encryption key; see the leaderboards page.
			if not err and user then zoko.user.submit_score("", score) end
		end)
		show_ad(self, "midgame")                                               -- natural break
	elseif message_id == hash("reward_button") then
		show_ad(self, "rewarded", function() print("reward granted") end)
	end
end
```

The wrapper handles sound: it sets the gain of the "master" sound group to 0 while an ad plays (`zoko.mute_audio_during_ads`) and while the portal asks for mute (`zoko.follow_portal_mute`), and restores your gain afterwards. Both are `true` by default; set one to `false` to handle that part yourself. Pausing the game (`set_time_step` above) stays your job.

About the leaderboard: a board **with** an encryption key counts only a correctly encrypted payload ([leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), and the library has no encryption helper, so `""` works only on a board without a key. Otherwise compute scores on your server and use the server API. The player id for encryption is the `__dangerousUserId` field of the user table.

## How calls work

<!-- search: headings-only -->

Names are snake_case. Calls that wait for the browser take an optional callback as the **last** argument with the shape `callback(err, result)`. `err` is `nil` on success and a table `{ code, message }` otherwise (`zoko.is_error(err, "purchaseCancelled")` tests a code).

State is available as plain fields once `init` has finished: `zoko.environment` (`"local"`, `"zokogames"` or `"disabled"`), `is_initialized`, `is_simulated`, `is_native`, `is_qa_tool`, `is_user_account_available`, `is_store_available`, `is_instant_multiplayer`, `is_offline`, `system_info`, `invite_params` and `settings`. `zoko.is_available()` is true when initialised and not disabled.

| JavaScript | Lua |
| --- | --- |
| `SDK.init()` | `zoko.init(callback)` |
| `SDK.ad.requestAd(type, cbs)` | `zoko.ad.request_ad("midgame", { started = f, finished = f, error = f })` |
| `SDK.ad.hasAdblock()` | `zoko.ad.has_adblock(callback)` |
| `SDK.banner.requestBanner(...)` | `zoko.banner.request_banner(id, width, height, rect, callback)` |
| `SDK.banner.requestResponsiveBanner(id)` | `zoko.banner.request_responsive_banner(id, rect, callback)` |
| `clearBanner`, `clearAllBanners` | `zoko.banner.clear_banner(id, callback)`, `zoko.banner.clear_all_banners(callback)` |
| `SDK.game.gameplayStart()` and friends | `zoko.game.gameplay_start()`, `gameplay_stop`, `loading_start`, `loading_stop`, `happytime`, `left_room` |
| `loadingProgress(n)` | `zoko.game.loading_progress(n, callback)` |
| `reportGameCompletedPercentage(n)` | `zoko.game.report_game_completed_percentage(n, callback)` |
| `setGameContext(obj)`, `clearGameContext()` | `zoko.game.set_game_context(table, callback)`, `clear_game_context` |
| `updateRoom(u)`, `inviteLink(p)` | `zoko.game.update_room(table, callback)`, `zoko.game.invite_link(table, callback)` |
| `showInviteButton(p)`, `hideInviteButton()` (deprecated) | `zoko.game.show_invite_button(table, callback)`, `zoko.game.hide_invite_button(callback)`; use `update_room` instead |
| `isInstantMultiplayer` | `zoko.game.is_instant_multiplayer()` (alias `is_instant_join()`), field `zoko.is_instant_multiplayer` |
| `SDK.game.settings` | `zoko.game.get_settings()`, `add_settings_change_listener(fn)`, `remove_settings_change_listener(fn)` |
| `isOffline`, offline listeners | `zoko.game.is_offline()`, `add_offline_listener(fn)` (gets the new boolean), `remove_offline_listener(fn)` |
| join room listeners | `zoko.game.add_join_room_listener(fn)`, `remove_join_room_listener(fn)` |
| `getInviteParam(k)` | `zoko.game.get_invite_param(key)` (synchronous) |
| `SDK.user.getUser()` | `zoko.user.get_user(callback)` |
| `SDK.user.isUserAccountAvailable`, `systemInfo` | `zoko.user.is_user_account_available()`, `zoko.user.get_system_info()` |
| `listFriends(opts)` | `zoko.user.list_friends(page, size, callback)` |
| `getUserToken(opts)` | `zoko.user.get_user_token(signing_key_type, callback)` (pass `nil` for the default) |
| `showAuthPrompt()`, `showAccountLinkPrompt()` | `zoko.user.show_auth_prompt(callback)`, `show_account_link_prompt(callback)`; listeners `add_auth_listener(fn)`, `remove_auth_listener(fn)` |
| `submitScore(opts)` | `zoko.user.submit_score(encrypted_score, score, callback)` |
| `SDK.data.*` | `zoko.data.get_item(key)` (`nil` when missing), `has_key`, `set_item(key, value)` (returns `true`, or `false` and an error table), `remove_item`, `clear` |
| `SDK.store.*` | `zoko.store.is_available()`, `get_catalog_items({ limit = 20 }, cb)`, `get_player_inventory(options, cb)`, `buy_item(sku, cb)`, `consume_item(sku, qty, cb)`, `get_purchase_token(cb)`, `set_sandbox(bool)` |
| `SDK.achievements.list()` / `unlock(key)` / `onUnlock` | `zoko.achievements.list(callback)`, `zoko.achievements.unlock(key, callback)`, `zoko.achievements.on_unlock(fn)`, `zoko.achievements.remove_unlock_listener(fn)`; see [achievements](https://docs.zokogames.com/sdk/achievements) |
| `SDK.analytics.trackOrder(p, o)` | `zoko.analytics.track_order(provider, order, callback)` |
| `SDK.analytics.track(name, params)` (1.7.0) | `zoko.analytics.track(name, params)` (no callback) |

`zoko.VERSION` is the JavaScript SDK release the library was written against. The published plugin (1.7.0) reports "1.7.0". Plugin versions are separate from the SDK version, and the plugins are repacked at the next plugin release. `zoko.SDK_SCRIPT_URL` is the script it loads. The deprecated `zoko.user.get_xsolla_user_token(callback)` is an alias of `zoko.store.get_purchase_token`. Error codes are in `zoko.ERROR_CODES` (a table keyed by module, for example `zoko.ERROR_CODES.store`).

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `zoko.settings.kidsMode` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `disableChat`, which the portal sets to true in the same cases. To test it, switch on `zoko.sim.kids_mode` in the simulator (it also turns chat off, as the portal does). See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

`zoko.game.room` carries it (also `zoko.room`). Payloads are JSON: tables, strings, numbers and booleans. Lua tables cannot hold `nil`, so use `remove_state` to delete a state key. Listen with `room.set_listener(self, fn)`, which calls `fn(self, event, data)` with `event` one of `"message"`, `"state"`, `"members"`, `"host_changed"` or `"error"`, or with the per-event `add_*_listener` functions. The native extension and the polling fallback share the same bridge, so there is nothing extra to build. Outside HTML5 the simulator is one room with one member that receives its own messages and state changes.

| JavaScript | Lua |
| --- | --- |
| `room.send(data, { to })` | `zoko.game.room.send(data, callback)`, `send_to(member_id, data, callback)` |
| `room.onMessage(cb)` | event `"message"` (`data` = `{ from, data, direct, seq, ts }`) or `add_message_listener(fn)` / `remove_message_listener(fn)` |
| `room.setState(patch)` | `set_state(patch, callback)`, `remove_state(keys, callback)` |
| `room.getState()`, `room.onState(cb)` | `get_state()`; event `"state"` (`{ state, change }`) or `add_state_listener(fn)` / `remove_state_listener(fn)` |
| `room.members()`, `room.onMembers(cb)` | `members()`; event `"members"` or `add_members_listener(fn)` / `remove_members_listener(fn)` |
| `room.isHost()`, `room.onHostChange(cb)`, `room.selfId` | `is_host()`; event `"host_changed"` (`{ host_id, is_host }`); `self_id()`; `add_host_change_listener(fn)` / `remove_host_change_listener(fn)` |
| `room.addLeftListener(cb)` (1.7.0) | event `"left"` (`{ reason, room_id }`) or `add_left_listener(fn)` / `remove_left_listener(fn)` |
| `room.onError(cb)` | event `"error"` or `add_error_listener(fn)` / `remove_error_listener(fn)` |

```lua
function init(self)
	zoko.init(function(err)
		if err then return end
		zoko.game.room.set_listener(self, function(self, event, data)
			if event == "message" then print(data.from, data.data.cell)
			elseif event == "host_changed" and data.is_host then zoko.game.room.set_state({ turn = "X" }) end
		end)
		zoko.game.update_room({ roomId = "match-1", isJoinable = true })
	end)
end

function on_input(self, action_id, action)
	if action.pressed then zoko.game.room.send({ cell = 4, mark = "X" }) end
end
```

## Banners

Banners are DOM elements drawn over the canvas. Describe where one should sit with a rectangle `{ x, y, w, h }` in window pixels with the origin at the **top left** (optional `area_w` and `area_h` name the window size the numbers refer to), or build one from a GUI node (centred pivot assumed). Request banners on menu screens only.

```lua
local rect = zoko.banner.rect_from_gui_node(gui.get_node("banner_slot"))
zoko.banner.request_responsive_banner("menu", rect, function(err)
	if err then print("banner:", err.code) end
end)
```

## Purchases

```lua
if zoko.store.is_available() then
	zoko.store.get_catalog_items({ limit = 20 }, function(err, items)
		if err or #items == 0 then return end
		zoko.store.buy_item(items[1].sku, function(e, paid)
			if zoko.is_error(e, "purchaseCancelled") then return end
			if e then print(e.code) return end
			zoko.store.get_purchase_token(function(_, token) print(token) end)   -- send to your server and verify there
		end)
	end)
end
```

Verify ownership on your server ([in-game purchases](https://docs.zokogames.com/sdk/purchases)). `examples/store.script` is the full flow.

## HTML5 export settings that matter

<!-- search: headings-only -->

- **Bundle > HTML5:** architecture `wasm-web`. Add `js-web` only if you must support very old browsers (it roughly doubles the size). Do not choose a threaded variant: threads need `SharedArrayBuffer`, which needs cross-origin isolation headers, and the portal sends none. Release, not Debug.
- **No renaming, no pre-compression.** Keep the engine's `.wasm` unmodified and do not rename files to `.br` or `.gz`: the loader requests plain names. The game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but only by file name, so it helps engines that request those names (Unity). The initial-download estimate uses uncompressed sizes. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile).
- **Size.** Use texture profiles (Basis or ASTC for web), remove unused engine components in `game.project`, and use collection proxies with excluded resources or live update to load later levels.
- **Canvas sizing.** The frame size changes with fullscreen and rotation. Choose a scale mode in the HTML5 section of `game.project` that keeps your aspect ratio, so the game fits every [required resolution](https://docs.zokogames.com/requirements/gameplay).
- **Memory.** The HTML5 heap is fixed by game settings; keep it modest for mobile browsers and unload collections you no longer need.
- **Audio unlock.** Browsers keep audio suspended until the first click or tap. Start music from a "tap to play" screen, not in `init`.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame). The frame permits fullscreen, so Defold's own fullscreen request works from an input event, but it fullscreens only your canvas; do not add a competing button.
- **Loading.** Call `zoko.game.loading_start()` when your loading collection starts, `loading_progress(p)` as proxies load, and `loading_stop()` when the player can act.

Upload: **Project > Bundle > HTML5**, zip the bundle folder **contents** so `index.html` is at the archive root, upload it in the developer console, and run the [Preview tool](https://www.zokogames.com/preview) first.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: `zoko.game.report_chat(report, callback)`, `zoko.game.set_screenshot_provider(fn)` and `zoko.data.mirror_local_storage({ prefix = "save_" })`. The canvas is only readable right after drawing, so call `zoko.game.screenshot_tick()` at the end of your render script (a 1.5 second timer answers if you do not). `sys.save` files live in IndexedDB, not `localStorage`, so the mirror does not see them; use `zoko.data.set_item`. The Lua simulator accepts all three.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`zoko.ad.request_ad("midgame", ...)`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with the `error` callback with `adCooldown` until your game has called `zoko.game.gameplay_start()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `zoko.game.gameplay_start()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **Outside HTML5** (the editor, desktop bundles) `zoko.is_simulated` is true and the Lua simulator answers. Edit fields of `zoko.sim` before `init`: `disabled`, `account_available`, `logged_in`, `username`, `user_id`, `friend_count`, `ad_behaviour` (`"fill"`, `"no_fill"` or `"error"`), `ad_duration` (seconds, default 1.5), `adblock`, `mute_audio`, `offline`, `disable_chat`, `store_available`, `verbose`. Cloud save is kept with `sys.save`; the simulated store has three items and an in-memory inventory.
- **Difference to remember.** The simulator does not enforce the three-minute midgame cooldown (`adCooldown`) that the portal and the browser's local mode do.
- **An HTML5 bundle on `localhost`** uses the JavaScript SDK's own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second ad overlay, fake players, `localStorage` saves, `?sdk_debug=true`, `?ad_response=unfilled`. Serve the bundle from a local web server; on another host the environment is `disabled` unless you add `?useLocalSdk=true`.
- **Then** open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## Known pitfalls

<!-- search: headings-only -->

- **`zoko.is_native` is false in the browser.** The bundle was made without native extensions. The polling fallback still works, with up to 50 ms latency.
- **`module 'zokogames.bridge_js' not found`.** Copy the whole `zokogames/` folder; regenerate the file with `node tools/embed-defold-bridge.mjs` after editing the bridge.
- **Callbacks never fire.** Call `zoko.init` first and keep the objects that own the callbacks alive (a script whose game object was deleted will not receive them).
- **Build server error in `zokogames_ext.cpp`.** Report the Defold version and the full log; or bundle without native extensions.
- **`sdkNotLoaded`.** The browser could not load the SDK script (offline or blocked).
- **Game stays paused after an ad.** Resume in `error` as well as `finished`. A request that cannot start at all (SDK disabled) calls only `error`, never `started`.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/engines/wonderland

# Wonderland Engine

The Wonderland package (`packages/sdk-engines/wonderland`) is a TypeScript package for **Wonderland Engine 1.x** web projects. `ZokoSDK` is a promise-based wrapper over `window.ZokoGames.SDK` with names identical to the JavaScript SDK (`ZokoSDK.game.gameplayStart()`), and the **zoko-sdk** component initialises it, makes it reachable from every other component, pauses the scene and silences audio while an ad plays, follows the portal's mute setting, ends the portal's loading bar and answers the feedback form with a picture of the canvas. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Plugin 1.7.3. Type-checked in strict mode against `@wonderlandengine/api` 1.6.1 and unit-tested with a stub of the engine. Verified 2026-11-23 with Wonderland Editor 1.6.1: a project packaged by the editor runs the plugin in the real runtime and passes the production check on all 12 areas. Observed in the runtime: the SDK boots once, components of paused types are deactivated during an ad and restored after, an audio context the plugin tracks is suspended during ads and resumed after, and banner projection gives a sane rectangle. Still unverified: the engine's own built-in audio sources, XR sessions and a camera with a partial viewport. Send the editor version and the exact error to [support](https://docs.zokogames.com/business/support) if something fails. Release 1.7.3 only adds a script-load timeout and is covered by unit tests; it was re-run in the engine and on production on 2026-11-23 (12 areas).

## Install

Download the Wonderland package: [/sdk-engines/zokogames-wonderland-1.7.3.zip](https://www.zokogames.com/sdk-engines/zokogames-wonderland-1.7.3.zip) (the same files as the folder in the repository).

[/sdk-engines/wonderland.zip](https://www.zokogames.com/sdk-engines/wonderland.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. Copy the package's `src/` folder into your project's `js/` folder as `js/zokogames/` (`ZokoSDK.ts`, `ZokoSdkComponent.ts`, `ZokoClient.ts`, `ZokoTypes.ts`, `ZokoSimulator.ts`, and the helpers `ZokoPause.ts`, `ZokoAdFlow.ts`, `ZokoProjection.ts`). The editor compiles `.ts` files under `js/`.
2. Make the editor see the component: editor 1.6.1 lists components only from files directly under `js/`, not from subfolders. Add `js/zoko-sdk-component.ts` containing `export { ZokoSdkComponent } from './zokogames/index';` (see `examples/zoko-sdk-component.ts`), add `engine.registerComponent(ZokoSdkComponent)` (from `./zokogames/index`) to `js/index.js`, then press **Rebuild**.
3. Add the **zoko-sdk** component to an object of your first scene.
4. Put one script tag for `https://sdk.zokogames.com/zokogames-sdk-v1.js` in the `<head>` of the page the editor generates (use your own HTML template for the packaged page), before the engine script. If the tag is missing, the wrapper injects the script on the first `ready()`, but the upload validator looks for the tag, so add it.

## Which path

| You are | Do this |
| --- | --- |
| A Wonderland developer with a web build | Copy the folder, add the component, wrap ad and save calls as below, package, upload. |
| Writing plain TypeScript tests | Use `ZokoClient.ts` (no engine imports) instead of `ZokoSDK.ts`, which imports `@wonderlandengine/api`. |

## A working component

One component covering init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score. The scene and audio pause by themselves during `ZokoSDK.requestAd`; the component only has to freeze its own logic.

```ts
import { Component } from "@wonderlandengine/api";
import { ZokoSDK } from "./zokogames/index";

export class Boot extends Component {
  static TypeName = "boot";
  private live = false;

  async start() {
    try { await ZokoSDK.ready(); } catch (e) { console.warn("ZokoGames init failed", e); }
    this.live = ZokoSDK.isAvailable;                       // initialised and not "disabled"
    if (!this.live) return this.beginGame();               // the game must run without the portal
    const best = Number(ZokoSDK.data.getItem("best") ?? "0") || 0;   // load: synchronous
    this.beginGame(best);
  }

  update(dt: number) {
    if (ZokoSDK.paused) return;                            // an ad is playing
    // ... your game logic
  }

  async showAd(type: "midgame" | "rewarded"): Promise<boolean> {
    if (!this.live) return false;
    const { finished, error } = await ZokoSDK.requestAd(type);   // never rejects for ad problems
    if (error) console.log("no ad:", error.code);                // adCooldown, unfilled, adblock ...
    return finished;
  }

  async onRewardClicked() { if (await this.showAd("rewarded")) this.grantReward(); }   // reward only when finished
  async onRoundEnded(score: number) {
    this.onPlayStop();
    this.save(score);
    await this.submitScore(score);
    await this.showAd("midgame");                          // natural break
  }

  onPlayStart() { if (this.live) void ZokoSDK.game.gameplayStart().catch(() => {}); }
  onPlayStop()  { if (this.live) void ZokoSDK.game.gameplayStop().catch(() => {}); }

  save(score: number) {
    if (!this.live) return;
    try { ZokoSDK.data.setItem("best", String(score)); }     // synchronous; uploaded in the background
    catch (e) { console.warn((e as { code?: string }).code); } // dataLimitExceeded
  }

  async submitScore(score: number) {
    if (!this.live) return;
    try {
      const user = await ZokoSDK.user.getUser();
      if (!user) return;                                     // guests are not ranked
      // "" works only on a board WITHOUT an encryption key; see leaderboards for the encrypted form.
      await ZokoSDK.user.submitScore({ encryptedScore: "", score });
    } catch (e) { console.warn((e as { code?: string }).code); }
  }

  private beginGame(_best = 0) { this.onPlayStart(); }
  private grantReward() { /* ... */ }
}
```

On a web build the Wonderland TypeScript runs in the page, where the Web Crypto API exists, so a keyed leaderboard is practical here: use the `encryptScore` function from the [leaderboards page](https://docs.zokogames.com/sdk/leaderboards#client-submission), passing `user.__dangerousUserId` and your game id, and send its result as `encryptedScore`. Keep in mind that a key shipped in the browser can be read; for real stakes compute scores on your server.

## The zoko-sdk component

| Property | Default | Meaning |
| --- | --- | --- |
| `syncMute` | on | Follow the portal's `muteAudio` setting. |
| `pauseTypes` | `animation` | Comma separated component type names stopped while the scene is paused. `animation` components are paused and resumed; every other type (native such as `physx`, or one of your own TypeNames) is deactivated and reactivated. |
| `captureAudio` | on | Wrap `AudioContext` so every context created from then on is suspended with the scene. |
| `reportLoading` | on | Call `game.loadingStop()` when the engine's loading screen ends. |
| `screenshots` | on | Answer the portal's feedback form with a JPG of the canvas. |
| `simulator` | off | Use the built-in simulator when the SDK script cannot load (offline preview). |

Wonderland has no switch that pauses a whole scene, so pausing is explicit: `pauseTypes` names what stops, and your own components read `ZokoSDK.paused` (or listen to `ZokoSDK.events.pause` and `resume`). Audio is silenced for every Web Audio `AudioContext` the wrapper tracked (created after the component's `init()`; call `ZokoSDK.captureAudio()` earlier, or `ZokoSDK.audio.track(context)` for one you hold), for Howler, and for `<audio>` and `<video>` elements. `ZokoSDK.pauseScene(reason)` and `resumeScene(reason)` do the same for your own pauses (a pause menu); several holds are counted. Ads are refused during an XR session (end the session first), and the feedback screenshot is `null` in XR or in a hidden tab. `pauseTypes` deactivates only the listed types, and `physx` loses its velocities.

## State and simulator

<!-- search: headings-only -->

| Member | Meaning |
| --- | --- |
| `ZokoSDK.ready()` (or `init()`) | Once, first; safe to call twice. Rejects with `sdkNotLoaded` when the script cannot load, unless the simulator is on. |
| `ZokoSDK.isInitialized`, `isAvailable`, `isSimulated`, `isSupportedPlatform` | Initialised; initialised and not disabled; the simulator is answering; running in a browser. |
| `ZokoSDK.environment` | `"local"`, `"zokogames"` or `"disabled"`. |
| `ZokoSDK.isQaTool` | Running in the QA tool. |
| `ZokoSDK.paused` | The scene is paused by an ad or by `pauseScene()`. |
| `ZokoSDK.events` | Wonderland emitters: `ready`, `adStarted`, `adFinished`, `adError`, `settingsChange`, `offlineChange`, `roomLeft`, `pause`, `resume`. |

`ZokoSDK.configureSimulator(options)` tunes the simulator; call it before `ready()`. Options: `disabled`, `accountAvailable`, `loggedIn`, `username`, `userId`, `friendCount`, `adBehaviour` (`"fill"`, `"no_fill"` or `"error"`), `adDurationMs` (default 1500), `adblock`, `muteAudio`, `disableChat`, `kidsMode`, `instantMultiplayer`, `offline`, `storeAvailable`, `verbose`.

## Mapping

<!-- search: headings-only -->

Names are identical to JavaScript; calls return promises (the `data` calls are synchronous). Errors are plain `{ code, message }` objects.

| JavaScript | Wonderland (TypeScript) |
| --- | --- |
| `SDK.init()` | `await ZokoSDK.ready()` |
| `SDK.ad.hasAdblock()` | `await ZokoSDK.ad.hasAdblock()` |
| `SDK.ad.requestAd(type, cbs)` | `await ZokoSDK.requestAd(type, cbs?)` (pauses the scene and audio, resolves `{ finished, error? }`) or the raw `await ZokoSDK.ad.requestAd(type, { adStarted, adFinished, adError })` |
| `SDK.banner.requestBanner(...)` | `ZokoSDK.banner.requestBanner(...)` (needs a DOM container) or `ZokoSDK.requestBannerForObject(id, object, width, height, size?)` |
| `SDK.banner.requestResponsiveBanner(id)`, `clearBanner(id)`, `clearAllBanners()` | The same names on `ZokoSDK.banner` |
| `SDK.game.*`, `SDK.user.*`, `SDK.data.*`, `SDK.store.*`, `SDK.analytics.*` | The same names (`game.loadingProgress`, `game.isOffline` with `addOfflineListener` / `removeOfflineListener`, invite params, `store.getPurchaseToken` included); `game.gameId` is `ZokoSDK.gameId` |
| `SDK.achievements.*` | `ZokoSDK.achievements.list()`, `unlock(key)`, `onUnlock(cb)` (returns an unsubscribe function); see [achievements](https://docs.zokogames.com/sdk/achievements) |
| `ERROR_CODES` | `ZOKO_ERROR_CODES.store`, `.ad`, `.banner`, `.user`, `.data`, `.room`, `.general` |

**Kids mode.** `ZokoSDK.game.settings.kidsMode` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `disableChat`, which the portal sets to true in the same cases. See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

`ZokoSDK.game.room` passes straight through to the JavaScript `SDK.game.room`. It is `undefined` when the portal's SDK is older than 1.3.0 and in the built-in simulator, which has no room channel, so check it before use and test rooms in a web build. The methods are `send(data, { to })`, `setState(patch)`, `getState()`, `members()`, `isHost()` and `selfId`, with `onMessage`, `onState`, `onMembers`, `onHostChange` and `onError` (each returns an unsubscribe function) or the `add...Listener` and `remove...Listener` pairs.

```ts
async startMatch() {
  await ZokoSDK.ready();
  await ZokoSDK.game.updateRoom({ roomId: "match-1", isJoinable: true });
  const room = ZokoSDK.game.room;
  if (!room) return;                                   // simulator or an older SDK
  room.onMessage((m) => {
    const move = m.data as { cell: number; mark: string };   // data is typed unknown
    this.placeMark(move.cell, move.mark);
  });
  room.onHostChange((_hostId, isHost) => { if (isHost) void room.setState({ turn: "X" }); });
  room.onError((e) => console.warn("room:", e.code));
}
```

## Banners

Banners are drawn in the page, not in the canvas. Put an object where the banner should sit and let the wrapper place a container over its projected box. The first active view is the camera and is assumed to fill the canvas. Request banners on menu scenes only.

```ts
await ZokoSDK.requestBannerForObject("menu-banner", this.object, 3, 0.75);           // 3 x 0.75 world units, largest size that fits
await ZokoSDK.requestBannerForObject("menu-banner", this.object, 3, 0.75, "300x250"); // a static size
await ZokoSDK.banner.clearBanner("menu-banner");
```

`ZokoSDK.rectOfObject(object, width, height)` returns the normalised rectangle for `ZokoSDK.banner.requestBannerForRect(id, rect, size?)`. A box behind the camera, or a scene without an active view, fails with `invalidArgument`.

## Purchases

```ts
if (ZokoSDK.store.isAvailable) {
  try {
    const items = await ZokoSDK.store.getCatalogItems({ limit: 20 });
    const { itemId } = await ZokoSDK.store.buyItem(items[0].sku);
    const token = await ZokoSDK.store.getPurchaseToken();      // send to your server and verify there
  } catch (e) {
    if ((e as { code?: string }).code === "purchaseCancelled") return;
  }
}
```

Verify ownership on your server ([in-game purchases](https://docs.zokogames.com/sdk/purchases)). `examples/ZokoStoreExample.ts` is a ready component, and `examples/ZokoProbe.ts` runs a smoke test of the wrapper and prints `[zoko-probe] <check> <result>` lines.

## Web export settings that matter

- **Package, then zip the contents of `deploy/`** so `index.html` is at the archive root. Every path must be relative.
- **No pre-compression.** Wonderland requests plain names for its `.bin` and `.wasm` files; the game origin serves a `.br` or `.gz` suffix with the matching `Content-Encoding`, but only for files that carry the suffix. The initial-download estimate uses uncompressed sizes. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile).
- **Size.** Compress textures (Basis or KTX2) and meshes (Draco) in the editor, keep the first scene small and load later scenes with `engine.loadScene` after the first frame.
- **Audio unlock.** Browsers keep audio suspended until the first tap or click. Start music from a "tap to play" screen.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar (it fullscreens the whole frame).
- **Loading.** The scene is already loaded when components start. To report loading while it downloads, call `await ZokoSDK.ready()` first, then `const loading = ZokoSDK.trackLoading()`, pass `loading.progress` to `engine.loadMainScene(file, loading.progress)` and call `await loading.done()`. Otherwise the `zoko-sdk` component ends the portal's loading bar when the engine's loading screen ends.

Upload: package, zip the build folder **contents**, upload it in the developer console, and run the [Preview tool](https://www.zokogames.com/preview) first.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: `ZokoSDK.game.reportChat(report)`, `ZokoSDK.game.onScreenshotRequest(handler)` and `ZokoSDK.data.mirrorLocalStorage({ prefix: "save_" })` (returns a stop function). `ready()` registers a default provider that reads the canvas in the microtask right after a frame was drawn (the component's `update()` marks the frame); turn it off with the component's `screenshots` property or `ZokoSDK.useDefaultScreenshots(false)` before `ready()`.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`ZokoSDK.requestAd("midgame")`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with `adError` with `adCooldown` until your game has called `ZokoSDK.game.gameplayStart()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `ZokoSDK.game.gameplayStart()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **The editor preview and a build served from `localhost`** use the real JavaScript SDK's [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second ad overlay, fake players, `localStorage` saves, `?sdk_debug=true`, `?ad_response=unfilled`. On another host without the portal around it, the environment is `disabled`, so calls reject with `sdkDisabled`; add `?useLocalSdk=true` to test.
- **Offline.** With the component's `simulator` property on, a missing script gives `ZokoSDK.isSimulated` true and fake ads and a fake player. The simulator does not enforce the three-minute midgame cooldown (`adCooldown`), so test ad handling on `localhost` as well.
- **Then** open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## API

### `init`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `pauseTypes` | `animation` |
| `init` | `await ZokoSDK.ready()` (or `await ZokoSDK.init()`) |
| `environment` | `ZokoSDK.environment` |
| `isQaTool` | `ZokoSDK.isQaTool` |

### `ad.*`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `ad.requestAd` | `await ZokoSDK.requestAd(type)` (pauses) or `ZokoSDK.ad.requestAd(type, callbacks)` (raw) |
| `ad.requestAd.adStarted` | `callbacks.adStarted` of `ZokoSDK.requestAd(type, callbacks)` / `ZokoSDK.ad.requestAd(type, callbacks)`; `ZokoSDK.events.adStarted` |
| `ad.requestAd.adFinished` | `callbacks.adFinished`; `ZokoSDK.requestAd` resolves `{ finished: true }`; `ZokoSDK.events.adFinished` |
| `ad.requestAd.adError` | `callbacks.adError(error)`; `ZokoSDK.requestAd` resolves `{ finished: false, error }`; `ZokoSDK.events.adError` |
| `ad.hasAdblock` | `ZokoSDK.ad.hasAdblock`() |

### `banner.*`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `banner.requestBanner` | `ZokoSDK.banner.requestBanner({ id, width, height })` |
| `banner.requestResponsiveBanner` | `ZokoSDK.banner.requestResponsiveBanner`() |
| `banner.clearBanner` | `ZokoSDK.banner.clearBanner`() |
| `banner.clearAllBanners` | `ZokoSDK.banner.clearAllBanners`() |

### `game.*`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `game.settings` | `ZokoSDK.game.settings` |
| `game.addSettingsChangeListener` | `ZokoSDK.game.addSettingsChangeListener(fn)` / `ZokoSDK.events.settingsChange.add(fn)` |
| `game.removeSettingsChangeListener` | `ZokoSDK.game.removeSettingsChangeListener`() |
| `game.gameplayStart` | `ZokoSDK.game.gameplayStart`() |
| `game.gameplayStop` | `ZokoSDK.game.gameplayStop`() |
| `game.loadingStart` | `ZokoSDK.game.loadingStart()` |
| `game.loadingStop` | `ZokoSDK.game.loadingStop()` |
| `game.loadingProgress` | `ZokoSDK.game.loadingProgress(percentage)` |
| `game.happytime` | `ZokoSDK.game.happytime`() |
| `game.reportGameCompletedPercentage` | `ZokoSDK.game.reportGameCompletedPercentage`() |
| `game.reportChat` | `ZokoSDK.game.reportChat(report)` |
| `game.onScreenshotRequest` | `ZokoSDK.game.onScreenshotRequest(handler)` / `ZokoSDK.setDefaultScreenshotProvider()` |
| `game.setGameContext` | `ZokoSDK.game.setGameContext`() |
| `game.clearGameContext` | `ZokoSDK.game.clearGameContext`() |
| `game.isInstantMultiplayer` | `ZokoSDK.game.isInstantMultiplayer` |
| `game.isInstantJoin` | `ZokoSDK.game.isInstantJoin` |
| `game.isOffline` | `ZokoSDK.game.isOffline` |
| `game.gameId` | `ZokoSDK.gameId` |
| `game.addOfflineListener` | `ZokoSDK.game.addOfflineListener(fn)` / `ZokoSDK.events.offlineChange.add(fn)` |
| `game.removeOfflineListener` | `ZokoSDK.game.removeOfflineListener(fn)` |
| `game.updateRoom` | `ZokoSDK.game.updateRoom`() |
| `game.leftRoom` | `ZokoSDK.game.leftRoom`() |
| `game.addJoinRoomListener` | `ZokoSDK.game.addJoinRoomListener`() |
| `game.removeJoinRoomListener` | `ZokoSDK.game.removeJoinRoomListener`() |
| `game.inviteParams` | `ZokoSDK.game.inviteParams` |
| `game.inviteLink` | `ZokoSDK.game.inviteLink`() |
| `game.getInviteParam` | `ZokoSDK.game.getInviteParam`() |
| `game.showInviteButton` | `ZokoSDK.game.showInviteButton(params)` |
| `game.hideInviteButton` | `ZokoSDK.game.hideInviteButton()` |
| `game.room` | `ZokoSDK.game.room` |
| `game.room.send` | `ZokoSDK.game.room.send(data, { to })` |
| `game.room.onMessage` | `ZokoSDK.game.room.onMessage(cb)` |
| `game.room.addMessageListener` | `ZokoSDK.game.room.addMessageListener(cb)` |
| `game.room.removeMessageListener` | `ZokoSDK.game.room.removeMessageListener(cb)` |
| `game.room.setState` | `ZokoSDK.game.room.setState(patch)` |
| `game.room.getState` | `ZokoSDK.game.room.getState()` |
| `game.room.onState` | `ZokoSDK.game.room.onState(cb)` |
| `game.room.addStateListener` | `ZokoSDK.game.room.addStateListener(cb)` |
| `game.room.removeStateListener` | `ZokoSDK.game.room.removeStateListener(cb)` |
| `game.room.members` | `ZokoSDK.game.room.members()` |
| `game.room.onMembers` | `ZokoSDK.game.room.onMembers(cb)` |
| `game.room.addMembersListener` | `ZokoSDK.game.room.addMembersListener(cb)` |
| `game.room.removeMembersListener` | `ZokoSDK.game.room.removeMembersListener(cb)` |
| `game.room.isHost` | `ZokoSDK.game.room.isHost()` |
| `game.room.onHostChange` | `ZokoSDK.game.room.onHostChange(cb)` |
| `game.room.addHostChangeListener` | `ZokoSDK.game.room.addHostChangeListener(cb)` |
| `game.room.removeHostChangeListener` | `ZokoSDK.game.room.removeHostChangeListener(cb)` |
| `game.room.selfId` | `ZokoSDK.game.room.selfId` |
| `game.room.onError` | `ZokoSDK.game.room.onError(cb)` |
| `game.room.addLeftListener` | `ZokoSDK.game.room.addLeftListener(cb)` / `ZokoSDK.events.roomLeft.add(cb)` |
| `game.room.removeLeftListener` | `ZokoSDK.game.room.removeLeftListener(cb)` |
| `game.room.addErrorListener` | `ZokoSDK.game.room.addErrorListener(cb)` |
| `game.room.removeErrorListener` | `ZokoSDK.game.room.removeErrorListener(cb)` |

### `user.*`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `user.isUserAccountAvailable` | `ZokoSDK.user.isUserAccountAvailable` |
| `user.systemInfo` | `ZokoSDK.user.systemInfo` |
| `user.getUser` | `ZokoSDK.user.getUser`() |
| `user.listFriends` | `ZokoSDK.user.listFriends`() |
| `user.getUserToken` | `ZokoSDK.user.getUserToken`() |
| `user.showAuthPrompt` | `ZokoSDK.user.showAuthPrompt`() |
| `user.addAuthListener` | `ZokoSDK.user.addAuthListener`() |
| `user.removeAuthListener` | `ZokoSDK.user.removeAuthListener`() |
| `user.showAccountLinkPrompt` | `ZokoSDK.user.showAccountLinkPrompt`() |
| `user.submitScore` | `ZokoSDK.user.submitScore`() |
| `user.getXsollaUserToken` | `ZokoSDK.user.getXsollaUserToken()` |

### `data.*`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `data.getItem` | `ZokoSDK.data.getItem(key)` |
| `data.setItem` | `ZokoSDK.data.setItem(key, value)` |
| `data.removeItem` | `ZokoSDK.data.removeItem`() |
| `data.clear` | `ZokoSDK.data.clear`() |
| `data.mirrorLocalStorage` | `ZokoSDK.data.mirrorLocalStorage(options)` |

### `store.*`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `store.isAvailable` | `ZokoSDK.store.isAvailable` |
| `store.getCatalogItems` | `ZokoSDK.store.getCatalogItems({ limit, offset })` |
| `store.getPlayerInventory` | `ZokoSDK.store.getPlayerInventory({ limit, offset })` |
| `store.buyItem` | `ZokoSDK.store.buyItem(itemId)` |
| `store.consumeItem` | `ZokoSDK.store.consumeItem`() |
| `store.getPurchaseToken` | `ZokoSDK.store.getPurchaseToken()` |
| `store.setSandbox` | `ZokoSDK.store.setSandbox`() |

### `achievements.*`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `achievements.list` | `ZokoSDK.achievements.list()` |
| `achievements.unlock` | `ZokoSDK.achievements.unlock(key)` |
| `achievements.onUnlock` | `ZokoSDK.achievements.onUnlock(fn)` |

### `analytics.*`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `analytics.track` | `ZokoSDK.analytics.track(name, params)` |
| `analytics.trackOrder` | `ZokoSDK.analytics.trackOrder`() |

### `constants`

<!-- search: headings-only -->

| JavaScript | Wonderland |
| --- | --- |
| `ERROR_CODES` | `ZOKO_ERROR_CODES.<module>` |
| `SDK_VERSION` | `ZokoSDK.version` |

## Known pitfalls

<!-- search: headings-only -->

- **`sdkNotLoaded`.** The SDK script did not load (offline, blocked, or the script tag is missing).
- **`sdkNotInitialized`.** `await ZokoSDK.ready()` first.
- **Sound keeps playing during an ad.** The audio is not on a Web Audio context created after the component's `init()`; call `ZokoSDK.captureAudio()` earlier or `ZokoSDK.audio.track(context)`.
- **A component keeps running during an ad.** Add its TypeName to `pauseTypes`, or return early from `update()` while `ZokoSDK.paused`.
- **Banner in the wrong place.** The box is projected with the first active view, which must fill the canvas; otherwise compute a rectangle yourself and use `requestBannerForRect`.
- **Black screenshot in the feedback form.** Report it with the editor version: the canvas is read right after the frame, which depends on the canvas keeping its picture until then.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/engines/playcanvas

# PlayCanvas

PlayCanvas games run in the browser, so you have two ways in. Use the **ZokoGames PlayCanvas integration** (`packages/sdk-engines/playcanvas`), which freezes the application and silences the sound manager around ads for you and ships ready-to-drop Editor scripts, or call the [JavaScript SDK](https://docs.zokogames.com/sdk/introduction) directly. Both use the same calls, limits and [error codes](https://docs.zokogames.com/sdk/introduction#errors). Jargon such as "midgame" and "rewarded" is explained in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Plugin 1.7.2. Verified with PlayCanvas engine 2.24.2: strict type check, the example run in a headless browser, and the production check on all 12 areas with an engine-only build. Not run inside the PlayCanvas Editor, which needs an account. Send the PlayCanvas version and the exact error to [support](https://docs.zokogames.com/business/support) if something fails. Release 1.7.2 (script-load timeout) was re-run on 2026-11-23, in a browser and on production.

## Install

Download the PlayCanvas integration: [/sdk-engines/zokogames-playcanvas-1.7.2.zip](https://www.zokogames.com/sdk-engines/zokogames-playcanvas-1.7.2.zip) (the same files as the folder in the repository).

[/sdk-engines/playcanvas.zip](https://www.zokogames.com/sdk-engines/playcanvas.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

Pick the route that matches your game.

| You have | Do this |
| --- | --- |
| An engine-only project (npm, Vite, Rollup, esbuild) | Copy `src/` into your project and call `ZokoPlayCanvas.attach(app)` (below), or skip the helper and use the [plain SDK](#without-the-integration). |
| A project in the PlayCanvas Editor | Upload `editor/zokogames.mjs` (ESM script, recommended) or `editor/zokogames-classic.js` (classic script) as a script asset and add it to the Root entity. Use one of them, not both. |

The integration is plain TypeScript in `packages/sdk-engines/playcanvas/src/`: `ZokoPlayCanvas.ts`, `ZokoClient.ts`, `ZokoAppHost.ts`, `ZokoAdFlow.ts`, `ZokoLoadingBridge.ts`, `types.ts`, an `index.ts` that re-exports them (no engine import) and `ZokoScript.ts`, the only file that imports `playcanvas`. The peer dependency is `playcanvas ^2.0.0`. The two Editor files are generated from `src/` by `tools/build-editor.mjs`, so they contain the same code in one file each.

You do not have to add a script tag: when `window.ZokoGames` is missing, the integration injects `https://sdk.zokogames.com/zokogames-sdk-v1.js` itself (pass `loadScript: false` to turn that off). A script tag in `index.html` is still better, because the upload validator looks for the SDK URL (see [build validation](https://docs.zokogames.com/requirements/build-validation)):

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
```

## A working game with the integration

This is the structure of the package's `examples/minimal` game: init, a loading report, gameplay start, a rewarded ad, a save and a load. Every portal call is wrapped so the game also runs when the SDK is `disabled` (see [local mode](#test-locally)).

```ts
import * as pc from "playcanvas";
import { ZokoPlayCanvas } from "./zokogames-playcanvas";

const app = new pc.Application(document.getElementById("game") as HTMLCanvasElement);
app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW);
const zoko = ZokoPlayCanvas.attach(app, { syncMute: true });     // one instance per app; also app.zoko

async function main() {
  // ready() loads the script if missing, then runs SDK.init(). It rejects with { code: "sdkNotLoaded" } when the script cannot load.
  await zoko.ready().catch((e) => console.warn("ZokoGames unavailable:", e.code));
  const live = zoko.isAvailable;                               // false on a disabled host: skip every SDK call

  const assets = [new pc.Asset("level", "json", { url: "assets/level.json" }) /* ... */];
  assets.forEach((a) => app.assets.add(a));
  if (live) zoko.trackAssets(assets);                          // loadingStart, loadingProgress per asset, loadingStop after the last
  await new Promise<void>((done) => new pc.AssetListLoader(assets, app.assets).load(() => done()));

  app.start();
  // ... build the scene ...
  let best = Number(live ? zoko.data.getItem("best") ?? "0" : "0") || 0;      // load: synchronous
  if (live) await zoko.game.gameplayStart();                   // input is live now, not at page load

  async function watchForBonus() {                             // call from a button press
    const { finished, error } = await zoko.requestAd("rewarded");   // timeScale 0 and sound suspended meanwhile
    if (!finished) { console.warn("no ad:", error?.code); return; } // adCooldown, unfilled, adblock ... the game just carries on
    best += 10;                                                // reward only after adFinished
    if (live) zoko.data.setItem("best", String(best));         // batched; sent about a second later
  }
}
void main();
```

Call `zoko.game.gameplayStop()` when a round ends or the page is hidden, and `gameplayStart()` again when play resumes. A midgame ad is requested at a natural break, after `gameplayStart` has been called once: since SDK 1.6.4 the local mode refuses a midgame ad with `adCooldown` until then.

### What the integration gives you

<!-- search: headings-only -->

| Member | Behaviour (verified in `ZokoPlayCanvas.ts`, `ZokoAppHost.ts` and `ZokoAdFlow.ts`) |
| --- | --- |
| `ZokoPlayCanvas.attach(app, config?)` | Creates the helper once per application and sets `app.zoko`; later calls return the same instance. Config: `syncMute` (default `true`), `screenshots` (`true`), `loadScript` (`true`), `forwardAppEvents` (`true`). |
| `ready()` | Loads the SDK script if `window.ZokoGames` is missing, then runs `SDK.init()`. Rejects with `{ code: "sdkNotLoaded" }` when the script cannot load. Safe to call repeatedly. When the environment is not `disabled` it also registers the settings and offline listeners, applies `muteAudio` to the sound manager volume (option `syncMute`) and registers the screenshot provider (option `screenshots`). |
| `requestAd("midgame" \| "rewarded")` | On `adStarted` it suspends the sound manager, sets its volume to 0 and sets `app.timeScale` to 0. On `adFinished`, on `adError`, and when the request itself throws, it restores the earlier `timeScale`, sets the volume to the portal's `muteAudio` (or what it was) and resumes the sound manager. Resolves `{ finished, error? }` and never rejects for ad problems. |
| `isAdPlaying`, `isAvailable`, `version` | `true` while an ad is on screen; `true` when ready and the SDK is not `disabled`; the JavaScript SDK release the integration was written against (`SDK_VERSION`). |
| `events` | Emits `adStarted`, `adFinished`, `adError(error)`, `settingsChange(settings)` and `offlineChange(offline)`. Each is also fired on the application as `zoko:<name>` (for example `app.on("zoko:adStarted", ...)`). |
| `sdk`, `client` | The raw SDK (throws `sdkNotInitialized` before `ready()` resolved) and the typed `ZokoClient`. |
| `ad`, `banner`, `game`, `user`, `data`, `store`, `achievements`, `analytics`, `environment`, `isQaTool` | The typed client, with the same module names as the JS SDK (`zoko.game.gameplayStart()`; `app.game` does not exist in PlayCanvas, so there is no clash). |
| `trackAssets(assets)` | Reports a list of assets (the list you give a `pc.AssetListLoader`) to the portal: `loadingStart`, `loadingProgress` (0 to 100) after each asset that loads or fails, `loadingStop` after the last. Assets already loaded count as done. Returns a function that detaches the listeners. |
| `trackPreload()` | Reports the application's own `preload:start`, `preload:progress` and `preload:end`. An Editor build runs its preload before any script, so it only helps when you attach earlier than that. |
| `requestBannerAt(id, x, y, w, h, size?)` | Positions a DOM container over a rectangle in canvas pixels (the graphics device's width and height) and requests a banner there; without `size` it requests the largest responsive size that fits. `rectFromCanvasPixels` gives the normalised rectangle. |
| `useDefaultScreenshot()` | Answers the portal's feedback form with the application's canvas as it stands at the end of the next rendered frame, as a JPEG. Registered by `ready()` unless `screenshots: false`; resolves no picture when no frame is rendered within a second. |
| `dispose()` | Detaches every listener, restores loop and sound and forgets the application. |

`runAdFlow`, `createAppAdHost`, `bindPreloadProgress` and `bindAssetProgress` are exported for custom setups, and `ZokoClient` can be used on its own in unit tests (it needs no PlayCanvas).

Setting `timeScale` to 0 freezes everything that scales with the engine's delta time: scripts that use `dt`, tweens, animation, physics. Rendering keeps running. Anything that reads the wall clock (`Date.now()`, `setTimeout`, CSS animations) does not stop, so pause those yourself on `adStarted`. A second `requestAd` while one is running resolves at once with error `other`. A `timeScale` or volume your game sets during an ad is kept.

## In the PlayCanvas Editor

Upload `editor/zokogames.mjs` as a script asset (run Parse if the Editor does not list the script), add the script `zokoGames` to the Root entity, and launch. The script has four attributes: `syncMute`, `screenshots`, `loadScript` and `autoLoadingStop` (call `loadingStop` as soon as the SDK is ready, default on). It attaches the helper (`app.zoko`), starts `ready()` and fires `zoko:ready` (with the helper) or `zoko:error` (with `{ code, message }`) on the script and on the application. `editor/zokogames-classic.js` does the same as a classic script (`pc.createScript("zokoGames")`) in a classic project.

From your own script:

```js
export class Game extends Script {
  static scriptName = "game";
  async initialize() {
    const zoko = await this.app.root.script.zokoGames.ready;   // the helper, or null when the SDK is unavailable
    if (!zoko || !zoko.isAvailable) return;
    await zoko.game.gameplayStart();
    this.app.on("zoko:settingsChange", (s) => console.log("muted:", s.muteAudio));
  }
}
```

Add the SDK script tag to the project's `index.html` as shown above if you use a custom one. The Editor's own loading screen runs before the scripts, so the portal's loading bar is closed by `autoLoadingStop` rather than driven by it; for assets you load later, call `zoko.trackAssets(...)`.

## Without the integration

If you do not want a helper, call the SDK yourself. Initialise before you start the application, and write the ad helper so it resumes on both outcomes.

```js
const SDK = window.ZokoGames?.SDK;
let live = false;

async function main() {
  if (SDK) { await SDK.init(); live = SDK.environment !== "disabled"; }   // init never rejects
  app.start();
  if (live) {
    const apply = (s) => { app.soundManager.volume = s.muteAudio ? 0 : 1; };
    apply(SDK.game.settings);
    SDK.game.addSettingsChangeListener(apply);
  }
}

function showAd(app, type) {
  if (!live) return Promise.resolve(false);
  let paused = false;
  let scale = 1;
  const pause = () => { if (paused) return; paused = true; scale = app.timeScale; app.timeScale = 0; app.soundManager.suspend(); app.soundManager.volume = 0; };
  const resume = () => {
    if (!paused) return; paused = false;
    app.timeScale = scale;
    app.soundManager.volume = SDK.game.settings.muteAudio ? 0 : 1;
    app.soundManager.resume();
  };
  return new Promise((done) => {
    SDK.ad.requestAd(type, {
      adStarted: pause,
      adFinished: () => { resume(); done(true); },
      adError: () => { resume(); done(false); },
    }).catch(() => { resume(); done(false); });          // throws (for example sdkDisabled) instead of calling adError
  });
}
main();
```

`requestAd` resolves only after `adFinished` or `adError` has been delivered, so `await showAd(...)` is a safe place to resume game logic. On PlayCanvas builds before the application had `app.soundManager`, the manager is `app.systems.sound.manager`.

**Kids mode.** `SDK.game.settings.kidsMode` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `disableChat`, which the portal sets to true in the same cases. To test it, add `?kidsMode=true` to the page address in local mode. See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Banners

Banner containers are DOM elements next to the canvas, not entities. Request them on menu screens only and clear them before play.

```html
<canvas id="game"></canvas>
<div id="menu-banner" style="width:728px;height:90px;margin:8px auto"></div>
```

```js
SDK.banner.requestBanner({ id: "menu-banner", width: 728, height: 90 }).catch(() => {});
// leaving the menu:
SDK.banner.clearAllBanners();
```

With the integration, `await zoko.requestBannerAt("hud", 20, 20, 300, 250, "300x250")` creates the container for you over that rectangle of the canvas. Banners are refused while a video ad plays (`videoAdPlaying`) and a container can refresh only every 30 seconds (`bannerCooldown`).

## Room data channel and purchases

Both are the SDK's own and are reached through the typed client, with no PlayCanvas-specific code: `zoko.game.room` (messages between the players of a room and a host-written shared state; `undefined` on an SDK older than 1.3.0; see [the game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room)) and `zoko.store` (`isAvailable`, `getCatalogItems`, `buyItem`, `getPurchaseToken`; see [in-game purchases](https://docs.zokogames.com/sdk/purchases)). Check `zoko.store.isAvailable` before showing any purchase UI and verify ownership on your server. On `localhost` the SDK's local mode serves a test store and makes two browser tabs in the same room id behave like two players.

```ts
if (zoko.store.isAvailable) {
  try {
    const items = await zoko.store.getCatalogItems({ limit: 20 });
    await zoko.store.buyItem(items[0].sku);
    const token = await zoko.store.getPurchaseToken();         // send to your server and verify there
  } catch (e) {
    if ((e as { code?: string }).code === "purchaseCancelled") return;
  }
}
```

## Export settings that matter on the web

- **Relative paths.** Bundle with relative paths (Vite `base: "./"`). Root-absolute paths (starting with a slash) break under the game's own origin and raise the `absolute_path` warning. See [technical requirements](https://docs.zokogames.com/requirements/technical#relative-paths-only). A PlayCanvas Editor web build already uses relative paths.
- **Do not pre-compress.** PlayCanvas asks for plain file names. A file ending in `.br` or `.gz` is served with `Content-Encoding`, but your page would still request the plain name, so ship plain files. Keep the files small: the initial-download estimate uses uncompressed sizes.
- **Size.** Compress textures (Basis or KTX2), keep audio at modest bitrates and load later levels after the first scene. The upload limits are 1,500 files, 250 MB unpacked and about 50 MB initial download (20 MB for mobile); see [first frame fast](https://docs.zokogames.com/guides/first-frame).
- **Canvas sizing.** The frame size changes with fullscreen and rotation. Use `FILLMODE_FILL_WINDOW` (or `KEEP_ASPECT`) and handle `resize`, so the game stays legible at every [required resolution](https://docs.zokogames.com/requirements/gameplay).
- **Audio unlock.** Browsers block sound until the first pointer or key event; the sound manager resumes its context on the first interaction. Start music from a button press, not unconditionally at startup. Ads and `syncMute` do not replace this.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar: it fullscreens the whole frame, including the portal's controls. Do not add a competing button.
- **Memory.** There is no threading or `SharedArrayBuffer` in the portal frame (the portal does not send cross-origin isolation headers).

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

`zoko.game.reportChat(report)`, `zoko.game.onScreenshotRequest(handler)` and `zoko.data.mirrorLocalStorage({ prefix: "save_" })`. `ready()` registers the default screenshot provider (the canvas at the end of the next frame); pass `screenshots: false` to `attach` to skip it, or register your own handler when your game draws into another canvas. The mirror only covers `localStorage`.

## SDK 1.7.0 additions

`zoko.analytics.track(name, params?)` records a custom event (fire-and-forget; an invalid call is dropped by the SDK). `zoko.game.room.addLeftListener(cb)` receives `{ reason, roomId? }` when the portal ends the player's room membership (`reason` is `left`, `kicked`, `closed` or `disconnected`) and returns a function that removes the listener; `removeLeftListener(cb)` does the same. `data.mirrorIndexedDB` is not bound yet: it has to run before the engine starts, so call it from your own page script. The `{ portalOnly: true }` option of `showInviteButton` / `hideInviteButton` is reachable through `zoko.sdk.game`.

## Test locally

PlayCanvas always runs in a browser, so there is no editor simulator. Serve the game from `localhost` and the SDK starts in its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second overlay stands in for each ad, banners are dashed boxes, two fake players exist, and cloud saves go to `localStorage`. Two things trip people up:

- A second midgame request within three minutes of the last ad fails with `adCooldown`, and since SDK 1.6.4 the first one fails the same way until the game has called `gameplayStart`. That is the real rule, so your game must handle it.
- `submitScore` is accepted and does nothing visible in local mode, and the local token is unsigned.

Add `?sdk_debug=true` to log every call, `?ad_response=unfilled` to force ad failure, and `?user_response=logged_out` to test the guest path. Then open the [Preview tool](https://www.zokogames.com/preview), enter your local address and watch the requirements checklist tick.

## API

### `init`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `init` | `await zoko.ready()` |
| `environment` | `zoko.environment` |
| `isQaTool` | `zoko.isQaTool` |

### `ad.*`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `ad.requestAd` | `zoko.requestAd(type)` (pausing) or `zoko.ad.requestAd(type, callbacks)` |
| `ad.requestAd.adStarted` | `callbacks.adStarted` of `zoko.ad.requestAd(type, callbacks)`; `zoko.requestAd(type)` pauses for you |
| `ad.requestAd.adFinished` | `callbacks.adFinished`; `requestAd` resolves `{ finished: true }` |
| `ad.requestAd.adError` | `callbacks.adError(error)`; `requestAd` resolves `{ finished: false, error }` |
| `ad.hasAdblock` | `zoko.ad.hasAdblock`() |

### `banner.*`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `banner.requestBanner` | `zoko.banner.requestBanner({ id, width, height })` |
| `banner.requestResponsiveBanner` | `zoko.banner.requestResponsiveBanner`() |
| `banner.clearBanner` | `zoko.banner.clearBanner`() |
| `banner.clearAllBanners` | `zoko.banner.clearAllBanners`() |

### `game.*`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `game.settings` | `zoko.game.settings` |
| `game.addSettingsChangeListener` | `zoko.game.addSettingsChangeListener(fn)` / `zoko.events.on("settingsChange", fn)` or `app.on("zoko:settingsChange", fn)` |
| `game.removeSettingsChangeListener` | `zoko.game.removeSettingsChangeListener`() |
| `game.gameplayStart` | `zoko.game.gameplayStart`() |
| `game.gameplayStop` | `zoko.game.gameplayStop`() |
| `game.loadingStart` | `zoko.game.loadingStart()` |
| `game.loadingStop` | `zoko.game.loadingStop`() |
| `game.loadingProgress` | `zoko.game.loadingProgress(percentage)` |
| `game.happytime` | `zoko.game.happytime`() |
| `game.reportGameCompletedPercentage` | `zoko.game.reportGameCompletedPercentage`() |
| `game.reportChat` | `zoko.game.reportChat(report)` |
| `game.onScreenshotRequest` | `zoko.game.onScreenshotRequest(handler)` / `zoko.useDefaultScreenshot()` |
| `game.setGameContext` | `zoko.game.setGameContext`() |
| `game.clearGameContext` | `zoko.game.clearGameContext`() |
| `game.isInstantMultiplayer` | `zoko.game.isInstantMultiplayer` |
| `game.isInstantJoin` | `zoko.game.isInstantJoin` |
| `game.isOffline` | `zoko.game.isOffline` |
| `game.addOfflineListener` | `zoko.game.addOfflineListener(fn)` / `zoko.events.on("offlineChange", fn)` or `app.on("zoko:offlineChange", fn)` |
| `game.removeOfflineListener` | `zoko.game.removeOfflineListener(fn)` |
| `game.updateRoom` | `zoko.game.updateRoom`() |
| `game.leftRoom` | `zoko.game.leftRoom`() |
| `game.addJoinRoomListener` | `zoko.game.addJoinRoomListener`() |
| `game.removeJoinRoomListener` | `zoko.game.removeJoinRoomListener`() |
| `game.inviteParams` | `zoko.game.inviteParams` |
| `game.inviteLink` | `zoko.game.inviteLink`() |
| `game.getInviteParam` | `zoko.game.getInviteParam`() |
| `game.showInviteButton` | `zoko.game.showInviteButton(params)` |
| `game.hideInviteButton` | `zoko.game.hideInviteButton()` |
| `game.room` | `zoko.game.room` |
| `game.room.send` | `zoko.game.room.send(data, { to })` |
| `game.room.onMessage` | `zoko.game.room.onMessage(cb)` |
| `game.room.addMessageListener` | `zoko.game.room.addMessageListener(cb)` |
| `game.room.removeMessageListener` | `zoko.game.room.removeMessageListener(cb)` |
| `game.room.setState` | `zoko.game.room.setState(patch)` |
| `game.room.getState` | `zoko.game.room.getState()` |
| `game.room.onState` | `zoko.game.room.onState(cb)` |
| `game.room.addStateListener` | `zoko.game.room.addStateListener(cb)` |
| `game.room.removeStateListener` | `zoko.game.room.removeStateListener(cb)` |
| `game.room.members` | `zoko.game.room.members()` |
| `game.room.onMembers` | `zoko.game.room.onMembers(cb)` |
| `game.room.addMembersListener` | `zoko.game.room.addMembersListener(cb)` |
| `game.room.removeMembersListener` | `zoko.game.room.removeMembersListener(cb)` |
| `game.room.isHost` | `zoko.game.room.isHost()` |
| `game.room.onHostChange` | `zoko.game.room.onHostChange(cb)` |
| `game.room.addHostChangeListener` | `zoko.game.room.addHostChangeListener(cb)` |
| `game.room.removeHostChangeListener` | `zoko.game.room.removeHostChangeListener(cb)` |
| `game.room.selfId` | `zoko.game.room.selfId` |
| `game.room.onError` | `zoko.game.room.onError(cb)` |
| `game.room.addLeftListener` | `zoko.game.room.addLeftListener(cb)` |
| `game.room.removeLeftListener` | `zoko.game.room.removeLeftListener(cb)` |
| `game.room.addErrorListener` | `zoko.game.room.addErrorListener(cb)` |
| `game.room.removeErrorListener` | `zoko.game.room.removeErrorListener(cb)` |

### `user.*`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `user.isUserAccountAvailable` | `zoko.user.isUserAccountAvailable` |
| `user.systemInfo` | `zoko.user.systemInfo` |
| `user.getUser` | `zoko.user.getUser`() |
| `user.listFriends` | `zoko.user.listFriends`() |
| `user.getUserToken` | `zoko.user.getUserToken`() |
| `user.showAuthPrompt` | `zoko.user.showAuthPrompt`() |
| `user.addAuthListener` | `zoko.user.addAuthListener`() |
| `user.removeAuthListener` | `zoko.user.removeAuthListener`() |
| `user.showAccountLinkPrompt` | `zoko.user.showAccountLinkPrompt`() |
| `user.submitScore` | `zoko.user.submitScore`() |
| `user.getXsollaUserToken` | `zoko.user.getXsollaUserToken()` |

### `data.*`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `data.getItem` | `zoko.data.getItem(key)` |
| `data.setItem` | `zoko.data.setItem(key, value)` |
| `data.removeItem` | `zoko.data.removeItem`() |
| `data.clear` | `zoko.data.clear`() |
| `data.mirrorLocalStorage` | `zoko.data.mirrorLocalStorage(options)` |

### `store.*`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `store.isAvailable` | `zoko.store.isAvailable` |
| `store.getCatalogItems` | `zoko.store.getCatalogItems({ limit, offset })` |
| `store.getPlayerInventory` | `zoko.store.getPlayerInventory({ limit, offset })` |
| `store.buyItem` | `zoko.store.buyItem(itemId)` |
| `store.consumeItem` | `zoko.store.consumeItem`() |
| `store.getPurchaseToken` | `zoko.store.getPurchaseToken()` |
| `store.setSandbox` | `zoko.store.setSandbox`() |

### `achievements.*`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `achievements.list` | `zoko.achievements.list()` |
| `achievements.unlock` | `zoko.achievements.unlock(key)` |
| `achievements.onUnlock` | `zoko.achievements.onUnlock(fn)` |

### `analytics.*`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `analytics.track` | `zoko.analytics.track(name, params)` |
| `analytics.trackOrder` | `zoko.analytics.trackOrder`() |

### `constants`

<!-- search: headings-only -->

| JavaScript | PlayCanvas |
| --- | --- |
| `ERROR_CODES` | `ZOKO_ERROR_CODES.<module>` |
| `SDK_VERSION` | `zoko.version` |

## Known pitfalls

<!-- search: headings-only -->

- **`trackAssets` before `ready()`.** The loading calls fail with `sdkNotInitialized` (a rejected promise, swallowed by the bridge) and nothing is reported. Await `zoko.ready()` first, then call `trackAssets`.
- **`sdkNotLoaded`.** The script was blocked or offline and `loadScript` is off or failed. Your game should still start; `ready()` rejecting is not fatal.
- **Calls on a disabled SDK throw `sdkDisabled`.** Check `zoko.isAvailable` first, as above, or an unhandled rejection reaches your console.
- **Sound stays muted after an ad.** Something else changed the sound manager volume during the ad. The integration restores the portal's `muteAudio` value, or the volume it saw at `adStarted`; a volume your game set during the ad is kept.
- **Things move during an ad.** They ignore `dt` (wall-clock timers, CSS animations). `app.timeScale` only scales the engine's own update.
- **Banner in the wrong place.** `requestBannerAt` converts canvas pixels using the graphics device size; check your canvas fill mode and resolution.
- **Two Editor scripts.** Use either `zokogames.mjs` or `zokogames-classic.js`, not both; the second attaches to the instance the first created.
- **Reward granted twice.** Grant on `finished === true` only, never on the button press.

## Next

- Plain JavaScript with another renderer: [Plain HTML5, Three.js and PixiJS](https://docs.zokogames.com/engines/html5-libraries).
- All engines at a glance: [engines overview](https://docs.zokogames.com/engines/overview).
- Upload: zip the build output with `index.html` at the archive root, then follow the [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/engines/gdevelop

# GDevelop

The **ZokoGames** extension (`ZokoGames.json`) for GDevelop 5 lives in `packages/sdk-engines/gdevelop`. It is an ordinary events extension: every action, condition and expression is a small JavaScript code event, so it works in previews and in every web export without any extra file. Terms such as "midgame" and "rewarded" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Plugin 1.7.2. Verified on 2026-11-23 with GDevelop 5.6.287: the extension file imports in the GDevelop web editor without errors, and an HTML5 export of the example made with GDevelop's own exporter passes the production check. The editor's preview button and editing event sheets by hand have not been exercised. If something fails, send the GDevelop version and the exact error to [support](https://docs.zokogames.com/business/support).

## Install

Download the GDevelop extension: [/sdk-engines/zokogames-gdevelop-1.7.2.zip](https://www.zokogames.com/sdk-engines/zokogames-gdevelop-1.7.2.zip). It holds `ZokoGames.json` (built from the `gdevelop` folder in the repository), an example project, the README and the changelog.

[/sdk-engines/gdevelop.zip](https://www.zokogames.com/sdk-engines/gdevelop.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. Unzip the download. In GDevelop open the **Project manager**, then **Extensions > Import extension**, and choose **`ZokoGames.json`** (not the zip).
2. The actions, conditions and expressions appear under **ZokoGames** in the events editor. Expressions are written `ZokoGames::UserName()`.
3. Run the **Initialize** action at the beginning of the first scene. The extension adds `https://sdk.zokogames.com/zokogames-sdk-v1.js` to the page itself, so you do not edit any export file.
4. Export as HTML5 and upload the zip.

To see it working first, open `examples/zokogames-example/game.json` from the download and preview it: the text on screen lists each check.

## Which path

| You are | Do this |
| --- | --- |
| A GDevelop creator with a finished game | Import the extension, add **Initialize** and the ad events below, export as HTML5, upload. No JavaScript needed. |
| Comfortable with JavaScript events | The same SDK is reachable from a JavaScript code event as `window.ZokoGames.SDK` once **Initialize** has completed. |

## Tags, results and errors

<!-- search: headings-only -->

Every asynchronous action takes a **Tag** first. When the call ends, **On request completed** (with that tag) or **On request failed** (with that tag) is true for one frame; **On any request failed** is true for every failure. Use one tag per request in flight.

GDevelop waits for these actions: the actions after one in the same event, and its sub-events, run only once the request has ended. That makes simple chains easy (the result expressions already hold the new value in the next action), but put an ad request or a slow call in its own event when the rest of the event should not wait for it.

| Expression | Contents |
| --- | --- |
| `ResultString` | The last result when it is text: a token, an invite link, a saved item. |
| `ResultNumber` | The last result as a number (booleans are 1 and 0; **Check ad blocker** sets 1 when blocked). |
| `ResultJSON` | The last result as JSON (the friends page, the account link answer). |
| `ErrorCode`, `ErrorMessage`, `ErrorContainerId` | Details of the last failure. `ErrorContainerId` is set for banner errors. `ErrorDescription(code)` gives the English text of a code. |

## Ads pause and mute the game for you

When an ad starts, the extension mutes all game sound at once, lets **On ad started** run for one frame, and then pauses the game. When the ad finishes or fails, it resumes the game and restores the sound before **On ad finished** or **On ad error** runs. A pause your game made itself is left alone. Switch either part off with **Pause the game during ads** and **Mute the game during ads** if your game handles it. Game sound also follows the portal's mute setting by default (**Follow the portal mute setting**).

## A working set of events

The events below cover init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score. Use the scene variables `Coins`, `Best` and `RewardPending`.

```
At the beginning of the scene (first scene)
    -> ZokoGames: Initialize (tag "init")

ZokoGames: On request completed ("init")
    -> ZokoGames: Get saved item (tag "load", key "best")
       ZokoGames: Loading stop (tag "ls")
    sub-event: ZokoGames::HasSavedItem("best") = 1
       -> Change Best: set to ToNumber(ZokoGames::SavedItem("best"))
ZokoGames: On request failed ("init")              // SDK missing or blocked: just start
    -> Change the scene to "Menu"

// Ads: the extension pauses and mutes; grant the reward only in On ad finished
ZokoGames: On ad finished
    + RewardPending = 1
    -> Add 10 to Coins ; Set RewardPending to 0
ZokoGames: On ad error
    -> Set RewardPending to 0

// Gameplay start/stop
Game scene: At the beginning of the scene (player can act)
    + ZokoGames: Is available
    -> ZokoGames: Gameplay start (tag "gs")
Game over (or pause menu opened)
    + ZokoGames: Is available
    -> ZokoGames: Gameplay stop (tag "gx")

// Midgame ad at a natural break, in its own event
Game over screen: At the beginning of the scene
    + ZokoGames: Is available
    -> ZokoGames: Request ad (type midgame, tag "mid")

// Rewarded ad
Reward button is clicked
    + ZokoGames: Is available
    -> Set RewardPending to 1 ; ZokoGames: Request ad (type rewarded, tag "rew")

// Save
Round ends and Score > Best
    -> Set Best to Score ; ZokoGames: Set saved item (tag "save", key "best", value ToString(Best))

// Leaderboard (signed-in players only; board enabled in the console)
Round ends
    + ZokoGames: Is available
    -> ZokoGames: Submit score (tag "score", encrypted "", score Score)
```

Two traps are built into this sheet on purpose:

- **On request completed ("rew") is not "ad finished".** When an ad is unfilled, blocked or in cooldown, the SDK delivers **On ad error** and the action still completes, so grant rewards in **On ad finished** only. When the SDK is disabled, the action fails (**On request failed**) and neither ad event fires; the game was never paused, so nothing is left to resume.
- **`Submit score` with an empty `encrypted` value** works only on a board without an encryption key (the plain score is validated against the board rules). A keyed board counts only a correctly encrypted payload ([leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), and the extension has no encryption helper: compute the score on your server and use the server API, or leave the board keyless for a casual game. A player who is not signed in is not ranked.

### Purchases

```
ZokoGames: On request completed ("init") + ZokoGames: Is store available
    -> Show the shop button ; ZokoGames: Get catalogue items (limit 50, offset 0, tag "cat")
ZokoGames: On request completed ("cat")
    -> Repeat ZokoGames::StoreItemCount() times: row with StoreItemName(i), StoreItemPrice(i), StoreItemCurrency(i)
Buy button is clicked
    -> ZokoGames: Buy item (ZokoGames::StoreItemSku(selected), tag "buy")
ZokoGames: On request completed ("buy")
    -> grant ZokoGames::PurchasedItemId() ; ZokoGames: Get purchase token (tag "tok")   // then send PurchaseToken to your server
ZokoGames: On request failed ("buy") + Last error is "purchaseCancelled"     -> (nothing)
ZokoGames: On request failed ("buy") + Last error is "userNotAuthenticated"  -> ZokoGames: Show login prompt (tag "login")
```

Verify ownership on your server (see [in-game purchases](https://docs.zokogames.com/sdk/purchases)). `StoreItemPrice` is -1 when there is none and `InventoryQuantity` is -1 when not counted.

## Actions

<!-- search: headings-only -->

| Group | Actions |
| --- | --- |
| Start-up | **Initialize** |
| Ads | **Request ad** (midgame or rewarded), **Check ad blocker**, **Pause the game during ads**, **Mute the game during ads**, **Follow the portal mute setting** |
| Banners | **Request banner** (id, size 728x90, 300x250, 320x50, 468x60 or 320x100, x, y, width, height), **Request responsive banner** (id, x, y, width, height), **Clear banner**, **Clear all banners** |
| Game | **Gameplay start**, **Gameplay stop**, **Loading start**, **Loading stop**, **Report loading progress** (0 to 100), **Happytime**, **Report completed percentage**, **Set game context** (JSON), **Clear game context**, **Report chat message**, **Set screenshot provider**, **Answer screenshot** |
| Multiplayer | **Update room**, **Set room public**, **Left room**, **Create invite link**, **Show invite button** and **Hide invite button** (deprecated), **Show invite button (portal only)** and **Hide invite button (portal only)** (SDK 1.7.0) |
| User | **Get user**, **List friends**, **Get user token**, **Show login prompt**, **Show account link prompt**, **Submit score** |
| Store | **Get catalogue items**, **Get player inventory**, **Buy item**, **Consume item**, **Set sandbox**, **Get purchase token**, **Get payment provider user token** (deprecated) |
| Cloud save | **Get saved item**, **Set saved item**, **Remove saved item**, **Clear saved data**, **Mirror localStorage to cloud save**, **Stop mirroring localStorage** |
| Achievements | **Unlock achievement** (key), **List achievements** |
| Analytics | **Track event** (SDK 1.7.0), **Track order** |

Banner rectangles are in game resolution pixels (the size in the project properties) with the origin at the top left; the extension converts them to the scaled canvas. Request banners on menu scenes only.

## Conditions

<!-- search: headings-only -->

- Status: **Is initialized**, **Is available** (false when the SDK is disabled), **Is QA tool**.
- Requests: **On request completed**, **On request failed**, **On any request failed**, **Last error is** (code).
- Ads: **On ad started**, **On ad finished**, **On ad error**, **Is ad playing**.
- Settings: **On settings changed**, **Is mute requested**, **Is chat disabled**, **Is kids mode**.
- Offline: **On offline changed**, **Is offline**.
- Multiplayer: **Is instant multiplayer**, **On join room**.
- Achievements: **On achievement unlocked**.
- Account: **On auth changed**, **Is logged in**, **Is account available**.
- Store: **Is store available**.
- Screenshots and storage mirror: **On screenshot requested**, **On mirror error**.

Triggers ("On ...") are true for one frame. When two of the same kind arrive together, the second is delivered on the next frame, so none is lost.

**Kids mode.** **Is kids mode** (`KidsMode`) is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring **Is chat disabled**. To test it, add `?kidsMode=true` to the page address in local mode. See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Expressions

<!-- search: headings-only -->

`Environment`, `SdkVersion`, `GameId`, `MuteAudio`, `DisableChat`, `KidsMode`, `InviteParam(key)`, `InviteParamsJSON`, `UserName`, `UserPictureUrl`, `UserId` (never trust it on a server; verify the token), `UserToken`, `FriendCount`, `FriendsTotal`, `FriendsHasMore`, `FriendName(i)`, `FriendId(i)`, `FriendPictureUrl(i)`, `Locale`, `CountryCode`, `DeviceType`, `SavedItem(key)`, `HasSavedItem(key)`, `ErrorCodes(module)` (comma separated codes for `ad`, `banner`, `user`, `data`, `store`, `room` or `general`), `ErrorDescription(code)`, `ResultJSON`, `ResultString`, `ResultNumber`, `ErrorCode`, `ErrorMessage`, `ErrorContainerId`, `MirrorErrorCode`, `MirrorErrorMessage`, the store expressions `StoreItemCount`, `StoreItemSku(i)`, `StoreItemName(i)`, `StoreItemDescription(i)`, `StoreItemImageUrl(i)`, `StoreItemPrice(i)`, `StoreItemCurrency(i)`, `StoreItemConsumable(i)`, `InventoryCount`, `InventorySku(i)`, `InventoryName(i)`, `InventoryDescription(i)`, `InventoryImageUrl(i)`, `InventoryQuantity(i)`, `PurchasedItemId`, `PurchaseToken`, `XsollaUserToken` (deprecated name for the purchase token), and the achievement expressions `AchievementCount`, `AchievementKeyAt(i)`, `AchievementNameAt(i)`, `AchievementDescriptionAt(i)`, `AchievementPointsAt(i)`, `AchievementUnlockedAt(i)`, `AchievementIsUnlockedAt(i)` (1 or 0), `LastUnlockReason`, `LastAchievementKey`, `LastAchievementName` and `LastAchievementPoints`. Run **List achievements** before the `...At(i)` expressions; **Unlock achievement** fills the `LastAchievement...` ones. For guests and unknown keys the action still completes, and `LastUnlockReason` is `guest`, `not_found`, `not_live`, `rate_limited` or `error`. See [achievements](https://docs.zokogames.com/sdk/achievements).

`SavedItem(key)` reads the SDK directly once **Initialize** has completed, so a value saved anywhere in the game is visible at once.

## JavaScript events

```js
// JavaScript code event, after the "init" request completed.
const SDK = window.ZokoGames.SDK;
SDK.user.getUser().then((user) => {
  runtimeScene.getVariables().get("PlayerName").setString(user ? user.username : "guest");
});
```

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after **Update room** (or after joining from an invite) and ends with **Left room**, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

Message and value parameters accept text: valid JSON (`{"x":1}`, `5`, `true`) is sent as that JSON value, anything else as plain text. On `localhost` the SDK's local mode makes two browser tabs that join the same room id behave like two players.

| Kind | Functions |
| --- | --- |
| Actions | **Send room message** (tag, data), **Send room message to member** (tag, member id, data), **Set room state key** (tag, key, value; host only), **Remove room state key** (tag, key; host only) |
| Triggers | **On room message**, **On room state changed**, **On room members changed**, **On room host changed**, **On room left** (SDK 1.7.0), **On room error** |
| Condition | **Is room host** |
| Message expressions | `RoomMessageData`, `RoomMessageFrom`, `RoomMessageDirect`, `RoomMessageSeq`, `RoomMessageValue(key)` |
| State expressions | `RoomStateJSON`, `RoomStateValue(key)`, `RoomStateChangedKeys`, `RoomStateChangedBy`, `RoomStateRev` |
| Member expressions | `RoomMemberCount`, `RoomMemberIdAt(i)`, `RoomMemberNameAt(i)`, `RoomMemberPictureUrlAt(i)`, `RoomHostId`, `RoomSelfId` |
| Left expressions | `RoomLeftReason` (`left`, `kicked`, `closed`, `disconnected`), `RoomLeftRoomId` (for **On room left**, SDK 1.7.0) |
| Error expressions | `RoomErrorCode`, `RoomErrorMessage` (for the room error trigger; request failures still use **On request failed**) |

```
ZokoGames: On room host changed
  + ZokoGames: Is room host        -> ZokoGames: Set room state key (key "turn", value "X", tag "turn")
Cell is clicked                    -> ZokoGames: Send room message ("{""cell"":" + ToString(Cell) + "}", tag "move")
ZokoGames: On room message         -> place a mark at ZokoGames::RoomMessageValue("cell")
ZokoGames: On room state changed   -> Text: set to ZokoGames::RoomStateValue("turn")
```

## Export settings that matter on the web

- **Export as HTML5** (local folder) and zip the export folder **contents** so `index.html` is at the archive root.
- **No pre-compression.** GDevelop requests plain file names; upload the export as is. Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile); compress images and audio, and see [first frame fast](https://docs.zokogames.com/guides/first-frame).
- **Canvas sizing.** The frame size changes with fullscreen and rotation. Set the game resolution to adapt (Project properties > Resolution and rendering) so the scene fits every [required resolution](https://docs.zokogames.com/requirements/gameplay).
- **Audio unlock.** Browsers keep audio suspended until the first click or tap. Start music from a "tap to play" button, not at the beginning of the first scene.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar; do not add a competing button.
- **Loading.** Run **Loading start** in your first scene, **Report loading progress** while you load resources, and **Loading stop** when play can begin.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0: the action **Report chat message** (name, message, reason, optional user id, room id and context JSON), the actions **Set screenshot provider** and **Answer screenshot** with the condition **On screenshot requested**, and **Mirror localStorage to cloud save** with the condition **On mirror error**. When the screenshot provider is on and the game does not answer within 1.5 seconds, the game canvas is sent. GDevelop's **Storage** actions keep their data in IndexedDB, so the mirror does not copy them; use the cloud save actions for those saves.

## SDK 1.7.0

- **Track event** (name, params JSON): fire and forget. Name: a lowercase letter, then lowercase letters, digits or underscore, at most 40 characters. Params: an optional flat JSON object with at most 10 text, number or yes/no values.
- **On room left** with `RoomLeftReason` and `RoomLeftRoomId`: the portal ended the player's room membership without the game asking (kicked, room closed, disconnected). The host flag is cleared.
- **Show invite button (portal only)** and **Hide invite button (portal only)**: the portal's invite button without changing whether the room is joinable. The link is in `ResultString`.
- `data.mirrorIndexedDB` is not an action: it must run in the page before the game reads its files, so call `ZokoSDK.data.mirrorIndexedDB` from a page script before the game loads.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (**Request ad** with type `midgame`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with **On ad error** with `adCooldown` until your game has called the **Gameplay start** action or 30 seconds of visible page time have passed. On the portal the first midgame ad needs the **Gameplay start** action first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

There is no separate simulator. When the page's host is `localhost`, `127.0.0.1` or a `*.localhost` name, the JavaScript SDK runs its own [local mode](https://docs.zokogames.com/getting-started/local-testing): a three-second overlay for each ad, a fake player, a `localStorage` cloud save and a three-item test store, so the same events fire as on the portal. On any other host the environment is `disabled`, and **Is available** is false.

- GDevelop's preview runs from a small local web server. If `Environment` reads `disabled` there (a network address instead of `localhost`), export the project and serve the folder from `localhost`, or open the page with `?useLocalSdk=true`.
- A second midgame request within three minutes fails with `adCooldown` (fires **On ad error**): the real rule, so your events must cope.
- Useful switches: `?sdk_debug=true`, `?ad_response=unfilled`, `?user_response=logged_out`.
- Then open the [Preview tool](https://www.zokogames.com/preview) with your local address and watch the checklist tick.

## API

### `init`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `init` | Action `Initialize`; conditions `IsInitialized`, `IsAvailable` |
| `environment` | Expression `Environment` |
| `isQaTool` | Condition `IsQaTool` |

### `ad.*`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `ad.requestAd` | Action `RequestAd`; conditions `OnAdStarted`, `OnAdFinished`, `OnAdError`, `IsAdPlaying` |
| `ad.requestAd.adStarted` | Condition `OnAdStarted`; `IsAdPlaying` true |
| `ad.requestAd.adFinished` | Condition `OnAdFinished` |
| `ad.requestAd.adError` | Condition `OnAdError`; expression `ErrorCode` |
| `ad.hasAdblock` | Action `HasAdblock` |

### `banner.*`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `banner.requestBanner` | Action `RequestBanner` |
| `banner.requestResponsiveBanner` | Action `RequestResponsiveBanner` |
| `banner.clearBanner` | Action `ClearBanner` |
| `banner.clearAllBanners` | Action `ClearAllBanners` |

### `game.*`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `game.settings` | Expressions `MuteAudio`, `DisableChat`, `KidsMode`; conditions `IsMuteRequested`, `IsChatDisabled`, `IsKidsMode` |
| `game.addSettingsChangeListener` | Condition `OnSettingsChanged` |
| `game.gameplayStart` | Action `GameplayStart` |
| `game.gameplayStop` | Action `GameplayStop` |
| `game.loadingStart` | Action `LoadingStart` |
| `game.loadingStop` | Action `LoadingStop` |
| `game.loadingProgress` | Action `LoadingProgress` |
| `game.happytime` | Action `Happytime` |
| `game.reportGameCompletedPercentage` | Action `ReportCompleted` |
| `game.reportChat` | Action `ReportChat` |
| `game.onScreenshotRequest` | Actions `SetScreenshotProvider`, `AnswerScreenshot`; condition `OnScreenshotRequested` |
| `game.setGameContext` | Action `SetGameContext` |
| `game.clearGameContext` | Action `ClearGameContext` |
| `game.isInstantMultiplayer` | Condition `IsInstantMultiplayer` |
| `game.isInstantJoin` | Condition `IsInstantMultiplayer` |
| `game.isOffline` | Condition `IsOffline` |
| `game.gameId` | Expression `GameId` |
| `game.addOfflineListener` | Condition `OnOfflineChanged` |
| `game.updateRoom` | Action `UpdateRoom`; action `SetRoomPublic` |
| `game.leftRoom` | Action `LeftRoom` |
| `game.addJoinRoomListener` | Condition `OnJoinRoom` |
| `game.inviteParams` | Expressions `InviteParamsJSON`, `InviteParam` |
| `game.inviteLink` | Action `InviteLink` |
| `game.getInviteParam` | Expression `InviteParam` |
| `game.showInviteButton` | Actions `ShowInviteButton`; `ShowInviteButtonPortalOnly` (`{ portalOnly: true }`) |
| `game.hideInviteButton` | Actions `HideInviteButton`; `HideInviteButtonPortalOnly` (`{ portalOnly: true }`) |
| `game.room` | Actions `SendRoomMessage`, `SendRoomMessageTo`, `SetRoomStateKey`, `RemoveRoomStateKey`; conditions `OnRoomMessage`, `OnRoomStateChanged`, `OnRoomMembersChanged`, `OnRoomHostChanged`, `OnRoomError`, `IsRoomHost` |
| `game.room.send` | Actions `SendRoomMessage`, `SendRoomMessageTo` |
| `game.room.onMessage` | Condition `OnRoomMessage`; expressions `RoomMessageData`, `RoomMessageFrom`, `RoomMessageDirect`, `RoomMessageSeq`, `RoomMessageValue` |
| `game.room.addMessageListener` | Condition `OnRoomMessage` |
| `game.room.setState` | Actions `SetRoomStateKey`, `RemoveRoomStateKey` |
| `game.room.getState` | Expressions `RoomStateJSON`, `RoomStateValue` |
| `game.room.onState` | Condition `OnRoomStateChanged`; expressions `RoomStateChangedKeys`, `RoomStateChangedBy`, `RoomStateRev` |
| `game.room.addStateListener` | Condition `OnRoomStateChanged` |
| `game.room.members` | Expressions `RoomMemberCount`, `RoomMemberIdAt`, `RoomMemberNameAt`, `RoomMemberPictureUrlAt` |
| `game.room.onMembers` | Condition `OnRoomMembersChanged` |
| `game.room.addMembersListener` | Condition `OnRoomMembersChanged` |
| `game.room.isHost` | Condition `IsRoomHost` |
| `game.room.onHostChange` | Condition `OnRoomHostChanged`; expression `RoomHostId` |
| `game.room.addHostChangeListener` | Condition `OnRoomHostChanged` |
| `game.room.selfId` | Expression `RoomSelfId` |
| `game.room.onError` | Condition `OnRoomError`; expressions `RoomErrorCode`, `RoomErrorMessage` |
| `game.room.addErrorListener` | Condition `OnRoomError` |
| `game.room.addLeftListener` | Condition `OnRoomLeft`; expressions `RoomLeftReason`, `RoomLeftRoomId` |

### `user.*`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `user.isUserAccountAvailable` | Condition `IsAccountAvailable` |
| `user.systemInfo` | Expressions `Locale`, `CountryCode`, `DeviceType` |
| `user.getUser` | Action `GetUser`; expressions `UserName`, `UserPictureUrl`, `UserId`; condition `IsLoggedIn` |
| `user.listFriends` | Action `ListFriends`; expressions `FriendCount`, `FriendsTotal`, `FriendsHasMore`, `FriendName`, `FriendId`, `FriendPictureUrl` |
| `user.getUserToken` | Action `GetUserToken`; expression `UserToken` |
| `user.showAuthPrompt` | Action `ShowAuthPrompt` |
| `user.addAuthListener` | Condition `OnAuthChanged` |
| `user.showAccountLinkPrompt` | Action `ShowAccountLinkPrompt` |
| `user.submitScore` | Action `SubmitScore` |
| `user.getXsollaUserToken` | Action `GetXsollaUserToken`; expression `XsollaUserToken` |

### `data.*`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `data.getItem` | Action `GetItem`; expressions `SavedItem`, `HasSavedItem` |
| `data.setItem` | Action `SetItem` |
| `data.removeItem` | Action `RemoveItem` |
| `data.clear` | Action `ClearData` |
| `data.mirrorLocalStorage` | Actions `MirrorLocalStorage`, `StopMirrorLocalStorage`; condition `OnMirrorError`; expressions `MirrorErrorCode`, `MirrorErrorMessage` |

### `store.*`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `store.isAvailable` | Condition `IsStoreAvailable` |
| `store.getCatalogItems` | Action `GetCatalogItems`; expressions `StoreItemCount`, `StoreItemSku`, `StoreItemName`, `StoreItemDescription`, `StoreItemImageUrl`, `StoreItemPrice`, `StoreItemCurrency`, `StoreItemConsumable` |
| `store.getPlayerInventory` | Action `GetPlayerInventory`; expressions `InventoryCount`, `InventorySku`, `InventoryName`, `InventoryDescription`, `InventoryImageUrl`, `InventoryQuantity` |
| `store.buyItem` | Action `BuyItem`; expression `PurchasedItemId` |
| `store.consumeItem` | Action `ConsumeItem` |
| `store.getPurchaseToken` | Action `GetPurchaseToken`; expression `PurchaseToken` |
| `store.setSandbox` | Action `SetSandbox` |

### `achievements.*`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `achievements.list` | Action `ListAchievements`; expressions `AchievementCount`, `AchievementKeyAt`, `AchievementNameAt`, `AchievementDescriptionAt`, `AchievementPointsAt`, `AchievementUnlockedAt`, `AchievementIsUnlockedAt` |
| `achievements.unlock` | Action `UnlockAchievement`; expressions `LastUnlockReason`, `LastAchievementKey`, `LastAchievementName`, `LastAchievementPoints` |
| `achievements.onUnlock` | Condition `OnAchievementUnlocked` |

### `analytics.*`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `analytics.track` | Action `TrackEvent` |
| `analytics.trackOrder` | Action `TrackOrder` |

### `constants`

<!-- search: headings-only -->

| JavaScript | GDevelop |
| --- | --- |
| `ERROR_CODES` | Expression `ErrorCodes`; condition `LastErrorIs` |
| `ERROR_CODE_DESCRIPTIONS` | Expression `ErrorDescription` |
| `SDK_VERSION` | Expression `SdkVersion` |

## Known pitfalls

<!-- search: headings-only -->

- **Import fails.** Import `ZokoGames.json`, not the zip.
- **A condition is never true.** The tag in **On request completed** must equal the tag passed to the action, and only one request per tag should be in flight.
- **Actions run but nothing happens.** Run **Initialize** first and wait for its completion.
- **`sdkNotLoaded`.** Offline or the SDK host is blocked; the preview needs internet access to load the script.
- **Actions after an ad request run late.** GDevelop waits for the request; start ads in their own event.
- **Banner in the wrong place.** Rectangles are game resolution pixels, origin top-left.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).

---

Source: https://docs.zokogames.com/porting/overview

# Bring your game to ZokoGames

This section is for studios whose game already ships as a web build on other web game portals. Your gameplay code stays as it is. What changes is the thin platform layer around it: the script that loads the portal SDK, the calls for ads, saves, leaderboards and purchases, and a few export settings. Each engine has its own page with the exact settings and calls; this page is the route through them. Unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## What carries over and what changes

| Part of your game | On ZokoGames |
| --- | --- |
| Gameplay, art, audio, levels | Unchanged. |
| The web export itself | Kept, with the settings on your engine's page: no threads, relative paths, `index.html` at the archive root. |
| The other portal's SDK script and calls | Replaced by the ZokoGames SDK (`https://sdk.zokogames.com/zokogames-sdk-v1.js`) or your engine's wrapper. |
| Ad breaks and rewarded ads | Same places in your game; the call and its callbacks change name. An interstitial or commercial break is a `midgame` ad, an opt-in reward video is `rewarded`; there are no other types and no prerolls. |
| Cloud saves | Same idea, new call. Old progress moves only if you migrate it ([data](https://docs.zokogames.com/sdk/data#migrating-from-localstorage)). |
| Leaderboards | Created again in the developer console, with a new encryption key ([leaderboards](https://docs.zokogames.com/sdk/leaderboards)). |
| In-game purchases | Products are defined again in the console. Purchases run as test purchases for now ([purchases](https://docs.zokogames.com/sdk/purchases)). |
| The other portal's logos, links, store badges and sitelock | Removed, and the sitelock set to allow `zokogames.com` ([sitelock](https://docs.zokogames.com/requirements/technical#sitelock)). |

## The five steps {#steps}

1. **Export for the web with the right settings.** No threads (the game frame is not cross-origin isolated), relative paths, plain file names except Unity's `.br` or `.gz` build files. Your engine's page lists every setting.
2. **Swap the platform layer.** Install your engine's wrapper, initialise it once, then replace each call your game makes for loading finished, gameplay start and stop, ads, saves, the player, leaderboards and purchases. Delete the other portal's script, branding and sitelock.
3. **Check size and mobile.** Limits: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile), estimated from uncompressed sizes. See [first frame fast](https://docs.zokogames.com/guides/first-frame) and [mobile](https://docs.zokogames.com/guides/mobile).
4. **Test.** Run the game on `localhost`, where the SDK starts in [local mode](https://docs.zokogames.com/getting-started/local-testing) with fake ads, fake players and local saves. Then upload the zip and open the game's **Preview and QA** tab in the developer console, which runs the exact build in the portal frame with ads on.
5. **Upload and submit.** Follow the [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

## Pick your engine

| Engine | Porting page | Full engine reference | Plugin folder (`packages/sdk-engines/`) |
| --- | --- | --- | --- |
| Unity (WebGL) | [Bring a Unity game](https://docs.zokogames.com/porting/unity) | [Unity](https://docs.zokogames.com/engines/unity) | `unity/` |
| Godot 4 (Godot 3 has its own addon) | [Bring a Godot game](https://docs.zokogames.com/porting/godot) | [Godot](https://docs.zokogames.com/engines/godot) | `godot/`, `godot3/` |
| Construct 3 | [Bring a Construct 3 game](https://docs.zokogames.com/porting/construct-3) | [Construct 3](https://docs.zokogames.com/engines/construct-3) | `construct3/` |
| GameMaker | [Bring a GameMaker game](https://docs.zokogames.com/porting/gamemaker) | [GameMaker](https://docs.zokogames.com/engines/gamemaker) | `gamemaker/` |
| Phaser and plain HTML5 | [Bring a Phaser or HTML5 game](https://docs.zokogames.com/porting/phaser-html5) | [Phaser](https://docs.zokogames.com/engines/phaser), [plain HTML5](https://docs.zokogames.com/engines/html5-libraries) | `phaser/` (plain HTML5 needs none) |
| Defold | [Bring a Defold game](https://docs.zokogames.com/porting/defold) | [Defold](https://docs.zokogames.com/engines/defold) | `defold/` |
| Cocos Creator 3 | [Bring a Cocos game](https://docs.zokogames.com/porting/cocos) | [Cocos](https://docs.zokogames.com/engines/cocos) | `cocos/` |

Each wrapper downloads from its engine page, and [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json) lists every package with its version and checksum. The wrappers are thin: behaviour, limits and [error codes](https://docs.zokogames.com/sdk/introduction#errors) are those of the [JavaScript SDK](https://docs.zokogames.com/sdk/introduction). As each wrapper's README states, they are written against the engines' documented APIs and have not yet been run in every engine's editor, so expect small fixes on first import and send them to [support](https://docs.zokogames.com/business/support) with your engine version.

## Two routes for JavaScript call sites

Games whose platform calls are written in JavaScript (Phaser, plain HTML5 and libraries, or JavaScript glue inside another engine's web template) can port in two ways:

- **Rename (recommended).** Point the calls at `window.ZokoGames.SDK`. Most web game portals use the same shapes (init, ads with started, finished and error callbacks, gameplay events, user, cloud save), so this is mostly renaming.
- **Compatibility shim (quick port).** Load `zokogames-compat-v1.js` after the SDK, with `data-global` set to the global name your game already reads. The shim forwards those calls to the ZokoGames SDK and translates the common differences.

Both routes, the mapping table and the shim's exact behaviour are in [migrating from another portal's SDK](https://docs.zokogames.com/guides/migrating). The shim covers JavaScript only: engine wrappers such as the Unity `.jslib` or the Godot shell replace a C#, GDScript, GML or Lua integration, which the per-engine pages describe.

## What every port must get right

- [ ] The SDK script is referenced in your files (the upload validator looks for the URL, even where a wrapper can inject it).
- [ ] Init runs once, first, and the game still plays when the SDK is `disabled`.
- [ ] Loading finished: `loadingStop` once the first screen can be played (the Unity and Godot templates send it when the engine has started; every other engine you send yourself).
- [ ] Gameplay start at first player control, gameplay stop at pause, game over and level end. A midgame ad is refused with `adCooldown` until `gameplayStart` has been called once.
- [ ] Every ad pauses the game and its audio, and resumes on finish **and** on error (unfilled ads, the three-minute midgame cooldown and ad blockers all end in an error).
- [ ] Rewards are granted only after the rewarded ad finished.
- [ ] Saves go through the data module; scores through a leaderboard created in the console.
- [ ] No other portal's script, logo, link or sitelock is left in the build.
- [ ] No threaded export, relative paths only, `index.html` at the archive root.
- [ ] Tested on `localhost` and in the console's **Preview and QA** tab.

The full lists are the [testing checklist](https://docs.zokogames.com/getting-started/testing-checklist) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).

## Next

- Pick your engine in the table above.
- Rules your build is checked against: [build validation](https://docs.zokogames.com/requirements/build-validation).
- Revenue terms before you upload: [revenue share](https://docs.zokogames.com/business/revenue-share).

---

Source: https://docs.zokogames.com/porting/unity

# Bring a Unity game

For a Unity WebGL game that already runs on other web game portals. You keep the project and the scenes; you swap the WebGL template and the portal calls, and check a few Player Settings. The full reference, with the mapping of every call, is the [Unity engine page](https://docs.zokogames.com/engines/unity). The overall route is in [bring your game](https://docs.zokogames.com/porting/overview).

## 1. Export settings

Install the package (`com.zokogames.sdk`, Unity 2021.3 or newer) as described in [Unity: install](https://docs.zokogames.com/engines/unity#install), then run **ZokoGames > Install WebGL Template**. Check these settings against what your build used before:

| Setting | On ZokoGames |
| --- | --- |
| **WebGL Template** | **ZokoGames**. It loads the SDK before the Unity loader and reports the download to the portal's loading bar. A custom template works if it keeps the canvas id `unity-canvas` and loads `https://sdk.zokogames.com/zokogames-sdk-v1.js` first. |
| **Compression Format** | **Brotli** or **Gzip**, one format for the whole build. The game origin sends the matching `Content-Encoding` for `.br` and `.gz` files. |
| **Decompression Fallback** | Off. Builds made for hosts that cannot set `Content-Encoding` often have it on; the portal does not need it. |
| Legacy `.unityweb` files | Not supported (validator warning `unity_unityweb`). Rebuild with Brotli or Gzip. |
| **Threading** | Off. A threaded build cannot start in the portal frame (`SharedArrayBuffer is not defined`). |
| Canvas Scaler | **Scale With Screen Size**: the canvas fills a frame whose size changes with fullscreen and rotation. |

Details and the reasons: [WebGL export settings that matter](https://docs.zokogames.com/engines/unity#webgl-export-settings-that-matter).

## 2. Replace the platform calls

Delete the other portal's template, `.jslib` and wrapper scripts first, so two SDKs never run side by side. Then call `ZokoSDK.InitAsync()` once in your first scene and map each call your game makes:

| Your game does | With ZokoSDK |
| --- | --- |
| Start the SDK | `await ZokoSDK.InitAsync()` once; then check `ZokoSDK.IsAvailable` (false when the SDK is `disabled`, and the game must still run). |
| Loading finished | Nothing to write for the engine download: the ZokoGames template sends `loadingStart` and `loadingStop` once the engine has started. Call `ZokoSDK.Game.LoadingStart()`, `LoadingProgress(p)` and `LoadingStop()` yourself only for a longer loading screen of your own or in a custom template. |
| Gameplay start and stop | `ZokoSDK.Game.GameplayStart()` at first control, `GameplayStop()` at pause, game over and level end. |
| Midgame ad (an interstitial or commercial break) | `ZokoSDK.Ad.RequestAdAsync(ZokoAdType.Midgame, adStarted: PauseForAd)`; resume after the `await`, which returns for every outcome. |
| Rewarded ad | The same with `ZokoAdType.Rewarded`; grant the reward only when it returns `null` (the ad finished). |
| Mute during ads | Nothing to write: `Ad.MuteAudioDuringAds` and `Ad.FollowPortalMute` are on by default. Pausing `Time.timeScale` stays your job. |
| Cloud save | `ZokoSDK.Data.SetInt`, `GetInt`, `SetString` and the other `Data` calls (synchronous after init). Games that saved to `PlayerPrefs` only can mirror them with `Data.PushPlayerPrefs` and `PullPlayerPrefs`, see [PlayerPrefs mirror](https://docs.zokogames.com/engines/unity#playerprefs-mirror-and-clipboard). |
| Leaderboard score | `ZokoSDK.User.SubmitScore(encryptedScore, score, done)` for a signed-in player, on a board you create in the console. No wrapper builds the encrypted payload; read [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission) before you choose a keyed board. |
| Purchases | `ZokoSDK.Store.GetCatalogItemsAsync`, `BuyItemAsync(sku)`, `ConsumeItemAsync(sku, qty)`, with products defined again in the console. Purchases are test purchases for now ([purchases](https://docs.zokogames.com/sdk/purchases)). |
| Sign-in prompt, player name | `ZokoSDK.User.ShowAuthPrompt(cb)`, `User.GetUserAsync()`. |

The working boot script on the engine page covers init, both ad types, save and score in one MonoBehaviour: [a working boot script](https://docs.zokogames.com/engines/unity#a-working-boot-script). Every other call is in the [mapping table](https://docs.zokogames.com/engines/unity#mapping).

The [compatibility shim](https://docs.zokogames.com/guides/migrating#two-ways-to-port) only helps JavaScript code. If your WebGL template or a `.jslib` of your own calls another portal's JavaScript SDK directly, the shim can bridge those calls, but your C# calls still move to `ZokoSDK`.

## 3. Build size and mobile

- The budget is 1,500 files, 250 MB unpacked and about 50 MB initial download (20 MB for mobile), estimated from **uncompressed** sizes, so Brotli does not rescue an oversized build.
- Keep the first scene small and load the rest with Addressables shipped inside the build; the rules are in [Addressables and custom builds](https://docs.zokogames.com/engines/unity#addressables-and-custom-builds).
- Managed Stripping Level High, Strip Engine Code on, ASTC textures for mobile, a small initial memory size.
- Unity games are off on iOS by default. Tick **Tested and works well on iOS** in the console only after testing on a real device ([mobile](https://docs.zokogames.com/guides/mobile)).
- Start music from a "tap to play" screen: browsers keep audio suspended until the first input.

## 4. Test before you submit

1. **In the Editor**, the simulator answers (`ZokoSDK.IsSimulated` is true). Tune it in `ZokoSDKSettings`: ad fill, no fill and error, a logged-out player, an ad blocker, a disabled SDK.
2. **A WebGL build on `localhost`** runs the SDK's own local mode, which also enforces the three-minute midgame cooldown that the simulator skips. Brotli builds need a server that sends `Content-Encoding: br`; build with compression Disabled for local tests if yours does not. See [Unity: test locally](https://docs.zokogames.com/engines/unity#test-locally).
3. **Upload the zip** (the build folder's contents, `index.html` at the archive root) and open the game's **Preview and QA** tab in the developer console. It runs the exact build in the portal frame with ads on and ticks the checklist as each call arrives ([build preview](https://docs.zokogames.com/getting-started/local-testing#the-build-preview-in-the-console)).

## Checklist

- [ ] ZokoGames WebGL template (or your own with `unity-canvas` and the SDK script first).
- [ ] Brotli or Gzip, Decompression Fallback off, no `.unityweb`, threading off.
- [ ] The other portal's template, `.jslib`, scripts, logos and sitelock removed.
- [ ] `InitAsync` first; the game plays when `IsAvailable` is false.
- [ ] Gameplay start and stop at the right moments.
- [ ] Both ad types pause and resume on every outcome; rewards only after a finished ad.
- [ ] Saves through `ZokoSDK.Data`; scores on a board created in the console.
- [ ] First scene within the initial download budget; iOS tested before you enable it.
- [ ] Tested on `localhost` and in **Preview and QA**.

## Next

- Full reference: [Unity](https://docs.zokogames.com/engines/unity).
- Before upload: [build validation](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/porting/godot

# Bring a Godot game

For a Godot game that already ships as a Web export on other web game portals. You keep the project; you enable the `zokogames` addon, switch the export's HTML shell and replace the portal calls. The full reference is the [Godot engine page](https://docs.zokogames.com/engines/godot), which also covers [Godot 3](https://docs.zokogames.com/engines/godot#godot-3). The overall route is in [bring your game](https://docs.zokogames.com/porting/overview).

## 1. Export settings

Copy `addons/zokogames` into `res://addons/` and enable **ZokoGames** under **Project > Project Settings > Plugins**, as in [Godot: install](https://docs.zokogames.com/engines/godot#install). Then check the Web export preset:

| Setting | On ZokoGames |
| --- | --- |
| **Custom HTML Shell** | `res://addons/zokogames/export/zokogames_shell.html`. It loads the SDK before the engine and defines the bridge the autoload talks to. If your old shell held another portal's script, replace it; with a shell of your own, copy the bridge block across. |
| **Thread Support** | Off. The portal frame is not cross-origin isolated, so a threaded export does not start. Godot 4.3 and later export single-threaded by default. |
| File names | Keep `index.html`, `index.js`, `index.wasm`, `index.pck` as exported. Do not rename them to `.br` or `.gz`: Godot requests the plain names. |
| Texture compression | VRAM compression for desktop and mobile, so every browser has a format. |
| Stretch | **Stretch Mode** `canvas_items` with aspect `expand` or `keep`: the frame changes size with fullscreen and rotation. |
| Export With Debug | Off. |

Details: [web export settings that matter](https://docs.zokogames.com/engines/godot#web-export-settings-that-matter).

## 2. Replace the platform calls

Remove the other portal's shell code, scripts and autoloads first. Then `await ZokoGames.init_async()` once at startup and map each call:

| Your game does | With the `ZokoGames` autoload |
| --- | --- |
| Start the SDK | `await ZokoGames.init_async()`; `ZokoGames.is_available()` is false when the SDK is `disabled`, and the game must still run. |
| Loading finished | Nothing to write for the engine download: the shell sends `loadingStart` and `loadingStop` once the engine has started. For a longer loading screen of your own call `ZokoGames.loading_start()`, `loading_progress(percent)` and `loading_stop()`. |
| Gameplay start and stop | `ZokoGames.gameplay_start()` and `gameplay_stop()`. |
| Midgame ad (an interstitial or commercial break) | `await ZokoGames.request_ad_async("midgame")`. It completes after the ad is over, whatever the outcome. |
| Rewarded ad | `await ZokoGames.request_ad_async("rewarded")`; grant the reward only when the result's `ok` is true. |
| Pause and mute during ads | Nothing to write: the addon pauses the tree and mutes Master from `ad_started` until `ad_finished` or `ad_error`, and follows the portal's mute setting. Nodes that must keep running need the **Always** process mode. |
| Cloud save | `ZokoGames.data_set_item(key, value)` and `data_get_item(key, default)`, synchronous Strings. |
| Leaderboard score | `await ZokoGames.submit_score_async(encrypted_score, score)` for a signed-in player, on a board created in the console. No wrapper builds the encrypted payload; see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission). |
| Purchases | `store_get_catalog_items_async`, `store_buy_item_async(item_id)`, `store_consume_item_async(sku, qty)`. Purchases are test purchases for now ([purchases](https://docs.zokogames.com/sdk/purchases)). |
| Sign-in prompt, player | `await ZokoGames.show_auth_prompt_async()`, `await ZokoGames.get_user_async()`. |

A complete script with init, both ads, save and score is in [a working script](https://docs.zokogames.com/engines/godot#a-working-script); every call is in [how calls work](https://docs.zokogames.com/engines/godot#how-calls-work). Godot's own `user://` files live in the browser's IndexedDB and stay on one device; move progress you want kept into `data_set_item`.

The [compatibility shim](https://docs.zokogames.com/guides/migrating#two-ways-to-port) is for JavaScript call sites only. A Godot game calls the autoload from GDScript, so it does not need the shim.

## 3. Build size and mobile

- Budget: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile), estimated from uncompressed sizes. Keep the `.wasm` and `.pck` small.
- A custom export template with unused modules disabled cuts the engine itself.
- Load later levels after the first scene with `ResourceLoader.load_threaded_request`, which still works in a non-threaded export.
- Cap the resolution on phones and start audio from a "click to play" screen; see [mobile](https://docs.zokogames.com/guides/mobile).

## 4. Test before you submit

1. **In the editor** the simulator answers (`ZokoGames.is_simulated`). Its settings are under **Project Settings > zokogames/simulator**: ad fill, no fill and error, an ad blocker, a logged-out player, a disabled SDK.
2. **The Web export on `localhost`** (a local web server, not a file opened from disk) runs the SDK's local mode, which also enforces the three-minute midgame cooldown the simulator skips. See [Godot: test locally](https://docs.zokogames.com/engines/godot#test-locally).
3. **Upload the zip** (export folder contents, `index.html` at the archive root) and open the game's **Preview and QA** tab in the developer console to run the build in the portal frame with ads on ([build preview](https://docs.zokogames.com/getting-started/local-testing#the-build-preview-in-the-console)).

## Checklist

- [ ] Addon enabled; custom HTML shell set; the other portal's shell code and scripts removed.
- [ ] Thread Support off; file names as exported.
- [ ] `init_async` first; the game plays when `is_available()` is false.
- [ ] Gameplay start and stop at the right moments.
- [ ] Rewards only when the rewarded ad finished; your own nodes behave while the tree is paused.
- [ ] Saves through `data_set_item`; scores on a board created in the console.
- [ ] Other portal's logos, links and sitelock removed.
- [ ] Tested on `localhost` and in **Preview and QA**.

## Next

- Full reference: [Godot](https://docs.zokogames.com/engines/godot).
- Before upload: [build validation](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/porting/construct-3

# Bring a Construct 3 game

For a Construct 3 game that already ships as an HTML5 export on other web game portals. The work happens in the event sheet: you replace the other portal's object and actions with the ZokoGames addon. No scripting is needed. The full reference is the [Construct 3 engine page](https://docs.zokogames.com/engines/construct-3). The overall route is in [bring your game](https://docs.zokogames.com/porting/overview).

## 1. Export settings

Install `zokogames.c3addon` (not the zip) through **Menu > View > Addon Manager**, restart Construct, and insert the **ZokoGames** object ([Construct 3: install](https://docs.zokogames.com/engines/construct-3#install)). The addon loads the SDK script itself, so you edit no export file. Then check the export:

| Setting | On ZokoGames |
| --- | --- |
| Export type | **HTML5 website**; zip the folder contents so `index.html` is at the archive root. |
| **Offline support** | No. It adds a service worker, which the validator warns about (`service_worker`). |
| **Use worker** | Yes is supported. |
| **Minify script** | Simple or Advanced. |
| Pre-compression | None. Construct requests plain file names; upload the export as it is. |
| **Fullscreen mode** | A letterbox or scale-outer mode, so the layout fits a frame that changes with fullscreen and rotation. |

Details: [export settings that matter on the web](https://docs.zokogames.com/engines/construct-3#export-settings-that-matter-on-the-web).

## 2. Replace the platform events

Delete the other portal's object and every event that uses it, so no action points at an SDK that is not there. Then rebuild those events with the ZokoGames object. Every asynchronous action takes a **Tag**; **On request completed** or **On request failed** with the same tag fires when it ends ([tags, results and errors](https://docs.zokogames.com/engines/construct-3#tags-results-and-errors)).

| Your game does | With the ZokoGames addon |
| --- | --- |
| Start the SDK | **Initialize** at the start of the first layout; wait for it before other actions. **Is available** is false when the SDK is `disabled`, and the game must still run. |
| Loading finished | **Loading stop** once the first layout can be played (optionally **Loading start** and **Report loading progress** before it). The addon does not send these on its own. |
| Gameplay start and stop | **Gameplay start** and **Gameplay stop**. |
| Midgame (interstitial) or rewarded ad | **Request ad** (midgame or rewarded). Pause on **On ad started**; resume on **On ad finished** and on **On ad error**. Grant a reward only in **On ad finished**. |
| Mute | **On settings changed** with **Is mute requested**. |
| Cloud save | **Set saved item**, **Get saved item** (then read `SavedItem(key)` in **On request completed**), **Remove saved item**. |
| Leaderboard score | **Submit score** for a logged-in player, on a board created in the console. No wrapper builds an encrypted payload; see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission). |
| Purchases | **Get catalogue items**, **Buy item**, **Consume item**, **Get player inventory**. Purchases are test purchases for now ([purchases](https://docs.zokogames.com/sdk/purchases)). |
| Sign-in prompt | **Show login prompt**; **On auth changed** and **Is logged in**. |

A complete event sheet is in [a working event sheet](https://docs.zokogames.com/engines/construct-3#a-working-event-sheet). The Local Storage object keeps data in IndexedDB on one device; move progress you want kept to the cloud save actions.

The [compatibility shim](https://docs.zokogames.com/guides/migrating#two-ways-to-port) is for JavaScript call sites. Use it only if a script in your project calls another portal's JavaScript SDK directly; event sheets move to the addon.

## 3. Build size and mobile

- Budget: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile), estimated from uncompressed sizes.
- Compress images (WebP) and audio (Opus or AAC); put large media in a second layout loaded once the first is interactive.
- Split rarely used layouts and keep sprite sheets small for phones.
- Start music from a "tap to play" button, not on start of layout. See [mobile](https://docs.zokogames.com/guides/mobile).

## 4. Test before you submit

1. **Preview on `localhost`.** There is no separate simulator: on `localhost` the SDK runs its own local mode with a three-second ad overlay, a fake player and local saves. If your preview is not on a localhost address, add `?useLocalSdk=true`. See [Construct 3: test locally](https://docs.zokogames.com/engines/construct-3#test-locally).
2. **Try the failures.** `?ad_response=unfilled` forces ad errors, `?user_response=logged_out` tests guests, and a second midgame within three minutes fails with `adCooldown`.
3. **Upload the zip** and open the game's **Preview and QA** tab in the developer console to run it in the portal frame with ads on ([build preview](https://docs.zokogames.com/getting-started/local-testing#the-build-preview-in-the-console)).

## Checklist

- [ ] Addon installed; the other portal's object and events removed.
- [ ] **Initialize** first; the game plays when **Is available** is false.
- [ ] Gameplay start and stop at the right moments.
- [ ] Ads resume on **On ad finished** and **On ad error**; rewards only on finish.
- [ ] One tag per request in flight.
- [ ] Saves through the cloud save actions; scores on a board created in the console.
- [ ] Offline support off; other portal's logos, links and sitelock removed.
- [ ] Tested on `localhost` and in **Preview and QA**.

## Next

- Full reference: [Construct 3](https://docs.zokogames.com/engines/construct-3).
- Before upload: [build validation](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/porting/gamemaker

# Bring a GameMaker game

For a GameMaker game that already ships as an HTML5 export on other web game portals. You replace the other portal's extension with the ZokoGames one and move your ad, save and score calls to the `zoko_*` functions. The full reference is the [GameMaker engine page](https://docs.zokogames.com/engines/gamemaker). The overall route is in [bring your game](https://docs.zokogames.com/porting/overview).

## 1. Export settings

Set up the `ZokoGames` extension as in [GameMaker: install](https://docs.zokogames.com/engines/gamemaker#install): `zokogames.js` ticked for HTML5 only, `zokogames_sim.gml` for every other platform, each function declared. Then:

| Setting | On ZokoGames |
| --- | --- |
| SDK script tag | Add `<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>` to the game's `index.html` through the HTML5 game options, and remove the other portal's tag. Without it every call fails with `sdkNotLoaded`. |
| Output | Export HTML5 to a clean folder; zip its contents so `index.html` is at the archive root. |
| Pre-compression | None. GameMaker requests plain file names. |
| Scaling | "Keep aspect ratio" or "Full scale", so the game fits a frame that changes with fullscreen and rotation. |
| Loading bar | If you report loading to the portal yourself, turn the built-in bar off. |

Details: [HTML5 export settings that matter](https://docs.zokogames.com/engines/gamemaker#html5-export-settings-that-matter).

## 2. Replace the platform calls

Remove the other portal's extension and its calls first. Asynchronous `zoko_*` functions return a request id at once; the answer arrives in the **Async - Social** event with `async_load[? "type"] == "zoko"` ([how calls work](https://docs.zokogames.com/engines/gamemaker#how-calls-work)). Use one **persistent** controller object for them.

| Your game does | With the extension |
| --- | --- |
| Start the SDK | `zoko_init()` once, from the controller; wait for its `response` event. |
| Loading finished | `zoko_game_loading_stop()` once the first room can be played (optionally `zoko_game_loading_start()` and `zoko_game_loading_progress(p)` before it). The extension does not send these on its own. |
| Gameplay start and stop | `zoko_game_gameplay_start()` and `zoko_game_gameplay_stop()`. |
| Midgame (interstitial) or rewarded ad | `zoko_ad_request_ad("midgame")` or `"rewarded"`. Pause on the `ad_started` event; resume on `ad_finished` and on `ad_error`. Grant a reward only on `ad_finished`. |
| Mute | The `settings_changed` event carries `{ disableChat, muteAudio }`. |
| Cloud save | `zoko_data_set_item(key, value)`, `zoko_data_get_item(key)` (`""` when missing), `zoko_data_has_key(key)`. |
| Leaderboard score | `zoko_user_submit_score(encrypted_score, score)` for a signed-in player, on a board created in the console. No wrapper builds the encrypted payload; see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission). |
| Purchases | `zoko_store_get_catalog_items(limit, offset)`, `zoko_store_buy_item(sku)`, `zoko_store_consume_item(sku, qty)`. Purchases are test purchases for now ([purchases](https://docs.zokogames.com/sdk/purchases)). |
| Sign-in prompt, player | `zoko_user_show_auth_prompt()`, `zoko_user_get_user()`. |

A complete controller is in [a working controller](https://docs.zokogames.com/engines/gamemaker#a-working-controller), and every function in [functions](https://docs.zokogames.com/engines/gamemaker#functions). Structured results are JSON text: wrap them in `json_parse`.

The [compatibility shim](https://docs.zokogames.com/guides/migrating#two-ways-to-port) is for JavaScript call sites only; GML calls move to the `zoko_*` functions.

## 3. Build size and mobile

- Budget: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile), estimated from uncompressed sizes.
- Use texture groups so only the first room's textures are in the initial download; use OGG audio and stream music.
- The HTML5 target is single-threaded: keep Step events cheap while ads show and memory modest for phones.
- Start music from a "click to play" room. See [mobile](https://docs.zokogames.com/guides/mobile).

## 4. Test before you submit

1. **On Windows, macOS or Linux** the GML simulator answers one tick later with the same events. Edit `global.zoko_sim_config` before `zoko_init()` to force ad errors, a logged-out player or a disabled SDK.
2. **The HTML5 export on `localhost`** runs the SDK's local mode, which also enforces the three-minute midgame cooldown the simulator skips. See [GameMaker: test locally](https://docs.zokogames.com/engines/gamemaker#test-locally).
3. **Upload the zip** and open the game's **Preview and QA** tab in the developer console to run it in the portal frame with ads on ([build preview](https://docs.zokogames.com/getting-started/local-testing#the-build-preview-in-the-console)).

## Checklist

- [ ] Extension set up for HTML5 and the simulator; the other portal's extension removed.
- [ ] SDK script tag in `index.html`; the other portal's tag removed.
- [ ] `zoko_init()` first, from a persistent controller; the game plays when the SDK is `disabled`.
- [ ] Gameplay start and stop at the right moments.
- [ ] Ads resume on `ad_finished` and `ad_error`; rewards only on finish.
- [ ] Saves through `zoko_data_*`; scores on a board created in the console.
- [ ] Other portal's logos, links and sitelock removed.
- [ ] Tested on `localhost` and in **Preview and QA**.

## Next

- Full reference: [GameMaker](https://docs.zokogames.com/engines/gamemaker).
- Before upload: [build validation](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/porting/phaser-html5

# Bring a Phaser or HTML5 game

For a Phaser game, or any game written in plain JavaScript or TypeScript (Three.js, PixiJS, Babylon.js, a bare canvas), that already runs on other web game portals. These games call the portal SDK from JavaScript, so they have the shortest port: change the script tag, then rename the calls or load the compatibility shim. The full references are the [Phaser page](https://docs.zokogames.com/engines/phaser) and [plain HTML5 and libraries](https://docs.zokogames.com/engines/html5-libraries). The overall route is in [bring your game](https://docs.zokogames.com/porting/overview).

## 1. Build settings

| Setting | On ZokoGames |
| --- | --- |
| SDK script tag | `<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>` before your game script, in place of the other portal's tag. Keep the exact URL: the validator looks for it, and a bundled copy is flagged (`sdk_bundled`). |
| Paths | Relative only. With Vite set `base: "./"`; root-absolute paths raise `absolute_path`. See [relative paths](https://docs.zokogames.com/requirements/technical#relative-paths-only). |
| Pre-compression | None. Your page requests plain file names. |
| Archive | The build output zipped with `index.html` at the archive root. |
| Canvas | Sized from the window: `Phaser.Scale.FIT` with `autoCenter: CENTER_BOTH`, or the resize handler in [sizing](https://docs.zokogames.com/engines/html5-libraries#5-sizing). |

## 2. Rename the calls, or shim them

Most web game portal SDKs share the shapes ZokoGames uses: `init()`, `ad.requestAd(type, callbacks)` with started, finished and error callbacks, gameplay start and stop, user, cloud save. Pick one route.

**Rename (recommended).** Point your code at `window.ZokoGames.SDK` and check the differences listed in [migrating](https://docs.zokogames.com/guides/migrating#mapping-table). The usual shape after the rename:

```js
const SDK = window.ZokoGames?.SDK;                 // undefined if the script was blocked
let live = false;

async function startPlatform() {
  if (!SDK) return;
  await SDK.init();                                // never rejects
  live = SDK.environment !== "disabled";           // the game must also run when disabled
}

function showAd(type, pause, resume) {
  if (!live) return Promise.resolve(false);
  return new Promise((done) => {
    SDK.ad.requestAd(type, {
      adStarted: pause,
      adFinished: () => { resume(); done(true); },   // grant a reward only here
      adError: () => { resume(); done(false); },     // unfilled, adCooldown, adblock
    }).catch(() => { resume(); done(false); });
  });
}
```

**Every `SDK.game.*`, `SDK.user.*`, `SDK.ad.*` and `SDK.banner.*` call returns a promise, and any of them can reject** (for example `sdkNotInitialized`, `sdkDisabled`, `rateLimited` or `unexpectedError`; `SDK.data` is the exception: it is synchronous and throws). Code ported from a portal whose calls never failed often fires them and forgets, which leaves an unhandled rejection in the console, or a stuck pause when the call that should resume the game failed. Add `.catch(() => {})` (or `try`/`await`) to every call you do not read the result of, and resume the game in the error path.

**Shim (quick port).** Keep your call sites and add the shim after the SDK, naming the global your game already reads:

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script src="zokogames-compat-v1.js" data-global="YourOldGlobal"></script>
```

Download `zokogames-compat-v1.js` from `https://www.zokogames.com/sdk/zokogames-compat-v1.js` and ship it in your zip next to `index.html`. It forwards every call, translates the common differences (an old error spelling, callback-style calls, renamed loading calls) and runs `init()` for games that never call it. What it translates, and what it does not, is in [migrating](https://docs.zokogames.com/guides/migrating#two-ways-to-port). Plan to rename later: the shim is a bridge.

**Phaser plugin.** For Phaser, the [ZokoGames Phaser plugin](https://docs.zokogames.com/engines/phaser#what-the-plugin-gives-you) does the ad pause for you: `requestAd` sleeps the game loop and mutes sound on start and restores both on finish and on error. If your old code paused only one scene, switch to the plugin or to `game.loop.sleep()`.

| Your game does | With the SDK |
| --- | --- |
| Midgame ad (an interstitial or commercial break) or rewarded ad | `SDK.ad.requestAd("midgame", callbacks)` or `"rewarded"`, as in `showAd` above. Any other type string rejects with `invalidArgument`, and ads before the game starts (prerolls) are not shown. |
| Gameplay start and stop | `SDK.game.gameplayStart()` and `gameplayStop()`. Call `gameplayStart()` before the first midgame request: until then the portal refuses it with `adCooldown`. |
| Loading finished | `SDK.game.loadingStart()`, `loadingProgress(0..100)`, then `loadingStop()` once the first screen can be played; the Phaser plugin's `trackLoading(this.load)` does it for a loader. Nothing sends these for you in plain HTML5. |
| Player name, sign-in | `SDK.user.getUser()` resolves `null` for a guest (not an error); `SDK.user.showAuthPrompt()` opens the sign-in dialog. |
| Mute | Apply `SDK.game.settings.muteAudio` at start and in `addSettingsChangeListener`. |
| Cloud save | `SDK.data.setItem(key, value)` and `getItem(key)`, strings only. Moving old `localStorage` saves: [data](https://docs.zokogames.com/sdk/data#migrating-from-localstorage). |
| Leaderboard score | `SDK.user.submitScore({ encryptedScore, score })` on a board created in the console. The page can encrypt with Web Crypto, see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission). |
| Purchases | `SDK.store.getCatalogItems()`, `buyItem(itemId)`, `consumeItem(sku, quantity)`. Purchases are test purchases for now ([purchases](https://docs.zokogames.com/sdk/purchases)). |

## 3. Build size and mobile

- Budget: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile), estimated from uncompressed sizes.
- Minify and tree-shake; pack textures into atlases; WebP or KTX2 textures; modest audio bitrates.
- Load later levels after the first scene, not in one big `preload`.
- Cap `devicePixelRatio` on phones and start audio from a pointer or key event. See [mobile](https://docs.zokogames.com/guides/mobile).

## 4. Test before you submit

1. **Serve the game from `localhost`.** The SDK starts in local mode: a three-second overlay per ad, fake players, saves in `localStorage`. Add `?sdk_debug=true` to log every call, `?ad_response=unfilled` to force ad errors and `?user_response=logged_out` for guests. A second midgame within three minutes fails with `adCooldown`. See [local mode](https://docs.zokogames.com/getting-started/local-testing).
2. **Open the [Preview tool](https://www.zokogames.com/preview)** with your local address and watch the checklist tick.
3. **Upload the zip** and open the game's **Preview and QA** tab in the developer console to run it in the portal frame with ads on ([build preview](https://docs.zokogames.com/getting-started/local-testing#the-build-preview-in-the-console)).

## Checklist

- [ ] ZokoGames SDK script tag; the other portal's tag and any bundled SDK copy removed.
- [ ] Relative paths; `index.html` at the archive root.
- [ ] Calls renamed, or the shim loaded after the SDK with `data-global`.
- [ ] `init()` first; the game plays when the SDK is missing or `disabled`.
- [ ] The whole loop and audio pause on ad start and resume on finish and error; rewards only on finish.
- [ ] Saves through `SDK.data`; scores on a board created in the console.
- [ ] Other portal's logos, links and sitelock removed.
- [ ] Tested on `localhost`, in the Preview tool and in **Preview and QA**.

## Next

- Full references: [Phaser](https://docs.zokogames.com/engines/phaser), [plain HTML5 and libraries](https://docs.zokogames.com/engines/html5-libraries).
- Before upload: [build validation](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/porting/defold

# Bring a Defold game

For a Defold game that already ships as an HTML5 bundle on other web game portals. You add the `zokogames` library, swap the other portal's extension and calls for `zoko.*`, and check the bundle settings. The full reference is the [Defold engine page](https://docs.zokogames.com/engines/defold). The overall route is in [bring your game](https://docs.zokogames.com/porting/overview).

## 1. Bundle settings

Add the library as in [Defold: install](https://docs.zokogames.com/engines/defold#install) and remove the other portal's extension from `game.project` dependencies. Then:

| Setting | On ZokoGames |
| --- | --- |
| SDK script tag | The module injects the SDK on the first `init`, but the upload validator reads your files and can report `no_sdk`. Use a custom HTML5 template (`htmlfile` in the `[html5]` section) with `<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>` in its `<head>`, and remove the other portal's tag. |
| Architecture | `wasm-web`; add `js-web` only for very old browsers. No threaded variant: the portal frame is not cross-origin isolated. |
| Variant | Release, not Debug. |
| File names | As bundled. Do not rename files to `.br` or `.gz`. |
| Scale mode | One that keeps your aspect ratio, so the game fits a frame that changes with fullscreen and rotation. |

Details: [HTML5 export settings that matter](https://docs.zokogames.com/engines/defold#html5-export-settings-that-matter).

## 2. Replace the platform calls

`local zoko = require "zokogames.zokogames"`, call `zoko.init(callback)` once, then map each call. Calls that wait for the browser take `callback(err, result)` last; `err` is `nil` on success ([how calls work](https://docs.zokogames.com/engines/defold#how-calls-work)).

| Your game does | With `zoko` |
| --- | --- |
| Start the SDK | `zoko.init(callback)`; `zoko.is_available()` is false when the SDK is `disabled`, and the game must still run. |
| Loading finished | `zoko.game.loading_stop()` once the first collection can be played (optionally `loading_start()` and `loading_progress(p)` before it). The module does not send these on its own. |
| Gameplay start and stop | `zoko.game.gameplay_start()` and `gameplay_stop()`. |
| Midgame (interstitial) or rewarded ad | `zoko.ad.request_ad("midgame", { started = f, finished = f, error = f })` (or `"rewarded"`). Pause in `started`; resume in `finished` and in `error`. A request that cannot start calls only `error`. Grant a reward only in `finished`. |
| Mute | `zoko.game.add_settings_change_listener(fn)`. |
| Cloud save | `zoko.data.set_item(key, value)`, `zoko.data.get_item(key)` (`nil` when missing). `sys.save` files stay on one device; move progress you want kept here. |
| Leaderboard score | `zoko.user.submit_score(encrypted_score, score, callback)` for a signed-in player, on a board created in the console. No wrapper builds the encrypted payload; see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission). |
| Purchases | `zoko.store.get_catalog_items`, `buy_item(sku, cb)`, `consume_item(sku, qty, cb)`. Purchases are test purchases for now ([purchases](https://docs.zokogames.com/sdk/purchases)). |
| Sign-in prompt, player | `zoko.user.show_auth_prompt(callback)`, `zoko.user.get_user(callback)`. |

A complete script is in [a working script](https://docs.zokogames.com/engines/defold#a-working-script).

The [compatibility shim](https://docs.zokogames.com/guides/migrating#two-ways-to-port) is for JavaScript call sites only; Lua calls move to `zoko.*`.

## 3. Build size and mobile

- Budget: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile), estimated from uncompressed sizes.
- Texture profiles (Basis or ASTC for web), unused engine components removed in `game.project`.
- Load later levels with collection proxies (excluded resources) or live update.
- Keep the HTML5 heap modest for phones and start music from a "tap to play" screen. See [mobile](https://docs.zokogames.com/guides/mobile).

## 4. Test before you submit

1. **In the editor and desktop bundles** the Lua simulator answers (`zoko.is_simulated`). Edit `zoko.sim` before `init` to force ad errors, a logged-out player or a disabled SDK.
2. **The HTML5 bundle on `localhost`** runs the SDK's local mode, which also enforces the three-minute midgame cooldown the simulator skips. See [Defold: test locally](https://docs.zokogames.com/engines/defold#test-locally).
3. **Upload the zip** (bundle folder contents, `index.html` at the archive root) and open the game's **Preview and QA** tab in the developer console to run it in the portal frame with ads on ([build preview](https://docs.zokogames.com/getting-started/local-testing#the-build-preview-in-the-console)).

## Checklist

- [ ] Library added; the other portal's extension and calls removed.
- [ ] SDK script tag in a custom HTML5 template.
- [ ] `wasm-web`, no threads, Release.
- [ ] `zoko.init` first; the game plays when `is_available()` is false.
- [ ] Gameplay start and stop at the right moments.
- [ ] Ads resume in `finished` and `error`; rewards only on finish.
- [ ] Saves through `zoko.data`; scores on a board created in the console.
- [ ] Other portal's logos, links and sitelock removed.
- [ ] Tested on `localhost` and in **Preview and QA**.

## Next

- Full reference: [Defold](https://docs.zokogames.com/engines/defold).
- Before upload: [build validation](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/porting/cocos

# Bring a Cocos game

For a Cocos Creator 3 game that already ships as a Web Mobile or Web Desktop build on other web game portals. Names in the ZokoGames module match the JavaScript SDK one to one, so the port is mostly swapping one object for another. The full reference is the [Cocos engine page](https://docs.zokogames.com/engines/cocos). The overall route is in [bring your game](https://docs.zokogames.com/porting/overview).

## 1. Build settings

Copy `assets/zokogames/` into your project's `assets/` folder ([Cocos: install](https://docs.zokogames.com/engines/cocos#install)). Then:

| Setting | On ZokoGames |
| --- | --- |
| Build templates | Paste `build-templates/zokogames-sdk-snippet.html` (the SDK script tag) into the `<head>` of `build-templates/web-desktop/index.ejs` and `build-templates/web-mobile/index.ejs`, and remove the other portal's tag. |
| Build target | **Web Mobile** or **Web Desktop**. |
| **Remote server address** | Empty: everything ships in the zip, with relative paths. |
| Pre-compression | None. Cocos requests plain file names. |
| Resolution policy | A design resolution with Fixed Height or Show All, so the game fits a frame that changes with fullscreen and rotation. |

Details: [web export settings that matter](https://docs.zokogames.com/engines/cocos#web-export-settings-that-matter).

## 2. Replace the platform calls

Remove the other portal's module and calls first. `import ZokoSDK from "./zokogames/ZokoSDK";`, `await ZokoSDK.init()` once, then map each call. Calls return promises; the `data` calls are synchronous ([mapping](https://docs.zokogames.com/engines/cocos#mapping)).

| Your game does | With `ZokoSDK` |
| --- | --- |
| Start the SDK | `await ZokoSDK.init()`; `ZokoSDK.isAvailable` is false when the SDK is `disabled`, and the game must still run. |
| Loading finished | `ZokoSDK.game.loadingStop()` once the first scene runs (optionally `loadingStart()` and `loadingProgress(p)` before it). The module does not send these on its own. |
| Gameplay start and stop | `ZokoSDK.game.gameplayStart()` and `gameplayStop()`. |
| Midgame (interstitial) or rewarded ad | `await ZokoSDK.ad.requestAd(type, { adStarted, adFinished, adError })`. Pause in `adStarted`; resume in a `finally`, because the call rejects without calling `adError` when it cannot start. Grant a reward only after `adFinished`. |
| Cloud save | `ZokoSDK.data.setItem(key, value)`, `getItem(key)`. On the web, `sys.localStorage` is the browser's `localStorage` and can be mirrored with `mirrorLocalStorage`. |
| Leaderboard score | `ZokoSDK.user.submitScore(...)` for a signed-in player, on a board created in the console. No wrapper builds the encrypted payload; a browser build can use Web Crypto, see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission). |
| Purchases | `ZokoSDK.store.getCatalogItems`, `buyItem`, `consumeItem`. Purchases are test purchases for now ([purchases](https://docs.zokogames.com/sdk/purchases)). |
| Sign-in prompt, player | `ZokoSDK.user.showAuthPrompt()`, `ZokoSDK.user.getUser()`. |

A complete component is in [a working component](https://docs.zokogames.com/engines/cocos#a-working-component).

The [compatibility shim](https://docs.zokogames.com/guides/migrating#two-ways-to-port) can stand in for another portal's JavaScript global during a quick port, but the `ZokoSDK` module is the cleaner route for Cocos: it adds the simulator, typed errors and banner placement on nodes.

## 3. Build size and mobile

- Budget: 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile), estimated from uncompressed sizes.
- Auto Atlas, ETC2 or ASTC textures for mobile, OGG or MP3 audio at modest bitrates.
- Asset Bundles loaded after the first scene; unused engine modules off in **Project Settings > Feature Cropping**.
- Release unused bundles on phones and start music from a "tap to play" screen. See [mobile](https://docs.zokogames.com/guides/mobile).

## 4. Test before you submit

1. **In the Creator editor** the simulator answers (`ZokoSDK.isSimulated`). Call `ZokoSDK.configureSimulator(options)` before `init()` to force ad errors, a logged-out player or a disabled SDK.
2. **A web preview or build on `localhost`** runs the real SDK's local mode, which also enforces the three-minute midgame cooldown. If the SDK script is blocked, `init()` falls back to the simulator; check `ZokoSDK.isSimulated` in your test builds. See [Cocos: test locally](https://docs.zokogames.com/engines/cocos#test-locally).
3. **Upload the zip** (build folder contents, `index.html` at the archive root) and open the game's **Preview and QA** tab in the developer console to run it in the portal frame with ads on ([build preview](https://docs.zokogames.com/getting-started/local-testing#the-build-preview-in-the-console)).

## Checklist

- [ ] Module copied; SDK snippet in both build templates; the other portal's module and tag removed.
- [ ] Remote server address empty; plain file names.
- [ ] `await ZokoSDK.init()` first; the game plays when `isAvailable` is false.
- [ ] Gameplay start and stop at the right moments.
- [ ] Ads resume in a `finally`; rewards only after `adFinished`.
- [ ] Saves through `ZokoSDK.data`; scores on a board created in the console.
- [ ] Other portal's logos, links and sitelock removed.
- [ ] Tested on `localhost` and in **Preview and QA**.

## Next

- Full reference: [Cocos](https://docs.zokogames.com/engines/cocos).
- Before upload: [build validation](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

---

Source: https://docs.zokogames.com/guides/troubleshooting

# Troubleshooting

This page is for when something does not work. Find the symptom or the error code below; each entry gives the cause and the fix. SDK errors are plain `{ code, message }` objects, console and API errors are `{ error, message }` JSON bodies; both kinds of code are listed here. Always compare the `code` (or `error`); the `message` text is for people, is written in English and can change in any SDK release (it did in 1.6.3), so never match on it.

Start here. First step for almost everything: add `?sdk_debug=true` to the page URL and watch the browser console. Every SDK call, result and event is logged. Then repeat the run in the [Preview tool](https://www.zokogames.com/preview), whose event log shows what reaches the portal.

## Find your error by its shape

| What you have | Where it comes from | Where to look |
| --- | --- | --- |
| A code such as `adsDisabled` or `sdkNotInitialized` in `e.code` | An SDK call | [SDK and environment](#sdk-and-environment), [ad error codes](#ad-error-codes), [banners](#banners), [cloud save](#cloud-save), [users, tokens and leaderboards](#users-tokens-and-leaderboards), [store](#store), [multiplayer rooms](#multiplayer-rooms) |
| A code such as `no_index` or `missing_reference` in the build report | The upload validator | [Build validation reference](https://docs.zokogames.com/requirements/build-validation), [upload and review](#upload-and-review) |
| A JSON body such as `{ "error": "locked_in_review" }` | A request in the developer console | [Upload and review](#upload-and-review) |
| A delivery status such as `request_failed` or `http_500` | A webhook delivery | [Webhooks](#webhooks) |
| A numbered reason such as "Controls unclear" | A reviewer's decision | [Quality guidelines](https://docs.zokogames.com/requirements/quality) |
| No code at all | | [The game does not load](#the-game-does-not-load-blank-frame), [local mode](#local-mode), [Preview tool](#preview-tool) |

## The game does not load (blank frame)

Open the browser developer tools on the game's own address (the `g-<name>.zokogames.com/<build>/` frame, or your local address) and read the Console and Network tabs.

| What you see | Cause | Fix |
| --- | --- | --- |
| Many 404s for `/assets/...`, `/main.js`, `/favicon.ico` | Root-absolute paths. The portal serves each build from its own folder, `https://g-<name>.zokogames.com/<build id>/`, so `/x.js` points at the origin root, not your build. The validator warns about this in `index.html`. | Use relative paths (`./assets/x.js`). Vite: `base: "./"`. Webpack: `publicPath: ""`. Engines: use their relative export option. |
| 404 on a file whose name you can see in the zip | File names are case-sensitive on the game origin. | Match case exactly (`Hero.PNG` is not `hero.png`). |
| Console: "Mixed Content: ... requested an insecure resource" | The page is `https`, and something asks for `http://`. The browser blocks it. | Change the URL to `https://`, or ship the file inside the zip. Never call plain `http` APIs. |
| Console: "blocked by CORS policy" for your own files | Rare: you fetch from another origin (a CDN or an old copy of the game). Files the portal serves carry `Access-Control-Allow-Origin: *` and allow `GET`, `HEAD` and `Range`. | Fetch files from the zip with relative URLs. A third-party API must send its own CORS headers; external requests also need reviewer approval, see [technical requirements](https://docs.zokogames.com/requirements/technical). |
| Console: "Refused to display ... in a frame" (game hosted on your own server) | Your server sends `X-Frame-Options` or a `frame-ancestors` that excludes zokogames.com. | Allow framing from `https://zokogames.com` and `https://*.zokogames.com` (the game page is on `www.zokogames.com`), or upload the zip so the portal hosts it. |
| Frame loads, canvas stays black, an engine error mentions `wasm`, `.data` or `Content-Encoding` | A compressed engine file was renamed or lost its `.br` / `.gz` suffix. Files ending in `.br` or `.gz` are served with the matching `Content-Encoding`, and the type comes from the name without that suffix. | Keep the exact file names the engine export wrote. Do not double-compress. See your [engine page](https://docs.zokogames.com/engines/overview). |
| Console: `SharedArrayBuffer is not defined`, or a blank canvas with a wasm error | Game pages are served without COOP/COEP headers, so the page is not cross-origin isolated and `SharedArrayBuffer` is unavailable. Threaded WebAssembly builds cannot run. | Export without threads: Unity, disable multithreading and native threads; Godot, Thread Support off (single-threaded export, Godot 4.3 and later). |
| Popup, `window.open` or a download from a script is blocked | The frame is sandboxed. Popups are off unless the game was approved for them; downloads and modals are allowed. | Avoid popups, or request popup approval on the Technical step. See [technical requirements](https://docs.zokogames.com/requirements/technical). |
| Works in a tab, fails inside the frame | The game uses `window.top`, cookies or third-party storage. | Use the [data module](https://docs.zokogames.com/sdk/data) and do not depend on the parent page. |

If the console shows nothing, add `?sdk_debug=true` and check whether `[ZokoGames SDK]` lines appear. No lines at all means your script never ran (check the Network tab for the failing file).

## Audio is silent, fullscreen does nothing

| Symptom | Cause | Fix |
| --- | --- | --- |
| No sound until the player clicks | Browsers allow audio only after a user gesture. | Create or `resume()` the audio context on the first click, tap or key press (the [technical page](https://docs.zokogames.com/requirements/technical) has a snippet). Do not start music at load. |
| No sound at all, even after a click | The player muted the game with the portal's mute button or the device setting "start games muted", so `SDK.game.settings.muteAudio` is `true`. | Read the setting at start and in `addSettingsChangeListener`, and apply it. In local mode test with `?muteAudio=true`. |
| Silent after an ad | You muted in `adStarted` and resumed only in `adFinished`. | Restore sound in `adFinished` and in `adError`. See [ads](https://docs.zokogames.com/sdk/ads). |
| `requestFullscreen()` rejects | It was not called from a click, tap or key handler, or the page asked for fullscreen at load. | Fullscreen needs a user gesture. The frame allows it, but the portal already has a fullscreen button and the [requirements](https://docs.zokogames.com/requirements/gameplay) ask you not to add one. Make your canvas fill the frame and react to `resize`. |
| Canvas is blurry or the wrong size after fullscreen | The game kept the old pixel size. | Resize on the `resize` event and multiply by `devicePixelRatio`. |

## Saves not persisting

| Symptom | Cause | Fix |
| --- | --- | --- |
| Progress gone on the next visit, but it worked locally | You used `localStorage`, IndexedDB or cookies. They live in the game's own origin, are cleared with site data, are blocked in some private windows and are not shared between devices. | Use the [data module](https://docs.zokogames.com/sdk/data). It keeps a copy in the browser for guests and syncs signed-in players to their account. |
| `getItem` returns `null` for something you just wrote | You read it in a different session or after `clear()`. The map is loaded once, at `init()`. | Read after `await SDK.init()`; do not cache `null`. |
| Save works but is lost after sign-in | The account already had a different save, and the player chose **Use my saved progress** when asked which copy to keep. | See [cloud saves](https://docs.zokogames.com/guides/cloud-saves#guests-and-signing-in). |
| `dataModuleDisabled` or the save silently does nothing | The data module is off for the game. | Tick it on the Technical step. |

## Ads never show

| Symptom | Cause | Fix |
| --- | --- | --- |
| You get `adsDisabled` in the live game | Basic launch has ads switched off; so do kids' games. | Expected. Ads start in full launch ([launch stages](https://docs.zokogames.com/getting-started/launch-stages)). |
| In the Preview tool you see a countdown screen, not a real ad | Preview and local mode use placeholder ads. On the live site, full-launch games show the portal's house ads; no ad network is connected yet. | Test the flow (pause, resume, reward), not the creative. |
| Second ad request fails at once | Midgame ads have a minimum gap (three minutes), and a session may have a limit. A request while an ad is on screen fails with `other`. | Request at natural breaks. Treat every `adError` as "continue". |
| `adblock` | Your browser has an ad blocker. The portal probes for one before every non-kids request. | Disable it for the test, or force it deliberately with `?ad_response=adblock` in local mode. |
| `unfilled` straight away while offline | No connection means no ad. | Continue. Use `SDK.game.isOffline` to avoid offering rewarded ads. |
| A midgame request "finishes" instantly with no screen | The player is an ad-free member: the portal runs `adStarted` and `adFinished` without showing anything. Rewarded ads still play when the player asks. | Nothing to fix. Your resume code runs as after a real ad. |
| Nothing at all happens | `requestAd` waits for `adFinished` or `adError`; your code may be waiting on the wrong thing. | Log inside all three callbacks with `?sdk_debug=true`. |

## SDK and environment

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `sdkNotInitialized` (message `SDK.init() has not completed yet: await SDK.init() before any other SDK call`) | A call ran before `init()` resolved. | `await SDK.init()` once at startup before touching any other member. Match the `code`, not the message text: since SDK 1.6.3 the wording is not part of the contract. |
| Console: `[ZokoGames SDK] Called before SDK.init() resolved (sdkNotInitialized): await SDK.init() first.` | SDK 1.6.2 prints this once per page the first time a member is used before `init()` resolved. | Same fix: `await SDK.init()` before any other call, including calls from a button handler that can fire during loading. |
| Console: `[ZokoGames SDK] Disabled: <reason>. To test outside the portal, add ?useLocalSdk=true to the page address. Local mode: https://www.zokogames.com/docs/getting-started/local-testing` | SDK 1.6.2 prints this info line once per page when the environment ends up `"disabled"`; since 1.6.3 it carries the `?useLocalSdk=true` hint for every reason except `the portal turned it off` (there the sentence is left out, because local mode is not a way out). The reason is one of `not framed by the portal and not on a local host`, `framed by <origin>, which is not the portal`, `framed by <origin>, which did not answer the handshake`, `unsupported host protocol` or `the portal turned it off`. | Not framed and not local: serve from `localhost` or add `?useLocalSdk=true`. Framed by your own page: add `?useLocalSdk=true` to the game address or test in the Preview tool. `unsupported host protocol`: the page that framed the game speaks a different protocol version than your SDK copy; load the latest SDK alias instead of a bundled or pinned copy. `the portal turned it off`: the portal answered that the SDK is off for this page, so the game must run without it. |
| `sdkDisabled` (message `The SDK is disabled: <reason>. Local mode: <docs link>`, with the same reasons as the console line above), or `SDK.environment` is `"disabled"` | The page is on a normal host and is not inside the portal frame, or the host did not answer the handshake. | Run on `localhost`, add `?useLocalSdk=true`, or open the game in the Preview tool. Your game must still run when disabled. Branch on `code === "sdkDisabled"`; the old text `disabled on this domain` appears only when no reason is known, so never search for it. |
| `window.ZokoGames` is undefined | The script tag is missing, is after your code, or was blocked. | Load `https://sdk.zokogames.com/zokogames-sdk-v1.js` before your bundle. Check the network tab. |
| Works on localhost, not when uploaded | You rely on local-only behaviour (always-filled ads, fake user). | Re-test in the Preview tool and handle failures. |
| `timeout` | The portal did not answer a call within 10 seconds. | Check the page is really framed by the portal. An ad request waits up to 30 seconds for the ad to start (then `adError` receives `timeout`) and has no limit once it plays; sign-in and account-link prompts and `store.buyItem` never time out. |
| `invalidArgument` | A wrong type or range. The `message` names the argument and, since SDK 1.6.3, what was received (for example `got "interstitial"`, `got 150` or `got object`; long strings are cut and values are never printed in full). | Fix the call. Example: `reportGameCompletedPercentage(150)`. Compare `e.code`, never the message text, which can change between releases. |
| Environment is `"disabled"` inside your own test iframe | The SDK waited 1.5 seconds for the portal, got no answer and the page is not on a local host. | Add `?useLocalSdk=true` to the game's URL, or test in the [Preview tool](https://www.zokogames.com/preview). See [testing](https://docs.zokogames.com/getting-started/local-testing). |
| `init()` seems to do nothing | It never rejects: failure is reported as `SDK.environment === "disabled"`. | Read `SDK.environment` after `await SDK.init()`. |
| Console: `[ZokoGames SDK] Local mode: the portal is simulated in this page and nothing is sent over the network.` | Information, printed once. The SDK chose local mode because the page is on `localhost` or has `?useLocalSdk=true`. The same line says that ads show a 3 s placeholder, saves stay in `localStorage` and submitted scores are only logged (before 1.6.3 it said leaderboards echo them). | Nothing. It is expected on your machine; if you see it on the live site, the game is not being framed by the portal. |
| Console (with `?sdk_debug=true`): `[ZokoGames SDK] host handshake failed`, with `The page that answered the handshake (<origin>) is not ZokoGames` or `Unsupported host protocol version` | The game is framed by a page that is not the portal (for example your own test page on a public host), or no portal answered in time. The SDK falls back to local mode where that is allowed, otherwise to `"disabled"`. | Test locally with `?useLocalSdk=true`, or upload the build and use the **Preview tool**. |
| Console (SDK 1.6.3, warning, once per page): `[ZokoGames SDK] ad.requestAd: <problem>. Pass { adStarted, adFinished, adError } as functions. Docs: https://www.zokogames.com/docs/sdk/ads` | The second argument of `SDK.ad.requestAd` can never run: a bare function instead of an object (`the second argument must be an object, got function, so no callback will run`), a misspelled name such as `onFinished`, or a value that is not a function (`<names> will never be called (unknown name or not a function)`). Only the first 20 keys are checked. `undefined`, `null` and `{}` stay silent. The request itself behaves as before. | Pass `{ adStarted, adFinished, adError }`, each a function. Without a working `adFinished` or `adError` your game never resumes. |
| Console (SDK 1.6.3, warning, once per page): `[ZokoGames SDK] user.getUserToken: options must be an object such as { signingKeyType: "IN_GAME_AUTH" }, got <type>; the default key is used. Docs: https://www.zokogames.com/docs/sdk/user` | A non-object (usually the string `"IN_GAME_AUTH"`) was passed to `SDK.user.getUserToken`. It is ignored, as before, and the default key is used. Only the type is printed, never the value. | Call `getUserToken()` with no argument, or with an object. Every token is signed the same way, so the option is not needed. |
| Console (local mode, SDK 1.6.3, warning, once per page): `[ZokoGames SDK] Local mode: unknown switch value ignored: ?user_response=guest (use user1, user2, logged_out). Docs: https://www.zokogames.com/docs/getting-started/local-testing` | A scenario switch in the page address has a misspelled value. It is ignored, so the default (for `user_response`, a signed-in player) applies. The line names every wrong switch with its accepted values: `user_response` (`user1`, `user2`, `logged_out`), `show_auth_prompt_response` (`user1`, `user2`, `user_cancelled`), `link_account_response` (`yes`, `no`, `logged_out`), `token_response` (`user1`, `user2`, `expired_token`, `logged_out`), `ad_response` (`adsDisabled`, `unfilled`, `adblock`, `other`). | Use one of the listed values, with exactly this spelling and case. |
| Console (local mode, SDK 1.6.3, info, on every call): `[ZokoGames SDK] Local mode: score <n> not sent (nothing is stored; real leaderboards run in the portal)` | `SDK.user.submitScore` was called in local mode. The call is validated and resolves, but the score is only logged: there is no leaderboard locally. | Nothing. To see a score ranked, test in the [Preview tool](https://www.zokogames.com/preview) or on the portal. |
| Console: `[ZokoGames SDK] Local mode: chat report not sent (…)` | Information. In local mode `SDK.game.reportChat` has nowhere to send the report, so the SDK prints it. | Nothing to fix; on the portal the report is sent. |
| Console (with `?sdk_debug=true`): `[ZokoGames SDK] local data save failed` | In local mode the save goes to the browser's `localStorage`, which is full or blocked (for example with site data blocked). | Free space or allow site data for the page; on the portal, saves are stored as usual. |
| Console: `[ZokoGames SDK] game.gameplayStart: the portal did not answer` (also `game.gameplayStop`, `game.loadingStart`, `game.loadingStop`, `game.happytime`, `game.leftRoom`) | The portal did not reply within 10 seconds. These calls resolve instead of rejecting, so only this warning tells you. | Check the page is framed by the portal; reload. If it happens in the portal, tell support. |
| Console: `[ZokoGames SDK] Cloud save sync failed: the save is kept locally and the SDK retries.` | SDK 1.6.2 prints this warning once per page, next to the first `data sync failed` error below. | See the next row. |
| Console: `[ZokoGames SDK] data sync failed` | A background save was refused or lost, for example while offline or past a rate limit. The SDK keeps the change and retries after 2, 4, 8 seconds and so on, up to 60 seconds. | Nothing, if it stops. If it repeats, your save may be over 1 MiB (`dataLimitExceeded` is thrown by `setItem` in that case) or the game writes too often. |
| Console: `[ZokoGames SDK] callback threw`, `listener threw` or `event handler threw` | Your own `adStarted`, `adFinished`, `adError` callback or a settings, auth or room listener threw an exception. The SDK caught it and carried on. | Read the error printed after the message and fix the callback; an exception in `adFinished` can leave the game paused. |
| Console: `[ZokoGames SDK] localStorage mirror:` followed by a code | `mirrorLocalStorage` could not save a key, usually `dataLimitExceeded`. | Save less, or pass `onError` to handle it. |
| Errors are not `Error` objects | SDK errors are plain `{ code, message }` objects (banner errors also carry `containerId`). | Read `e.code`; do not test `e instanceof Error`. |
| Code behaves differently after an SDK release | You load the latest alias, which is cached for about an hour at most. | Pin a release with `https://sdk.zokogames.com/<version>/zokogames-sdk-v1.js` while you investigate. See [versioning](https://docs.zokogames.com/sdk/versioning). |

## Ad error codes

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `adsDisabled` | Basic launch, kids' game, ads not enabled, or the provider is off. | Expected. Continue without an ad. In local mode force it with `?ad_response=adsDisabled`. |
| `adCooldown` | A midgame ad was requested less than three minutes after the previous ad, or the portal's per-session or per-day ad limit was reached. | Request at natural breaks only; do not add your own timers. |
| `adCooldown` in local mode on the first midgame request | Since SDK 1.6.4 local mode refuses a midgame ad until the game has called `gameplayStart()` or 30 seconds of visible page time have passed, like the portal. The message reads "Midgame ads are available after gameplay starts: call game.gameplayStart() first". | Call `gameplayStart()` when the player starts to play, before the first ad break. Rewarded ads are not gated. |
| `adblock` | An ad blocker stopped the request. `SDK.ad.hasAdblock()` reports it. | Continue without an ad. In local mode force it with `?ad_response=adblock`. |
| `other` | Another request is already running, or an unexpected failure (read `message`). | Wait for `adFinished` / `adError` before requesting again. |
| `unfilled` | No ad was available. | Continue the game. Try at the next break. |
| Game stuck paused after an ad | You resumed only in `adFinished`. | Resume in `adError` too. |
| Reward granted for no ad | Reward given in `adStarted` or `adError`. | Grant it only in `adFinished`. |
| Second request does nothing | Another request is already running; its `adError` gets `other`. | Disable the trigger while waiting. |

## Banners

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `missingId` | The `id` is empty or not a string. | Pass the container's element id. |
| `bannersDisabled` | Banners are off for this game or stage. | Normal. Never depend on a banner being visible. |
| `notCreated` | No element with that `id` in the DOM yet. | Create the container first. |
| `notVisible` | The container is `display:none`, zero sized, transparent or outside the viewport. | Show it and give it a size before requesting. |
| `invalidSize` | Not in the static list (728x90, 300x250, 320x50, 468x60, 320x100). | Use a listed size or `requestResponsiveBanner`. |
| `noAvailableSizes` | Container smaller than every responsive size. | Make it at least 120 x 600, 320 x 50 or another listed size. |
| `bannerCooldown` | Same container requested again within 30 seconds. | Refresh less often. |
| `maxRefreshReached` | More than 60 banner refreshes in this session, or three banners are already on screen. | Stop refreshing; keep the banner you have, or clear one before you request another container. |
| `videoAdPlaying` | A video ad is on screen. | Request again after `adFinished`. |
| Request resolves but nothing shows | Banners are off for the game's stage. | Normal. Never depend on a banner being visible. |

## Cloud save

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `dataLimitExceeded` | The whole save is over 1,048,576 bytes as JSON. | Store ids and numbers, not world snapshots. |
| `dataModuleDisabled` | The data module is not enabled for the game. | Tick **Uses the SDK data module** on the Technical step of the submission. |
| Save resets after sign-in | The account already had a different save, and the player kept it when asked. | Load all state at start: the game is reloaded with the account's save. See [cloud saves](https://docs.zokogames.com/guides/cloud-saves#guests-and-signing-in). |
| Guest progress not offered after sign-in; the account's save loads instead | The guest copy on the device is over 1,048,576 bytes (`DATA_LIMIT_BYTES`) as JSON and cannot be uploaded, so the player is not asked and the account's save replaces it. | Keep saves well under the limit (see `dataLimitExceeded` above). |
| Last write lost on close | The tab was killed before the sync. | Writes flush on `pagehide` and when the tab is hidden; avoid very frequent tiny writes and save at checkpoints. |

`setItem`, `getItem`, `removeItem` and `clear` are synchronous: they throw `{ code, message }` instead of returning a rejected promise, so wrap them in `try`/`catch`. More causes are under [saves not persisting](#saves-not-persisting).

## Users, tokens and leaderboards

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `userNotAuthenticated` | A guest called a signed-in feature (token, friends, store, `getPurchaseToken`). | Offer `showAuthPrompt()` on a button, or continue as a guest. |
| `userAlreadySignedIn` | `showAuthPrompt()` while someone is signed in. | Check `getUser()` first. In local mode use `?user_response=logged_out`. |
| `userCancelled` | The player closed the sign-in prompt. | Continue as a guest. |
| `showAuthPromptInProgress`, `showAccountLinkPromptInProgress` | The prompt is already open. | Disable the button while it is open. |
| Server rejects the token | Wrong key set, expired token, or wrong `gameId`. | Verify RS256 against `https://www.zokogames.com/.well-known/jwks.json`, check `exp` and compare `gameId`. |
| Console: `Access to fetch at 'https://api.example.com/...' from origin 'https://g-your-game.zokogames.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present` | Your own game server does not allow the game's origin, or it answers the call with an error before it adds the CORS headers (a 401, 404 or 500 without them looks the same). | Send `Access-Control-Allow-Origin: https://g-<your-game-slug>.zokogames.com` (the exact origin shown on the Technical step) on every answer, including errors. Do not use `*.zokogames.com`. |
| Console: `Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response` | The browser sent an `OPTIONS` preflight before your call (any `Authorization` header or a JSON `Content-Type` triggers one) and your server did not list the header. | Answer `OPTIONS` with status 204, `Access-Control-Allow-Origin`, `Access-Control-Allow-Headers: authorization, content-type` and the methods you use. Do not add `Access-Control-Allow-Credentials`. |
| Console: `Mixed Content: The page ... was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://...'` | The game opens `ws://` or calls `http://` from the `https` game page. | Use `wss://` and `https://` with a valid certificate. A raw IP address cannot have one: use a host name. |
| Console: `WebSocket connection to 'wss://...' failed` and nothing about CORS | A WebSocket upgrade is not subject to CORS. Your server refused the upgrade (it checks `Origin` and does not know the game's origin), the host or port is unreachable, or the certificate does not match the host name. | Allow the game's `Origin` in the upgrade check, open the address in a normal browser tab to see the certificate state, and check the server log for the refused upgrade. |
| Your server answers 401 after the game was open for a while | The token lasts one hour and your long-lived connection or cached copy kept the old one. | Call `getUserToken()` again (the SDK caches it and renews it a minute before expiry) and re-authenticate the connection with the new token before the old one expires. |
| Server rejects a local-mode token | Local tokens are unsigned (`alg: none`). | Expected. Test against the Preview tool or a test-only bypass. |
| `rateLimited` on `listFriends` | Calls less than 250 ms apart. | Wait between pages. |
| `requestInProgress` | Another friends request (or, for the store, another catalog, inventory or consume request) is running. | Wait for it. |
| `unexpectedError` | The portal failed unexpectedly. | Retry later; report it with the `sdk_debug` log if it repeats. |
| Score never appears on the board | Not signed in, outside the board range, inside the cooldown, wrong key or payload older than 2 minutes. The portal drops these silently. | Check each rule in [leaderboards](https://docs.zokogames.com/sdk/leaderboards) and encrypt at submission time. |
| Server API returns 401 | Missing or revoked key. | Send `X-API-Key` with the current key. |

## Store

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `SDK.store.isAvailable` is `false` | This host offers no purchases. | Hide purchase buttons. |
| `catalogFetchFailed`, `inventoryFetchFailed`, `purchaseInitFailed`, `consumeItemFailed` | The portal could not complete that request, or the item is unknown. | Retry later; check the sku in the console. |
| `purchaseInProgress` | A checkout is already open. | Disable the buy button until it settles. |
| `purchaseCancelled` | The player closed checkout. | Do nothing; no charge was made. |
| `itemNotConsumable`, `itemNotInInventory`, `insufficientItemQuantity` | Wrong sku, a durable item, or fewer owned than requested. | Read the inventory first. |
| `invalidArgument` | Bad `limit` (1 to 50), `offset`, `sku` or `quantity` (integer, 1 or more). | Fix the call. |
| `getXsollaUserToken` is flagged deprecated | Old name of `store.getPurchaseToken()`. | Switch to the new name; see [versioning](https://docs.zokogames.com/sdk/versioning#10-to-11). |

## Multiplayer rooms
Details are in [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms).

| Symptom or code | Cause | Fix |
| --- | --- | --- |
| `roomUnavailable` | The player is a guest, kids mode is on, or realtime is off. | Offer `showAuthPrompt()` first; give guests a single-player mode. |
| Rooms never open in a game made for children | Rooms are off for kids games: the frame refuses room calls with `roomUnavailable`, and the realtime server refuses rooms of a kids game with its own `room_closed` error, which your game does not receive. After the kids flag is removed, rooms can stay closed for up to an hour. | Do not offer multiplayer in a kids game; give it a single-player mode. |
| `notInRoom` | `updateRoom` was not called, or the signed-in account has no 13+ birthday on file and so no realtime identity. | Call `updateRoom` before `send` and `setState`. |
| `notHost` | A non-host called `setState`. | Guard with `isHost()`; re-check in `onHostChange`. |
| `payloadTooLarge` | A message or state patch is over 8 KB. | Send less. |
| `stateTooLarge` | The shared state would pass 64 KB. | Remove keys by setting them to `null`. |
| `unknownMember` | `to` is not in the room, or is yourself. | Take `to` from `members()`. |
| `rateLimited` | More than 20 messages per second. Ten rejected messages in ten seconds close the realtime connection. | Throttle; merge updates. |
| `invalidArgument` on `setState` | An empty patch, more than 64 keys, or a key outside `A-Z a-z 0-9 _ . : -` (1 to 40 characters). | Fix the keys. |
| A friend cannot join | The room is full (your maximum lobby size, at most 100, or 8 when none is set), `isJoinable` is false, or the host has blocked them. The refusal is not an SDK error. | Show your own message; raise the lobby size in the submission. |
| Messages never arrive in local mode | The tabs use different room ids or origins. | Use the same `roomId` and the same address in both tabs. |
| Everything works for you, not for the reviewer | The reviewer is a guest or on another account state. | Offer sign-in clearly and handle `roomUnavailable`. |

## Upload and review
Build findings are listed in full on [build validation](https://docs.zokogames.com/requirements/build-validation). The common ones:

| Code or symptom | Cause | Fix |
| --- | --- | --- |
| `no_index` ("index.html not found") | It is not at the zip root. | Zip the contents, not the parent folder (one top-level folder is accepted). |
| `blocked_type` | A `.php`, `.exe`, `.sh`, `.py` or similar file. | Remove it; games are static. |
| `too_large`, `too_many_files`, `too_many_entries` | Over 250 MB unpacked, 1,500 files or 6,500 zip entries. | Combine files; load assets later. |
| `initial_too_large` | The first load is estimated above 50 MB. | Lazy-load levels and audio. See [first frame fast](https://docs.zokogames.com/guides/first-frame). |
| `unsafe_path`, `symlink`, `encrypted`, `zip64` | The zip has a path with `..` or a backslash, a symbolic link, a password or Zip64. | Re-zip real files with a standard tool. |
| `missing_reference`, `case_mismatch`, `absolute_path` | A referenced file is missing, differs by letter case or starts with `/`. | Use relative paths with the exact case. |
| `no_sdk` | The SDK script is not referenced. Ads, saves and scores will not work, and full launch needs it. | Load `https://sdk.zokogames.com/zokogames-sdk-v1.js`. |
| `origin_*`, `external_url` | The code calls other hosts. | Bundle the files; ad hosts are not allowed. |
| Keys scroll the page | Default actions are not cancelled. | See [scroll and keys](https://docs.zokogames.com/requirements/technical#scroll-and-keys). |
| Keyboard dead after an ad | The frame lost focus. | Call `canvas.focus()` in `adFinished`. |

The **Report** on a build prints these messages. Search this page for the sentence you see; `{size}`, `{hosts}` and the like stand for the values the report fills in. An error stops the upload, a warning does not, and a note is information only.

| Message in the report | Code | Kind | Cause | Fix |
| --- | --- | --- | --- | --- |
| `index.html must be at the root of the zip.` | `no_index` | Error | You zipped the parent folder twice, or the export has no `index.html`. | Put `index.html` at the top level, or inside a single top-level folder. |
| `A file path is unsafe and was rejected.` | `unsafe_path` | Error | A name has an absolute path, a drive letter, `..`, a backslash, `?` or `#`. Zips made by some Windows tools use backslashes. | Rename it, or zip with the file manager or `tar -a -c -f game.zip *`. |
| `Symbolic links are not allowed.` | `symlink` | Error | The zip holds a link instead of a file. | Replace the link with a real copy of the file. |
| `Encrypted zip entries are not supported.` | `encrypted` | Error | The zip has a password. | Re-create the zip without a password. |
| `The same path appears twice in the archive.` | `duplicate` | Error | A zip tool added a file twice. | Remove the duplicate entry. |
| `Executable or server-side files are not allowed.` | `blocked_type` | Error | The zip holds `.php`, `.exe`, `.sh`, `.py` or a similar file. | Remove the file; games are static files only. |
| `A .gz file is not gzip data and would fail to load.` | `bad_precompressed` | Error | A file named `.gz` was not compressed with gzip. | Re-export with gzip compression, or upload the files uncompressed. |
| `Two paths differ only by letter case and break on some systems.` | `case_collision` | Warning | `Hero.png` and `hero.png` both exist. | Rename one of them. |
| `A file name starts with _zoko, a reserved prefix, so the file is never served.` | `reserved_name` | Warning | A file such as `_zoko-data.json`. | Rename the file and the code that loads it. |
| `The top-level __zk folder is reserved, so nothing in it is served.` | `reserved_path` | Warning | Files in a `__zk/` folder at the top of the zip. | Move them to another folder and update the paths. |
| `A file or folder whose name starts with a dot is never served.` | `hidden_file` | Warning | A `.git` folder, a `.env` file or a `.vite` folder in the zip. | Delete it, or rename it without the dot if the game loads it. |
| `index.html uses a root-absolute path, which 404s under a build folder.` | `absolute_path` | Warning | A path starts with `/`, as in `/game.js`. | Use relative paths such as `./game.js`. |
| `index.html references a file that is not in the zip.` | `missing_reference` | Warning | A file named in `index.html` was left out of the zip. | Add the file or fix the path. |
| `index.html references a file whose name differs only by letter case.` | `case_mismatch` | Warning | `Game.js` in the page, `game.js` in the zip. The host is case sensitive. | Match the exact letter case of the file name. |
| `index.html does not look like an HTML document.` | `index_not_html` | Warning | The file is empty, a redirect stub or not HTML. | Check that the export produced a real HTML page. |
| `The ZokoGames SDK script is not referenced, so ads, saves and scores will not work.` | `no_sdk` | Warning | There is no script tag for `https://sdk.zokogames.com/zokogames-sdk-v1.js`. | Add the SDK script tag and call `init()`. |
| `A copy of the SDK appears to be bundled in the build.` | `sdk_bundled` | Warning | The SDK file was copied into the zip, so fixes cannot reach players. | Load the SDK from its hosted URL. |
| `A third-party portal SDK was detected.` | `third_party_sdk` | Warning | The build still loads another portal's SDK. | Remove it (the migration guide shows the equivalent calls). |
| `A file name is not stored as UTF-8 and may be garbled.` | `non_utf8_name` | Warning | The zip tool used a legacy code page. | Re-zip with UTF-8 names, or use plain ASCII file names. |
| `One file is {size} MB, above the {limit} MB mobile initial-download target.` | `large_file` | Warning | A single file is larger than the mobile budget. | Split it, compress it, or load it after the game starts. |
| `External font origins are referenced: {hosts}.`, `External CDN origins are referenced: {hosts}.`, `External analytics origins are referenced: {hosts}.`, `External advertising origins are referenced: {hosts}.` or `External unclassified origins are referenced: {hosts}.` | `origin_fonts`, `origin_cdn`, `origin_analytics`, `origin_ads`, `origin_unknown` | Warning | The code loads files from other websites. | Bundle what the game needs into the zip. Your own game server is allowed; ad networks and tracking never are. |
| `Absolute http:// URLs ({count}) are blocked as mixed content, for example {example}.` | `mixed_content` | Warning | An `http` address on an `https` page. | Use `https://` or relative paths. |
| `The build registers a service worker.` | `service_worker` | Warning | The code calls `navigator.serviceWorker.register`. | Remove the registration; offline saving is handled by the portal. |
| `Code reads or writes document.cookie.` | `cookie_access` | Warning | Cookies are not shared inside the frame. | Use the SDK data module. |
| `Code touches the top or parent location.` | `top_navigation` | Warning | A sandboxed frame cannot navigate the portal. | Remove the call. |
| `Files ending in .unityweb are served without Content-Encoding, so the loader unpacks them in JavaScript and the game starts slower.` | `unity_unityweb` | Warning | Unity's Decompression Fallback, or an old Unity export. | Turn Decompression Fallback off and re-export with Brotli or Gzip. |
| `Build files mix .br and .gz.` | `unity_mixed_compression` | Warning | Two compression formats in one `Build` folder. | Re-export so every Build file uses the same compression. |
| `Some Build files are uncompressed while others are compressed.` | `unity_compression_mismatch` | Warning | Part of a Unity build was copied from another export. | Check the `dataUrl`, `frameworkUrl` and `codeUrl` names in `index.html`. |
| `The SDK is pinned to version {version}.` | `sdk_pinned` | Note | The script URL names a version. | Use the latest URL unless you need a fixed version. |
| `No SDK init call was found by a static scan.` | `sdk_no_init` | Note | Minified bundles and engine wrappers hide the call from a text scan. | If the script tag is present and the Preview tool logs an init, ignore the note; otherwise add the call. |
| `The SDK is loaded through the compat shim.` | `sdk_compat_shim` | Note | The legacy global hides the init call from the scan. | Nothing, if the Preview tool shows the init call. |
| `Everything was inside one folder ({folder}); it was used as the root.` | `nested_root` | Note | The zip holds one top-level folder. | Nothing; zip the contents if you prefer. |
| `The engine ({engine}) was guessed from text signatures only.` | `engine_low_confidence` | Note | The export has no clear engine fingerprint. | Nothing. |
| `The static scan stopped early, so some findings may be missing.` | `scan_truncated` | Note | The build hit the scan's size or time budget. | Nothing, but check the build in the Preview tool. |
| `This file is not a readable zip archive.` | `not_zip` | Shown in the report | The message states what the check found. | Create the zip again with your system's zip tool (right-click, Compress on a Mac; Send to, Compressed folder on Windows). Other formats such as .rar or .7z are not accepted, and the zip must have no password. |
| `The zip is damaged or could not be unpacked.` | `corrupt` | Shown in the report | The message states what the check found. | The upload may have been cut short, or the zip tool wrote a broken archive. Create the zip again from your export folder and upload it again. |
| `The zip's file list does not match its contents.` | `central_mismatch` | Shown in the report | The message states what the check found. | Create the zip again with a standard tool; zips edited or merged by hand often break this way. |
| `A file inside the zip is larger than the size the zip declares for it.` | `size_mismatch` | Shown in the report | The message states what the check found. | Create the zip again with a standard tool. The portal never trusts declared sizes, so a mismatch is treated as a damaged archive. |
| `The zip unpacks to more than the total size limit.` | `total_bytes` | Shown in the report | The message states what the check found. | Remove files the game does not load, and compress textures and audio. The limits are in the Limits table. |
| `Zip64 archives are not supported.` | `zip64` | Shown in the report | The message states what the check found. | Zip64 is used for very large archives. Split large data into fewer, smaller files and create a normal zip. |
| `The zip has more entries than the limit allows.` | `too_many_entries` | Shown in the report | The message states what the check found. | Combine many small files into atlases or packs, then create the zip again. |
| `The zip contains no files.` | `empty` | Shown in the report | The message states what the check found. | Zip the contents of your export folder (select the files inside it, not an empty folder). |
| `A file uses a zip compression method that is not supported.` | `compression` | Shown in the report | The message states what the check found. | Create the zip again with the standard Deflate method, or store files without compression. |
| `A file or the whole zip expands far more than normal data does.` | `compression_ratio` | Shown in the report | The message states what the check found. | The portal rejects archives that could exhaust memory when unpacked. Do not zip data that expands this far; store large generated or repeated data in a smaller form. |
| `The zip has more files than the limit allows.` | `too_many_files` | Shown in the report | The message states what the check found. | Combine files, for example sprites into atlases and small data files into one pack. |
| `The unpacked build, or one file in it, is above the size limit.` | `too_large` | Shown in the report | The message states what the check found. | Compress textures and audio, remove files the game never loads, and load optional content after the game starts. |
| `The first download is above the limit, so the game would take too long to start.` | `initial_too_large` | Shown in the report | The message states what the check found. | The first download is index.html, the files it references and the engine files. Load levels and audio after the first frame. |
| `The first download is above the mobile target.` | `mobile_initial_large` | Shown in the report | The message states what the check found. | Reviewers test on a phone. Load levels and audio after the first frame to get under the target. |
| `The zip has files of a type the portal does not recognise; they are served as generic binary downloads.` | `unknown_type` | Shown in the report | The message states what the check found. | Check that your engine does not need a specific Content-Type for them. Most engines load such files themselves and need nothing. |
| `System files such as __MACOSX and .DS_Store were ignored.` | `junk_ignored` | Shown in the report | The message states what the check found. | Nothing to do; they are left out of the build. |
| `There are more problems than this report lists.` | `more` | Shown in the report | The message states what the check found. | Fix the ones shown and upload again; the next check shows the rest. |
| `The safety scan blocked this build (rule {rule}).` | `unsafe_rule` | Shown in the report | The message states what the check found. | Remove the file or code named below and upload again. The rules are explained in the safety scan section of the docs. |

The upload zone prints these messages itself, before or instead of a report.

| Message | Cause | Fix |
| --- | --- | --- |
| `Only a .zip file can be uploaded. Zip the contents of your export folder first; a folder, .rar, .7z or .tar file is not accepted.` | The file you chose does not end in `.zip`. | Zip the folder contents; other archive formats are not read. |
| `The file is larger than the {max} MB build limit.` | The zip is bigger than the unpacked limit. | Shrink the assets below the build limit (250 MB unpacked). |
| `The zip could not be used. Check that it is a valid zip of your game with an index.html, then choose it again.` | The server could not read the archive (`upload_invalid`). | Re-create the zip with a standard tool and check it with `unzip -l`. |
| `The zip is larger than the size limit. Shrink it and try again.` | The request was refused as too large (`payload_too_large`). | Shrink the zip. |
| `Your studio has reached its build storage limit. Delete old builds, then try again.` | Old versions fill the studio's storage (`quota_exceeded`). | Delete versions you no longer need in the version list. |
| `Too many uploads were started and not finished. Unfinished uploads expire after 24 hours, and you can start a new one as soon as some have expired. Uploads that finish do not count.` | At most 20 uploads can be open at once (`too_many_open_uploads`), and a daily bound on unfinished ones gives the same message (`daily_upload_limit`). A single-request upload that was never sent stops counting after 20 minutes; a multipart upload (a zip above 50 MB) counts for 24 hours. | Choose the same file again to resume an interrupted upload, or wait for old ones to expire. |
| `Too many uploads in the last hour. Try again in {minutes} minutes.` (`rate_limited`) | More than 20 upload starts or 20 confirmations in an hour. The message names the wait. | Wait that long, then retry. |
| `The upload failed. Retry to try again.` | The upload stopped for a reason the console could not name. | Press **Retry upload**. The line under it says whether parts are kept: `Nothing was published and no version was created. {done} of {total} parts are stored on the server, so retry sends only the rest.` or, for a small file, `Retry sends the file again from the start.` |
| `The connection dropped during the upload. Once you are back online, press Retry.` | Your network went away, or the connection timed out. | Press **Retry upload** once you are online; stored parts are not sent again. |
| `Something went wrong on our side during the upload. Press Retry in a moment; if it keeps failing, write to Support.` | The server answered with an error (HTTP 5xx). | Retry in a moment; if it repeats, contact support. |
| `Upload paused. Nothing was published yet; {done} of {total} parts are stored on the server. Continue to send the rest.` (or `Upload cancelled. Nothing was published and no version was created. Upload again to send the file from the start.`) | You pressed **Pause upload**. | Press **Continue upload**, or choose the same file again to resume. |
| `An upload of {name} was interrupted ({done} of {total} parts sent). Choose the same file to resume it.` | You left or reloaded the page during a multipart upload. | Choose the same file again. |
| `An upload is still running. If you leave this page it stops. Leave anyway?` | The browser asks before you close the tab mid-upload. | Stay until "Step 2 of 2: checking and publishing the build" shows, or until the version list has the build. |
| `Your studio is suspended, so builds cannot be uploaded. Your file was not sent. Open Support and send a request to appeal.` (`developer_suspended`) | The studio is suspended. | Contact support to appeal. |
| `The upload request was not valid. Choose the zip again.` (`invalid_body`) | The request was malformed, for example a zip below 22 bytes. | Choose the zip again; an empty or truncated file cannot be uploaded. |
| `The file had not reached storage when we checked. Retry to finish.` | You confirmed before the last part arrived. | Retry the upload. |
| `This upload is no longer valid, so it cannot be resumed. Choose the zip again to start a new upload.` | An interrupted upload expired. | Choose the zip again. |
| `Storage is not available right now. Try again in a moment.` | Storage is unreachable (`storage_unavailable`). | Retry in a few minutes. |
| `The server is still publishing this build. Large builds can take a minute or two, sometimes longer.` (also `The connection to the server dropped, so this page is watching the build on the server. It is not lost.`) | A large build is still being checked. | Wait; the build appears in the version list with its report, and you need not upload again. |
| `Version {version} has safety findings, so it was sent to a moderator. The current version stays live until it is approved.` | The safety scan marked the build as needs review, so activating it waits for a person. | Nothing is lost: wait for the decision. Add release notes saying what the build does if the scan could not tell. |
| `The game is in review, so builds cannot change until the reviewer decides.` | The game is submitted or in QA (`locked_in_review`). | Wait for the decision, or withdraw the submission. |
| `Only builds that passed validation can be activated.` | You activated an invalid build (`build_invalid`). | Fix the errors in its report and upload again. |

The console answers with `{ "error": "<code>", "message": "..." }`. Codes you can meet while uploading and submitting:

| Code (HTTP status) | Cause | Fix |
| --- | --- | --- |
| `locked_in_review` (409) | The game is Submitted, In review or in Full QA; builds, covers and the listing are frozen. | Wait for the decision, or withdraw a submitted game. |
| `upload_not_found` (404), `upload_closed` (409), `already_processed` (409) | The upload id is wrong, already finished or already turned into a build. | Start the upload again. |
| `not_uploaded` (409) | You confirmed before the file reached storage. | Finish the upload, then confirm. |
| `upload_invalid` (409 or 422) | The stored size differs from the size you declared, or the build failed validation. | Read the message and the build report; upload again. |
| `invalid_part_number`, `invalid_part_size`, `parts_required`, `not_multipart` (400) | A multipart upload was driven out of order or with wrong part sizes. | Use the console uploader, or follow the sizes in the start response exactly. |
| `rate_limited` (429) | More than 20 upload starts in an hour, or another per-route limit. | Wait for the time in `Retry-After`. |
| `storage_unavailable` (503) | Storage is not reachable. | Retry in a few minutes. |
| `build_invalid` (409) | You activated a build that did not pass validation. | Fix the errors and upload again. |
| `already_active` (409), `build_active` (409), `build_in_review` (409) | The build is already live, is live and cannot be deleted, or is part of a submission. | Activate another build first; for a build waiting for review, withdraw the update or wait for the decision. |
| `review_started` (409), `no_pending_update` (404) | You tried to withdraw a build update that a reviewer has already started, or that is not waiting for review. | Wait for the decision; the current build stays live meanwhile. |
| `update_pending` (409) | An update to a full-launch game is already waiting for review. | Wait for the decision. |
| `not_ready` (422) | A required listing item is missing. The body lists `missing` and `missingCovers`. | See the [launch checklist](https://docs.zokogames.com/guides/launch-checklist#2-fill-in-the-listing). |
| `kids_rating` (400) | A made-for-children game has a rating above 7+. | Choose all ages or 7+. |
| `cover_invalid`, `video_invalid` (422) | A cover or video misses the size, format or weight rule. | See [covers](https://docs.zokogames.com/requirements/covers). |
| `nothing_to_submit` (409), `artwork_review_pending` (409) | No staged artwork changes, or artwork is already in review. | Stage a change, or wait. |
| `not_live` (409) | You tried to unpublish a game that is not live. | Only live games can be unpublished; a game in full QA needs [support](https://docs.zokogames.com/business/support). |
| `stale_status` (409) | The game changed state while you looked at it. | Reload and try again. |

Every console route can also answer `invalid_body` (400, the message names the field), `unauthenticated` (401), `forbidden` (403), `forbidden_origin` (403, the request did not come from the console page), `not_found` (404), `payload_too_large` (413), `rate_limited` (429), `internal_error` (500, with a short `digest` to quote to support) and `unavailable` (503).

Other sentences the console shows when it refuses something, with the code behind each (the code is the `error` of the API response; the console shows the sentence):

| Code | Why it happens | Fix |
| --- | --- | --- |
| `conflict` | A teammate saved the game after you opened it. | Reload to see their changes, then redo yours. |
| `slug_locked` | The game address (slug) is fixed once a build is uploaded or the game is submitted, because players and links use it. | Keep the address, or write to [support](https://docs.zokogames.com/business/support) with the reason. |
| `hosting_needs_review` | The address of a game in Full Launch cannot change in the console. | Write to [support](https://docs.zokogames.com/business/support) to have the change reviewed. |
| `draft_limit` | The studio already holds the maximum number of unpublished games. | Submit or delete a draft, then create the new game. |
| `kids_blocked`, `kids_no_iap`, `kids_no_leaderboard`, `kids_rating`, `kids_commitment_required` | The game is made for children and breaks a rule of [kids mode](https://docs.zokogames.com/guides/kids-mode), or the commitment was not confirmed. | Turn off what the message names, or switch Made for children off, then save. |
| `step_up_required`, `second_factor_required` | The action is sensitive (deleting a studio, handing it over, removing payout details) and needs a passkey or code check, or a second sign-in step is not set up. | Finish the check, or set up a passkey or authenticator app in your account security settings, then repeat. |
| `last_owner`, `use_transfer` | A studio always needs an owner, and ownership is handed over, not set as a role. | Use **Make owner** next to a member on the Team page, then leave. See [team and roles](https://docs.zokogames.com/guides/team-and-roles). |
| `studio_not_empty` | A studio with games or money history cannot be deleted in the console. | Request the deletion from [support](https://docs.zokogames.com/business/support). |
| `too_many_tokens`, `webhook_limit` | The studio holds the maximum number of active API tokens or webhooks. | Revoke or delete one you no longer use. |
| `game_not_live` | Artwork experiments run only on games in Full Launch. | Finish the [launch stages](https://docs.zokogames.com/getting-started/launch-stages), then create the experiment. |

| Review symptom | Cause | Fix |
| --- | --- | --- |
| Changes requested | A reviewer failed a line of the QA list. | Read the numbered reasons and the note, fix each, submit again. See the [launch checklist](https://docs.zokogames.com/guides/launch-checklist#6-what-the-reviewer-checks). |
| Rejected | A final reason, or the game was rejected and not yet reopened. | Read the reasons; reopen as a draft if the reason is fixable. |
| Kids game sent back with **Audience flag** | It breaks a made-for-children rule, or looks like a kids game without the flag. | See [kids mode](https://docs.zokogames.com/guides/kids-mode). |

## Webhooks
Details are in [webhooks](https://docs.zokogames.com/guides/webhooks).

| Symptom | Cause | Fix |
| --- | --- | --- |
| The endpoint is refused when you add it | It is not `https` on port 443, has a username or password, is `localhost` or a single-label name, or resolves to a private address. | Use a public HTTPS address; tunnel a local server. |
| Delivery status `request_failed` | No answer: the name did not resolve, the connection failed or it timed out after 5 seconds. | Answer within 5 seconds and do the work after you respond. |
| Delivery status `http_<status>` | Your server answered something other than `2xx`. Redirects are not followed. | Answer `2xx` on the exact registered address. |
| Your signature check fails | You parsed the JSON first, used the wrong secret, or signed the wrong text. | Hash `"<t>.<raw body>"` with the whole `whsec_...` string; compare `v1` in constant time. |
| The same event arrives twice | Delivery is at least once. | Store `X-Zoko-Event-Id` and ignore repeats. |
| Events arrive out of order | Retries can arrive after newer events. | Order by `createdAt`. |
| The endpoint shows as switched off | Five deliveries in a row went dead. | Fix the server, then **Re-enable**. |
| **Redeliver** is refused (`webhook_disabled`, `not_redeliverable`) | The endpoint is off, or the delivery is not retrying or dead. | Re-enable first. |
| A lost signing secret | It is shown once. | **Rotate secret**; the old one stops at once. |


## Local mode
See [local testing](https://docs.zokogames.com/getting-started/local-testing) for every query parameter.

| Symptom | Cause | Fix |
| --- | --- | --- |
| `SDK.environment` is `"disabled"` on your own server | The host is not local and there is no `?useLocalSdk=true`. | Use `localhost`, or add the parameter. |
| Ads always fill, the user is always `user1` | That is the mock. | Force a failure with `?ad_response=unfilled`, `adblock` or `adsDisabled`, a guest with `?user_response=logged_out`. |
| `inviteParams` is never `null` | Every query parameter counts as an invite parameter. | Pass explicit parameters when you test a join. |
| `dataModuleDisabled` never appears | The data module is always on locally. | Test it in the Preview tool. |
| Tokens fail on your server | Local tokens are unsigned. | Test the server path against the Preview tool. |
| Kids behaviour cannot be switched on | Before SDK 1.5.0 the mock has no kids switch; from 1.5.0 `?kidsMode=true` sets only `kidsMode` and `disableChat`. | Use `?kidsMode=true` (`?disableChat=true` on older SDKs), and the build preview's **Kids mode** for the other rules. See [kids mode](https://docs.zokogames.com/guides/kids-mode#test-it). |

## Preview tool

| Symptom | Fix |
| --- | --- |
| Game URL refused | Use an `http` or `https` address with no username or password, not a page on this site. |
| Plain `http` game blocked on the https portal | Serve over `https` or run it on `localhost`. |
| **The frame is slow to load**: "The build has not finished loading after 10 seconds. Reduce the initial download, and check that every file path is relative (no leading slash or http address)." | Shrink the first download (the first-frame guide), use relative paths, and open the browser console (F12) for a failed or blocked file. |
| **The frame loaded but the SDK never started**: "No SDK call arrived within 10 seconds." It then lists what to look for in the browser console: a refused frame, mixed content, a Content-Security-Policy error or 404s. | Check the script tag and that `init()` runs; open the game with `?sdk_debug=true`. If the console is clean, the build never loads the SDK script. |
| Check **SDK initialised** fails: "The SDK never reported in." It turns red once the frame has loaded and no SDK call arrived within 10 seconds. | Same as above: `index.html` must load `https://sdk.zokogames.com/zokogames-sdk-v1.js` and your code must call `SDK.init()`. The check turns green by itself if the call arrives later. |
| Check **gameplayStart called** reads "Waiting for you to play" after 20 seconds without the call. It never turns red, because a game sitting in its menu is fine. | Press Play in the frame. If you already started a round, call `SDK.game.gameplayStart()` when input becomes live; do not wait for a second click. |
| Check **First gameplayStart within 20 seconds** shows **Recommended**: "The first gameplayStart came after 20 seconds. If you waited in the menu, restart and press Play at once to time the game itself; if play began on its own, reduce the initial download." | Restart the game and press Play straight away. If it is still slow, show a playable first screen sooner. |
| Check **loadingStop called when the game is ready** shows **Recommended**: "SDK.game.loadingStop() was not called within 20 seconds." It is never required. | Call `loadingStop()` when the first screen is playable; `gameplayStart()` also removes the loading bar. |
| Check **gameplayStop called on pause, menu and game over** stays **Not run yet** (it is never red; the line reads "Measures: SDK.game.gameplayStop() was called when play stops. Limit: at least once."). | Call `gameplayStop()` at every pause, menu and result screen. |
| Check **gameplayStop before each ad request** fails: "SDK.ad.requestAd() was called while gameplay was running. Call SDK.game.gameplayStop() before requesting an ad." | Stop gameplay first, then request the ad. |
| Check **Play resumed after an ad finished** shows **Recommended**: "An ad finished but SDK.game.gameplayStart() has not followed yet. Call it in adFinished and in adError, when play continues." | Call `gameplayStart()` when play continues after `adFinished` or `adError`. |
| Check **Banner rules respected** fails: "An SDK.banner.requestBanner() call broke a documented banner rule. The calls marked Requirement broken in the event log say which." | Open the calls marked **Requirement broken** in the log; see the advertisement rules. |
| Check **Saves stay under 1 MiB** fails: "A save was 1 MiB or more, so SDK.data.setItem() would throw dataLimitExceeded. Save ids and numbers, not whole worlds." | Save ids and numbers, not whole worlds. |
| Log mark **Requirement broken**: "Ad requested while gameplay was running. Call gameplayStop first.", "Same banner container requested again within 30 seconds.", "Banner requested during gameplay. Banners belong on menu and results screens.", "More than 60 banner refreshes in one session.", "More than two banners on one screen." or "Save is 1 MiB or more (1,048,576 bytes)." | The text names the rule; fix the call it marks. |
| Checklist never ticks | The matching SDK call did not reach the portal. Read the event log, then check the call is made in the portal environment, not only in local mode. |

## Next steps

- [Launch checklist](https://docs.zokogames.com/guides/launch-checklist) for the path to a live game.
- [Multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms) and [kids mode](https://docs.zokogames.com/guides/kids-mode) for those features in depth.
- [Build validation](https://docs.zokogames.com/requirements/build-validation) for every finding code.

No answer to a request from the Support page? Replies go by email to your account address, usually within a working day, so check spam and the address on your account; the page lists each request with its reference and status (open, answered or closed). The form allows five requests an hour, and when you reach that the message says how long to wait. Still stuck? Send the game name, the stage, the steps and the `sdk_debug` console output through [support](https://docs.zokogames.com/business/support).

---

Source: https://docs.zokogames.com/guides/first-frame

# Getting to the first frame fast

This guide shows how to cut your game's load time so players reach gameplay before they give up. Most players who leave never saw your game, and every second before the first playable frame costs plays. Neither load time nor download size is a scored number in [basic launch metrics](https://docs.zokogames.com/guides/basic-launch-metrics), but both drive the scored ones: a slow start lowers conversion (the share of views that play for a minute) and play time. The upload validator also errors on an initial download above 50 MB, see [build validation](https://docs.zokogames.com/requirements/build-validation). Examples assume `const SDK = window.ZokoGames.SDK;` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Set a budget

- Initial download under **20 MB** if you want mobile placement, under **50 MB** at the very most. See [technical requirements](https://docs.zokogames.com/requirements/technical). "Initial download" is the files the game needs before the first frame, not the whole zip.
- Time to gameplay of about **10 seconds** or less on 4G, which is what the [requirements checklist](https://docs.zokogames.com/requirements/checklist) asks for. This is a target a reviewer will test by eye; the portal does not measure it for you.

Measure with the browser's network panel on a cold cache and with throttling set to "Fast 4G".

## Split what you load

1. **Boot** (a few hundred KB): a small page with your logo and a progress bar. Show it as fast as possible.
2. **Level 1**: only what the first minute of play needs.
3. **Everything else**: after the player is playing.

```js
async function start() {
  await SDK.init();                      // never rejects; SDK.environment may be "disabled" (see below)
  await SDK.game.loadingStart();         // the portal shows its thin loading bar over your game
  await loadCoreAssets((done, total) => {
    SDK.game.loadingProgress((done / total) * 100);   // optional; fine to call often (coalesced)
  });                                    // level 1 only
  await SDK.game.loadingStop();          // removes the bar
  showMainMenu();                        // or go straight into play
  loadRestInBackground();                // levels, music, extra skins
}
```

`loadingStart` and `loadingStop` are optional but cheap: the portal draws a progress bar for you (indeterminate until you call `loadingProgress`, which takes 0 to 100). Calling `gameplayStart` also removes the bar. Your own loading screen is fine as well; do not show two bars.

What to expect: on the portal you see a thin bar across the top of the game area while loading. In local mode (your own `localhost` page) the calls resolve and nothing is drawn, so test the bar in the [Preview tool](https://www.zokogames.com/preview). If the SDK is disabled (the page is not on localhost and not inside the portal frame) every call throws `sdkDisabled`; guard with `if (SDK.environment !== "disabled")` for standalone runs.

## Cut bytes

- **Textures.** Use atlases, power-of-two sizes where your engine needs them, and a compressed format (WebP, or Basis/KTX2 where supported). Halve texture sizes that are only shown small.
- **Audio.** Use Opus or AAC, mono for effects, and a lower bitrate for music. Stream music instead of preloading it.
- **Code.** Minify, tree-shake, drop unused engine modules and dependencies, and compress with Brotli or Gzip.
- **Fonts.** Subset to the glyphs you use.
- **Video.** Do not ship video intros.

## Cut waiting

- Do not make the player click through a splash screen, a language picker and a menu before they play. For full launch new players must reach gameplay in at most one click.
- Start downloading the next scene while the player reads the current one.
- Defer your own analytics and other non-essential scripts until after the first `gameplayStart`.
- Avoid synchronous work in the boot path; a long task freezes the progress bar and looks like a hang.

## Show progress honestly

A bar that moves smoothly is better than one that jumps. If a stage cannot report progress, animate to a stage boundary and wait there.

## Check for regressions

Re-measure on each release. A "small" new asset pack can double the initial download without anyone noticing.

## Next steps

- [Optimisation tips](https://docs.zokogames.com/guides/optimisation)
- [Build validation reference](https://docs.zokogames.com/requirements/build-validation)

---

Source: https://docs.zokogames.com/guides/optimisation

# Optimisation tips

This guide gives memory, CPU and rendering advice so a game stays smooth on low-end laptops, phones with throttled CPUs and 4 GB Chromebooks; a game that runs well there runs everywhere. Examples that use `SDK` assume `const SDK = window.ZokoGames.SDK;` and `await SDK.init();` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading). Unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Frame budget

At 60 Hz you have about 16 ms per frame; at 144 Hz about 7 ms. Profile with the browser's Performance panel. Fix the longest tasks first, and always use a time delta, never a fixed step per frame. See [gameplay requirements](https://docs.zokogames.com/requirements/gameplay).

## Rendering

- Batch draw calls: atlases, instancing, a single material per batch.
- Cap `devicePixelRatio`. On phones and low-memory devices render at 1, and scale the canvas with CSS. High-DPI canvases quadruple fill rate and memory.
- Do not redraw static layers every frame; cache them in an offscreen canvas.
- Pause rendering when the page is hidden:

```js
let playing = false;                      // set true when a round starts, false when it ends
document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    loop.stop();
    if (playing) SDK.game.gameplayStop().catch(() => {});
  } else {
    loop.start();
    if (playing) SDK.game.gameplayStart().catch(() => {});
  }
});
```

Both SDK calls are asynchronous and throw `sdkDisabled` when the SDK is off (for example a standalone run), hence the `.catch`. Pausing on hidden also keeps your measured playtime honest, because the portal counts the time between `gameplayStart` and `gameplayStop` (see the [metrics reference](https://docs.zokogames.com/guides/analytics-metrics)).

## Memory

- Free what you do not need: unload level textures, close audio buffers, null large arrays.
- Avoid allocating in hot loops. Reuse objects and typed arrays so the garbage collector does not stutter.
- Keep decoded image memory in mind: a 2048x2048 texture is 16 MB uncompressed no matter how small the file is.
- Unity and similar engines: reduce the heap size setting to what the game needs; browsers can refuse large allocations.

## Audio

- Limit simultaneous voices.
- Reuse audio sources instead of creating one per sound effect.
- Unlock the `AudioContext` on first gesture (see [technical requirements](https://docs.zokogames.com/requirements/technical#audio-on-ios)).

## Input latency

- Read input in the same frame you draw.
- Avoid heavy work in event handlers.

## Test on slow hardware

Use the browser's CPU throttling (4x or 6x slowdown) and a throttled network. If you cannot find a low-end device, throttling is a good approximation. Test in Chrome, Safari and Firefox; fix any browser-specific bugs.

## Ads and banners

Ad requests and banner placement do not affect frame time, but pausing the game cleanly does. Pause logic, timers and physics on `adStarted` and verify nothing keeps running underneath the ad.

## Next steps

- [Getting to the first frame fast](https://docs.zokogames.com/guides/first-frame)
- [Mobile, touch and orientation](https://docs.zokogames.com/guides/mobile)

---

Source: https://docs.zokogames.com/guides/input-controls

# Mouse, keyboard and touch control pitfalls

This guide lists the mouse, keyboard, touch and gamepad bugs that most often break web games inside the portal's frame, and how to avoid each one. Your game runs in an iframe on a page that also has scrollbars, buttons and an ad overlay, so input behaves differently from a standalone page. Examples that use `SDK` assume `const SDK = window.ZokoGames.SDK;` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading).

## Page scrolling

Arrow keys, space and the mouse wheel scroll the page that hosts your game unless you cancel them. Prevent the default for those events (outside text fields). See the snippet in [technical requirements](https://docs.zokogames.com/requirements/technical#scroll-and-keys).

## Focus

Keys only reach your game if the game's frame has focus. After an ad, a dialog or a click on the portal's UI, focus may have moved. Give the canvas focus at start and again whenever an ad ends (the portal's ad overlay sits on top of your game and can take focus):

```js
const SDK = window.ZokoGames.SDK;
await SDK.init();
canvas.tabIndex = 0;
canvas.focus();

async function playAd() {
  await SDK.ad.requestAd("rewarded", {
    adStarted: pauseAll,
    adFinished: () => {},
    adError: () => {},
  });
  resumeAll();
  canvas.focus();                    // input works again without a click
}
window.addEventListener("focus", resume);
```

In local mode the "ad" is a black overlay for three seconds, which is enough to test that focus comes back.

Also clear held keys on `blur` so a character does not keep walking:

```js
window.addEventListener("blur", () => keys.clear());
```

## Key codes

Use `event.code` (physical key) for movement, so WASD works on non-QWERTY layouts, and `event.key` for text. Offer rebinding if you can.

## Mouse

- Right-click shows the browser menu. Call `preventDefault` on `contextmenu` if you use it.
- Use pointer events (`pointerdown`, `pointermove`, `pointerup`) instead of separate mouse and touch handlers, and call `setPointerCapture` for drags.
- Pointer lock needs a user gesture and the sandbox allows it. Handle the player pressing Escape: pointer lock exits and your game should pause.
- Do not rely on `mouseleave`; the cursor can leave the iframe while a button is held.

## Touch

The [mobile guide](https://docs.zokogames.com/guides/mobile) covers orientation, safe areas and memory in more depth.

- Do not detect mobile by `"ontouchstart" in window`. Laptops report touch. Use `SDK.user.systemInfo.device.type` (`"desktop"`, `"tablet"` or `"mobile"`; read it after `await SDK.init()`, and fall back to your own check when `SDK.environment === "disabled"`, where reading it throws `sdkDisabled`).
- Set `touch-action: none` on the canvas to stop the browser panning or zooming.
- Provide touch targets of at least 44 px, away from screen edges where the OS has gestures.
- Support multi-touch deliberately: track touches by `identifier`.
- Do not require hover.
- On iOS, resume audio inside a gesture handler.

## Text input

Use a real `<input>` for text and the on-screen keyboard. Canvas-drawn fields do not bring up the keyboard on mobile. When the keyboard opens the visual viewport shrinks; make sure the field stays visible.

## Gamepads

If you support gamepads, use the Gamepad API and show the right prompts. The portal frame allows gamepad access.

## Fullscreen and orientation

The portal supplies a fullscreen button and a rotate prompt. Do not add your own fullscreen toggle or lock orientation in code.

## Test checklist

- [ ] Hold a key, click elsewhere, return: nothing is stuck.
- [ ] Wheel and arrows never scroll the page.
- [ ] Right-click never opens the browser menu in-game.
- [ ] On a phone: no accidental zoom, no text selection, no pull-to-refresh.
- [ ] After an ad, input works without clicking first.

## Next steps

- [Mobile, touch and orientation](https://docs.zokogames.com/guides/mobile)
- [Audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads)

---

Source: https://docs.zokogames.com/guides/mobile

# Mobile, touch and orientation

This guide shows how to make a game playable on phones and tablets inside the portal's frame: detecting the device, orientation, safe areas, touch controls, audio and memory. Most players arrive on a phone. If you tick **Works on mobile** in the submission, reviewers test on one, and the game must offer the same features as on desktop. Examples assume `const SDK = window.ZokoGames.SDK;` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Know the device

```js
const SDK = window.ZokoGames.SDK;
await SDK.init();
const info = SDK.environment !== "disabled" ? SDK.user.systemInfo : null;
const isMobile = info?.device.type === "mobile";
const inAppShell = info !== null && info.applicationType !== "web";
```

`device.type` is `"desktop"`, `"tablet"` or `"mobile"`. Use it, not `"ontouchstart" in window`: laptops have touch screens and tablets have keyboards. `applicationType` is `"web"`, `"pwa"`, `"google_play_store"` or `"apple_store"`; the last three mean the portal runs inside an app shell, where safe areas matter more. In local mode (your own `localhost` page) `systemInfo` is read from your own browser (and `applicationType` is always `"web"`), so confirm the values the portal reports in the [Preview tool](https://www.zokogames.com/preview). When the SDK is disabled `info` is `null` and the code above falls back to desktop; add your own check such as `matchMedia("(pointer: coarse)")` for standalone runs.

## Orientation

You declare orientation in the submission: landscape, portrait or both. The portal shows a rotate prompt when the phone is held the wrong way, so you do not lock orientation in code.

- A game that declares **both** must lay out correctly in each. Listen to `resize`, not `orientationchange`, and read `innerWidth` and `innerHeight` fresh.
- Portrait games should make the playfield fit a 360 x 640 CSS pixel viewport without scrolling.
- Keep important UI away from the corners and bottom edge, where the OS reserves gesture zones.

## Safe areas

```css
.hud {
  padding-top: max(8px, env(safe-area-inset-top));
  padding-bottom: max(8px, env(safe-area-inset-bottom));
  padding-left: max(8px, env(safe-area-inset-left));
  padding-right: max(8px, env(safe-area-inset-right));
}
```

Include `<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">` in `index.html`.

## Touch controls

- Use pointer events and track each finger by `pointerId`.
- Touch targets are at least 44 x 44 CSS pixels with a gap between them.
- Put virtual sticks and buttons where thumbs rest, and let the player see through them.
- `touch-action: none` on the canvas stops panning and pinch zoom. Add `user-select: none` and `-webkit-touch-callout: none` to the body.
- Never require hover or a right-click. Offer a long-press or a visible button instead.
- Show on-screen controls only when `device.type` is `"mobile"` or `"tablet"` and hide keyboard hints there. Show keyboard hints on desktop.

More input pitfalls are in [control pitfalls](https://docs.zokogames.com/guides/input-controls).

## Audio on iOS

Resume the `AudioContext` inside the first touch or click handler. See [audio on iOS](https://docs.zokogames.com/requirements/technical#audio-on-ios). Also honour `SDK.game.settings.muteAudio`.

## Memory and performance

- Cap `devicePixelRatio` at 1 on phones for large canvases; 2 is usually the most you can afford.
- Keep textures compressed or small. A 2048 x 2048 texture uses about 16 MB of memory however small the file.
- Mobile initial download target is 20 MB. Above it the validator warns and reviewers test on a phone.
- Avoid allocating in the frame loop. Phones throttle when they heat up.
- Unity WebGL is off on iOS by default. Tick **Works on iOS** only after testing.

## Text input

Use a real `<input>` so the on-screen keyboard opens, and keep it visible when the visual viewport shrinks. Use `window.visualViewport` to reposition UI when the keyboard opens.

## Ads and banners on small screens

- Use banners on menus, game-over and shop screens, never over controls. A 320x50 or 320x100 banner fits a 360 px wide phone; see [banners](https://docs.zokogames.com/sdk/banners).
- Pause on `adStarted` and refocus the canvas after `adFinished`.

## Test checklist

- [ ] Playable at 360 x 640 and at 360 x 800 with no clipped buttons.
- [ ] Rotating the phone does not reset the game or break the layout, if both orientations are declared.
- [ ] No accidental zoom, text selection or pull-to-refresh.
- [ ] Sound starts after the first tap and respects mute.
- [ ] The game runs on a mid-range Android phone with a throttled network. The target is about 10 seconds to reach play on 4G.
- [ ] Works with the on-screen keyboard open when there is text input.

## Next steps

- [Mouse, keyboard and touch control pitfalls](https://docs.zokogames.com/guides/input-controls)
- [Audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads)

---

Source: https://docs.zokogames.com/guides/audio-and-ads

# Audio, pausing and ads

Several things can require your game to go quiet or to stop: the portal's mute setting, a video ad, the player clicking outside the game or switching tabs, and your own pause menu. Reviewers check that the game is silent and paused in each case and that it comes back correctly afterwards. This page states the contract and gives one small controller that implements it. It assumes you load and initialise the SDK as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction).

## The contract

| Situation | How your game learns about it | Gameplay | Sound | Afterwards |
| --- | --- | --- | --- | --- |
| Portal mute | `SDK.game.settings.muteAudio` at start, then `SDK.game.addSettingsChangeListener` | Keeps running | Off while `muteAudio` is `true` | Sound returns only when the setting is `false` again |
| Video ad | Call `SDK.game.gameplayStop()` before `requestAd`; `adStarted` when it shows | Stopped | Off from `adStarted` | Restore in both `adFinished` and `adError`; call `gameplayStart()` when input is live again |
| Focus lost or tab hidden | The window's `blur` event, `visibilitychange` with `document.hidden` | Paused, with `gameplayStop()` | Off while the tab is hidden | Continue, or show your pause menu, and call `gameplayStart()` when play continues |
| Your pause menu | Your own button | Paused, with `gameplayStop()` | Your choice | `gameplayStart()` when the player resumes |
| Before the first gesture | Nothing yet | Not affected | Browsers block it | Create or `resume()` the `AudioContext` inside the first tap, click or key press |

The one rule that is easy to break: **never switch sound on blindly**. Sound is on only while none of the reasons to be silent holds. A game that sets the volume back to full when an ad finishes ignores a player who muted the portal, and reviewers test exactly that.

## A small controller

```js
// Sound is on only while no reason to be silent is active.
const SDK = window.ZokoGames.SDK;
const quiet = new Set(); // active reasons: "portal", "ad", "hidden"
let audioCtx = null;

function applyAudio() {
  if (!audioCtx) return;
  if (quiet.size > 0) audioCtx.suspend();
  else audioCtx.resume();
}

function setQuiet(reason, on) {
  if (on) quiet.add(reason);
  else quiet.delete(reason);
  applyAudio();
}

// 1. Browsers allow sound only after a gesture, so create the context in the first one.
function unlockAudio() {
  audioCtx = audioCtx || new AudioContext();
  applyAudio();
}
window.addEventListener("pointerdown", unlockAudio, { once: true });
window.addEventListener("keydown", unlockAudio, { once: true });

// 2. The portal's mute setting, at start and on every change.
async function startSdk() {
  await SDK.init(); // never rejects
  if (SDK.environment === "disabled") return;
  setQuiet("portal", SDK.game.settings.muteAudio);
  SDK.game.addSettingsChangeListener((settings) => setQuiet("portal", settings.muteAudio));
}

// 3. Losing focus pauses play; a hidden tab is also silent.
window.addEventListener("blur", () => pauseGame()); // your own pause, which calls gameplayStop()
document.addEventListener("visibilitychange", () => setQuiet("hidden", document.hidden));

// 4. Ads: gameplay stops first, sound is off during the ad, and both outcomes restore it.
async function showAd(type) {
  if (SDK.environment === "disabled") return false;
  let finished = false;
  try {
    await SDK.game.gameplayStop();
    await SDK.ad.requestAd(type, {
      adStarted: () => setQuiet("ad", true),
      adFinished: () => { finished = true; },
      adError: (error) => console.info("No ad:", error.code),
    });
  } catch (error) {
    console.warn("SDK:", error.code); // sdkNotInitialized, sdkDisabled or invalidArgument
  } finally {
    setQuiet("ad", false); // after adFinished, adError or a rejection
  }
  return finished; // grant a reward only when this is true
}

startSdk();
```

Call `gameplayStart()` yourself when the player is in control again: at the start of the next round, or when they leave your pause menu. Background music and effects all go through the one `AudioContext`, so suspending it silences both. If you use an audio library, put its mute switch where `applyAudio` suspends and resumes the context.

For an ad-free member, a midgame request runs `adStarted` and `adFinished` at once without showing anything, so the same code path resumes the game straight away. Rewarded ads still play for them.

## Engines

The contract is the same in every engine. Each [engine page](https://docs.zokogames.com/engines/overview) shows how its wrapper reports the start and end of an ad, and the portal settings where the wrapper exposes them. For Three.js, PixiJS and plain canvas games, [Plain HTML5, Three.js and PixiJS](https://docs.zokogames.com/engines/html5-libraries) shows where each library's pause and volume switches are.

## Test it

- [ ] Reload the game: nothing plays before your first tap, click or key press.
- [ ] Locally with `?muteAudio=true`, or with **Platform mute is on** in the build preview's **Simulate the player** card: the game is silent at once and stays silent after an ad.
- [ ] Turn **Platform mute is on** off again: sound comes back without a reload.
- [ ] Click outside the game and switch tabs during a round: play stops and the event log shows `gameplayStop`.
- [ ] Locally with `?ad_response=adblock`, or with **Ad blocker installed**: the game continues with sound, and no reward is granted.
- [ ] Watch a whole ad: the game is silent during it and play continues after it, with `gameplayStart` in the log.

## Next steps

- [Video ads](https://docs.zokogames.com/sdk/ads)
- [Advertisement rules](https://docs.zokogames.com/requirements/advertisements)
- [Mobile, touch and orientation](https://docs.zokogames.com/guides/mobile)

---

Source: https://docs.zokogames.com/guides/localisation

# Localisation guide

This guide shows how to choose the player's language from the SDK, keep English as the fallback and avoid the layout and font problems translations cause. English is required for every visible string. Extra languages are welcome and help the game reach more players, but they never replace English. Examples assume `const SDK = window.ZokoGames.SDK;` and `await SDK.init();` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Pick the language

`SDK.user.systemInfo.locale` is a BCP 47 language tag (a language code such as `"de"`, optionally with a region such as `"pt-BR"`). Inside the portal it is the language the player chose for the **portal's own pages**, not the browser language. The portal currently offers: `en`, `nl`, `it`, `es`, `id`, `fr`, `pt-BR`, `ru`, `uk`, `nb` (Norwegian), `ro`, `fi`, `sv`, `da`, `cs`, `hu`, `tr`, `ar`, `vi`, `th`, `ko`, `ja`, `pl`, `el` and `de`, so a Japanese-speaking player on the English site gets `"en"`. `countryCode` is an ISO country code such as `"BR"`, taken from the request. Read both after `await SDK.init()`; `systemInfo` is synchronous but throws `sdkDisabled` when the SDK is disabled, hence the guard below.

```js
const SDK = window.ZokoGames.SDK;
await SDK.init();

const SUPPORTED = ["en", "es", "pt", "de", "fr"];

function pickLanguage() {
  const raw = SDK.environment !== "disabled" ? SDK.user.systemInfo.locale : navigator.language;
  const base = String(raw).toLowerCase().split("-")[0];
  return SUPPORTED.includes(base) ? base : "en";
}
const lang = pickLanguage();
```

Rules:

- Decide the language **automatically**. Do not make players choose before they can play. A small language switch in settings is fine.
- Always fall back to English, for the whole game and for any single missing string.
- In local mode (your own `localhost` page) the locale is your browser's language and the country is always `"US"`. Change the browser language to test, or force a language with your own query parameter (for example `?lang=de` read by your code).
- Guests, ad-blocked and offline players get the same locale; it is a property of the portal page, not of the account.
- The [Preview tool](https://www.zokogames.com/preview) shows what the portal reports to the game.

## Keep strings out of code

```js
const STRINGS = {
  en: { play: "Play", gameOver: "Game over", score: "Score: {n}" },
  es: { play: "Jugar", gameOver: "Fin del juego", score: "Puntos: {n}" },
};

function t(key, vars = {}) {
  const table = STRINGS[lang] ?? STRINGS.en;
  const raw = table[key] ?? STRINGS.en[key] ?? key;
  return raw.replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? ""));
}
```

- Use named placeholders (`{n}`), never string concatenation. Word order differs between languages.
- Use `Intl.NumberFormat(locale)` and `Intl.DateTimeFormat(locale)` for numbers and dates.
- Use `Intl.PluralRules(locale)` for plurals; many languages have more than two forms.
- Load only the language you need, so translations do not grow the initial download.

## Layout and fonts

- Text expands: German and Finnish are often 30 percent longer than English. Size buttons from their content and test with the longest language.
- Right-to-left languages (Arabic, Hebrew) need mirrored layout and `dir="rtl"`. Only ship them when you have tested them.
- Pick a font that covers your scripts. A pixel font with only Latin glyphs shows empty boxes for Cyrillic or CJK. Subset fonts to keep them small.
- Do not bake text into images. Put it in a text layer so it can be translated.

## Engines

- **Unity:** the Localization package or your own table; read the locale from the wrapper's system info before the first scene loads.
- **Godot:** `TranslationServer.set_locale()` with the SDK locale.
- **Construct 3:** a language object or the Localization plugin.
- **Phaser and library games:** your own table as above.

See the [engine pages](https://docs.zokogames.com/engines/overview) for how each wrapper exposes `systemInfo`.

## Listing text

The title, descriptions and controls you enter in the console are in English. Make sure the in-game controls text matches the description. Other languages inside the game do not need separate listing text.

## Checklist

- [ ] Every visible string, including errors and the tutorial, exists in English.
- [ ] Language is chosen from `systemInfo.locale` with an English fallback.
- [ ] Longest translation still fits every button.
- [ ] Fonts contain the glyphs for each shipped language.
- [ ] No language prompt blocks the first play.

## Next steps

- [Gameplay requirements](https://docs.zokogames.com/requirements/gameplay)
- [Mobile, touch and orientation](https://docs.zokogames.com/guides/mobile)

---

Source: https://docs.zokogames.com/guides/cloud-saves

# Cloud saves in practice

This guide shows how to design your game's save data for the [data module](https://docs.zokogames.com/sdk/data), a `localStorage`-shaped store with synchronous reads, background writes and 1 MiB for the whole save, and how it behaves for guests who sign in mid-game. Examples assume `const SDK = window.ZokoGames.SDK;` and `await SDK.init();` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

Turn the module on first: in the console, tick **Uses the SDK data module** on the game's listing. While it is off, every `SDK.data` call throws `dataModuleDisabled`. The four methods (`getItem`, `setItem`, `removeItem`, `clear`) are synchronous and take and return strings, and they throw the error object rather than rejecting.

## One key or many

Each `setItem` is cheap, and several writes in a burst become a single upload. Prefer a few focused keys over one giant blob, so a corrupt value does not lose everything:

```js
SDK.data.setItem("profile", JSON.stringify({ v: 2, name, coins, unlocked }));
SDK.data.setItem("settings", JSON.stringify({ v: 1, music, sfx }));
SDK.data.setItem("run", JSON.stringify({ v: 1, level, seed }));   // small checkpoint, not a replay
```

The 1 MiB limit counts the whole save serialised as JSON. Store ids and numbers, not world snapshots. A `setItem` that would break the limit throws `dataLimitExceeded` and writes nothing.

## Version every value

Players keep saves for years. Put a version in each value and migrate on load:

```js
function load(key, version, migrate, fallback) {
  try {
    const raw = SDK.data.getItem(key);
    if (!raw) return fallback;
    let obj = JSON.parse(raw);
    while (obj.v < version) obj = migrate[obj.v](obj);
    return obj;
  } catch {
    return fallback;          // corrupt or unreadable: start clean, never crash
  }
}
```

## Write at meaningful moments

Save when something worth keeping changed (level complete, purchase, setting), not every frame. The SDK debounces for one second, uploads at least every 30 seconds while writes continue and flushes when the page is hidden or closed. Do not build your own timer around that.

## Guests and signing in

Signed-in players have a save on the portal's servers. Guests have a save in the browser. When a guest signs in during play:

- If the account has **no save for your game**, the guest's progress is uploaded and becomes the account's save.
- If the account **already has a different save**, the portal asks the player which one to keep: **Keep this device's progress** or **Use my saved progress**. It asks the same when a signed-in player opens your game while the device still holds different guest progress; the game then starts from the device copy. Until the player answers, your game runs on the guest's progress and its `SDK.data` writes stay on the device, never uploaded. **Keep this device's progress** uploads the newest device copy, those writes included, and your game carries on without a reload. **Use my saved progress** drops those writes and reloads your game: `init()` runs again and `SDK.data` holds the account's save. Writes your game makes while the portal is still sending the guest's progress at sign-in count as the guest's too. A choice made in one tab closes the question in the player's other open tabs, which follow it. If the player uses **Delete cloud save** while the question is open, only the account's copy is deleted: the device copy stays and becomes the account's save when your game next loads.
- If the player signs in while offline, or the portal cannot read the account's save, nothing is asked and nothing is overwritten: the guest's progress stays on the device, and the comparison runs when the connection returns or on the next load.

The portal does the upload and asks the question for you, so you do not write anything extra when the player signs in. It happens **in the background, right after your auth listener is called**, so do not assume it has finished. No SDK event reports the question or the answer, and `SDK.data` never changes under a running game: your game keeps the data it started with until it is reloaded. If your game had saved nothing yet and the account has a save, the portal offers the player a reload instead of asking. Signing out restarts the game as a guest. Keep saves small and versioned so either outcome loads cleanly on the next start.

After a sign-out, or a switch straight to another account (which also restarts the game), `SDK.data` calls keep working as usual until the restart, but nothing your game writes in that window is stored. When a signed-in player signs out with changes not uploaded yet (offline, or a failed upload) and later signs in again with the same account, those changes are uploaded first, before any guest progress on the device is compared with the account, instead of being replaced by the older cloud save; if another device saved in the meantime, the portal asks which copy to keep.

```js
SDK.user.addAuthListener(() => {
  // The merge is still running. Refresh your account UI here;
  // do not rewrite keys from stale in-memory state, and do not start a new save slot.
  hud.refreshAccount();
});
```

## Two devices

A signed-in player can play on two devices. If another device saved since this one last synced, the portal pauses uploads and asks the player which copy to keep; choosing the other device's copy reloads your game so it starts from it. Nothing in your code is needed, which is one more reason to load all state at start and never cache it across sessions yourself.

## Keep the browser-local fallback honest

Do not use `localStorage` for progress. Inside the portal's frame it may be partitioned or cleared; `SDK.data` follows the player. If you are migrating existing players, copy old keys once (see [data](https://docs.zokogames.com/sdk/data#migrating-from-localstorage)).

## Ported games that use localStorage

If a game saves with `localStorage` and you cannot change its code, SDK 1.4.0 can mirror those writes into the cloud save: see [mirroring `localStorage`](https://docs.zokogames.com/sdk/data#mirroring-localstorage-ported-games).

## Ported games that use IndexedDB

Unity (`/idbfs`), Godot and GameMaker save into IndexedDB. SDK 1.7.0 can mirror those databases too: `await SDK.data.mirrorIndexedDB({ databases: ["/idbfs/mygame"] })` after `init()` and **before the engine starts**, so the restore finishes before the game reads its files. See [mirroring IndexedDB](https://docs.zokogames.com/sdk/data#mirroring-indexeddb-unity-godot-gamemaker) for the limits: the snapshot shares the 1 MiB save, a save that does not fit is skipped, never cut, and a save in the last moments before the tab closes can be lost. Keep big asset caches out of `databases`.

## When the SDK is disabled

Without the SDK (`SDK.environment` is `"disabled"`: not on localhost and not inside the portal frame, or before `init()` finishes), `SDK.data` throws `sdkDisabled` or `sdkNotInitialized`. Wrap storage in a tiny adapter that falls back to `localStorage` for standalone runs:

```js
await SDK.init();
const live = SDK.environment !== "disabled";
const store = {
  get: (k) => (live ? SDK.data.getItem(k) : localStorage.getItem(k)),
  set: (k, v) => (live ? SDK.data.setItem(k, v) : localStorage.setItem(k, v)),
};
```

## Things not to store

- Anything that must be authoritative or tied to payments: keep it on your server and verify the player with the [token](https://docs.zokogames.com/sdk/user#tokens).
- Secrets, tokens and personal data.
- Large assets and replays.

## Testing

- Local mode (your own `localhost` page) keeps the whole save as one JSON object in `localStorage` under `zoko-sdk-data`; delete that key for a new player. Nothing is uploaded and there is no merge or two-device prompt, so test those on the live portal with two accounts.
- Offline or ad-blocked players: the module needs no ads, and while the player is offline it reads and writes the device copy and uploads when the connection returns ([offline play](https://docs.zokogames.com/guides/offline-play)).
- Pass `?user_response=logged_out` to test the guest path, then `?show_auth_prompt_response=user1` and press your sign-in button to test the upgrade.
- In the [Preview tool](https://www.zokogames.com/preview) the "Data module used for saves" checklist item ticks when your game writes.

## Next steps

- [Data (cloud save)](https://docs.zokogames.com/sdk/data)
- [Making a game playable offline](https://docs.zokogames.com/guides/offline-play)

---

Source: https://docs.zokogames.com/guides/leaderboard-setup

# Leaderboards step by step

This guide takes you from "no leaderboard" to a working weekly board in six steps: choose the rules, set them in the console, submit scores from the game or your server, show ranks and test. The [leaderboards reference](https://docs.zokogames.com/sdk/leaderboards) has the full contract. Examples assume `const SDK = window.ZokoGames.SDK;` and `await SDK.init();` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## 1. Decide what the board measures

| You want to rank | Sorting | Incremental | Label |
| --- | --- | --- | --- |
| Best single score | Highest first (`DESC`) | Off | `POINTS` or `XP` |
| Fastest time | Lowest first (`ASC`) | Off | `MINUTES` |
| Total progress this week | Highest first | **On**: each submission adds to the weekly total | `XP` |

Boards reset every week (Monday 09:00 UTC). At the end of the week, ranks 1 to 3 earn gold, silver and bronze trophies on their profile; with at least 10 players, the top 1 %, 5 % and 10 % earn trophies too.

## 2. Configure it in the console

Open the game's **Leaderboard** tab. It holds the one switch, **Leaderboard enabled**: turn it on, set the rules and press **Save rules** (the **Technical** step only shows whether the leaderboard is on and links here). Only studio admins and owners can change it. Keys are opt-in. Without an **Encryption key** the board accepts plain scores, which anyone can forge; press **Generate** next to it to accept only encrypted scores from then on. Generate a **Server API key** only if your own server submits scores. Keys can be generated once the rules are saved, and creating, rotating or revoking one asks for a second step (a passkey or an authenticator app on your player account; add one first in the account's security settings). Generate the encryption key before you launch: on a live game the first key makes the board ignore the plain scores of the build players already have. A new key is shown once; copy it immediately. Rotating the encryption key breaks builds that still use the old one.

- Set the **minimum and maximum** to values a legitimate player can reach. Anything outside is dropped. On an incremental board the range applies to each submitted amount, not to the total.
- Set a **cooldown** to stop spam submissions (for example 10 seconds).
- Write a one-line **player guide** that tells players how to score.

## 3. Submit from the game (client)

```js
const KEY = "<encryption key from the console>";
const GAME_ID = "<your game id>";   // the id in your console address: /developer/games/<id>. Anything in a browser can be read; see the warning below

async function encryptScore(score, keyBase64, userId, gameId) {
  const raw = Uint8Array.from(atob(keyBase64), (c) => c.charCodeAt(0));
  const key = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt"]);
  const iv = crypto.getRandomValues(new Uint8Array(12));
  const additionalData = new TextEncoder().encode(`zoko-score-v1|${userId}|${gameId}`);   // binds the payload to this player and game
  const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData }, key, new TextEncoder().encode(`${score}|${Date.now()}`)));
  const out = new Uint8Array(iv.length + sealed.length);
  out.set(iv, 0);
  out.set(sealed, iv.length);
  return btoa(String.fromCharCode(...out));
}

async function finishRun(score) {
  const user = await SDK.user.getUser();
  if (!user) return;                         // guests do not appear on boards
  await SDK.user.submitScore({ encryptedScore: await encryptScore(score, KEY, user.__dangerousUserId, GAME_ID), score });
}
```

Encrypt at the moment you submit: payloads are bound to the player and game, expire after 2 minutes and work once. Submit once per run, at the end. The call resolves (with no value) whether or not the score was accepted, so do not treat it as a confirmation; the portal shows the player a rank toast when it was. The one rejection to handle is `rateLimited`, thrown when a player goes past 30 submissions per minute per game. A guest's submission records nothing; when the score would reach the top 10 of the current week's board, the portal invites them to sign in, at most once per game per page view. A run that does not place does not use up that invitation. Offline players cannot submit: the call needs the portal (see [offline play](https://docs.zokogames.com/guides/offline-play)).

> [!WARNING]
> The client path stops casual tampering, not a determined cheater, because the key ships in the browser. For competitive games compute the score on your server and use the server API.

### Submit once per finished run

Our own games submit through one small shared helper. The sketch below keeps its rules and leaves out the rest: detect the feature first, submit once per run, never for a child, never a value the board would drop, and keep a guest's score until they sign in.

```js
// Uses KEY, GAME_ID and encryptScore() from the example above. Set KEY to "" when the board has no encryption key.
const RANGE = { min: 1, max: 300 };   // the same min and max as on the Leaderboard tab
const handled = new Set();            // ids of runs already submitted or skipped
let kept = null;                      // best score of a signed-out player, sent after sign-in

function boardAvailable() {
  if (SDK.environment === "disabled" || typeof SDK.user.submitScore !== "function") return false;
  if (!SDK.user.isUserAccountAvailable) return false;
  const s = SDK.game.settings;
  return !(s.kidsMode ?? s.disableChat);   // kids mode: no boards
}

async function send(user, score) {
  const encryptedScore = KEY ? await encryptScore(score, KEY, user.__dangerousUserId, GAME_ID) : "";
  try {
    await SDK.user.submitScore({ encryptedScore, score });
    return "sent";                          // delivered; the portal shows the rank toast if it counted
  } catch (e) {
    return e?.code === "rateLimited" ? "too-fast" : "error";
  }
}

async function onRunFinished(runId, score) {
  if (handled.has(runId) || !boardAvailable()) return "off";
  handled.add(runId);
  if (!Number.isFinite(score) || score < RANGE.min || score > RANGE.max) return "out-of-range";
  const user = await SDK.user.getUser();
  if (user) return send(user, score);
  kept = kept === null ? score : Math.max(kept, score);   // highest-first board: keep the better run
  return "guest";                                          // show a "Sign in to rank" button
}

async function onSignInClicked() {
  const user = await SDK.user.showAuthPrompt().catch(() => null);
  if (!user || kept === null) return;
  const score = kept;
  kept = null;
  await send(user, score);
}
```

- **Detect the feature.** Show no board UI when the SDK is disabled, when the host has no player accounts (`isUserAccountAvailable` is `false`) or when `submitScore` is missing.
- **Once per run.** Key each submission by a run id, so a second game-over screen or a double tap cannot send the same run twice. More than 30 calls a minute per player and game (10 on a board without an encryption key) reject with `rateLimited`.
- **When `rateLimited` happens.** Nothing was recorded, so the run is still worth sending: keep the score (not the payload), wait about a minute, encrypt it again and send one score for the backlog, when the sketch returns `"too-fast"`. A retry that lands after Monday 09:00 UTC counts for the new week. The full retry rule is in the leaderboards reference, under Client submission.
- **Guests.** The SDK does not check whether the player is signed in: it passes the call to the portal. For a signed-out player the portal records nothing and resolves the call; when the score would reach the top 10 of the current week's board it also invites the player to sign in, at most once per game per page view. The sketch checks `getUser()` first instead, keeps the guest's best run and sends it once `showAuthPrompt()` resolves with a player. On an incremental board, add the kept runs up instead of keeping the best one.
- **Offline.** A run that ends offline records nothing unless you also pass `delayed` (SDK 1.6.4): a copy sealed at the end of the run with `earnedAt = Date.now()`. The portal keeps it on the device for a signed-in player and sends it when they are back online, within 72 hours; it counts for the all-time board only, not the weekly board. How to seal it: [Offline scores](https://docs.zokogames.com/sdk/leaderboards#offline-scores). Without `delayed`, an offline score is not queued.
- **Kids mode.** There are no boards: the portal records nothing and shows no sign-in prompt, `getUser()` resolves `null`, and the server API answers `403` `kids-game` for a game with the kids flag. Hide the board UI.
- **Range and cooldown.** Set the min, max and cooldown on the **Leaderboard** tab. The portal enforces them and drops a value outside the range, or one sent inside the cooldown, without telling the game. Checking the range in the game only saves a pointless call. On an incremental board the range applies to each run's amount.
- **No confirmation.** `submitScore` resolves with no value whether or not the score counted; the portal shows the rank toast when it did. Treat `"sent"` as delivered, not as ranked.

### What the encryption key protects

With a key, the portal accepts only a payload encrypted with it, made for this player and this game, less than 2 minutes old and not seen before. That stops a number typed into the browser's developer tools, a payload copied from another player or game, and an old payload sent again. It does not stop a player who reads the key from your game's files (everything shipped to a browser can be read) and encrypts any score they like, and a board without a key accepts the plain number. When scores matter, compute or check them on your server and submit them with the server API key (step 4): that key never leaves your server, and the server API answers with explicit errors, for example `403` `developer-suspended` while your studio is suspended. Every code is listed in the [leaderboards reference](https://docs.zokogames.com/sdk/leaderboards#server-api).

## 4. Submit from your server (authoritative)

1. The game sends `await SDK.user.getUserToken()` with the run to your server.
2. Your server verifies the token against the [JWKS](https://docs.zokogames.com/sdk/user#verifying-on-your-server), checks the `gameId` claim and takes `userId`.
3. Your server validates the run and posts the score:

```js
const res = await fetch("https://www.zokogames.com/api/v1/leaderboard/scores", {
  method: "POST",
  headers: { "x-api-key": process.env.ZOKO_LEADERBOARD_KEY, "content-type": "application/json" },
  body: JSON.stringify({ scores: [{ userId, score }] }),
});
const { ok, results } = await res.json();    // results[i].ok, .rank, .score or .error
```

Batch up to 100 scores per request (more is rejected with `too-many-items`). The API key must never be shipped in the game.

## 5. Show it to players

The portal already shows the leaderboard next to the game and refreshes the player's rank after an accepted submission, so you may not need anything else. To show ranks inside your own UI, read the public endpoint. A game on its own origin (`https://g-<slug>.zokogames.com`) can call it directly from the browser: the endpoint answers CORS for game origins and the portal only, without credentials, so the player's session is not sent and `me` is empty. You can also call it from your server.

```js
// in the game, or on your server (Node 20+)
const r = await fetch(`https://www.zokogames.com/api/leaderboard/${GAME_ID}?scope=global&limit=10`);
const { entries, me, neighbours, season, seasonEndsAt } = await r.json();
```

Without a session (a server call, or a browser call without credentials) there is no signed-in player, so `me` is empty and `scope=friends` answers 401. Cache the answer for a short time instead of calling per player.

## 6. Test

- Local mode accepts `submitScore` and records nothing: it has no board. It logs one console line per call, and offline (`?offline=true`) with a signed-in player and `delayed` it shows "Score saved offline". Use the [Preview tool](https://www.zokogames.com/preview) to confirm the call is made ("A leaderboard score was submitted" in the game's preview checklist), and test acceptance on a build in basic launch with a real account.
- If scores seem to vanish, check in this order: the player is signed in, the board is enabled, the value is inside min and max, the cooldown has passed, the key in the build matches the console key.

## Next steps

- [Leaderboards](https://docs.zokogames.com/sdk/leaderboards)
- [Achievements](https://docs.zokogames.com/sdk/achievements)

---

Source: https://docs.zokogames.com/guides/player-accounts

# Player accounts and your backend

This guide shows how to read who is playing, offer sign-in, send a verified identity to your own backend and link an existing game account, with the minimum code for each [account scenario](https://docs.zokogames.com/requirements/accounts). Players are either signed in to ZokoGames or guests, and your game must work for both. Examples assume `const SDK = window.ZokoGames.SDK;` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); terms such as guest and token are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## 1. Show who is playing

```js
await SDK.init();
const user = await SDK.user.getUser();            // null for guests
if (user) hud.setName(user.username, user.profilePictureUrl);

SDK.user.addAuthListener((u) => hud.setName(u.username, u.profilePictureUrl));
```

The auth listener also fires when the player signs in through the portal's own header while your game is open. `getUser()` is asynchronous and resolves `null` for a guest. When the player signs out, the portal restarts your game as a guest.

What you see in other situations: offline, the player is the last one signed in on this device, or a guest. In kids mode there is no sign-in at all (`showAuthPrompt` ends as `userCancelled`). In local mode (your own `localhost` page) the player is a fake `user1` unless you use the switches in step 5.

## 2. Offer sign-in on a player action

```js
if (SDK.user.isUserAccountAvailable && !user) signInButton.hidden = false;
signInButton.onclick = async () => {
  try { await SDK.user.showAuthPrompt(); }
  catch (e) { if (e.code !== "userCancelled") console.warn(e.code); }
};
```

Never open the prompt automatically at start.

## 3. Send a verified identity to your server

The browser can lie about `__dangerousUserId`; a token cannot be forged.

```js
async function callBackend(path, body) {
  let token = null;
  try { token = await SDK.user.getUserToken(); } catch (e) { /* userNotAuthenticated: guest */ }
  return fetch("https://api.example.com" + path, {
    method: "POST",
    headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
    body: JSON.stringify(body),
  });
}
```

On the server, verify the signature with the portal's public keys, check expiry and check that `gameId` equals your game's id. A complete verifier in Node.js, Python and C# is in the [user module reference](https://docs.zokogames.com/sdk/user#verifying-on-your-server). Express middleware:

```js
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));

export async function zokoAuth(req, res, next) {
  const raw = (req.headers.authorization || "").replace(/^Bearer /, "");
  if (!raw) { req.player = null; return next(); }            // guest
  try {
    const { payload } = await jwtVerify(raw, JWKS, {
      algorithms: ["RS256"],
      issuer: "zokogames",
      audience: process.env.ZOKO_GAME_ID,
      clockTolerance: 5,
    });
    if (payload.gameId !== process.env.ZOKO_GAME_ID) throw new Error("wrong game");
    req.player = { id: payload.userId, name: payload.username };
    next();
  } catch {
    res.status(401).json({ error: "invalid_token" });
  }
}
```

Tokens last one hour and carry `userId`, `gameId`, `username`, `profilePictureUrl`. The SDK caches a token until a minute before it expires, so call `getUserToken()` before every backend request. Local mode issues unsigned tokens that a correct verifier rejects.

To submit scores for the weekly leaderboard from the same token, see [leaderboards step by step](https://docs.zokogames.com/guides/leaderboard-setup).

## 4. Link an existing game account (full integration)

```js
async function onSignedIn() {
  const { linked } = await (await callBackend("/session", {})).json();
  if (linked) return;                                           // userId already linked: load that account
  const { response } = await SDK.user.showAccountLinkPrompt();
  if (response === "yes") await callBackend("/link", {});       // server links the verified userId to this game account
}
```

Prefer linking to a fresh account over merging two accounts that both have progress, and always treat the verified `userId` as the key. A complete walkthrough with a server-side example is in [account linking step by step](https://docs.zokogames.com/guides/account-linking).

## 5. Test every path locally

| Path | URL switch |
| --- | --- |
| Guest | `?user_response=logged_out` |
| Signed-in at start | `?user_response=user1` |
| Sign in on a button | `?user_response=logged_out&show_auth_prompt_response=user2` |
| Player cancels | `?show_auth_prompt_response=user_cancelled` |
| Link accepted / declined | `?link_account_response=yes` / `no` |
| Token fails / expired | `?token_response=logged_out` / `expired_token` |
| No accounts at all | `?user_account_available=false` |

## Next steps

- [Account linking step by step](https://docs.zokogames.com/guides/account-linking)
- [User module](https://docs.zokogames.com/sdk/user)

---

Source: https://docs.zokogames.com/guides/ad-monetisation

# Ad monetisation guide

This guide shows how to place midgame ads, rewarded ads and banners so that revenue grows without costing you players. The binding rules are in the [advertisement rules](https://docs.zokogames.com/requirements/advertisements); this page is how to do well inside them. Examples assume `const SDK = window.ZokoGames.SDK;` and `await SDK.init();` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading). Unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## When ads run

- **Full launch only.** Ads are off during basic launch, for kids games and for players who are ad-free members. Build the integration during basic launch anyway. Until ads are live, `SDK.ad.requestAd` fails with `adsDisabled`, so the error path below is the code that runs, and you can test it today. In full launch the ads shown today are the portal's own house ads: no ad network is connected yet, so they earn no revenue (see [feature status](https://docs.zokogames.com/business/faq#feature-status)).
- **Local mode** (your own `localhost` page): `requestAd` shows a black "Local ad" overlay for three seconds, then calls `adFinished`. Midgame ads honour the three-minute cooldown (a second midgame request inside it fails with `adCooldown`). Since SDK 1.6.4 local mode refuses a midgame request made before `gameplayStart()` too, like the portal (see below). Banners appear as grey dashed boxes. Add `?ad_response=unfilled`, `adblock`, `adsDisabled` or `other` to the page address to force each failure.
- **Ad-blocked players and players who close an ad:** `requestAd` calls `adError` with a code such as `adblock` or `unfilled`. A rewarded ad the player closes early also ends in `adError`, with no reward.

A design that earns today and loses players next week earns less in total. These patterns respect both. For where each format fits in action, clicker, driving, io, idle, puzzle and word games, see [monetisation by genre](https://docs.zokogames.com/guides/monetisation-by-genre).

## Midgame ads

### Choose the breaks

Good: end of a level, return to the menu, after a game-over screen has been read, after a shop closes. Bad: right after a death in the middle of a streak, when the player just opened the game, on any button players press repeatedly.

### Start gameplay first

Call `SDK.game.gameplayStart()` when the player starts to play. Until your game has called it once, the portal refuses every midgame request with `adCooldown` and the message "Midgame ads are available after gameplay starts: call game.gameplayStart() first". A game that never calls it gets midgame ads 30 seconds after play begins. Rewarded ads are not affected. Local mode shows this refusal from SDK 1.6.4; with 1.6.3 and earlier you saw it only on the site and in the [Preview tool](https://www.zokogames.com/preview).

### Pace them

The portal allows one midgame ad every three minutes, and any ad (rewarded too) restarts that timer. Rewarded ads themselves are not held back by it. Do not try to hit exactly that:

- Make the first ad later than the cooldown, once the player has played a round. Players who see an ad in the first thirty seconds leave more.
- Count breaks (levels, runs), not seconds, and show an ad every second or third break.
- If a request fails (`unfilled`, `adCooldown`, `adblock`, `adsDisabled`), just continue. Do not retry immediately. An admin can also set a longer minimum gap or a cap per session for your game, which shows up as `adCooldown` too, and so does a request made before `gameplayStart()`.

```js
let breaks = 0;

async function showMidgame() {
  await SDK.ad.requestAd("midgame", {
    adStarted: () => { pauseAll(); },    // pause game and mute here
    adFinished: () => {},                // nothing to do: we resume below
    adError: () => {},                   // no fill, cooldown, adblock, ads off: carry on
  });
  resumeAll();                           // runs after finish or error; the promise resolves in both cases
}

async function onLevelEnd() {
  await SDK.game.gameplayStop();
  breaks++;
  if (breaks % 2 === 0) await showMidgame();
  showLevelSummary();
}
```

`pauseAll`, `resumeAll` and `showLevelSummary` are your own functions. `requestAd` resolves once the ad has finished or failed, and never rejects for an ad outcome (it rejects only for bad arguments or a disabled SDK).

### Be clean

Block clicks while the request is pending, pause and mute in `adStarted`, and resume on both `adFinished` and `adError`. After resuming, return focus to the game.

## Rewarded ads

Rewarded ads convert when the reward is obviously worth thirty seconds.

- **Offer, don't push.** Show the button on a screen where the player is already deciding: results screen ("double your coins"), a shop, or a continue screen.
- **Be explicit.** Name the reward on the button. Mark it as an ad.
- **Always provide a no-ad route** to the same reward, even if slower or smaller.
- **Reward only after `adFinished`.** On `adError` show a friendly message and no reward.
- **Limit frequency.** Cap how many rewards can be claimed per session or per timer. Rewards that never run out devalue themselves.
- **Don't stack.** No midgame ad directly followed by a rewarded offer between the same two levels.

```js
async function onDoubleCoins() {
  let ok = false;
  await SDK.ad.requestAd("rewarded", {
    adStarted: pauseAll,
    adFinished: () => { ok = true; },
    adError: (e) => console.warn("rewarded ad failed:", e.code),
  });
  resumeAll();
  if (ok) addCoins(runCoins); else toast("No ad available right now");
}
```

Only one ad can run at a time: a second `requestAd` while one is on screen calls its `adError` at once.

## Banners

- Only on screens that stay open at least about five seconds: menus, level select, results.
- Never over the playfield or over a control.
- Clear them before gameplay (`clearAllBanners`).
- Do not request again inside 30 seconds; each container can refresh once per 30 seconds and a session has a cap of 60 refreshes.
- Banner requests while a video ad is on screen fail with `videoAdPlaying`; request them again after `adFinished`.
- Make the layout work without a banner; they can fail or be disabled.

Banner calls reject with an error object (`code`, `message`, `containerId`) instead of calling a callback, so wrap them. The container must be an element that is on screen with a real size:

```js
// <div id="menu-banner" style="width:100%;height:100px"></div>
try {
  await SDK.banner.requestResponsiveBanner("menu-banner");
} catch (e) {
  // bannersDisabled (ads off, kids, ad-free), notVisible, videoAdPlaying, bannerCooldown, ...
  console.warn("no banner:", e.code);
}
// leaving the menu:
await SDK.banner.clearAllBanners();
```

In local mode you see a grey dashed placeholder inside the container; anywhere else nothing appears until your game is in full launch.

## When to show what

| Moment | Midgame | Rewarded | Banner |
| --- | --- | --- | --- |
| First 30 seconds of a first session | No | No | No |
| During active play | Never | Never | Never |
| Level or round complete, results read | Yes, every second or third break | Offer "double it" | Yes, on the results screen |
| Death or fail screen | After the screen was read, not instantly | "Continue" offer with a no-ad route | Yes |
| Shop, upgrade or pause menu | No | Offer a reward tied to what the player is looking at | Yes |
| Returning to the main menu | Yes, if the cooldown allows | Optional daily bonus | Yes |
| Loading screens | No | No | No |

The [starter kits](https://docs.zokogames.com/getting-started/starter-kits) implement exactly this pattern.

## Measure

- Watch session length and retention alongside revenue in the console. If a change raises ad frequency and lowers day-1 retention, undo it.
- Change one thing at a time and give it a few days of traffic.

## Adblock players

They are still players. `await SDK.ad.hasAdblock()` resolves `true` when a blocker is detected (and `false` in kids mode, where no ad script loads). Hide the rewarded button or offer the alternative route to the same reward, and do not shame them. A midgame ad that a blocker stops simply reaches `adError` with `adblock`; carry on.

## Next steps

- [Monetisation by genre](https://docs.zokogames.com/guides/monetisation-by-genre)
- [Audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads)

---

Source: https://docs.zokogames.com/guides/multiplayer-invites

# Multiplayer and invites

This guide shows how to connect your game's rooms to the portal's social layer: announcing a room, producing invite links, handling friends' invites and testing it all with two browser tabs. The portal's social layer (rooms, friends, invites) is what this guide covers. Since SDK 1.3.0 the portal can also carry small gameplay messages and a shared state between the players of a room (see [the room data channel](#6-exchange-game-data-in-the-room)); bigger or authoritative traffic stays on your own servers. Signed-in players see an **Invite friends** tray under the game that lists their friends with an Invite button, plus a **Copy invite link** button. Your game tells the portal which room the player is in, and the portal turns that into an invite.

The requirements are on the [multiplayer page](https://docs.zokogames.com/requirements/multiplayer); the method reference is in the [game module](https://docs.zokogames.com/sdk/game#rooms-and-invites). This guide is the order to do it in. Examples assume `const SDK = window.ZokoGames.SDK;` and `await SDK.init();` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## How the pieces fit

| Piece | What it does |
| --- | --- |
| `updateRoom({ roomId, isJoinable, inviteParams })` | Tells the portal "this player is in this room". While `isJoinable` is true the **Invite friends** button shows under the game. |
| Invite (friend list) | The host presses Invite on a friend. See [the friend invite flow](#the-friend-invite-flow). |
| `inviteLink(params)` | The game page's URL with your parameters added as query parameters. Players paste it anywhere. |
| `inviteParams` / `getInviteParam(key)` | Every query parameter the game page was opened with, as strings. Read them at start. |
| `addJoinRoomListener(fn)` | Fires when an invite is accepted **while your game is already open**, so you can move the player into the room without a reload. |
| `isInstantMultiplayer` | `true` when the page was opened with `instantJoin=true` ("play together"): skip the menu and go straight to a lobby. The old name `isInstantJoin` still works. |

`showInviteButton(params)` and `hideInviteButton()` are deprecated aliases of `updateRoom({ isJoinable: true, inviteParams })` and `updateRoom({ isJoinable: false })`. New code should call `updateRoom`. They stay because the portal's button follows the room, which a game without rooms cannot use. From SDK 1.7.0 the same two methods take `{ portalOnly: true }`: `showInviteButton(params, { portalOnly: true })` shows the portal's **Invite friends** button with `params` in the link it shares and resolves that link, `hideInviteButton({ portalOnly: true })` hides it again, and neither creates a room or changes `isJoinable`. The `params` follow the same rules as `inviteLink` (a flat object of strings; the page that opens the link keeps a parameter only within the limits listed above). The ask resets when the game reloads, and an `updateRoom` that sets `isJoinable` hands the button back to the room. There is no button in kids mode.

Rooms and presence need a signed-in player. For guests, `updateRoom` succeeds and nothing is announced. A guest with a joinable room can still share the link directly from the button; a guest without one is asked to sign in.

## The friend invite flow

1. Your game calls `updateRoom` with `isJoinable: true`. The **Invite friends** button appears under the game for multiplayer games and whenever a room is joinable.
2. A signed-in host opens the tray, which lists friends, and presses **Invite** on one. The tray also has a copy-link button.
3. The invite is delivered live to the friend, and a copy is stored so it is still in their notifications later. The friend sees a toast, "{name} invited you to play {game}.", with an **Accept** button, for 15 seconds. Accepting from the toast or from the notification list is the same action.
4. If the friend is **not** in your game, accepting opens the game page with the invite parameters in the address, and your game reads them at start. If they are **already on the game's page**, nothing reloads: your `addJoinRoomListener` callback receives the parameters.
5. The friend needs notifications for invites switched on to see the live toast; the stored notification is kept either way.

Limits worth knowing: only friends can be invited; a host can send 20 invites per hour; a second invite to the same friend for the same game within 2 minutes is treated as a duplicate and not sent again; blocked players and banned accounts cannot be invited.

### What arrives in the parameters

The parameters are the ones you passed in `inviteParams`, plus `roomId`, which the portal always adds (generating one if you omitted it). The same set is in the address as query parameters and in `SDK.game.inviteParams`.

- At most 16 parameters; keys of 1 to 40 letters, digits, `_`, `.` or `-`; values are strings up to 200 characters. The keys `__proto__`, `constructor` and `prototype` are not allowed.
- `roomId` is 1 to 64 letters, digits, `_`, `.` or `-`.
- `inviteParams` returns **every** query parameter on the page address, so it also contains things such as `instantJoin`, `utm_*` or parameters you did not set. Read only the keys you expect and validate them.
- It is `null` when the address has no query string.
- The parameters you pass to `updateRoom` are checked by the portal against the limits above. If one key or value breaks them, **all of your `inviteParams` are dropped silently** (the room is still announced with only `roomId`), and the call does not reject. Keep them short and flat. Keep parameters small, such as a room code or a level id, and test them in the Preview tool before you publish.
- In the portal the address is the **portal page's** address (`/game/<slug>?room=abc`), which the portal passes through to your game; your own game page's address is not used.

The portal limits above apply to what your game sends. The page that hosts your game then filters the query string once more, with one rule, before it fills `inviteParams`: a parameter is kept when its key has 1 to 64 characters from `A-Z a-z 0-9 _ . -` (it may start with a digit or `_`) and its value is any text of up to 256 characters without control characters. At most 30 different keys are kept, and when a key repeats, the last value wins. Only the kinds of parameter in the table are dropped, each on its own; the rest still arrive. The names `roomId`, `instantJoin`, `ref`, `useLocalSdk`, `sdk_debug`, `utm_*` are always accepted as key names, but their values are still checked.

| What | Result | Why |
| --- | --- | --- |
| Every other key and value: values with `/`, `=`, `?`, `%`, spaces or non-Latin letters, and keys that start with a digit or `_` | Kept | These are ordinary game data (a room, a mode, a level, a map link). |
| A key named like a secret or a navigation target of the portal: `token`, `access_token`, `id_token`, `refresh_token`, `jwt`, `bearer`, `csrf`, `otp`, `password`, `pass`, `pwd`, `secret`, `sig`, `signature`, `session`, `auth`, `reset`, `verify`, `verification`, `magic`, `email`, `mail`, `next`, `return`, `returnTo`, `redirect`, `redirect_uri`, `callback`, `callbackUrl`, `apikey`, `ticket`, `nonce`, and `code`, `key`, `state` when they are the whole key. Matching ignores case and also finds the word inside a longer key (`reset_token`, `authCode`, `magicLink`). A key that also has a game word (`room`, `game`, `level`, `map`, `mode`, `lobby`, `match`, `team`, `invite`, `player`, `seed`) is kept: `roomCode`, `roomHash`, `gameState`, `inviteKey` pass. | Dropped | A sign-in, verification or reset token, a one-time code, an email address or a redirect target in a portal address must never reach a game. |
| A value shaped like a JWT, or containing 64 or more unbroken letters, digits or `+`, `/`, `_`, `=`, `-` | Dropped | It looks like a credential, whatever the key is called. |
| A key with other characters or more than 64 characters, a value of more than 256 characters or with a control character, and every key after the 30th | Dropped | It is not valid invite data, or there are too many of them. |

Example 1: a link whose parameters all pass.

```text
/game/my-game?room=abc&mode=ranked&level=12&name=Zo%C3%AB%20%C3%9Cnal
-> { room: "abc", mode: "ranked", level: "12", name: "Zoë Ünal" }
```

Example 2: `token=` is dropped, `roomCode=` is kept.

```text
/game/my-game?token=abc123&roomCode=ABCD&mode=ranked
-> { roomCode: "ABCD", mode: "ranked" }
```

Put secrets in your own backend, never in an invite link.

## 1. Join from the page address

```js
await SDK.init();

const roomFromLink = SDK.game.getInviteParam("room");
if (SDK.game.isInstantMultiplayer) startMatchmaking();
else if (roomFromLink) joinRoom(roomFromLink);
else showMenu();
```

## 2. Announce the room you host

Create your room on your server, then tell the portal. Use the same id you will put in the link.

```js
async function hostRoom() {
  const room = await myServer.createRoom({ max: 4 });              // your own backend
  await SDK.game.updateRoom({
    roomId: room.id,                                               // letters, digits, _ . - (64 characters max; anything else is replaced by _)
    isJoinable: true,
    inviteParams: { room: room.id },                               // flat map of strings only
  });
  copyBtn.onclick = async () => navigator.clipboard.writeText(await SDK.game.inviteLink({ room: room.id }));
}
```

If you omit `roomId`, the portal generates one and always adds it to `inviteParams` as `roomId`. The portal shows the room's capacity as the game's maximum lobby size, capped at 100.

## 3. Update and leave

```js
await SDK.game.updateRoom({ isJoinable: false });                  // room full or round started
await SDK.game.leftRoom();                                          // the player left the room
```

Call `updateRoom` again when the room changes, and `leftRoom` on exit, disconnect and when the game goes back to the menu.

## 4. Handle invites accepted mid-game

```js
SDK.game.addJoinRoomListener(async (params) => {
  if (currentRoom) await leaveCurrentRoom();
  await joinRoom(params.room);
});
```

## 5. Respect chat settings

```js
const apply = (s) => { chatPanel.hidden = s.disableChat; };
apply(SDK.game.settings);
SDK.game.addSettingsChangeListener(apply);
```

Chat needs moderation (a profanity filter and a report option) and must never render raw HTML from other players.

## 6. Exchange game data in the room

Once the player is in a room you can send messages to the other members with `SDK.game.room.send(data, { to })`, receive them with `onMessage`, and keep a small host-written state with `setState` / `onState`. The sender id is added by the platform. (Each `on*` also exists as `addMessageListener` / `removeMessageListener` and so on.) Watch `onHostChange`: when the host leaves, the longest-standing member becomes host. Limits are 8 KB per message, 20 per second per player and 64 KB of state; the full reference, error codes and a 40-line example are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel). This is not a text chat, so `disableChat` does not apply to it.

## Test with two tabs

1. Serve the game on `localhost` and open `http://localhost:8080/?sdk_debug=true` (`sdk_debug=true` logs every SDK call to the browser console).
2. Host a room. In local mode `inviteLink` returns your own page address with the parameters added, for example `http://localhost:8080/?sdk_debug=true&room=abc`.
3. Open that link in a second tab (or an incognito window). In local mode `inviteParams` is every query parameter of the page (here `{ sdk_debug: "true", room: "abc" }`), `getInviteParam("room")` returns `"abc"` and `?instantJoin=true` makes `isInstantMultiplayer` true, so the "join from the address" path can be tested fully. Open the link without a query string and `inviteParams` is `null`.
4. The local host does not simulate friends' invites or join events: `addJoinRoomListener` never fires. `updateRoom` joins the local room channel, so two tabs that use the same `roomId` can exchange `SDK.game.room` messages and shared state (each tab is a member; the first is the host), and `leftRoom` leaves it. To exercise those, load the game in the [Preview tool](https://www.zokogames.com/preview) and use the event log to confirm the `updateRoom` and `leftRoom` calls arrive, then test the real invite tray with two accounts on the live portal. For a guest, `updateRoom` still resolves but nothing is announced to friends.

## Checklist

- [ ] `updateRoom` on create and join; `leftRoom` on leave.
- [ ] If you use `SDK.game.room`: messages stay under 8 KB and 20 per second, host changes are handled, and no free text is sent without moderation.
- [ ] Parameters from `inviteParams` joined at start; join listener registered.
- [ ] `isInstantMultiplayer` skips the menu.
- [ ] Lobby sizes in the listing match the game; a full room sets `isJoinable: false`.
- [ ] A dropped player does not freeze the room; your server being down shows a message, not a hang.

For the room API in detail, see [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms).

## Next steps

- [Multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms)
- [Multiplayer](https://docs.zokogames.com/requirements/multiplayer)

---

Source: https://docs.zokogames.com/guides/offline-play

# Making a game playable offline

This guide shows how to make your game eligible for **Save for offline** and how to design it for play with no connection. Players can save a game to their device and play it with no internet connection: on a train, on a plane, or on a flaky phone signal. The option appears in the **More** menu of the game bar as **Save for offline**, and saved games are listed on the player's **Offline games** page. Unfamiliar terms (build, active build, origin) are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

Nothing is installed. The browser stores your build's files for the game's own origin, and our player starts the game from that copy when the network is not there.

## Turning it on

Open your game in the developer console and, under **Video and multiplayer extras**, tick **Allow save for offline**. The option only reaches players when the **active build** also passes every check below. Admins see the opt-in, and anything blocking it, in the review view.

| Check | Requirement |
| --- | --- |
| Hosting | The game is hosted by ZokoGames (an uploaded build, not your own server) |
| Build size | 60 MB or less, as stored (pre-compressed `.br` / `.gz` files count at their compressed size) |
| Multiplayer | The game is not listed as multiplayer |
| External hosts | The build validator found no references to hosts outside the platform |
| Upload date | The build was uploaded after offline support shipped (older builds have no file list: upload the build again) |

When you publish a new build, players who saved the game get it automatically the next time they open the game page online. The old copy is deleted only after the new one has downloaded completely.

## What gets saved

Every file of the build, exactly as uploaded, plus the platform files your build loads from outside its folder:

- the SDK script from `https://sdk.zokogames.com/...`
- per-game helpers under `/sdk/` and `/_shared/`

Files are checked against the size and SHA-256 recorded when you uploaded the build. Anything the build fetches from elsewhere at runtime is **not** saved, which is why external hosts make a build ineligible.

Keep every asset inside the zip and load it with relative URLs (`assets/level1.json`, not `/assets/level1.json` or a CDN URL). Files the game builds at runtime, such as `blob:` URLs, are fine.

## How the SDK behaves offline

| Feature | Offline behaviour |
| --- | --- |
| `init` / handshake | Answers at once from local state; it never waits for the network |
| Player | The last player signed in on this device, or a guest |
| Data module (cloud saves) | Reads and writes the device copy; changes upload when the connection returns, with the usual conflict check against saves made on another device |
| Video ads (`requestAd`) | Fail straight away with `unfilled`: carry on as you would with no fill |
| Banners | Not shown |
| Leaderboard scores (`submitScore`) | Resolves without recording. Offline, the score is not lost if you also pass `delayed`: a copy sealed at the end of the run with `earnedAt = Date.now()`, additional data `zoko-score-v3|<userId>|<gameId>|<earnedAt>` and plaintext `<score>|<earnedAt>`. The portal keeps it on the device for a signed-in player (keyed boards only, never in kids mode) and sends it when they are back online, within 72 hours. It counts for the all-time board only, not the weekly board. Without `delayed`, or on a portal older than SDK 1.6.4, an offline score is not queued. On a game with a leaderboard (never in kids mode), the offline notice over the game tells the player: **Scores are not saved while you're offline.** See [Offline scores](https://docs.zokogames.com/sdk/leaderboards#offline-scores). |
| Play events (`gameplayStart`, `trackOrder`) | Not recorded; nothing is queued for later |
| Friends, invites, purchases | Unavailable; calls fail with their normal network errors |

To react to the connection in your own code, use the SDK (1.2.0 and later). The portal keeps the flag current when the browser goes offline or back online, and sets it from the start when the game is launched from the **Offline games** library:

```js
const SDK = window.ZokoGames.SDK;
await SDK.init();

function onNetwork(offline) {
  // hide your "global leaderboard" button, show a small offline badge, ...
}
onNetwork(SDK.game.isOffline);
SDK.game.addOfflineListener(onNetwork); // receives the new boolean on every change
// SDK.game.removeOfflineListener(onNetwork);
```

In local mode (a game opened outside the portal) `isOffline` mirrors `navigator.onLine`, and `?offline=true` on the page URL pins it to `true` so you can test the offline paths without touching your network. On a portal that does not send the flag, `isOffline` stays `false`.

**Older SDK versions** (before 1.2.0) have no such members. Fall back to the browser's own state, which is accurate inside the game frame:

```js
function onNetwork() {
  const offline = !navigator.onLine;
}
window.addEventListener("online", onNetwork);
window.addEventListener("offline", onNetwork);
onNetwork();
```

To support both, use `SDK.game.addOfflineListener ? SDK.game.isOffline : !navigator.onLine`, and register the `online` / `offline` listeners only in the second case.

## Designing for offline play

- **Treat ads as optional.** A rewarded ad that fails with `unfilled` should not block progress. Offer the reward another way, or skip it.
- **Save small and often.** The data module keeps the device copy, and the upload queue survives a closed tab. See [Cloud saves in practice](https://docs.zokogames.com/guides/cloud-saves).
- **Do not require a fresh download on start.** Version checks, remote config and analytics beacons must time out quietly.
- **Test it.** Once the game is live (basic launch or later), open its page on the portal, choose **Save for offline** in the **More** menu and wait for it to finish. Then open your browser's developer tools, switch the network to *Offline* and reload the page. The game must reach its first frame, and you should see it listed on your **Offline games** page. To test your offline code paths without the portal, run the game on `localhost` with `?offline=true` (see above); that pins `SDK.game.isOffline` to `true` but does not test saving.
- **Ad-blocked and guest players** behave as online ones do: guests get the guest save on the device, and a blocker changes nothing here because offline ads fail with `unfilled` anyway.

## Storage and removal

Players see the total space used on the **Offline games** page, and can remove one game or all of them. Browsers may also clear saved games when the device runs low on storage. The game then plays online again until the player saves it once more. In kids mode only games made for kids can be saved.

## Next steps

- [Cloud saves in practice](https://docs.zokogames.com/guides/cloud-saves)
- [Getting to the first frame fast](https://docs.zokogames.com/guides/first-frame)

---

Source: https://docs.zokogames.com/guides/basic-launch-metrics

# Basic launch metrics explained

This guide explains the four numbers a reviewer uses to decide whether your game moves from basic launch to full launch, what each target is and how to improve it. During basic launch your game is live with ads off, and we use that traffic to learn whether it deserves a full launch (see [launch stages](https://docs.zokogames.com/getting-started/launch-stages); other terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary)). Everything is measured automatically, but plays and play time are counted only when your game calls `gameplayStart` and `gameplayStop`:

```js
const SDK = window.ZokoGames.SDK;
await SDK.init();
await SDK.game.gameplayStart();   // when real play begins (after menus and loading)
await SDK.game.gameplayStop();    // on game over, pause or return to the menu
```

On your own `localhost` page these calls send nothing, so the launch card stays empty until the game is live. Exact definitions of every metric are in the [metrics reference](https://docs.zokogames.com/guides/analytics-metrics).

## How long it lasts

The basic launch window is over once the game has been live for at least **7 days and has reached 500 plays**, or after **21 days** whatever the plays, whichever applies first. The game is then flagged for a reviewer, who decides: promote to full QA, extend for another round, or end it. Updates you upload during basic launch go live right away. The console's launch card shows days live, plays and each metric against its target. Statistics update hourly, and next-day retention appears a day later than the other numbers. The card counts from the start of the stage, so its numbers can differ from the Performance section, which covers the range you pick and ends yesterday. These numbers are defaults: the portal team may adjust the window, and the console shows the values that apply to your game.

## The numbers

| Metric | What it measures | On target | Weight |
| --- | --- | --- | --- |
| Average play time | Play time per session among players who allow analytics (sessions are capped at 30 minutes) | 10 minutes or more (half credit from 5 minutes) | 30 % |
| Day-1 retention | Share of players who return the next day | 15 percent or more is full marks; 10 to 15 percent is close; 5 to 10 percent earns a little | 30 % |
| Conversion | Share of views whose session lasts at least a minute | 80 percent or more (half credit from 60 percent) | 20 % |
| Click-through rate | Share of people who saw your tile and opened it, ranked against other games in your category | The 50th percentile or better (half credit from the 25th) | 20 % |

Click-through shows "Not enough data yet" while your tile has not been shown in any list or no other game in your category can be compared with; it is not judged as a miss. Load time and initial download are not scored, but they drive conversion: see [first frame fast](https://docs.zokogames.com/guides/first-frame).

The portal combines these into a score between 0 and 1 and gives the reviewer a **recommendation**: *promote* at 0.75 or more (with play time and retention both above zero), *end* below 0.4, otherwise *extend*. With fewer than 200 plays the data is too thin and the recommendation is always *extend*.

> [!NOTE]
> The score is advice, never a decision. A reviewer weighs the numbers together with quality, so meeting every target does not guarantee promotion and missing one does not always rule it out.

## Improving each metric

**Conversion** is mostly about the first minute: load time, a game that starts quickly, no wall of menus. See [first frame fast](https://docs.zokogames.com/guides/first-frame). If conversion is low and load time is high, shrink the build first.

**Play time** comes from depth. Add a reason to play another round: progression, unlocks, variety, goals the player sets.

**Retention** comes from reasons to return: daily rewards, progress saved through the [data module](https://docs.zokogames.com/sdk/data), things that change from day to day, and a first session that ends on "I want to try that again".

**CTR** is the cover and the title, compared with other games in your category. Use [artwork experiments](https://docs.zokogames.com/guides/artwork-experiments) once your game is in full launch, and follow the [cover specs](https://docs.zokogames.com/requirements/covers) now.

## Reading the dashboard

- Compare against games in your category, not the whole portal.
- A small sample swings widely. Judge trends over days, not hours.
- Split by device. A great desktop game with poor mobile conversion often has a touch-control or size problem.
- If a number looks wrong, check the preview tool and the console log for errors first.

## After basic launch

A promotion needs the full SDK integration, so prepare it while you wait: gameplay start and stop, ads at natural breaks, cloud save. See the [requirements overview](https://docs.zokogames.com/requirements/overview).

## Next steps

- [Analytics and metrics reference](https://docs.zokogames.com/guides/analytics-metrics)
- [Artwork experiments](https://docs.zokogames.com/guides/artwork-experiments)

---

Source: https://docs.zokogames.com/guides/analytics-metrics

# Analytics and metrics reference

This page defines every number on the **Dashboard**, the **Analytics** page, a game's **Performance** and analytics sections and the **Revenue** page of the developer console, exactly as the portal computes it today. Read it before you compare two numbers, tune a game against a launch target or question a drop. Unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## What your game must do

Nothing is instrumented for you except the two calls that start and stop a play. Call them around real gameplay (not around menus or loading), once per play:

```js
const SDK = window.ZokoGames.SDK;
await SDK.init();

startRound();                     // your code
await SDK.game.gameplayStart();   // counts one play and starts the playtime clock
// ... the player plays ...
await SDK.game.gameplayStop();    // ends the clock; also call it on pause, game over and menu
```

Both calls are asynchronous. In local mode (your own `localhost` page) they resolve and send nothing, so the console stays empty until the game is live. When the player has not allowed analytics cookies, the play is still counted but its playtime is missing (see the consent section). A game that never calls `gameplayStart` records no plays and no playtime, whatever players do.

The SDK side (`SDK.analytics`, `trackOrder`) is on the [analytics module page](https://docs.zokogames.com/sdk/analytics); `trackOrder` counts one anonymous order event per accepted call and does not store the order itself. For the launch targets built on these numbers see [basic launch metrics](https://docs.zokogames.com/guides/basic-launch-metrics) and [launch stages](https://docs.zokogames.com/getting-started/launch-stages).

## Where the numbers come from

Three sources feed the console:

1. **Game events.** The portal's player frame sends events to the portal's own event endpoint: a *view* when the player presses Play, `gameplay_start` and `gameplay_stop` when your game calls `SDK.game.gameplayStart()` and `gameplayStop()`, and the ad events below. Each event is stored with a device class and a country (from the request) and, only with consent, a random visitor id.
2. **Tile counters.** Game tiles on the portal report *impressions* and *clicks* as anonymous daily counters. No visitor id is sent or stored for them.
3. **Revenue.** Gross revenue is **imported** by the portal team from the ad provider's reports. It is not computed from events.

Events from games that are not live (drafts, games in review, the Preview tool) are ignored. Only games in basic launch, full QA or full launch are counted.

## Definitions

| Metric | Exactly what it is |
| --- | --- |
| **Plays** | Number of `gameplay_start` events. A play is counted when **your game calls `gameplayStart()`**; the portal does not infer it. A game that never calls it records no plays and no playtime. |
| **Views** | Number of times a player pressed Play and the game loaded in the frame. |
| **Players** | Distinct visitors per day, added up over the days of the range. Someone who plays on three days counts three times. |
| **Playtime** | For each `gameplay_start`, the time until the next `gameplay_stop` of the same visitor, capped at **30 minutes**. A start with no stop (or followed by another start) adds 0 seconds. A session belongs to the day it started. |
| **Average playtime** | Playtime divided by plays, both counted only for players who allowed analytics (only they record a stop). |
| **Conversion** | Sessions of at least **60 seconds** divided by views. |
| **Impressions** | A tile was at least 50 % visible for at least 1 second while the page was visible, counted **once per tile per page view** (a client-side navigation starts a new page view). One impression per game and surface per batch; a game can sit on several surfaces of one page. |
| **Clicks** | A click on a tile link that opens the game page. At most one per game per batch. |
| **CTR (click-through rate)** | Game views divided by tile impressions for the same visitors (see the consent section). Never above 100 %. In an artwork experiment the per-arm CTR is tile clicks divided by impressions of that arm. |
| **Ad requests** | `ad_started` events: every ad the portal asked a provider to play. |
| **Ad impressions** | `ad_impression` events: an ad the provider actually displayed. A rewarded ad the player closed early after it appeared still counts as an impression, without the reward. |
| **Fill rate** | Ad impressions divided by ad requests. Shown as a dash until your game has requested an ad. |
| **eCPM** | Gross revenue divided by ad impressions, times 1,000. Shown as a dash until an ad has been shown. |
| **D1 retention** | Of the players seen on a day, the share who show up again the **next** day. |
| **D7 retention** | Same, seven days later. Only days that already have a day 7 are counted. |
| **D30 retention** | Same, thirty days later. The **Retention by day played** table shows day 1, 7 and 30 for each day: everyone identified who played that day, new or not, so a player who plays on several days is in each of them. |
| **New and returning players** | A visitor is *returning* for a game when they had any event for it on an earlier day, otherwise *new*. Based only on identified visitors (see below). |
| **Rating** | Thumbs up divided by all votes, over the lifetime of the game. |

The CSV downloads and the developer API name the same figures with fixed column names, which do not change with the console's language:

| Column | Console name |
| --- | --- |
| `gameplays` | Plays (Games started in the funnel) |
| `views` | Views (Play pressed in the funnel) |
| `impressions` | Impressions (Shown in a list in the funnel) |
| `players` | Players |
| `playtime_sec` | Playtime, in seconds |
| `avg_playtime_sec` | Average playtime, in seconds |
| `d1_retention`, `conversion`, `ctr`, `fill_rate` | Day 1 return, Conversion, Click-through, Ad fill rate, as fractions from 0 to 1 |
| `ad_requests`, `ad_impressions` | Ad requests, Ad impressions |
| `revenue_usd`, `gross_usd`, `share_usd`, `ecpm_usd` | Revenue, Gross revenue, Your share, eCPM, in the currency the name ends with |
| `share` (country and device files) | Share of plays, as a fraction from 0 to 1 |
| `plays` (country and device files only) | Plays. These two files predate the others and name this figure `plays`; everywhere else it is `gameplays` |
| `day`, `game` and `slug`, `country` or `device` | The row's key: a UTC date (`YYYY-MM-DD`), the game's name and address slug, or the country code or device class (`other` folds in groups under five players) |

The columns of a game's table on screen are all in its CSV except eCPM, which the file leaves out (divide `revenue_usd` by `ad_impressions` and multiply by 1,000). The "By player type" file is built in the browser from the table and uses the same names.

Every CSV starts with a UTF-8 byte order mark, so Excel shows accented and non-Latin game names correctly; a script that reads the file as plain UTF-8 should strip it (in Python, open the file with `utf-8-sig`). A rate that cannot be calculated, such as click-through on a day with no impressions or retention on a day nobody played, is an **empty cell**, the same as the dash on screen; a count of nothing is `0`. The per-game file lists every game of the studio, with zeros for a game that had no activity in the range.

Ad breaks that an ad-free member skips (see [player features](https://docs.zokogames.com/guides/player-features)) request no ad and are not counted at all.

## What needs player consent

Players choose cookie categories in the portal's consent banner. Kids mode and kids games turn every optional category off. The split matters for reading your numbers:

| Event | Needs the *analytics* category? |
| --- | --- |
| `gameplay_start` (plays), `ad_started`, `ad_impression`, `ad_finished` | **No.** Always recorded, as anonymous aggregate rows with no visitor id. `order` events work the same way: `SDK.analytics.trackOrder` sends one, counted anonymously. |
| Views, `gameplay_stop`, loading, happy time, completion | **Yes.** Not sent without it. |
| Tile clicks, and impressions in experiment arms | No. Counters only. |
| Tile impressions in the all-traffic numbers (the denominator of CTR) | **Yes.** Counted only for visitors who allowed analytics, so the CTR numerator and denominator come from the same group. |

Effects you will see:

- **Rates compare the same players.** Playtime needs a recorded stop, which only consenting players produce, so average playtime, conversion, CTR, retention and plays per player are measured among consenting players on both sides of the division. Plays still count everyone, so plays can be far higher than views.
- **Views, conversion, CTR and impressions cover consenting players only.** They are a sample, not a census, and can be lower than the real total.
- **Retention follows consenting players.** Visitors who did not allow analytics have no id, so they cannot be followed from one day to the next. They share one anonymous id, which never counts as returned.
- **Players is a floor.** Non-consenting visitors collapse into one anonymous id per game, country, device and day.
- **New versus returning** includes only identified visitors; anonymous traffic appears only in the "all players" view.
- **Country and device breakdowns.** Plays count everyone and players count only players who allow analytics, with one exception: for days recorded before consenting players were stored separately, and for groups made up only of visitors who did not allow analytics, the player count falls back to all traffic, where those visitors count as one. When a row has no consenting plays on record, its playtime per play is shown as unknown rather than estimated.

The console says so next to the figures ("counts only visitors who allowed analytics"). Compare periods and games with the same audience mix, and judge trends rather than single values. Small samples swing: below 100 plays in a range the console shows a "not enough data" notice. In the country and device splits (and browser and system on a game page), rows with fewer than five players are grouped under **Other** on screen and in the CSV, so a small group of players cannot be singled out; when no row reaches five players, the split says it is held back instead of listing anything.

## Days and time zones

Every day boundary is **midnight to midnight UTC**, in the charts, the CSV exports, retention and the statements. The periods are complete days ending yesterday: the dashboard totals cover the last 30, a game's Performance and the Analytics page open on 28, and Analytics also offers 7, 30 and 90. The thumbs-down card on a game's Feedback page is the exception: it counts the last 7, 30 or 90 days up to now, by the time of the vote. A game popular late in the evening in the Americas can show those plays on the next UTC day. A session is attributed to the day it started, even if it ends after midnight.

## When numbers update

| What | Refreshes |
| --- | --- |
| Plays, views, playtime, ad counts, retention | A scheduled job runs **hourly, at five past the hour**. It recomputes yesterday and today from the raw events, so a day settles once the job after midnight has run. |
| Tile impressions and clicks | Added to today's counters immediately. |
| D1 retention of a day | Needs the following day, so it appears after the job that rolls the next day. The newest day shows a lower number until tomorrow. |
| D7 retention of a day | Needs seven more days. |
| Revenue, eCPM | When the portal team imports the provider's figures; usually later than the counts. Estimates until the month closes. No ad network is connected yet, so both stay empty for now. |
| Launch KPIs | A separate hourly job snapshots them for reviewers. |

Raw events are kept for a limited time and rolled into daily totals; retention for the oldest cohorts is derived from what is still stored.

## Limits that can drop events

The event endpoint is public, so it bounds each client:

- Per IP address and game, per day: 40 views, 60 gameplay starts, 120 ad requests, 120 ad impressions and 120 ad finishes. Further events are dropped silently.
- Ad events are accepted only for games in full launch with ads enabled that are not kids games, at most one ad request or impression per IP and game every 10 seconds. An ad impression must carry the short-lived ticket returned for its ad request.
- Tile batches are capped (40 items, 5 per game and kind), bots are ignored, and each IP has hourly and daily budgets.
- Many players behind one shared address (a school or office network) can hit a per-IP cap.

## Reading it in practice

- In **basic launch** ads are off, so Revenue, Ad impressions, Ad fill rate and eCPM show a dash under "Ads are off in Basic Launch" instead of 0. Only a few basic launch games are placed on category, tag and New lists, so Impressions can stay low and Click-through empty; plays from your own links still count.
- Use **plays per player**, **average playtime** and **D1** together; any one alone misleads.
- Split by device and country before concluding anything. See [mobile](https://docs.zokogames.com/guides/mobile).
- A fill rate below 100 % is normal: it falls when an ad blocker is detected, the provider has nothing to show, or the break was capped.
- eCPM is revenue-side only. Compare it across periods, not with player counts.

## Next steps

- [Basic launch metrics explained](https://docs.zokogames.com/guides/basic-launch-metrics)
- [Developer API reference](https://docs.zokogames.com/guides/developer-api)

---

Source: https://docs.zokogames.com/guides/webhooks

# Webhooks

A webhook makes our servers send a signed `POST` request to your server when something changes in your studio. Use it to post to a chat channel, start your own pipeline when a build goes live, or keep an internal dashboard in step, instead of polling the console.

Webhooks belong to the studio, not to one game. Owners and admins manage them on the **Webhooks** page of the developer console.

## Set one up

1. Open **Webhooks** in the console and choose **Add an endpoint**. Adding an endpoint asks you to confirm it is you with a passkey or an authenticator app; if you have neither yet, set one up first in your player account on zokogames.com (console account menu, **Settings**, then **Account**).
2. Enter an `https://` address (up to 500 characters), an optional description (up to 120 characters) and the events you want. Each event is described in the Events table below with an example payload under Payload examples. The address must follow the rules under Which addresses are accepted: public `https` on port 443, so use a tunnel while developing locally, and the console says which rule an address breaks before it saves.
3. Copy the **signing secret** (it starts with `whsec_`). It is shown once. If you lose it, use **Rotate secret**; the old one stops working at once. Rotating the secret asks for the same confirmation. A delivery your server refuses during the switch is retried, and every retry is signed with the secret current at that moment, so once your server has the new secret the retries verify (a **Send test** ping is never retried).
4. Press **Send test**. A `ping` event is delivered immediately and the result (HTTP status or error) is shown. Open **Show the exact request and response** under it to see the headers and body we sent (including the signature, so you can compare it with your own) and the status line, content type and first 1 KB of the body your server answered. That detail is not stored; it stays on screen until you leave the page.

A studio can have up to **5** endpoints. Use **Edit** on an endpoint to change its address, description or events; the signing secret stays the same, and changing the address or events asks for the same confirmation as adding one. You can pause and resume an endpoint without losing it. The console keeps the **50** most recent delivery results for the studio, with time, event, status and duration, and a delivery history that shows every event with its status, attempts, next retry and response code. The delivery history can be filtered by status (delivered, retrying, dead) and by endpoint. While an endpoint has failing deliveries, its card says how many are waiting or dead, the latest problem, and how many dead deliveries in a row switch it off.

## Events

| Event | Sent when | `data` fields |
| --- | --- | --- |
| `review.outcome` | A reviewer approved, rejected or asked for changes. | `gameId`, `gameSlug`, `gameName`, `outcome`, `note`, `rejectionReasons` (list) |
| `build.published` | A new build passed validation and was stored. It is not necessarily live: a build of a live game, and every build uploaded with an API token, stays inactive until someone activates it (watch `build.activated`). | `gameId`, `gameSlug`, `buildId`, `version` (the build number, an integer: 1, 2, 3...), `totalBytes`, `fileCount`; only for a build uploaded with an API token (CI): `uploadedBy`, an object with `type` (`api_token`), `id` and `name` of the token |
| `build.activated` | A build became the live version, including a rollback. | `gameId`, `gameSlug`, `buildId`, `version` (integer build number), `previousBuildId` |
| `feedback.replied` | Someone on your team replied to player feedback. | `gameId`, `feedbackId`, `subject`, `emailed`, `resolved` |
| `leaderboard.reset` | Leaderboard scores were reset. | `gameId`, `gameSlug`, `scope`, `season` (the running season as an ISO week string, such as `2026-W47`, also for `scope: "all"`), `deleted` (rows removed) |
| `statement.created` | The monthly payout statement for your studio was created (on the second day of the next month). Not sent for a statement that already existed. | `statementId`, `period` (`YYYY-MM`), `state`, `payableMicros`, `currency` |
| `statement.updated` | A statement was marked paid, or the portal team held or released it. | `statementId`, `change` (`paid`, `held` or `released`), `period`, `state`, `payableMicros` (`null` when the amount is settled by hand), `currency`, `paidAt` and `paidReference` (set only when `change` is `paid`), `paidMicros` and `heldBackMicros` (what was actually sent and what the new-studio holdback kept back; set only when `change` is `paid`, otherwise `null`) |
| `feedback.received` | A player sent feedback about one of your games: a report, a message to your studio or a reason after a thumbs-down. Not sent for kids games. | `feedbackId`, `gameId`, `gameSlug`, `gameName`, `kind` (`report`, `developer` or `dislike`), `subject`, `message` (up to 2,000 characters, may be empty), `gameContext` (what the game set with `setGameContext`, or `null`) |
| `experiment.finished` | A cover experiment ran its full 14 days and is ready for a winner decision. Not sent when you stop an experiment yourself. | `experimentId`, `gameId`, `gameSlug`, `gameName`, `name`, `type` (`covers`, `videos` or `both`), `startedAt`, `endedAt`, `winnerSuggested` (`variant`, `baseline` or `inconclusive` from the click-through test; `null` if it could not be computed) |
| `ping` | You pressed **Send test**. Cannot be subscribed to. | `message`, `studio` |

## The request

```http
POST /hooks/zoko HTTP/1.1
Content-Type: application/json
User-Agent: ZokoGames-Webhooks/1
X-Zoko-Event: build.published
X-Zoko-Delivery: 6f1c2d1e-8a54-4e0b-9a39-0f4c9a5b7d10
X-Zoko-Event-Id: 6f1c2d1e-8a54-4e0b-9a39-0f4c9a5b7d10
X-Zoko-Attempt: 1
X-Zoko-Signature: t=1763424000,v1=5b1f...c9
```

```json
{
  "id": "6f1c2d1e-8a54-4e0b-9a39-0f4c9a5b7d10",
  "event": "build.published",
  "createdAt": "2026-11-18T00:00:00.000Z",
  "studioId": "…",
  "data": { "gameId": "…", "gameSlug": "my-game", "buildId": "…", "version": 3, "totalBytes": 18400000, "fileCount": 212 }
}
```

`id` is the **event id**. It is the same as the `X-Zoko-Event-Id` header (and the older `X-Zoko-Delivery` header, kept for compatibility), it is unique per event and per endpoint (two endpoints subscribed to one event get different ids), and it stays the same on every retry and manual redelivery. `X-Zoko-Attempt` is the attempt number, starting at 1. The signature is made again for every attempt, so `t` is always fresh.

## Payload examples

Every request has the envelope shown above. These are the `data` objects, one per event. Values are examples.

```json
// review.outcome: outcome is changes_requested, rejected, basic_launch, full_launch or update_approved
{ "gameId": "…", "gameSlug": "my-game", "gameName": "My Game", "outcome": "changes_requested", "note": "Please fix the loading screen.", "rejectionReasons": [] }

// build.published
{ "gameId": "…", "gameSlug": "my-game", "buildId": "…", "version": 3, "totalBytes": 18400000, "fileCount": 212 }

// build.activated (previousBuildId is null for the first live build)
{ "gameId": "…", "gameSlug": "my-game", "buildId": "…", "version": 3, "previousBuildId": "…" }

// feedback.replied
{ "gameId": "…", "feedbackId": "…", "subject": "Lost progress", "emailed": true, "resolved": false }

// leaderboard.reset (scope is season or all)
{ "gameId": "…", "gameSlug": "my-game", "scope": "season", "season": "2026-W47", "deleted": 1280 }

// statement.created
{ "statementId": "…", "period": "2026-10", "state": "invoiced", "payableMicros": 1250000, "currency": "USD" }

// statement.updated
{ "statementId": "…", "change": "paid", "period": "2026-10", "state": "paid", "payableMicros": 1250000, "currency": "USD", "paidAt": "2026-12-20T09:00:00.000Z", "paidReference": "TR-1042", "paidMicros": 1250000, "heldBackMicros": 0 }

// statement.updated for a paid statement of a new studio: payableMicros is the full amount, paidMicros what was sent, heldBackMicros what the holdback kept back
{ "statementId": "…", "change": "paid", "period": "2026-10", "state": "paid", "payableMicros": 200000000, "currency": "USD", "paidAt": "2026-12-20T09:00:00.000Z", "paidReference": "0x5f2c…", "paidMicros": 160000000, "heldBackMicros": 40000000 }

// statement.updated for a statement whose amount is settled by hand (payableMicros is null, never 0)
{ "statementId": "…", "change": "held", "period": "2026-10", "state": "held", "payableMicros": null, "currency": "USD", "paidAt": null, "paidReference": null, "paidMicros": null, "heldBackMicros": null }

// feedback.received
{ "feedbackId": "…", "gameId": "…", "gameSlug": "my-game", "gameName": "My Game", "kind": "dislike", "subject": "Dislike: Too many ads", "message": "", "gameContext": null }

// experiment.finished
{ "experimentId": "…", "gameId": "…", "gameSlug": "my-game", "gameName": "My Game", "name": "Close-up cover", "type": "covers", "startedAt": "2026-11-05T00:00:00.000Z", "endedAt": "2026-11-19T00:00:00.000Z", "winnerSuggested": "variant" }

// ping
{ "message": "Test delivery from the developer console", "studio": "My Studio" }
```

The block above is annotated for reading; real payloads are plain JSON without comments.

The `note` of `review.outcome` and the `subject` and `message` of `feedback.received` and `feedback.replied` are untrusted plain text written by people (they can contain link addresses as visible text): escape them before showing them in HTML and never treat them as markup.

Fields are stable: new fields may be added to an event's `data` (appended at the end, as `paidMicros` and `heldBackMicros` were on 20 November 2026), and existing ones are not renamed or removed. Ignore fields you do not know, and never reject an event because it has one: a delivery you answer with an error is retried, and repeated dead deliveries switch the endpoint off.

## Verify the signature

Anyone who learns your URL can post to it, so check every request. The `X-Zoko-Signature` header has two parts:

- `t`: the time we signed, in Unix seconds.
- `v1`: the lowercase hex **HMAC-SHA256** of the text `"<t>.<raw body>"`, keyed with your endpoint secret (the whole `whsec_...` string).

Steps: read the **raw** request body before any JSON parsing, build `t + "." + body`, compute the HMAC, compare it to `v1` in constant time, and reject a `t` that is more than five minutes from your clock to stop replays.

:::tabs
== Node.js
```js
import { createHmac, timingSafeEqual } from "node:crypto";
import express from "express";

const SECRET = process.env.ZOKO_WEBHOOK_SECRET;
const app = express();

app.post("/hooks/zoko", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("x-zoko-signature") ?? "";
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
  const t = Number(parts.t);
  if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > 300) return res.sendStatus(400);

  const expected = createHmac("sha256", SECRET).update(`${t}.`).update(req.body).digest("hex");
  const given = Buffer.from(parts.v1 ?? "", "hex");
  const want = Buffer.from(expected, "hex");
  if (given.length !== want.length || !timingSafeEqual(given, want)) return res.sendStatus(401);

  const event = JSON.parse(req.body.toString("utf8"));
  // de-duplicate on event.id, then handle event.event
  res.sendStatus(204);
});
```
== Python
```python
import hashlib, hmac, os, time
from flask import Flask, request, abort

SECRET = os.environ["ZOKO_WEBHOOK_SECRET"].encode()
app = Flask(__name__)

@app.post("/hooks/zoko")
def zoko_hook():
    header = request.headers.get("X-Zoko-Signature", "")
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        abort(400)
    if abs(time.time() - t) > 300:
        abort(400)

    body = request.get_data()  # raw bytes, before any JSON parsing
    expected = hmac.new(SECRET, f"{t}.".encode() + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, parts.get("v1", "")):
        abort(401)

    event = request.get_json()
    # de-duplicate on event["id"], then handle event["event"]
    return "", 204
```
:::

## Delivery, retries and timeouts

- Every event is queued first and sent once straight away. If that attempt fails, we retry up to **6** more times after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 24 hours (each wait varies by up to 20 percent so retries do not arrive in a burst). These are minimum waits: the retry job runs every 15 minutes, so a retry can arrive up to 15 minutes after its wait ends. After the last attempt the delivery is marked **dead**.
- Your server must answer with a `2xx` status within **5 seconds**. Anything else, including a timeout, counts as failed and is retried. Do the real work after you respond.
- Redirects are **not followed**. Answer on the exact URL you registered.
- Deliveries are sent after the action that triggered them finishes, and a broken endpoint never blocks that action.
- Order is not guaranteed, and a retry can arrive after a newer event. Use `createdAt` to order events.
- Retries for an endpoint are also sent when a new event for that endpoint is dispatched, so a busy studio sees retries sooner.
- Only the first 64 KB of your response is read, and an event larger than 64 KB is sent with `"data": { "truncated": true }`. Every payload documented here is far smaller.
- The `ping` from **Send test** is sent once, is not queued and is never retried. Its result appears at once in the console.
- Delivered events are kept in the history for 30 days, dead ones for 90 days.

### De-duplicate on the event id

A retry or a redelivery sends the same event again, and a timeout does not tell us whether your server processed it. Delivery is therefore **at least once**: store the `X-Zoko-Event-Id` of every event you handled, and when you see one again answer `2xx` without repeating the work. Keyed on that stable id, your handler is idempotent: handling the same event twice has the same effect as handling it once. Do not use a hash of the body as the key: a retry carries the same fields and values, but the fields can come in a different order than in the first attempt (the signature is computed over the bytes of each attempt, so verify each one as received).

### Automatic switch-off

After **5** dead deliveries in a row, with no successful delivery in between, the endpoint is switched off and the studio's owners and admins get a notification. The console shows the endpoint as switched off. That in-app notice is the only message sent (no email), so check the console if events stop arriving. Fix your server and press **Re-enable**; events that were still waiting are then sent. A person pausing an endpoint is not counted as a failure.

A delivery only counts as dead after its last retry, a day and a half after the event, so an endpoint that is down is switched off after five such events, and one that gets a few events a day takes days to reach that point. Pressing **Re-enable** or a delivery that succeeds starts the count from zero.

### Events while an endpoint is paused or switched off

An endpoint that is paused or switched off receives **nothing new**: an event that happens meanwhile is not stored for it and is not sent when you resume. Only deliveries that were already queued before it stopped (waiting for a retry) are sent after **Re-enable**, and a dead one can be sent with **Redeliver** once the endpoint is on. To catch up after a break, read the current state from the [developer API](https://docs.zokogames.com/guides/developer-api) (for example `GET /api/v1/games/{id}/builds`, `GET /api/v1/statements` or `GET /api/v1/games/{id}/feedback`) instead of waiting for events that were never queued.

### Redeliver

In the delivery history, a delivery that is retrying or dead has a **Redeliver** button (owners and admins). It sends the event again immediately with the same event id and a fresh set of retries. The endpoint must be enabled.

## Which addresses are accepted

To protect everyone, endpoints must be reachable on the public internet:

- `https` only, on the default port 443, with no username or password in the URL.
- No `localhost`, `.local`, `.internal` or single-label host names.
- The host name must resolve, and **every** address it resolves to must be public. Private, loopback, link-local, carrier-grade NAT and multicast ranges are refused.
- The check runs again before each delivery, so a name that later points at a private address stops receiving events.

For local development, expose your dev server through a public HTTPS tunnel.

## Troubleshooting

| Log shows | Meaning |
| --- | --- |
| `Timed out after 5 seconds` | Respond first, work later. |
| A `3xx` status | Redirects are not followed; register the final URL. |
| `4xx` / `5xx` | Your server refused or failed; check the signature code and the raw-body handling. |
| `The address must be reachable on the public internet.` | The host resolves to a private address. |
| `That host name does not resolve.` | DNS has no answer yet. |

Signature mismatches almost always come from parsing and re-serialising the JSON before hashing. Hash the exact bytes you received.

Webhook signatures use your endpoint secret. The public keys at `/.well-known/jwks.json` are for [purchase tokens](https://docs.zokogames.com/sdk/purchases#verifying-a-purchase-on-your-server) and for player tokens from `getUserToken` ([verifying on your server](https://docs.zokogames.com/sdk/user#verifying-on-your-server)); they never sign a webhook. Purchases have no webhook; verify the purchase token instead.

`payableMicros` is in millionths of the statement currency (`1250000` is 1.25). See [payouts](https://docs.zokogames.com/business/payouts) for the states. For the notifications your team receives in the console, by push and by email, see [notifications](https://docs.zokogames.com/guides/notifications).

`payableMicros` is `null` when the statement's amount is outside the range we can state exactly: beyond 9,007,199,254,740,991 micros (about 9 billion units of the currency), positive or negative. We never round such an amount. The portal team settles that statement with you by hand, and the [developer API](https://docs.zokogames.com/guides/developer-api) answers `409 amount_unsafe` for it. Do not treat `null` as `0`: the statement is not empty, its amount is just not in the payload. Show it as needing attention, and contact developer support if you need the figure.

`paidMicros` and `heldBackMicros` were added on 20 November 2026; the other fields did not change. When `change` is `paid`, `paidMicros` is the amount actually sent to you for this statement and `heldBackMicros` is the part the new-studio holdback kept back from it (`0` when no holdback applied), both taken from the payment record and in millionths of the statement currency. `payableMicros` keeps its meaning, the full payable amount: a statement of 200.00 paid with a 20% holdback has `payableMicros: 200000000`, `paidMicros: 160000000` and `heldBackMicros: 40000000`. Payouts are sent in whole cents, so `paidMicros + heldBackMicros` can be lower than `payableMicros` by less than one cent. If a payment arrived short and the portal team accepted it, `paidMicros` is the amount that arrived and the difference is added to your next statement. If more arrived than was sent for, `paidMicros` is that higher amount, so `paidMicros + heldBackMicros` can exceed `payableMicros`; the extra is not taken back automatically. A Stripe transfer reversed after payment sends no new event: the `statement.updated` you received keeps the amount sent, and the portal team settles the reversal with you. In the developer API, `paid_minor` stays the amount sent after a partial reversal and becomes `null` after a full one. The held-back amount is paid back later as a holdback line on a newer statement, which you see in that statement's `statement.created`; no separate event is sent for it. Both fields are `null` when `change` is `held` or `released`, when the amount cannot be stated exactly (as for `payableMicros`), and when the payment record cannot be read reliably (for example an amount in another currency). Do not treat `null` as `0`.

## Related

- [Statements, PDFs and sandbox payouts](https://docs.zokogames.com/guides/statements-and-pdf) for `statement.created` and `statement.updated`.
- [Player feedback emails and dislike reasons](https://docs.zokogames.com/guides/feedback-emails) for `feedback.received` and `feedback.replied`.
- [Artwork experiments](https://docs.zokogames.com/guides/artwork-experiments) for `experiment.finished`.

---

Source: https://docs.zokogames.com/guides/artwork-experiments

# Artwork experiments

This guide explains how to test a cover or preview-video variant against your live artwork, and how to read and apply the result. An experiment shows half of the players on the portal's game tiles your variant, compares click-through with the live artwork, and tells you whether the gap is real. Use it to answer questions such as "does a character close-up beat a scene shot?". It needs no SDK code and no change to your build. Unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Who can run one

Owners and admins of the studio (other roles can read results). Games in full launch with a complete artwork set (three covers and two preview videos, see [cover and video specs](https://docs.zokogames.com/requirements/covers)) and no artwork review pending.

## Create an experiment

1. Open the game in the console and select **Experiments**, then **New experiment**.
2. Name it (up to 30 characters) and choose what you are testing: covers, videos or both.
3. Add an optional description of your hypothesis.
4. Upload the variant artwork. It must follow the [cover and video specs](https://docs.zokogames.com/requirements/covers).
5. Start the experiment, or save it as a draft.

Data collection begins at the next midnight UTC, and the 14 days count from then. If you stop an experiment before that moment it is cancelled, keeps no data and does not use the monthly allowance.

Variant artwork goes through the same artwork review as a cover change on a live game, and no visitor sees a variant before a reviewer approves it. When you start an experiment whose files were not approved for this game before, it shows **Waiting for artwork review**, and it starts at the next midnight UTC after approval, with the 14 days counted from then. If the artwork is not approved, the experiment is archived with the reviewer's note, does not use the monthly allowance, and you can create a new one with changed artwork. A waiting experiment has no time limit and, until a reviewer decides, no other artwork change of the game can be submitted, so cancel it if you no longer want it: that withdraws it from review. If the month's allowance is used up by the time of approval, or the game has left full launch, the approved experiment is archived instead of starting; its artwork stays approved for a new experiment. Files that are already approved for the game (the same content as a live cover, or as a variant a reviewer approved earlier) start without a second review.

## Limits

- One experiment per game at a time. One waiting for artwork review holds that place, but its 14 days and its data collection begin only when it starts.
- Two per game per calendar month.
- 14 days maximum per experiment.
- Up to 3 drafts per game at once, and experiment names must be unique within the game.
- The monthly allowance counts experiments by the month they start in. A draft, or one you cancel before it starts, does not use it.
- Do not replace your live artwork while an experiment runs. The current cover is the control group, so a new one approved mid-test would put two different covers in one group.
- If the game is unpublished or taken down, a running experiment ends at once and keeps the data it has; one that has not begun is cancelled. Neither sends a finished notice.

## What is tested and who sees it

The test type is **covers**, **videos** or **both**. Covers are swapped on the portal's game tiles. Variant preview videos are not shown on the tiles yet, so a **videos** test changes nothing players see and its click-through cannot differ; test covers to measure click-through. In a **both** test only the variant cover is visible to players. Each visitor is assigned to one of two groups, the **current** artwork (control) or your **variant**, by a stable hash of a random id, so the same visitor sees the same cover on every tile of your game. The split is 50 / 50 and cannot be changed.

- The random id is kept in the browser only when the player allowed the *preferences* cookie category; otherwise a fresh id is used per page load and never stored. In kids mode nothing is stored.
- Tiles that load eagerly, such as the hero banner and the first row, keep the current cover for everybody and are **excluded**: their impressions and clicks are not counted. Results come from the other tiles.
- Only games in full launch can run an experiment, and variant covers are shown only while it runs.
- A play counts for an arm when the player clicked a tile of that arm just before opening the game.

## Reading results

Each arm records tile **impressions**, tile **clicks** and **plays**. Click-through rate is clicks divided by impressions. Players, playtime and retention are not recorded per arm, so the verdict rests on click-through. The device filter (desktop, mobile, tablet) narrows the table; a cover that wins on desktop may lose on mobile because the thumbnail is smaller. Results use UTC days and refresh as the counters grow.

### How sure are we

A result needs at least **1,000 impressions and 10 clicks for each arm**. Below that the page shows progress and the wording "too early to call" (a very low click-through can have many impressions and still too few clicks for the maths to be reliable). After that we run a two-sided two-proportion z-test on the click-through rates and show how likely the gap is luck (the p-value):

| Wording | When |
| --- | --- |
| Very likely a real difference | p below 0.01 |
| Probably a real difference | p below 0.05 |
| Leaning, cannot rule out luck | p below 0.2 |
| No clear difference | p of 0.2 or more |

The page also shows the click-through uplift of the variant over the current cover. The suggested winner, and the `winnerSuggested` value in the notice, is the variant or the current artwork only when both arms have the minimum sample and the difference is significant (p below 0.05); otherwise it is inconclusive. No other metric can name a winner: the table's other rows (conversion, playtime, plays per player) are shown as measured, are not significance-tested and are not coloured as better or worse.

Two limits of the test. It treats every impression as independent, so a few visitors who click many times can make a gap look more certain than it is. And it is built for one look at the end: checking a running experiment every day and stopping at the first "probably real" makes a false win far more likely than 5%. Wait for the end date unless the gap is very large. If you filter by device, you are running several tests at once, so treat a win in one device only as a lead, not proof.

## Finishing and applying a winner

An experiment ends after 14 days, or earlier when you stop it (it cannot be restarted). Then **you** choose: keep the current artwork or use the variant. Nothing is applied automatically, and picking before the data is clear is allowed but the console warns you, and it warns again if you apply a variant that got significantly fewer clicks or discard one that got significantly more. Choosing a variant that a reviewer approved for the test replaces the live artwork at once, with no second review. A variant whose files were never reviewed (an experiment that began before variants were reviewed) is sent through artwork review, and the live artwork changes only after a reviewer approves. You can pick once per experiment.

### The finished notice

When the 14 days run out, the portal marks the experiment finished once and tells your studio in four ways: a notification in the console and by push, an email to the owner and admins (through your developer email preferences) and the `experiment.finished` [webhook](https://docs.zokogames.com/guides/webhooks) with `winnerSuggested` set to `variant`, `baseline`, `inconclusive` or `null`. The check runs hourly, so the notice does not depend on someone opening the console.

Stopping an experiment yourself finishes it too, but sends no notice and no webhook. You can archive an experiment that is not running. Archiving a finished experiment before you pick a winner closes the choice for good.

## Tips

- Change one thing: colours, framing or title treatment, not all three.
- Let the experiment run to its end date; a few hundred clicks is noise.
- A "no clear difference" result is a real answer: the two covers perform the same, so keep the one you prefer.
- Keep the loser. What did not work is information too.

## Related

- [Cover and video specs](https://docs.zokogames.com/requirements/covers)
- [Promoting your game](https://docs.zokogames.com/guides/promoting-your-game) for paid sponsored placements.
- [Webhooks](https://docs.zokogames.com/guides/webhooks) for the `experiment.finished` payload.
- [Player feedback emails and dislike reasons](https://docs.zokogames.com/guides/feedback-emails) for another way to learn why players leave.

---

Source: https://docs.zokogames.com/guides/notifications

# Notifications for studios

This guide lists which notifications your studio receives, who gets them and how to tune each channel. The portal tells your studio when something needs attention through three channels: the **in-app** list in the developer console, **push** notifications on devices that enabled them, and **email**. For machine-readable events sent to your own server, use [webhooks](https://docs.zokogames.com/guides/webhooks). Nothing here involves the SDK or your game's code. Terms such as studio and build are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Who receives them

Studio notifications go to the studio **owner** and every member with the **admin** role. Members with a lower role do not receive them. Each person controls their own channels.

## What you receive

| Notice | In-app | Push | Email | Notes |
| --- | --- | --- | --- | --- |
| Review outcome (approved to basic launch or full launch, update approved, changes requested, rejected) | Yes | Yes | Yes | Includes the reviewer's note and rejection reasons. Not sent to banned members. |
| Submission received | Yes | Yes | No | Your submission entered the review queue. |
| Build passed validation | Yes | Yes | No | See the [build validation reference](https://docs.zokogames.com/requirements/build-validation). |
| Build rejected by validation | Yes | Yes | No | Sent even during the recipient's quiet hours. |
| Player message (feedback or "contact the developer") | Yes | Yes | No | One push per game collapses into a single notification. Not sent for messages on kids games. |
| Payout statement created | Owner's row is written by the statement run | Yes | Yes | The email states the period and the amount payable. Sent once per statement, whether the month was closed on schedule or by the portal team. |
| Payout paid | Yes | Yes | n/a | |
| Payout on hold | Yes | Yes (urgent, ignores quiet hours) | n/a | Open the statement for the reason. |
| Hold released | Yes | Yes | n/a | |
| Studio-wide payout hold or release by the portal team | Yes | Yes | n/a | |
| Payout details changed or payout account connected | Yes | Yes (urgent, ignores quiet hours) | n/a | Says who made the change and when (UTC), shows the new payee masked, and links to the studio's audit trail in **Settings**. |
| Team invitation or addition | Yes | n/a | Yes | Sent to the invited person. |

"n/a" means the notice type has no sender for that channel.

## Tune your channels

Each person sets channels per type in the account notification settings. The types that apply to studios are:

| Type | Defaults (in-app, email, push) | Can be turned off? |
| --- | --- | --- |
| Developer (reviews, builds, submissions) | on, on, on | Yes |
| Payouts | on, on, on | Email is always on; in-app and push can be switched off |
| Feedback (player messages) | on, no email channel, on | In-app and push |
| System and announcements | on, on for system only, on | Yes |

Quiet hours apply to push only, in your own time zone; urgent notices (a rejected build, a payout hold) ignore them. Push needs a browser that supports it and permission granted on that device. Kids mode never receives push. The in-app list is in the developer console, where items can be marked as read.

## Webhooks versus notifications

Notifications are for people and are tuned per person. Webhooks are for your systems: they belong to the studio and carry the same facts as machine-readable events (the full list is on the [webhooks page](https://docs.zokogames.com/guides/webhooks#events)). Delivery is at least once with automatic retries, and an endpoint that keeps failing is switched off and triggers a notification to your owners and admins. Webhooks are not a substitute for the console: reconcile from it if you need a complete record.

## Replying to players

When a player uses "contact the developer", the message arrives in the game's feedback inbox in the console and notifies your studio as above. See [player features](https://docs.zokogames.com/guides/player-features) for who can write and how replies are sent.

For the feedback email modes and dislike reasons, see [feedback emails](https://docs.zokogames.com/guides/feedback-emails).

## Next steps

- [Webhooks](https://docs.zokogames.com/guides/webhooks)
- [Player feedback emails and dislike reasons](https://docs.zokogames.com/guides/feedback-emails)

---

Source: https://docs.zokogames.com/guides/player-features

# Player features that affect your game

This guide lists the portal features that change what your game sees or what players can do around it, and what your game should do about each. None needs special code, but each case must be handled. Examples assume `const SDK = window.ZokoGames.SDK;` and `await SDK.init();` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary). None of these features exist in local mode (your own `localhost` page): there the SDK behaves like a normal, signed-in, ad-showing player, so test them on the live portal or the [Preview tool](https://www.zokogames.com/preview).

## Ad-free members

Players will be able to become ad-free members, or receive a time-boxed ad-free pass from the portal team. The membership is **planned** (see [feature status](https://docs.zokogames.com/business/faq#feature-status)): it is built but switched off, so today no player is ad-free and passes have no effect. Once it is on, while a player is ad-free the portal frame changes what the SDK returns:

| Call | What your game gets |
| --- | --- |
| `requestAd("midgame")` | `adStarted` and then `adFinished` fire straight away, with **no ad shown and no error**. It does not look like an ad blocker and never returns `adblock`. Resume the game exactly as after a normal ad. |
| `requestAd("rewarded")` | Plays normally. The player asks for it, so it stays available, and the reward rules are unchanged. |
| Prerolls | Not shown. |
| `SDK.banner.requestBanner` | Fails with `bannersDisabled`, as when banners are off for the game. |

Do not assume a finished midgame ad means time passed or an ad was seen, and never gate content on a midgame ad. The same code handles both cases:

```js
await SDK.ad.requestAd("midgame", {
  adStarted: pauseAll,
  adFinished: () => {},   // fires at once for an ad-free member
  adError: () => {},
});
resumeAll();
```

Ad-free breaks are not counted as ad requests. The player also never sees a pitch for membership in kids mode.

Because ad-free players earn no ad revenue for the game they play, the portal plans a membership pool to compensate studios. See [revenue share](https://docs.zokogames.com/business/revenue-share).

## Kids mode and kids games

Kids mode is a switch a parent turns on (turning it off needs an arithmetic parent gate). A game flagged as a kids game behaves the same way inside the player frame. Kids mode itself also keeps the whole visit inside the kids area: other portal pages redirect to it, and saving for offline is limited to kids games. In both cases, inside the frame:

- No sharing, invites, multiplayer rooms, leaderboards, sign-in or account-link prompts. `showAuthPrompt` ends as cancelled by the user and `showAccountLinkPrompt` reports no signed-in user.
- For a kids game, `SDK.game.settings.disableChat` is `true` from the start. Respect it.
- Players can report a problem only with preset reasons, never free text, and "contact the developer" is closed.
- Optional cookie categories are off: no analytics-only events and no personalised ads. Plays and anonymous counts still work. Push notifications are never sent.
- `hasAdblock` returns `false`, and no ad network script is loaded. Games the portal marks as kids games never serve ads; see [advertisement rules](https://docs.zokogames.com/requirements/advertisements).
- Embedding on partner sites is never available for kids games.

## Device notices

On the technical step of the submission you declare **Works on mobile**, **Works on iOS** and **Works in Safari**. They drive what players see:

- If a visitor is on iOS or iPadOS and you did not tick iOS, a dismissible notice appears above the player saying the studio has not confirmed it works on iPhone or iPad. If they are on desktop Safari and you did not tick Safari, a similar notice names the browser. Chrome, Firefox, Edge and Opera on desktop never see it.
- The notice offers **Play anyway** and **Dismiss**; the choice is remembered per game on that device. It disappears once Play was pressed.
- A game not marked as working on mobile is labelled desktop-only, and the page offers phone visitors a code to save it for later at a keyboard. The "works on iOS" fact on the game page needs both Works on mobile and Works on iOS.

Tick a box only after testing. A notice costs plays; a broken experience costs more. See [mobile](https://docs.zokogames.com/guides/mobile).

## Contact the developer

A signed-in player can write to your studio from a game's page. The message lands in that game's **Feedback** inbox in the console and notifies your owner and admins (see [notifications](https://docs.zokogames.com/guides/notifications)).

- Players pick a subject (bug, suggestion, business, other) and write 5 to 2,000 characters. Each player may send 5 messages per hour.
- It is **not available** in kids mode, for kids games, or for accounts whose birthday does not show they are at least 13.
- The studio's email address is never sent to the player's browser, and the reply address is read from the player's account when you reply, never from the request.
- **Replying.** You can reply in the inbox and optionally mark the item resolved. Email goes out only when the message was written by a signed-in account **with a verified email**; the reply is mailed to that verified address. Anonymous reports, reports from unverified accounts and old typed addresses can be answered in the console but cannot be emailed (`no_reply_possible`). A typed address is never used as a mail target.
- A studio can send up to 200 replies per game per day. Every new player message fires the `feedback.received` webhook. Replying fires the `feedback.replied` [webhook](https://docs.zokogames.com/guides/webhooks).

Players can also send a game report with preset subjects from the player; those arrive in the same inbox and cannot be replied to by email.

## Guide link

The optional **guide link** on your listing shows an "open guide" button on the game page that opens your wiki or guide in a new tab. It must be `https`, at most 300 characters, contain no user name or password and have a real host name; an empty value removes it. The link opens in a new tab and is marked `nofollow`. Link to something that helps a player.

## Moderated chat and instant join

Two declarations on the listing help reviewers and keep the integration honest:

- **Moderated chat:** tick it only if your game has its own chat and you moderate it. Reviewers see the flag with your submission. Your game must still honour `disableChat`.
- **Instant join:** tick it if a player can join a room straight from an invite link. Reviewers see the flag. When a page is opened with `instantJoin=true`, `SDK.game.isInstantMultiplayer` is `true` and your game should skip its menu; see [multiplayer and invites](https://docs.zokogames.com/guides/multiplayer-invites).

These flags are declarations. The portal does not moderate your chat or test your join flow for you.

For what changes for children, see [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Next steps

- [Kids mode and games made for children](https://docs.zokogames.com/guides/kids-mode)
- [Player feedback emails and dislike reasons](https://docs.zokogames.com/guides/feedback-emails)

---

Source: https://docs.zokogames.com/guides/migrating

# Migrating from another portal's SDK

This guide shows how to move a game that already uses another web portal's SDK onto ZokoGames, either by renaming calls (recommended) or by adding a small compatibility shim. Most web game portals offer a similar SDK: init, ads, gameplay events, user, cloud save. The ZokoGames SDK deliberately uses the same shapes, so porting is mostly renaming a global and checking a few differences. Unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Two ways to port

1. **Rename (recommended).** Replace the other SDK's global with `window.ZokoGames.SDK` and fix the differences below. You end up with clean code and no shim.

2. **Compatibility shim (quick port).** Add the shim to your build instead of changing call sites. It exposes the object other portals' scripts use and forwards each call to the ZokoGames SDK.

Download the shim from `https://www.zokogames.com/sdk/zokogames-compat-v1.js`, put it in your build zip next to `index.html` and load it with a relative path. (The copy on `sdk.zokogames.com` is a legacy copy that is not kept up to date, and a script from another host would be reported as an external reference.) Add it **after** the ZokoGames SDK and tell it which global name your game already reads, using the `data-global` attribute. You supply the name; the shim defines `window.<name>.SDK`.

```html
<!-- quick port: load the ZokoGames SDK, then the shim -->
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script src="zokogames-compat-v1.js" data-global="YourOldGlobal"></script>
```

`data-global` must be a plain identifier (letters, digits, `_` and `$`, up to 64 characters, not starting with a digit). It cannot be `ZokoGames` or a name the browser already owns such as `window`, `document`, `location`, `top` or `parent`; the shim logs an error and installs nothing in that case. Besides forwarding every call to `window.ZokoGames.SDK`, it translates the differences below:

| Old shape | What the shim does |
| --- | --- |
| Error code `dataLimitExcedeed` (misspelt) | Our code is `dataLimitExceeded`. Errors that pass through the shim carry the old spelling, so existing `switch` statements keep working. |
| `game.isInstantJoin` | Alias of `game.isInstantMultiplayer`. |
| `game.showInviteButton(params)` / `hideInviteButton()` | Deprecated; mapped to `game.updateRoom({ isJoinable, inviteParams })`. `showInviteButton` resolves the invite link. |
| `game.sdkGameLoadingStart()` / `sdkGameLoadingStop()` | `loadingStart()` / `loadingStop()`. |
| `getEnvironment(cb)` | Calls `cb(null, environment)`. |
| Callback style, `method(args, (error, result) => ...)` | Supported on every promise method. `ad.requestAd` also accepts `(type, adStarted, adFinished, adError)`. |
| `SDK.environment` equal to the old host's name | Add `data-environment="oldname"` to the script tag and the shim reports that string in place of `zokogames`. `local` and `disabled` pass through. |
| `user.getXsollaUserToken()` | Forwarded to the SDK's deprecated alias of `store.getPurchaseToken()`. New code should call `SDK.store.getPurchaseToken()` directly (see [purchases](https://docs.zokogames.com/sdk/purchases)). |
| `user.addScore(score)` (old high-score call) | `user.submitScore({ encryptedScore: "", score })`, valid only for boards without an encryption key. |
| A game that never calls `init()` | The shim runs `init()` before the first asynchronous call. |
| `game.isOffline`, `game.addOfflineListener(fn)` / `removeOfflineListener(fn)` | Passed straight through, in the same property and listener style as `game.settings`. |

The `store` module, `analytics`, banners and listeners pass straight through to the SDK, and the shim does not replace the engine wrappers: engine projects use the wrappers in the [engines](https://docs.zokogames.com/engines/overview) section. Prefer the rename route for new work; the shim is a bridge, not a place to stay.

The shim keeps the old shape and adds nothing the old SDK never had. For ZokoGames-only features a ported game calls `window.ZokoGames.SDK` directly: `game.reportChat(report)`, `game.onScreenshotRequest(handler)`, `game.room`, `data.mirrorLocalStorage(options)` and `achievements`. It is the same SDK instance the shim forwards to (one `init()`, one player, one save), so using both in one game is safe. `ERROR_CODES` and `SDK_VERSION` exist only in the module build; the script tag does not define them, so compare `error.code` strings instead (through the shim the save limit error keeps the old spelling `dataLimitExcedeed`).

The validator's static scan may report `third_party_sdk` (a warning) for a call such as `YourOldGlobal.SDK.init()`. That warning is expected while the shim is in use; the build is still accepted. It disappears once you rename to `ZokoGames.SDK`.

### The rename route in full

```html
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script>
  const SDK = window.ZokoGames.SDK;       // was: the other portal's global
  (async () => {
    await SDK.init();                      // never rejects; check SDK.environment
    if (SDK.environment === "disabled") return startStandalone();   // your own function
    startGame();
  })();
</script>
```

On your own `localhost` page the SDK runs in local mode with a fake player, a three-second fake ad and an in-browser save, so you can test the whole port before uploading. Players who are guests, ad-blocked or offline get the same API, with the differences described in the guides for [ads](https://docs.zokogames.com/guides/ad-monetisation), [accounts](https://docs.zokogames.com/guides/player-accounts) and [offline play](https://docs.zokogames.com/guides/offline-play).

**Every `SDK.game.*`, `SDK.user.*`, `SDK.ad.*` and `SDK.banner.*` call returns a promise, and any of them can reject** (for example `sdkNotInitialized`, `sdkDisabled`, `rateLimited` or `unexpectedError`; `SDK.data` is the exception: it is synchronous and throws). Code ported from a portal whose calls never failed often fires them and forgets, which leaves an unhandled rejection in the console, or a stuck pause when the call that should resume the game failed. Add `.catch(() => {})` (or `try`/`await`) to every call you do not read the result of, and resume the game in the error path.

## Mapping table

The left column is the usual shape of another portal's SDK. Names there vary slightly between portals; match them by meaning.

| Another portal | ZokoGames | Notes |
| --- | --- | --- |
| `SDK.init()` | `SDK.init()` | Same. Never rejects here; check `SDK.environment`. |
| Environment check | `SDK.environment` | `zokogames`, `local`, `disabled`. |
| `ad.requestAd(type, callbacks)` | `SDK.ad.requestAd(type, callbacks)` | Same callback names (`adStarted`, `adFinished`, `adError`). Types are `"midgame"` and `"rewarded"`. A portal's interstitial, commercial break or mid-roll is `"midgame"`; its rewarded or opt-in video is `"rewarded"`. Any other string rejects with `invalidArgument`, and prerolls are not shown, so drop that call. |
| `ad.hasAdblock()` | `SDK.ad.hasAdblock()` | Same. |
| `banner.requestBanner` / `requestResponsiveBanner` | `SDK.banner.requestBanner({id,width,height})`, `requestResponsiveBanner(id)` | Check your sizes against [banners](https://docs.zokogames.com/sdk/banners#requestbanner). |
| `game.gameplayStart` / `gameplayStop` | `SDK.game.gameplayStart` / `gameplayStop` | Same. A midgame ad is refused with `adCooldown` until `gameplayStart` has been called once. |
| `game.loadingStart` / `loadingStop` (loading finished) | `SDK.game.loadingStart` / `loadingStop` | Same. Call `loadingStop` once the first screen can be played; `loadingProgress(0..100)` is optional in between. |
| `game.happytime` | `SDK.game.happytime` | Same. |
| Completion percentage | `SDK.game.reportGameCompletedPercentage(0..100)` | Out-of-range values throw. |
| Game context | `SDK.game.setGameContext(obj)`, `clearGameContext()` | Flat object, primitives only. |
| Settings and listener | `SDK.game.settings`, `addSettingsChangeListener` | `disableChat`, `muteAudio`. |
| Rooms and invites | `SDK.game.updateRoom`, `leftRoom`, `inviteLink`, `inviteParams`, `getInviteParam`, `addJoinRoomListener` | Invite params are flat string maps. |
| `user.getUser()` | `SDK.user.getUser()` | `null` when logged out. The id field is `__dangerousUserId`. |
| `user.systemInfo` | `SDK.user.systemInfo` | Same fields. |
| `user.getUserToken()` | `SDK.user.getUserToken()` | Verify with [our JWKS](https://docs.zokogames.com/sdk/user#verifying-on-your-server) and check the `gameId` claim. |
| `user.showAuthPrompt()` | `SDK.user.showAuthPrompt()` | Same error codes. |
| `user.showAccountLinkPrompt()` | `SDK.user.showAccountLinkPrompt()` | Resolves `{ response: "yes" \| "no" }`. |
| `user.listFriends` | `SDK.user.listFriends({page,size})` | Size 1 to 50. |
| Cloud save | `SDK.data.getItem/setItem/removeItem/clear` | Synchronous, with no promise or callback: read after `await SDK.init()`. Strings only (store objects as `JSON.stringify` text); 1 MiB for all keys together. Error `dataLimitExceeded`. |
| Purchase tracking | `SDK.analytics.trackOrder(provider, order)` | Real-money [purchases](https://docs.zokogames.com/sdk/purchases) are sandbox only for now. |
| Leaderboard submit | `SDK.user.submitScore({encryptedScore, score})` | New key, see [leaderboards](https://docs.zokogames.com/sdk/leaderboards). The call resolves even when the score is dropped or the player is a guest, and the SDK has no call that reads a board: use the rankings endpoint described there. |

## What changes

- **Script URL and global:** `https://sdk.zokogames.com/zokogames-sdk-v1.js` defines `window.ZokoGames.SDK`.
- **Token verification and audience:** change your server to fetch keys from `https://www.zokogames.com/.well-known/jwks.json` (RS256) and verify the signature, the expiry, the issuer (`zokogames`) and the audience: the `aud` claim must equal your ZokoGames game id, and so must the `gameId` claim. Keys, issuer and audience all differ from the other portal's tokens, so verification code cannot be reused as it is, and a token minted for one ZokoGames game is not valid for another. Tokens live 3600 seconds; ask for a new one with `SDK.user.getUserToken()` instead of storing one.
- **Environments that do nothing:** some SDKs answer every call with an empty result when the game runs outside the portal, so unguarded calls never fail. Here, outside the portal and outside `localhost` the environment is `"disabled"` and every `SDK.game`, `SDK.user`, `SDK.ad`, `SDK.banner` and `SDK.store` call rejects with `sdkDisabled` (properties and `SDK.data` throw it); only `init()`, `SDK.environment` and `SDK.isQaTool` keep working. Read `SDK.environment` once after `await SDK.init()` and skip portal features when it says `"disabled"`.
- **Loading and gameplay events:** `loadingStart`, `loadingStop`, `gameplayStart` and `gameplayStop` keep their names. The portal measures play time from `gameplayStart`, so call `gameplayStop` at every pause, menu and before each ad, and call `gameplayStart` again afterwards; a port that only sends the first one reports wrong play time.
- **Sitelock:** allow `zokogames.com` and `*.zokogames.com`. See [technical requirements](https://docs.zokogames.com/requirements/technical#sitelock).
- **Branding:** remove the other portal's logos, links and store badges. Cross-promotion rules are in [gameplay requirements](https://docs.zokogames.com/requirements/gameplay#cross-promotion).
- **Error codes:** compare your `switch` statements with the lists in [SDK introduction](https://docs.zokogames.com/sdk/introduction#errors).
- **Leaderboards:** scores need a new encryption key from the console; see [leaderboards](https://docs.zokogames.com/sdk/leaderboards).
- **Saves:** existing players keep their old progress only if you migrate it yourself; see the `localStorage` migration snippet in [data](https://docs.zokogames.com/sdk/data#migrating-from-localstorage).

## Test

Run the game with `?sdk_debug=true`, open it in the [Preview tool](https://www.zokogames.com/preview) and walk through ads, user, data and invites. The tool's checklist ticks as each call arrives.

## Next steps

- [Versioning and migration notes](https://docs.zokogames.com/sdk/versioning)
- [Testing checklist before you submit](https://docs.zokogames.com/getting-started/testing-checklist)
- [Bring your game to ZokoGames](https://docs.zokogames.com/porting/overview): the porting guide for each engine

---

Source: https://docs.zokogames.com/guides/monetisation-by-genre

# Monetisation by genre

The [ad monetisation guide](https://docs.zokogames.com/guides/ad-monetisation) covers pacing and clean integration for every game. This page applies it to the rhythm of seven common genres: where the natural breaks are, what makes a fair rewarded offer, and which screens can carry a banner. The binding rules stay in the [advertisement rules](https://docs.zokogames.com/requirements/advertisements): midgame ads only at breaks, rewarded ads always optional with an equally visible way to skip, banners never during play.

Every genre shares three habits:

- **Count breaks, not seconds.** Show a midgame ad every second or third break and let the portal's cooldown absorb the rest; failed requests (`adCooldown`, `unfilled`, `adblock`, `adsDisabled`) just continue the game.
- **One rewarded offer per decision.** Never stack a midgame ad and a rewarded offer on the same break, and never reward on `adError`.
- **Measure before you add.** Watch average playtime and day-1 retention in the console after each change; a format that lifts revenue for a week and costs retention earns less over the month.

## Action and shooter

Sessions are intense and short, and players hate losing momentum.

- **Breaks:** the end of a match, wave or mission, after the results screen has been read. Never on death in the middle of a run.
- **Rewarded:** a second chance on a run that went well (revive once per run, not after every death), double match rewards, or an early look at a new weapon for one match.
- **Banners:** the loadout or armoury screen and the results screen, where players stay for several seconds.

## Clicker and incremental

Players come back many times a day and tolerate long sessions, so rewarded ads carry most of the value.

- **Breaks:** prestige or rebirth, and the "welcome back" screen after an absence.
- **Rewarded:** a timed production boost (for example two times for a few minutes), doubling offline earnings on return, or skipping a long upgrade timer. Keep a non-ad route to the same boost, such as a daily free claim.
- **Banners:** the upgrade shop and statistics screens. Keep them away from the main tapping area so a missed tap never becomes an ad click.

## Driving and racing

Races have clear starts and finishes, which makes pacing easy.

- **Breaks:** after the race results, before returning to the garage. Not between a restart press and the countdown.
- **Rewarded:** double the race payout, try a locked car for one race, or a free repair. Show the offer on the results screen next to an equally large "Continue" button.
- **Banners:** the garage and car-select screens.

## io and hyper-casual

Rounds are seconds to a few minutes long and the next round is one click away, so midgame frequency must stay low.

- **Breaks:** after the death or round-over screen, at most every third round. For multiplayer rooms, only when the player leaves the room, never while friends are waiting in a lobby they created with `updateRoom`.
- **Rewarded:** cosmetic unlocks (a skin for one session), or a head start such as a larger starting size. Never sell a competitive advantage that other real players feel.
- **Banners:** the skin picker or name entry screen. Hide them when the round starts.

## Midcore and idle RPG

Long sessions, deep progression and returning players. The risk is over-monetising an engaged audience.

- **Breaks:** after a dungeon or chapter, and on returning from a long idle period.
- **Rewarded:** an extra chest roll, a quest reroll, a speed-up on a long timer, or bonus idle rewards. Cap rewarded views per day in your own logic so the economy does not depend on ads.
- **Banners:** inventory, map and character screens. Never on combat screens, even paused.

## Puzzle

Players think between moves; an ad that interrupts a solve is the worst moment in the genre.

- **Breaks:** after the level-complete screen, every second or third level. Never on a retry of the same level.
- **Rewarded:** a hint, an undo, or extra moves when the player is one or two moves short. Offer it once per level, after the player has tried.
- **Banners:** the level-select map and the level-complete screen.

## Word

Daily habits and streaks matter more than session length. Players often play one or two puzzles and leave.

- **Breaks:** after a finished puzzle, before the next one starts. Skip the ad entirely after the first puzzle of a session.
- **Rewarded:** reveal a letter, check a word, or keep a streak alive once a week. A streak-saver must also be earnable without an ad.
- **Banners:** the archive or puzzle list and the results screen with the share button.

## Checklist

- [ ] Every midgame request sits on a break listed for your genre, and failed requests continue the game.
- [ ] Each rewarded offer has an equally prominent skip and a way to earn the same thing without an ad.
- [ ] Banners appear only on screens players stay on for several seconds, and never during play.
- [ ] You compared playtime and day-1 retention in the [metrics](https://docs.zokogames.com/guides/analytics-metrics) before and after the change.

## Next steps

- [Ad monetisation guide](https://docs.zokogames.com/guides/ad-monetisation)
- [Advertisement rules](https://docs.zokogames.com/requirements/advertisements)

---

Source: https://docs.zokogames.com/guides/account-linking

# Account linking step by step

Use this guide when your game has its own accounts and its own server, and you want a signed-in ZokoGames player to land in the right game account on every launch. It is the full version of scenario 4 in [account integration scenarios](https://docs.zokogames.com/requirements/accounts). If your game has no accounts, or you only need a name and an avatar, [player accounts and your backend](https://docs.zokogames.com/guides/player-accounts) is enough.

The idea in one line: your server trusts only a **verified token**. The token carries a stable `userId`; you store a link from that `userId` to your own account, and from then on the ZokoGames identity decides which account loads.

Terms such as guest and token are in the [glossary](https://docs.zokogames.com/getting-started/glossary). Examples assume `const SDK = window.ZokoGames.SDK;`.

## What you need

- A server you control that can answer HTTPS requests from the game.
- Your game's id (shown on the game page in the developer console), stored in your server's configuration as `ZOKO_GAME_ID`.
- A table that maps `zoko_user_id` to your own account id. Make `zoko_user_id` unique, so one ZokoGames player can never be linked to two accounts.

## The flow

```text
launch
  -> getUser()                         null: play as a guest, stop here
  -> getUserToken()  -> POST /session  server verifies the token, answers { linked }
        linked: true   -> load that game account (the ZokoGames identity wins)
        linked: false  -> showAccountLinkPrompt()
                              "yes" -> POST /link  server links userId to the game account
                              "no"  -> continue as a guest
```

Guests must always be able to play. Never block the game on sign-in, and never open the sign-in dialog by yourself at start; see [offer sign-in on a player action](https://docs.zokogames.com/guides/player-accounts#2-offer-sign-in-on-a-player-action).

## 1. Read the player and get a token

```js
await SDK.init();

async function token() {
  try {
    return await SDK.user.getUserToken();      // cached by the SDK, valid for one hour
  } catch (e) {
    if (e.code === "userNotAuthenticated") return null;   // a guest
    throw e;
  }
}

async function api(path, body = {}) {
  const t = await token();
  return fetch(`https://api.example.com${path}`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      ...(t ? { authorization: `Bearer ${t}` } : {}),
    },
    body: JSON.stringify(body),
  });
}
```

Call `getUserToken()` before every request instead of keeping the string yourself: the SDK renews it a minute before it expires. `getUser()` is fine for the name in your HUD, but its `__dangerousUserId` can be faked in the browser, so never send it to your server as proof of identity.

## 2. Verify the token on your server

A game token is a JWT signed with **RS256**. Its header has `alg: "RS256"`, `typ: "JWT"` and a `kid`. Its claims are:

| Claim | Value |
| --- | --- |
| `iss` | Always `zokogames`. |
| `aud` | Your game id. A token minted for another game has a different `aud`. |
| `sub` and `userId` | The stable player id. Use it as the key of the link. |
| `gameId` | Your game id again. |
| `username`, `profilePictureUrl` | Display name and avatar at the time of issue. |
| `iat`, `exp` | Issue time and expiry, one hour apart (seconds since 1970). |

Verify the signature against the public keys at `https://www.zokogames.com/.well-known/jwks.json` (a standard JWKS), and check the issuer, the audience and the expiry. With `jose` that is one call:

```js
// zoko-auth.js
import { createRemoteJWKSet, jwtVerify } from "jose";

const GAME_ID = process.env.ZOKO_GAME_ID;
const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));

/** Returns { userId, username } for a valid token, or throws. */
export async function verifyZokoToken(raw) {
  const { payload } = await jwtVerify(raw, JWKS, {
    algorithms: ["RS256"],       // never accept anything else
    issuer: "zokogames",
    audience: GAME_ID,           // a token for another game fails here
    requiredClaims: ["exp", "iat", "aud"],
    clockTolerance: 5,           // seconds of clock drift
  });
  if (payload.gameId !== GAME_ID || payload.sub !== payload.userId) {
    throw new Error("malformed token");
  }
  return { userId: String(payload.userId), username: String(payload.username) };
}

/** Express middleware: req.player is null for a guest, 401 for a token that does not verify. */
export async function zokoAuth(req, res, next) {
  const raw = (req.headers.authorization || "").replace(/^Bearer /, "");
  if (!raw) {
    req.player = null;
    return next();
  }
  try {
    req.player = await verifyZokoToken(raw);
    next();
  } catch {
    res.status(401).json({ error: "invalid_token" });
  }
}
```

`createRemoteJWKSet` caches the keys and refetches them when it meets an unknown `kid`, so a key rotation needs no change on your side. If your JWT library only accepts a static key, fetch the same key as a PEM document from `https://www.zokogames.com/.well-known/public-key.json`, which answers `{ "alg": "RS256", "kid": "…", "publicKey": "-----BEGIN PUBLIC KEY-----…" }`:

```js
import { importSPKI, jwtVerify } from "jose";

const doc = await (await fetch("https://www.zokogames.com/.well-known/public-key.json")).json();
const key = await importSPKI(doc.publicKey, doc.alg);
const { payload } = await jwtVerify(raw, key, { algorithms: ["RS256"], issuer: "zokogames", audience: GAME_ID });
if (payload.gameId !== GAME_ID || payload.sub !== payload.userId) throw new Error("wrong game or subject");
```

A static key stops working when the portal rotates its key. Refetch the document when verification fails with a `kid` you have not seen, or prefer the JWKS. Local mode (your own `localhost` page) issues unsigned test tokens that a correct verifier rejects; see [test every path locally](#5-test-every-path-locally). Verifiers for Python, C# and Go are in the [user module reference](https://docs.zokogames.com/sdk/user#verifying-on-your-server).

## 3. Answer "is this player linked?"

```js
// server.js
import express from "express";
import { zokoAuth } from "./zoko-auth.js";
import { db } from "./db.js";   // your own data layer

const app = express();
app.use(express.json());
app.use(zokoAuth);

app.post("/session", async (req, res) => {
  if (!req.player) return res.json({ guest: true, linked: false });
  const row = await db.links.findByZokoUser(req.player.userId);
  if (!row) return res.json({ guest: false, linked: false });
  // Keep the display data fresh, then load the account the link points to.
  await db.accounts.update(row.accountId, { displayName: req.player.username });
  res.json({ guest: false, linked: true, profile: await db.accounts.load(row.accountId) });
});
```

When `linked` is `true` the ZokoGames identity wins: load that account and ignore any local progress that belongs to a different one.

## 4. Offer the link, then store it

Only a player who is signed in and not yet linked sees the prompt. Ask at a calm moment, for example after the first session or on a settings screen, not in the middle of play.

```js
async function onSignedIn() {
  const res = await (await api("/session")).json();
  if (res.guest || res.linked) return res.profile ?? null;

  try {
    const { response } = await SDK.user.showAccountLinkPrompt();
    if (response === "yes") {
      const out = await api("/link", { gameAccountId: currentAccountId() });
      if (out.status === 409) showMessage("That ZokoGames player is already linked to another account.");
    }
    // "no": stay a guest, the question can be asked again later
  } catch (e) {
    if (e.code !== "userNotAuthenticated" && e.code !== "showAccountLinkPromptInProgress") throw e;
  }
}

SDK.user.addAuthListener(onSignedIn);   // also runs when the player signs in from the portal header
onSignedIn();
```

On the server, link the **verified** `userId` and nothing the browser says about itself:

```js
app.post("/link", async (req, res) => {
  if (!req.player) return res.status(401).json({ error: "sign_in_required" });
  const accountId = String(req.body.gameAccountId || "");
  // Your own proof that the caller controls this game account (session cookie, password, device secret...).
  if (!(await db.accounts.callerOwns(req, accountId))) return res.status(403).json({ error: "not_your_account" });
  try {
    await db.links.insert({ zokoUserId: req.player.userId, accountId });   // zoko_user_id is UNIQUE
  } catch (e) {
    if (e.code === "unique_violation") return res.status(409).json({ error: "already_linked" });
    throw e;
  }
  res.json({ linked: true });
});
```

Three rules keep this safe:

- Prefer linking to a **fresh account** over merging two accounts that both have progress. If a merge is unavoidable, let the player choose which progress to keep.
- Treat `userId` as the key and `username` as a label: refresh the label on every launch, never use it to find an account.
- Prove ownership of the game account yourself in `/link`. A token only proves who the ZokoGames player is.

## 5. Test every path locally

On your own `localhost` page the SDK runs in local mode with a fake player, and every step above can be forced with a URL switch:

| Path | URL switch |
| --- | --- |
| Guest | `?user_response=logged_out` |
| Signed in at launch | `?user_response=user1` |
| Player accepts the link | `?link_account_response=yes` |
| Player declines the link | `?link_account_response=no` |
| Token fails or is expired | `?token_response=logged_out` / `?token_response=expired_token` |

The local token is unsigned, so your verifier should reject it. Test the signed path with the [Preview tool](https://www.zokogames.com/preview) or a live build. The full list of switches is in the [user module](https://docs.zokogames.com/sdk/user#in-local-mode-as-a-guest-offline-or-ad-free).

## In an engine

The calls are the same in every engine; only the names change. In Unity, `User.GetUserToken(cb, ZokoSigningKeyType)` returns the token and `User.ShowAccountLinkPrompt(cb)` calls back `true` for yes. The mapping for Unity, GameMaker, Defold, Godot and others is in the [engine overview](https://docs.zokogames.com/engines/overview) and each engine page. Your server code does not change.

## Checklist

- Guests play without signing in, and a failed `getUserToken()` with `userNotAuthenticated` never shows an error.
- The server verifies signature, `RS256`, `iss`, `aud`, expiry and `gameId` on every request that uses the identity.
- `zoko_user_id` is unique in your link table.
- A linked player loads the linked account on every launch.
- Declining the prompt leaves the player in the game as a guest.

## Next steps

- [Player accounts and your backend](https://docs.zokogames.com/guides/player-accounts)
- [User module](https://docs.zokogames.com/sdk/user)

---

Source: https://docs.zokogames.com/guides/statements-and-pdf

# Statements, PDFs and sandbox payouts

This guide explains what is on a monthly statement, how to get it as a PDF or CSV for your accounting, and what a statement marked **SANDBOX** means. For the states and the schedule in short form, see [payouts](https://docs.zokogames.com/business/payouts).

## When a statement is created

A statement covers one calendar month. It is cut automatically on the second day of the following month. A statement you can see is a frozen snapshot of that month: the figures on the page, in the PDF and in the CSV all read the same snapshot, so they cannot differ.

A new statement sends the `statement.created` [webhook](https://docs.zokogames.com/guides/webhooks) and a notification to your studio. A re-run of the same month does not create a second statement and does not send the event again. The notification (an email to each owner and admin, and a push) is sent once per statement, whether the month was closed by the monthly schedule or by the portal team.

## What a statement contains

| Section | What it shows |
| --- | --- |
| Header | Studio legal name, period (`YYYY-MM`), invoice number, currency and state. |
| Game lines | One line per game with ad revenue: gross, invalid traffic removed, net, your share rate and your share. |
| Store lines | In-game store revenue on its own line per game, with its own share rate. Sales tax and VAT are never counted, refunds and chargebacks are deducted, and sandbox purchases are excluded. |
| Adjustments | Manual lines added by the portal team, positive or negative. |
| Totals | Share of games, adjustments, amount carried in from earlier months, total payable, payout and the amount carried out. |
| Payment | The payment reference and date, once the statement is paid. |

Amounts are rounded down to the cent. In the API they are integers in micros (1,000,000 micros is one unit of the currency).

A statement below the minimum payout is shown as **rolled over**: nothing is invoiced and the whole balance moves into the next statement. The PDF says so in a note.

**An amount too large to state exactly.** A statement whose payable amount is outside the range we can state exactly (beyond 9,007,199,254,740,991 micros, about 9 billion units of the currency) is never rounded. The console does not show that figure and asks you to contact developer support, the portal team settles it with you by hand, the `statement.updated` [webhook](https://docs.zokogames.com/guides/webhooks) carries `payableMicros: null` for it, and the [developer API](https://docs.zokogames.com/guides/developer-api) statements endpoints answer `409 amount_unsafe`.

## Lines that need explaining

**Late revenue.** Revenue of an earlier month that is reported after that month's statement was cut is not lost, and a settled statement is never reopened. The next statement pays the difference on its own lines, marked **Late revenue for** and the month, after the month's own lines, with a subtotal when there are several. A month whose revenue was revised down appears as a deduction among the adjustments, at the game's share rate. Late lines use the share rates in force when the new statement is made and reach back at most 12 months. In the CSV they carry the month in the `late_period` column.

**Invalid traffic.** Ad revenue found to come from invalid traffic is deducted on the game's line, in the **Invalid traffic** column, and the totals show the sum. A deduction never takes a line below zero: whatever exceeds the game's revenue for the month is taken from the balance at the game's share rate, on an adjustment line called **Invalid traffic beyond the period's revenue**. A game with only a deduction that month still gets a line. Invalid traffic is not deducted from store lines or late-revenue lines.

**A game that changed studios.** Ad revenue is counted per UTC day, and each day goes to the studio that owned the game at the end of that day: on the day of a transfer the whole day belongs to the new studio, whatever the time. Each day is counted once, so the two studios' statements for that month add up to the game's revenue. Store revenue stays with the studio that owned the game when each purchase was recorded. Late revenue follows the same rules: a revision of a day before the transfer belongs to the studio that owned the game on that day.

**Removed game.** A line for a game that no longer existed when the statement was made is labelled **Removed game**. The amount is still yours; only the name is gone.

## Why a statement is on hold

A held statement says why, on the **Payouts** page and on the statement itself.

| Reason | What it means | How it ends |
| --- | --- | --- |
| Tax form | The studio's tax form is not approved yet, or the terms are not accepted. | Released automatically once both are done, at the latest with the next statement run. Owners see a link to the payout profile; admins are told that the owner can submit the form. |
| Dispute | The portal team holds this one statement while a question about it is reviewed. | Released by the portal team, one statement at a time. |
| Studio | Payouts for the whole studio are on hold. | Lifted by the portal team for the whole studio. |

When the portal team gave a reason in the hold notice your studio received, the page shows it as **Note from ZokoGames**. Internal notes are never shown. A released statement is paid together with later ones, as described in [payouts](https://docs.zokogames.com/business/payouts).

## Download a statement

1. Open **Payouts** in the developer console and choose a statement.
2. Press **Download PDF** for the self-billing invoice, or download the CSV.

Only owners and admins of the studio can download. A statement that is still **open** has no PDF yet. The PDF has the same lines as the page, including late revenue with its subtotal and a footnote, the invalid traffic deducted and any **Removed game** lines. Its labels are in the language you use the site in (or your browser's language), and in English when that language's script cannot be printed; game names and adjustment notes appear as stored. The CSV is a data file for accounting tools and reads the same in every language: its column names, section and total names (such as `late_revenue` and `payable`), the statement status and the labels of late-revenue and invalid-traffic deductions are fixed English, and game names and adjustment notes appear as stored.

The same files are available from the API of the studio. These routes use your console session, not an API token.

| Request | Returns |
| --- | --- |
| `GET /api/developer/orgs/{studioId}/statements/{statementId}/pdf` | The PDF, as `statement-<studio-slug>-<period>.pdf`. |
| `GET /api/developer/orgs/{studioId}/statements/{statementId}?format=csv` | The CSV: a header block, one row per game or store line, adjustments, then the totals. |
| `GET /api/v1/statements` | The list of cut statements as JSON, with scope `statements:read`. See [developer API](https://docs.zokogames.com/guides/developer-api). |

| Status | Code | Meaning |
| --- | --- | --- |
| 404 | `not_found` | The statement does not exist in this studio, or it is still open. A statement id from another studio looks the same. |
| 429 | `rate_limited` | More than 20 PDF downloads in a minute. Wait and retry. |

## Sandbox and production

Production pays by hand (manual payouts, see [payouts](https://docs.zokogames.com/business/payouts)). A studio whose payout account is still the built-in test provider (a reference that starts with `stub_`, from before manual payouts or on a test copy of the portal) gets sandbox statements until its owner confirms manual payouts. The test provider links no bank account and moves no money.

| | Sandbox | Production (manual payouts) |
| --- | --- | --- |
| Payout account | A reference that starts with `stub_`. | A reference that starts with `manual_`, set when the owner confirms manual payouts. |
| PDF | Carries a **SANDBOX** watermark and a note that nothing on it is payable. | No watermark. |
| Test-mode money | Shown on the page for reference and never included in the totals or on statements. | Not applicable. |
| Payment | None. | Made by hand by the portal team outside the console, to the method in your payout profile, with its reference recorded on the statement. |

A statement with the watermark is not an invoice. Do not book it in your accounts.

## Next steps

- [Payouts](https://docs.zokogames.com/business/payouts) for the states, minimum and invoices.
- [Webhooks](https://docs.zokogames.com/guides/webhooks) for `statement.created` and `statement.updated`.
- [Revenue share](https://docs.zokogames.com/business/revenue-share) for the rates behind the share column.

---

Source: https://docs.zokogames.com/guides/feedback-emails

# Player feedback emails and dislike reasons

This guide explains how player feedback reaches you, how to choose between a daily digest and one email per message, what the thumbs-down reasons mean and how to answer a player.

## What counts as feedback

Players can send three kinds of message about a game. Each arrives in the game's feedback inbox in the console.

| Kind | Subject starts with | Example |
| --- | --- | --- |
| Report | A preset such as `Bug`, `Game does not load`, `Game crashes or freezes`, `Controls do not work`, `Lost progress`, `Help with a purchase` or `Suggestion` | `Lost progress` |
| Message to your studio | `Developer: ` | `Developer: Business` |
| Thumbs-down reason | `Dislike: ` | `Dislike: Too many ads` |

The **Feedback** page in the console menu lists the open items of all your games, newest first, with the number open per game; open a game from it to reply. On a game's **Feedback** page the inbox shows open items by default. Switch to **Resolved** or **All**, narrow the list by reason, period (7, 30 or 90 days), build number or a search in the message text, and use **Load more** past the first 100. When nothing is open the page says everything is resolved, and **Show all feedback** brings the closed items back. **Mark resolved** and **Reopen** on an item change only its state; the reply is a separate step.

Games made for children take preset reasons only, with no free text, and their feedback is never sent to your studio by email, webhook or notification.

## Choose how the email arrives

Feedback email is **off by default**. Turn on the email channel of the **Player feedback** group in your notification settings (see [notifications](https://docs.zokogames.com/guides/notifications)). Then pick a mode in the **Feedback email** card on the **Feedback** page of a game in the console. The choice is saved to your account, so it applies to every studio you belong to.

| Mode | `feedbackMail` | What you get |
| --- | --- | --- |
| Daily digest | `digest` (default) | One email a day at 08:00 in your own time zone, with the number of new messages per game. Nothing is sent on a day without messages. |
| Right away | `immediate` | An email for each new message, with its subject and text. |

The digest window runs from your previous digest to 08:00 today, so a skipped day is added to the next digest, up to 14 days back. Every owner and admin chooses for themselves. With the email channel off you get no feedback email in either mode.

## Webhook for each message

The `feedback.received` [webhook](https://docs.zokogames.com/guides/webhooks) carries the kind (`report`, `developer` or `dislike`), the subject, the message (up to 2,000 characters) and the game context. It has no visitor id, address or user agent.

## Dislike reasons

After a thumbs-down, a player can pick one reason. These are the presets.

| Reason | Meaning |
| --- | --- |
| Did not load | The game did not start. |
| Too slow | Loading or play felt slow. |
| Controls | Input did not work well. |
| Too many ads | Ad breaks annoyed the player. |
| Not fun | The player did not enjoy it. |
| Inappropriate | The content was unsuitable. |
| Other | Anything else. An unknown reason also counts here. |

### The breakdown view

Open **Feedback** for a game and use **Why players disliked this game**. Choose the last 7, 30 or 90 days. Each reason shows as a bar with its count and share, and a text table gives the same numbers. Every preset appears even with a count of zero, most frequent first. Thumbs-downs that came without any reason are counted as their own row, and the percentages are over all thumbs-downs.

A vote that was switched to thumbs-down later is dated by the original vote.

## Reply to a player

Open a message and write a reply of up to 2,000 characters. You can tick **Email the reply to the player** and **Mark resolved**.

- The email goes only to the verified address of the signed-in account that wrote the message. You cannot type an address.
- Anonymous messages and accounts without a verified email cannot be emailed. Sending by email is refused with `no_reply_possible` (409).
- A studio can send up to 200 replies per game per day (`rate_limited`, 429).
- Each reply sends the `feedback.replied` webhook with `emailed` and `resolved`.

## Next steps

- [Notifications](https://docs.zokogames.com/guides/notifications) for channels and quiet hours.
- [Webhooks](https://docs.zokogames.com/guides/webhooks) for `feedback.received` and `feedback.replied`.
- [Player features](https://docs.zokogames.com/guides/player-features) for what the player sees.

---

Source: https://docs.zokogames.com/guides/developer-api

# Developer API reference

The developer API lets your own server read your studio's data without opening the console. It is **read-only**, scoped to one studio, and authenticated with a **studio API token**. The one write is uploading a build from CI with the optional `builds:write` scope (see [Upload a build from CI](#upload-a-build-from-ci)); nothing else changes a game through it, and a build uploaded that way is never made live by the API. A pipeline that must react to a new build can subscribe to the `build.published` and `build.activated` webhooks. It is separate from the leaderboard server API key, which only submits scores for one game (see [leaderboards](https://docs.zokogames.com/sdk/leaderboards)).

Base URL: `https://www.zokogames.com/api/v1`

The machine-readable description is an OpenAPI 3.1 file at `https://www.zokogames.com/api/v1/openapi.json`. It is generated from the same schemas the API uses, so it always matches. Load it into your API client or code generator. It also describes `POST /leaderboard/scores`, the one write, which takes a game's leaderboard server key instead of a studio token (see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#server-api)).

## Tokens

Owners and admins create tokens on the **Studio API tokens** page of the developer console (left menu) (or with `POST /api/developer/orgs/{studioId}/tokens` while signed in to the console). Creating or revoking a token asks you to confirm it is you with a passkey or an authenticator app. If you have neither yet, set one up first in your player account on zokogames.com (console account menu, **Settings**, then **Account**).

- A token looks like `zst_` followed by 43 characters (256 bits of randomness). It is **shown once**, when you create it. We store only a one-way hash, so we cannot show it again: if you lose it, revoke it and create a new one.
- Each token has a **name** (up to 60 characters), one or more **scopes**, a **rate limit** (10 to 1,200 requests per minute, default 300) and an optional expiry (1 to 730 days; the console offers 30, 90 or 365 days, or never). The console has no rate-limit field, so a token created there gets 300 a minute; `GET /api/v1` shows a token's limit as `rate_limit_per_min`. Spread a large pull over time, or split it across tokens, rather than spending one token's minute at once.
- A studio can have up to **10** active tokens. Revoking a token stops it working at once.
- **Rotating a token.** There is no rotate button, and a token's name, scopes and limit cannot be edited. Create the new token, switch your server to it, wait until the old token's **Last used** time stops moving, then revoke the old one. Both work side by side until then, so nothing fails during the switch.
- The console shows when each token was **last used** (recorded at most once a minute) and the first characters of the token so you can tell them apart. Creating and revoking a token is written to the studio's audit trail, and the studio's team gets an email when a token is created or revoked (the email names the token and its first characters, never the token). Owners and admins also get a notice in the console, and an email, 7 days before a token expires, once per token, so a token with an expiry does not stop a pipeline without warning: create its replacement then.
- Treat a token like a password. Keep it on your server, never in a game build or a web page, and never in a URL: a request with `token`, `access_token`, `api_key` or similar in the query string is refused with `400 invalid_query` before the token is even looked at (the response names the parameter, never its value, and `details` says `token_in_url`).

**Scopes**

| Scope | Allows |
| --- | --- |
| `games:read` | `GET /api/v1/games`, `GET /api/v1/games/{id}`, `GET /api/v1/games/{id}/builds`, `GET /api/v1/games/{id}/feedback`, `GET /api/v1/leaderboards` |
| `stats:read` | `GET /api/v1/games/{id}/stats`, `GET /api/v1/games/{id}/stats/daily` |
| `statements:read` | `GET /api/v1/statements`, `GET /api/v1/statements/{id}/lines` |
| `builds:write` | `POST /api/v1/games/{id}/builds/uploads`, `POST /api/v1/games/{id}/builds/uploads/{uploadId}/parts`, `POST /api/v1/games/{id}/builds/uploads/{uploadId}/confirm`, `GET /api/v1/games/{id}/builds/uploads/{uploadId}` |

`GET /api/v1` itself needs only a valid token. Give a token the fewest scopes it needs: for example, a dashboard that shows plays does not need `statements:read`. `builds:write` is off by default in the console's create form: tick it only for a token that is used by CI. A request without the needed scope gets `403 insufficient_scope`. The scopes of an existing token cannot be changed: create a new token with the scopes you need, then revoke the old one.

**Authentication.** Send the token as a bearer token:

```bash
curl -H "Authorization: Bearer zst_your_token" https://www.zokogames.com/api/v1
```

`X-API-Key: <token>` is accepted as well. Session cookies are **never** accepted on `/api/v1`: a request with only a cookie gets `401`.

**Browsers and CORS.** The API is for servers. No `/api/v1` response carries CORS headers, so a web page on any origin cannot read it, and an `OPTIONS` request answers `204` with `Allow: GET, HEAD, OPTIONS` and allows nothing cross-origin. The only exception is `openapi.json`, which is public, holds no studio data and may be loaded from any origin.

## Requests and responses

- Apart from the four build-upload calls (scope `builds:write`), only `GET` (and `HEAD`) exist. A request body over 1 KB (600 KB on the build-upload calls), or any chunked body, is refused with `413 payload_too_large`; URLs are limited to 2,048 characters (longer: `414 uri_too_long`). Any other method answers `405 method_not_allowed` with an `Allow` header, and an unknown path under `/api/v1` answers `404 not_found`; both use the JSON error envelope. `HEAD` returns the headers of the `GET` and no body.
- Use the paths exactly as listed, **without a trailing slash**. `/api/v1/` is answered by the web framework with a `308` redirect to `/api/v1` before the API sees the request, so it carries no API headers; many HTTP clients drop the `Authorization` header when they follow a redirect. Call `/api/v1` directly.
- Always call the `www.zokogames.com` host. `zokogames.com` answers with a `308` redirect to `www`, and HTTP clients drop the `Authorization` header when they follow a redirect to another host, so the request arrives without your token.
- Query parameters are strict: an unknown or repeated parameter is `400 invalid_query`.
- **Ids.** `{id}` in a path is always the UUID in the `id` field of the list that holds it: a game's `id` from `GET /api/v1/games` (also the `game_id` of leaderboards, feedback and stats), a statement's `id` from `GET /api/v1/statements`. A game's `slug` (its address name) and its name are **not** accepted as `{id}`; they answer `400 invalid_params`. The game id never changes, also after launch. The console shows it too, on a game's Leaderboard page as **Your game id**.
- Every response except `openapi.json` has an `x-request-id` header, including those of `POST /leaderboard/scores`. Quote it when you contact support. The same value is in `error.requestId` for errors.
- Dates and times are ISO 8601 in UTC with a trailing `Z`, such as `2026-11-18T09:30:00.000Z`. Calendar days are `YYYY-MM-DD` (UTC) and months `YYYY-MM`.
- Field names are `snake_case` and stable: new fields may be added, existing ones are not renamed or removed within `v1`. Ignore fields you do not know.
- Money is an **integer number of minor units** (cents for USD) next to its ISO 4217 `currency` and `currency_exponent`. Amounts are truncated toward zero to whole minor units, the way payouts are. Never use floating point for these.
- Successful `GET` responses carry an `ETag` and `Cache-Control: private, no-cache`. Send it back as `If-None-Match` to get a `304` with no body when nothing changed. A `304` still counts against your rate limit. It may arrive without `RateLimit-*` headers (the hosting edge can drop them), so read your remaining quota from the last `200` response (or any non-`304` response). The public `/api/v1/openapi.json` is the exception: it needs no token, is cached by the CDN for an hour, is not metered and never carries `RateLimit-*` headers, so a `304` from it has none either.

### Rate limits

Each token has its own fixed one-minute window (see **Tokens** for the limit). Every authenticated response, errors included, reports it, except that a `304` may arrive without these headers:

| Header | Meaning |
| --- | --- |
| `RateLimit-Limit` | Requests allowed per window. |
| `RateLimit-Remaining` | Requests left in this window. |
| `RateLimit-Reset` | Seconds until the window resets. |
| `RateLimit-Policy` | For example `300;w=60`: 300 requests per 60 seconds. |

Every request that carries a valid token spends one unit of its minute, including `HEAD`, `304` and `4xx` answers (a request refused for a bad token, a suspended studio or an oversized body spends none). When the budget is spent you get `429 rate_limited` with `Retry-After` (whole seconds; for a token's own limit the same number as `RateLimit-Reset`, at most 60). Back off and retry after that time. With curl, `--retry 3` does this for you: it waits for `Retry-After` on a `429`.

An example of the answer when a token's minute is spent:

```http
HTTP/2 429
retry-after: 23
ratelimit-limit: 300
ratelimit-remaining: 0
ratelimit-reset: 23
ratelimit-policy: 300;w=60
```

Every `/api/v1` endpoint except the build-upload calls is a read-only `GET`, so repeating a request is idempotent and always safe to retry. The upload calls have their own retry rules (see below). Repeated bad or missing tokens from one address are throttled too (30 a minute), and also answer `429`; a valid token from that address is still served. A very high total request rate from one address (far above what any token is allowed) also answers `429` with `Retry-After`, whatever the token.

### Errors

Every error of the studio-token endpoints is JSON with the same envelope and an HTTP status, and is never cached. The one exception is `POST /api/v1/leaderboard/scores`, which takes a game's server key instead of a studio token: it answers `{ "ok": false, "error": "invalid-api-key", "message": "…", "hint": "…" }` with its own dash-style codes, listed with their fixes under [errors of the server API](https://docs.zokogames.com/sdk/leaderboards#errors-of-the-server-api). It has no `error.requestId`; its `x-request-id` header is the id to quote.

```json
{
  "error": {
    "code": "insufficient_scope",
    "message": "This token needs the \"games:read\" scope. A token's scopes cannot be changed: create a token with that scope on the API tokens page of the developer console, then revoke this one if nothing else uses it.",
    "requestId": "6f0c9a3e-3b1d-4a53-9c1e-2d1f6a7b8c90"
  }
}
```

Branch on `code`, which is stable; `message` is for people, says what to do next, and may change. Errors about the request itself (`invalid_query`, `invalid_params`, `invalid_cursor`) also carry `details`, an array with one `{ "field", "problem" }` entry per problem, for example:

```json
{
  "error": {
    "code": "invalid_query",
    "message": "limit must be an integer between 1 and 100. Unknown query parameter: foo.",
    "requestId": "6f0c9a3e-3b1d-4a53-9c1e-2d1f6a7b8c90",
    "details": [
      { "field": "limit", "problem": "out_of_range" },
      { "field": "foo", "problem": "unknown_parameter" }
    ]
  }
}
```

`problem` is one of `unknown_parameter`, `duplicate_parameter`, `invalid_value`, `out_of_range` or `token_in_url`.

A `401 invalid_token` also carries one `details` entry, with `field` `authorization`, that says why the token was not accepted:

| `problem` | Meaning | What to do |
| --- | --- | --- |
| `missing` | No `Authorization` or `X-API-Key` header was sent. | Send `Authorization: Bearer <token>`. |
| `malformed` | A header was sent, but it does not hold `zst_` and 43 characters. | Copy the whole token, without quotes or spaces. |
| `unknown` | The token is well formed but is not one of ours. | Check the copy; if the token is lost, create a new one. |
| `revoked` | The token was revoked in the console. | Create a new token. |
| `expired` | The token's expiry date has passed. | Create a new token. |

The `code` is `invalid_token` in every case, so branch on `details[0].problem` when you need the reason. For example, a revoked token answers `"details": [{ "field": "authorization", "problem": "revoked" }]`. `details` is absent on other errors.

Checks run in a fixed order, so you can tell which problem you hit first: body and URL size (`413`, `414`), a token in the URL (`400 invalid_query`), the token (`401`), a suspended studio (`403 developer_suspended`), the token's rate limit (`429`), the scope (`403 insufficient_scope`), the query string (`400 invalid_query`), the `{id}` in the path (`400 invalid_params`), then the data itself (`400 invalid_cursor`, `404 not_found`, `409 amount_unsafe`). A request with the wrong scope and a bad query therefore answers `403`, and every request that got past the token, whatever it answers, spent one unit of the token's minute.

Every `200` and every error response carries `x-request-id` and `Vary: Authorization, X-API-Key`; a `304` may arrive without them. Authenticated responses (200, and errors after the token was accepted and its budget spent, 429 included; not `developer_suspended`, which is answered first) also carry the `RateLimit-*` headers, and a 429 has `Retry-After`.

| Status | `code` | Meaning |
| --- | --- | --- |
| 400 | `invalid_query` | A query parameter is unknown, repeated, malformed or out of range (including a bad stats date range). `message` says which and `details` names each field. |
| 400 | `invalid_params` | The `{id}` in the path is not a UUID, for example a game's slug or name. Use the `id` from the list endpoint. |
| 400 | `invalid_cursor` | The `cursor` is not one we issued. Start again without it. |
| 401 | `invalid_token` | No token, or one that is malformed, unknown, revoked or expired; `details[0].problem` says which (see above). It carries `WWW-Authenticate: Bearer realm="zokogames"`, with `error="invalid_token"` added when a credential header was sent. |
| 403 | `insufficient_scope` | The token lacks the scope this endpoint needs; `message` names it. Create a token with that scope. |
| 403 | `developer_suspended` | The token's studio is suspended, so all its tokens are refused until it is reinstated. Contact developer support. |
| 404 | `not_found` | The game is not one of your studio's (a game of another studio looks the same as one that does not exist), or the path is not an endpoint. |
| 405 | `method_not_allowed` | The method is not `GET`, `HEAD` or `OPTIONS`. `Allow` lists the supported ones. |
| 409 | `amount_unsafe` | Statements endpoints only. An amount of a statement on the page you asked for is outside the range the API can state exactly (beyond 9,007,199,254,740,991 micros), so the whole response is refused rather than rounded. Retrying gives the same answer. Contact developer support: the portal team settles that statement by hand. The `statement.updated` webhook carries `payableMicros: null` for the same statement. |
| 413 | `payload_too_large` | The request body is over 1 KB (600 KB on the build-upload calls), or it was sent chunked. The read endpoints take no body at all. |
| 414 | `uri_too_long` | The URL is longer than 2,048 characters. |
| 429 | `rate_limited` | Too many requests. Wait `Retry-After` seconds. |
| 400 | `invalid_body` | Build upload only. The JSON body is not valid JSON or a field is wrong; `details` names each field. |
| 409 | `too_many_inactive_builds` | Build upload only. The game already holds 10 builds uploaded with API tokens that are not active. Delete old inactive builds on the game's **Builds and updates** page in the console, then start again. |
| 409 | `locked_in_review` | Build upload only. The game is in review, so builds cannot change. Upload again once it is decided. |
| 404 | `upload_not_found` | Build upload only. No such upload for this game and this token's creator. |
| 409 | `upload_closed` | Build upload only. The upload was refused, expired or cleaned up. Start a new one. |
| 409 | `already_processed` | Build upload only. The upload was already confirmed. |
| 409 | `upload_in_progress` | Build upload only. Another confirm is still processing this upload; poll its status. |
| 409 | `not_uploaded` | Build upload only. The file has not arrived in storage yet: finish the `PUT`, then confirm again. |
| 422 | `upload_invalid` | Build upload only. The stored file is not what you declared (a size mismatch answers `409` with the same code). |
| 400 | `parts_required` | Build upload only. A multipart confirm needs the list of parts. |
| 400 | `not_multipart` | Build upload only. A part was requested for an upload that is not multipart. |
| 400 | `invalid_part_number` | Build upload only. The part number is outside the upload's part count. |
| 400 | `invalid_part_size` | Build upload only. A part must be exactly the size the start call announced. |
| 429 | `too_many_open_uploads` | Build upload only. Too many uploads are still waiting to finish (the console's cap, per token creator). |
| 429 | `daily_upload_limit` | Build upload only. Too many uploads were started in 24 hours without being finished. |
| 503 | `storage_unavailable` | Build upload only. Storage did not answer; retry in a minute. |
| 500 | `internal_error` | Our side. Retry after a short wait; if it keeps happening, send us the `requestId`. |

### Pagination

List endpoints take `limit` (1 to 100, default 25) and `cursor`, and answer:

```json
{ "data": [ ... ], "next_cursor": "eyJ0Ijoi...", "meta": { "limit": 25, "count": 25, "has_more": true } }
```

`meta` is on every list: `limit` is the page size applied, `count` the items in `data`, and `has_more` is true exactly when `next_cursor` is set. Some lists add fields to `meta` that describe the whole answer (for example `game_id` or the resolved `range`). Pass `next_cursor` as `cursor` to get the next page; it is `null` on the last page. A cursor is opaque: do not build or change one. Pages are stable while you walk them: a game created meanwhile does not shift the rows you have not seen yet.

### Walk every page

The loop below follows `next_cursor` until it is `null` and prints every game id. It needs `curl` and `jq`.

```bash
cursor=""
while :; do
  page=$(curl -fsS --retry 3 -H "Authorization: Bearer $ZOKO_TOKEN" \
    "https://www.zokogames.com/api/v1/games?limit=100${cursor:+&cursor=$cursor}")
  jq -r '.data[].id' <<<"$page"
  cursor=$(jq -r '.next_cursor // empty' <<<"$page")
  [ -n "$cursor" ] || break
done
```

A cursor only uses the characters `A-Z a-z 0-9 - _`, so it can go into the URL as it is.

## API index

`GET /api/v1`. Any valid token. Lists every endpoint, which of them this token may call, and the token's own details.

```json
{
  "version": "1",
  "studio_id": "…",
  "token": { "id": "…", "name": "reporting", "prefix": "zst_AbCdEfGh", "scopes": ["games:read"],
             "rate_limit_per_min": 300, "expires_at": null },
  "endpoints": [ { "method": "GET", "path": "/api/v1/games", "summary": "List the studio's games",
                   "scope": "games:read", "allowed": true } ],
  "docs_url": "https://www.zokogames.com/docs/guides/developer-api",
  "openapi_url": "https://www.zokogames.com/api/v1/openapi.json"
}
```

It is the quickest way to test a new token: a `200` proves the token works, and `allowed` shows what it can reach.

## Games list

`GET /api/v1/games?limit=&cursor=`. Your studio's games, newest first (scope `games:read`).

```bash
curl -H "Authorization: Bearer zst_your_token" "https://www.zokogames.com/api/v1/games?limit=10"
```

Each item:

```json
{
  "id": "5b0c…", "slug": "sky-runner", "name": "Sky Runner", "status": "full_launch",
  "category": "arcade", "technology": "html5", "orientation": "landscape",
  "plays": 18230, "upvotes": 412, "downvotes": 9, "is_kids": false, "has_iap": false,
  "devices": { "desktop": true, "phone": true, "tablet": true, "chromebook": true, "android": true, "ios": true },
  "allow_embed": false, "allowed_origins": [],
  "published_at": "2026-09-01T10:00:00.000Z",
  "created_at": "2026-08-20T08:15:00.000Z", "updated_at": "2026-11-02T16:40:00.000Z"
}
```

`published_at` is `null` until the game goes live. `status` is one of `draft`, `submitted`, `in_qa`, `changes_requested`, `rejected`, `basic_launch`, `full_qa`, `full_launch` or `unpublished`; players can open the game in `basic_launch`, `full_qa` and `full_launch`, and a state you do not know should be treated as not live. `plays`, `upvotes` and `downvotes` are running totals, not per day.

`has_iap` is `true` when the game offers in-game purchases; a made-for-children game cannot turn it on.

## Game detail

`GET /api/v1/games/{id}` (scope `games:read`).

```bash
curl -H "Authorization: Bearer zst_your_token" "https://www.zokogames.com/api/v1/games/5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d"
```

The fields above plus `short_description`, `description`, `hosting`, `age_rating` (or `null`), `locales` (ISO 639-1 codes), `is_multiplayer`, `has_leaderboard`, `ads_enabled`, `offline_play` and `guide_url` (or `null`). A game of another studio answers `404 not_found`.

### Text format of description and release notes

`description` in the game detail and `release_notes` in the builds list come back exactly as stored. A value saved now is **Markdown** with the fixed set of formatting described in [text formatting](https://docs.zokogames.com/requirements/text-formatting).

A value last saved before 21 November 2026 can still be HTML from the old editor (`description`) or plain text (`release_notes`) until someone saves that field again. There is no format flag: a value that begins with an HTML tag such as `<p>` is most likely old HTML.

Treat every value as untrusted text. Render it through your own sanitiser and never insert it into a page as unsanitised HTML. The controls, FAQ and studio description are not part of the API.

The token API is read-only and cannot write these fields. When a signed-in studio member saves them in the console, the server sanitises them as Markdown.

## Game stats

`GET /api/v1/games/{id}/stats?from=YYYY-MM-DD&to=YYYY-MM-DD`. Daily stats of one of your games (scope `stats:read`).

```bash
curl -H "Authorization: Bearer zst_your_token" \
  "https://www.zokogames.com/api/v1/games/5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d/stats?from=2026-11-01&to=2026-11-18"
```

Days are UTC and both ends are inclusive. `to` defaults to today and `from` to 29 days before `to`. The longest range is **92 days**, `from` must not be after `to`, and `to` cannot be in the future; otherwise `400 invalid_query`. The numbers come from the same report as a game's **Performance** section in the console, so the same days give the same figures; today is still being counted (hourly) and the console leaves it out. Fields use the CSV column names: `gameplays` is the console's **Plays**, `views` its **Views**; the analytics and metrics reference maps every one. Revenue is not part of this endpoint; money is in statements.

```json
{
  "game_id": "5b0c…",
  "range": { "from": "2026-10-20", "to": "2026-11-18" },
  "totals": { "impressions": 1200, "views": 480, "players": 130, "gameplays": 310,
              "playtime_sec": 52000, "avg_playtime_sec": 168, "ctr": 0.4, "conversion": 0.12, "d1_retention": 0.21,
              "orders": 7 },
  "by_day": [ { "day": "2026-10-20", "impressions": 40, "views": 16, "players": 5, "gameplays": 11,
                "playtime_sec": 1800, "avg_playtime_sec": 164, "ctr": 0.4, "conversion": 0.1, "d1_retention": 0.2,
                "orders": 0 } ]
}
```

`by_day` has one entry for every day in the range, with zeros for quiet days. `ctr`, `conversion` and `d1_retention` are fractions from 0 to 1. `players` is the sum of daily unique players, so across several days it can count one person more than once. `orders` is the number of in-game orders your game reported through [`SDK.analytics.trackOrder`](https://docs.zokogames.com/sdk/analytics): self-reported by the game, capped per game and day, and never ZokoGames revenue or part of a payout.

## Statements list

`GET /api/v1/statements?limit=&cursor=`. Your studio's cut statements, newest period first (scope `statements:read`). Open months are not listed until the month is closed.

```bash
curl -H "Authorization: Bearer zst_your_token" "https://www.zokogames.com/api/v1/statements"
```

Sample response (`StatementList`, generated from the test fixture):

```json
{
  "data": [
    {
      "id": "9a1f4c2e-6b3d-4e8a-b5c7-0d2e1f3a4b6c",
      "period": "2026-10",
      "state": "invoiced",
      "currency": "USD",
      "currency_exponent": 2,
      "invoice_number": "INV-2026-10-0007",
      "gross_minor": 1334,
      "share_minor": 675,
      "adjustments_minor": 25,
      "carried_in_minor": 123,
      "payable_minor": 798,
      "paid_at": null,
      "paid_reference": null,
      "paid_minor": null,
      "held_back_minor": null
    },
    {
      "id": "3c7e9b1a-2d4f-4a6c-8e0b-5f1a2c3d4e6f",
      "period": "2026-09",
      "state": "paid",
      "currency": "USD",
      "currency_exponent": 2,
      "invoice_number": "INV-2026-09-0007",
      "gross_minor": 40000,
      "share_minor": 20000,
      "adjustments_minor": 0,
      "carried_in_minor": 0,
      "payable_minor": 20000,
      "paid_at": "2026-11-16T10:00:00.000Z",
      "paid_reference": "TR-1042",
      "paid_minor": 16000,
      "held_back_minor": 4000
    }
  ],
  "next_cursor": null,
  "meta": {
    "limit": 25,
    "count": 2,
    "has_more": false
  }
}
```

Amounts are in minor units (the [webhooks](https://docs.zokogames.com/guides/webhooks) use micros, millionths of the currency: to compare a `statement.updated` `payableMicros` with `payable_minor`, divide by `10^(6 - currency_exponent)`, which is 10,000 for USD, and truncate toward zero): `gross_minor: 1334` with `currency: "USD"` is 13.34 USD. `currency_exponent` is the number of decimal digits of the minor unit (2 for USD, 0 for JPY). `payable_minor` is the share plus the amount carried in, truncated to whole minor units; it can differ by one minor unit from adding the rounded parts. `state` is `invoiced`, `held`, `paid` or `rolled_over`. For a printable or downloadable invoice, use **Download PDF** on the statement page in the console: it is the same document, generated for you, with a watermark when the statement comes from the sandbox payout provider. `paid_minor` and `held_back_minor` are set once `state` is `paid`: the amount actually sent to you and the part the new-studio holdback kept back (`0` when none applied), from the payment record; both are `null` before payment and when the amount cannot be read exactly. `payable_minor` keeps its meaning. After a Stripe transfer is reversed in full both become `null`; after a partial reversal `paid_minor` stays the amount sent. An accepted Circle payment that arrived over or under is stated as it arrived, so `paid_minor + held_back_minor` can differ from `payable_minor`.

## Daily stats, paginated

`GET /api/v1/games/{id}/stats/daily?from=YYYY-MM-DD&to=YYYY-MM-DD&limit=&cursor=` (scope `stats:read`). The same daily numbers as `by_day` above, one row per UTC day, **oldest first**, read page by page. Use it when you pull long histories: the range may be up to **366 days** (the report above is limited to 92). `from` and `to` follow the same rules (`to` defaults to today, `from` to 29 days before `to`, no future days). `meta.range` echoes the range that was applied. A game of another studio answers `404 not_found`.

```bash
curl -H "Authorization: Bearer zst_your_token" \
  "https://www.zokogames.com/api/v1/games/5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d/stats/daily?from=2026-11-17&to=2026-11-18&limit=25"
```

Sample response (`DailyStatsList`, generated from the test fixture):

```json
{
  "data": [
    {
      "day": "2026-11-17",
      "impressions": 40,
      "views": 16,
      "players": 5,
      "gameplays": 11,
      "playtime_sec": 1800,
      "avg_playtime_sec": 164,
      "ctr": 0.4,
      "conversion": 0.1,
      "d1_retention": 0.2,
      "orders": 2
    },
    {
      "day": "2026-11-18",
      "impressions": 80,
      "views": 32,
      "players": 10,
      "gameplays": 22,
      "playtime_sec": 3600,
      "avg_playtime_sec": 164,
      "ctr": 0.4,
      "conversion": 0.1,
      "d1_retention": 0.2,
      "orders": 4
    }
  ],
  "next_cursor": null,
  "meta": {
    "limit": 25,
    "count": 2,
    "has_more": false,
    "game_id": "5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d",
    "range": {
      "from": "2026-11-17",
      "to": "2026-11-18"
    }
  }
}
```

## Builds

`GET /api/v1/games/{id}/builds?limit=&cursor=` (scope `games:read`). Every build uploaded for one of your games, newest version first, the same list as the console's Builds tab. `active` is true for the live build, `pending_review` when an update submission for it is waiting for review. `validation` is the result of the upload checks (`ok` and a list of `issues`), or `null`. The machine-readable error codes (`issueDetails`) are returned only by the upload check itself; see [what the build check returns](https://docs.zokogames.com/requirements/build-validation#what-the-build-check-returns).

A build in this list has no address. To open one, use the console preview: for a build players are not being served (a draft, an update waiting for review, an older build) it adds a short-lived preview link (`zk_preview_token`, valid for 15 minutes), for signed-in members of your studio only. The console's own build list (`GET /api/developer/games/{id}/builds`, signed-in session, not an API token) keeps the same `url` field as before; for such a build that `url` now carries the preview link, and the answer is sent with `Cache-Control: private, no-store`. Do not store or share it: open it within 15 minutes.

```bash
curl -H "Authorization: Bearer zst_your_token" \
  "https://www.zokogames.com/api/v1/games/5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d/builds"
```

Sample response (`BuildList`, generated from the test fixture):

```json
{
  "data": [
    {
      "id": "e7f8a9b0-c1d2-4e3f-a4b5-c6d7e8f9a0b1",
      "version": 3,
      "active": true,
      "pending_review": false,
      "entry_file": "index.html",
      "file_count": 42,
      "total_bytes": 8388608,
      "release_notes": "New desert level.",
      "validation": {
        "ok": true,
        "issues": []
      },
      "created_at": "2026-11-02T16:40:00.000Z"
    }
  ],
  "next_cursor": null,
  "meta": {
    "limit": 25,
    "count": 1,
    "has_more": false,
    "game_id": "5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d"
  }
}
```

### Check a build from your pipeline

To upload from CI, see [Upload a build from CI](#upload-a-build-from-ci). After an upload, a pipeline can wait for what happens next with this script, which reads the newest build of a game and waits until it is live. It needs `curl` and `jq`, and a token with the `games:read` scope kept as a secret in your CI system.

```bash
#!/usr/bin/env bash
# usage: ZOKO_TOKEN=zst_... ./check-build.sh <game id> <expected build number>
set -euo pipefail
game="$1"; want="$2"
url="https://www.zokogames.com/api/v1/games/$game/builds?limit=1"
for i in $(seq 1 30); do
  body=$(curl -fsS -H "Authorization: Bearer $ZOKO_TOKEN" "$url")
  build=$(jq -c '.data[0] // empty' <<<"$body")
  if [ -n "$build" ] && [ "$(jq .version <<<"$build")" -ge "$want" ]; then
    if [ "$(jq .validation.ok <<<"$build")" = "false" ]; then
      echo "Build $want failed its checks:"; jq -r '.validation.issues[]' <<<"$build"; exit 1
    fi
    if [ "$(jq .active <<<"$build")" = "true" ]; then echo "Build $want is live."; exit 0; fi
    if [ "$(jq .pending_review <<<"$build")" = "true" ]; then echo "Build $want is waiting for review."; exit 3; fi
  fi
  sleep 10
done
if [ "$(jq .validation.ok <<<"${build:-null}")" = "true" ]; then
  echo "Build $want passed its checks but is not live: press Activate or Send for review in the console."
else
  echo "Build $want is not live yet."
fi
exit 2
```

`curl -f` makes a `4xx` or `5xx` fail the step but hides the error body (with its `code` and `requestId`); drop `-f` and print the body while you are setting this up. Exit codes: `0` live, `1` failed the upload checks, `2` not live within five minutes (the message says when the build passed its checks and is only waiting for someone to press **Activate** or **Send for review**, which a build of a live game always needs), `3` uploaded but waiting for review. A `429` means the token's minute is spent; this script makes at most 30 requests in five minutes, far below the default 300 a minute. To react to a build without polling, subscribe to the `build.activated` [webhook](https://docs.zokogames.com/guides/webhooks) instead.

## Upload a build from CI

A token with the `builds:write` scope can upload a build the way the console does, without a browser. The API only **creates and checks** the build: the same upload checks, the same size and file-count limits ([limits](https://docs.zokogames.com/requirements/build-validation#limits)) and the same zip checks as the console. It cannot activate a build, send a game for review, publish, roll back or delete anything. **A build uploaded with a token always lands inactive**, even for a game that is not live yet (the console makes a new valid build active automatically before launch; the API does not). Open the game's **Builds and updates** page, look at the build, and press **Activate** (or **Send for review** for a live game) yourself.

Set it up once:

1. Create a token on the **API tokens** page with **only** the `builds:write` scope (least privilege: a CI token should not read stats or statements). Creating it asks you to confirm with a passkey or authenticator app, like any token. Only an owner or admin can create it, and the token stops working if that person leaves the studio or is no longer an owner or admin.
2. Store the token as a **secret** of your CI system (for example `ZOKO_TOKEN`), never in the repository or in a build log. Treat it like a password and **rotate** it: create a new token, update the secret, then revoke the old one. Give it an expiry (the console offers 30, 90 or 365 days).
3. Find your game's id (the last part of its address in the console, or `GET /api/v1/games`).

The upload has three steps, for a zip of any size. A game of another studio answers `404 not_found`, the same as a game that does not exist.

**1. Start.** Send the zip's size in bytes. The answer is where to send the file.

```bash
curl -X POST "https://www.zokogames.com/api/v1/games/5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d/builds/uploads" \
  -H "Authorization: Bearer $ZOKO_TOKEN" -H "Content-Type: application/json" \
  -d "{\"size\": $(wc -c < game.zip | tr -d ' ')}"
```

```json
{
  "uploadId": "8d2f1c64-9b7e-4a30-8f55-3c1e6a0b9d72",
  "multipart": false,
  "put": {
    "url": "https://storage.example/upload?signature=...",
    "headers": { "Content-Type": "application/zip" },
    "expiresAt": 1790000000000
  }
}
```

**2. Send the file** straight to storage with the headers the answer gives (it does not pass through this API, and it needs no token):

```bash
curl -X PUT -H "Content-Type: application/zip" --data-binary @game.zip "<put.url>"
```

A zip over 50 MB answers `"multipart": true` with `multipartId`, `partSize` and `partCount`. Cut the file into `partSize` pieces (the last one is smaller). For each part, `POST /api/v1/games/{id}/builds/uploads/{uploadId}/parts` with `{ "multipartId", "partNumber", "contentLength" }` returns a fresh `PUT` URL (call it again to retry a part), and the storage answer to each `PUT` carries an `ETag` header to keep.

**3. Confirm and read the report.** `POST /api/v1/games/{id}/builds/uploads/{uploadId}/confirm` finishes a multipart upload (send `{ "multipartId", "parts": [{ "partNumber", "etag" }] }`; a single upload needs no such fields), runs the build check and stores the build. Optional `releaseNotes` (basic Markdown, sanitised like the console's) appear in the build history. It answers `200` **whether the build passes or not**: read `ok`.

```bash
curl -X POST "https://www.zokogames.com/api/v1/games/5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d/builds/uploads/8d2f1c64-9b7e-4a30-8f55-3c1e6a0b9d72/confirm" \
  -H "Authorization: Bearer $ZOKO_TOKEN" -H "Content-Type: application/json" \
  -d '{"releaseNotes": "Build from CI."}'
```

The answer is the console's confirm answer (see [what the build check returns](https://docs.zokogames.com/requirements/build-validation#what-the-build-check-returns)) plus `findings`, one entry per finding with the stable `code`, `severity` (`error`, `warn`, `info`), a `message`, a `hint` that says how to fix it, the `path` and `line` when known, and a `docs` link: the same codes and fix hints as the console's report. `activated` is always `false` and `next` is `activate`.

```json
{
  "ok": false,
  "buildId": null,
  "version": null,
  "activated": false,
  "validation": { "ok": false, "issues": ["index.html must be at the root of the zip"] },
  "findings": [
    {
      "code": "no_index",
      "severity": "error",
      "message": "index.html must be at the root of the zip.",
      "hint": "Zip the contents of your export folder, not the folder itself.",
      "path": null,
      "line": null,
      "count": null,
      "paths": null,
      "docs": "https://www.zokogames.com/docs/requirements/build-validation#code-no-index"
    }
  ]
}
```

**If the confirm answer is lost** (a timeout in CI), do not start again: `GET /api/v1/games/{id}/builds/uploads/{uploadId}` answers `state` (`presigned`, `uploaded`, `processing`, `processed` or `failed`), and for a refused build the stored `validation` and `findings`. When it says `processed`, the build exists: read it with `GET /api/v1/games/{id}/builds` (scope `games:read`) or on the **Builds and updates** page. Only uploads made by the token's creator for that game are visible.

A plain shell script for any CI job. Keep `ZOKO_TOKEN` in the CI system's secret store and pass it to the job as an environment variable, with `ZOKO_GAME_ID` next to it. Never add `set -x` or `curl -v`: they print request headers, and with them your token, into the job log. Needs `curl` and `jq`:

```bash
#!/usr/bin/env bash
# usage: ZOKO_TOKEN=zst_... ZOKO_GAME_ID=... ./zoko-upload.sh game.zip   (single upload, zips up to 50 MB)
# Never add `set -x` or `curl -v`: the token would be printed to the job log.
set -euo pipefail
API="https://www.zokogames.com/api/v1/games/$ZOKO_GAME_ID/builds/uploads"
AUTH="Authorization: Bearer $ZOKO_TOKEN"
size=$(wc -c < "$1" | tr -d ' ')
start=$(curl -sS -X POST "$API" -H "$AUTH" -H "Content-Type: application/json" -d "{\"size\": $size}")
id=$(jq -er .uploadId <<<"$start") || { echo "$start"; exit 1; }
[ "$(jq .multipart <<<"$start")" = "false" ] || { echo "Over 50 MB: use the multipart steps"; exit 1; }
curl -fsS -X PUT -H "Content-Type: application/zip" --data-binary @"$1" "$(jq -r .put.url <<<"$start")"
done=$(curl -sS -X POST "$API/$id/confirm" -H "$AUTH" -H "Content-Type: application/json" -d '{}')
if [ "$(jq .ok <<<"$done")" != "true" ]; then
  echo "Build rejected:"; jq -r '.findings[]? | "[\(.severity)] \(.code): \(.message) \(.hint // "")"' <<<"$done"
  jq -r '.error.message? // empty' <<<"$done"; exit 1
fi
echo "Build $(jq .version <<<"$done") uploaded. It is inactive: activate it in the console."
```

Limits, on top of the token's per-minute limit: each token may make 10 start calls, 300 part calls, 10 confirm calls and 240 status calls an hour, and the whole studio 20, 600, 20 and 480. Beyond that you get `429 rate_limited` with a `Retry-After` of the real wait. Uploads started with a token also have their own daily bucket, apart from the console's: at most 10 unfinished uploads per token and 20 per studio in 24 hours (`429 daily_upload_limit`), which never use up, and are never limited by, any person's console uploads. A game keeps at most 10 builds made by tokens that are not active; past that, starting another is refused with `409 too_many_inactive_builds` until you delete old inactive builds on the game's **Builds and updates** page.

Every build stored this way is written to the studio's audit trail with the token's id and name (not a person), and so is a rejected one. Each uploaded build also sends the studio's owners and admins a notice in the console that names the token, linking to the game's **Builds and updates** page: if nobody on your team did the upload, revoke the token at once. The `build.published` [webhook](https://docs.zokogames.com/guides/webhooks) carries `uploadedBy` with the token's id and name, and the build is not live.

The upload calls never answer from a cache, and the `PUT` URLs they return are valid for a short time only (about 15 minutes): start the upload right before sending the file.

## Feedback

`GET /api/v1/games/{id}/feedback?resolved=all&limit=&cursor=` (scope `games:read`). Player feedback for one of your games, newest first. `resolved` is `false` (open items, like the console inbox), `true` or `all` (default). `reply_count` is how many replies the studio has sent. Player email addresses, account ids and the technical context are never part of this endpoint; answer players from the console.

```bash
curl -H "Authorization: Bearer zst_your_token" \
  "https://www.zokogames.com/api/v1/games/5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d/feedback?resolved=false"
```

Sample response (`FeedbackList`, generated from the test fixture):

```json
{
  "data": [
    {
      "id": "b4c5d6e7-f8a9-4b0c-91d2-e3f4a5b6c7d8",
      "game_id": "5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d",
      "subject": "Bug report",
      "message": "The jump button stops responding after level 3.",
      "resolved": false,
      "reply_count": 1,
      "created_at": "2026-11-02T16:40:00.000Z"
    }
  ],
  "next_cursor": null,
  "meta": {
    "limit": 25,
    "count": 1,
    "has_more": false,
    "game_id": "5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d"
  }
}
```

## Leaderboards

`GET /api/v1/leaderboards?limit=&cursor=` (scope `games:read`). The settings of every leaderboard in your studio, ordered by game id, with the number of scores in the running season (`season`, `season_entries`) and across all seasons (`all_entries`). `has_api_key` says whether a server API key exists; the key and the encryption key are never returned. Scores of individual players are not part of the API.

```bash
curl -H "Authorization: Bearer zst_your_token" "https://www.zokogames.com/api/v1/leaderboards"
```

Sample response (`LeaderboardList`, generated from the test fixture):

```json
{
  "data": [
    {
      "game_id": "5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d",
      "game_slug": "sky-runner",
      "enabled": true,
      "score_label": "POINTS",
      "sorting": "DESC",
      "min_value": 0,
      "max_value": 999999999,
      "cooldown_seconds": 0,
      "is_incremental": false,
      "has_api_key": true,
      "season": "2026-W47",
      "season_entries": 214,
      "all_entries": 1893
    }
  ],
  "next_cursor": null,
  "meta": {
    "limit": 25,
    "count": 1,
    "has_more": false
  }
}
```

## Statement lines

`GET /api/v1/statements/{id}/lines?limit=&cursor=` (scope `statements:read`). The line items of one cut statement, as snapshotted when the month closed, in statement order. `{id}` is the `id` from the statements list; a statement of another studio, or one still open, answers `404 not_found`. Each line is one game and one `source` (`ads`, or `store` for real-money in-game store revenue, which has its own share rate). Amounts are minor units in `meta.currency`, with `meta.currency_exponent`; `share_percent` is the studio's rate on the line. `game_id` is `null` on the single summary line of statements cut before per-game lines existed.

```bash
curl -H "Authorization: Bearer zst_your_token" \
  "https://www.zokogames.com/api/v1/statements/9a1f4c2e-6b3d-4e8a-b5c7-0d2e1f3a4b6c/lines"
```

Sample response (`StatementLineList`, generated from the test fixture):

```json
{
  "data": [
    {
      "game_id": "5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d",
      "game_name": "Sky Runner",
      "source": "ads",
      "gross_minor": 1200,
      "ivt_minor": 20,
      "net_gross_minor": 1180,
      "share_percent": 50,
      "share_minor": 590
    },
    {
      "game_id": "5b0c7d3e-8a41-4f6b-9c2d-1e7f0a3b4c5d",
      "game_name": "Sky Runner",
      "source": "store",
      "gross_minor": 134,
      "ivt_minor": 0,
      "net_gross_minor": 134,
      "share_percent": 70,
      "share_minor": 93
    }
  ],
  "next_cursor": null,
  "meta": {
    "limit": 25,
    "count": 2,
    "has_more": false,
    "statement_id": "9a1f4c2e-6b3d-4e8a-b5c7-0d2e1f3a4b6c",
    "period": "2026-10",
    "currency": "USD",
    "currency_exponent": 2
  }
}
```

## Game settings

Game settings are changed from the console, which uses `PATCH /api/developer/games/{id}` with a session (not a token). The body is strict: unknown fields are rejected. These fields matter here:

- **`allowedOrigins`**: a list of up to 10 sites that may embed the game, validated and normalised as described in [Restrict which sites may embed](https://docs.zokogames.com/requirements/embedding#restrict-which-sites-may-embed-allowed-sites). Invalid input is a `400` that names the entry. `[]` removes the restriction.
- **`desktopEnabled`, `phoneEnabled`, `tabletEnabled`** (booleans, all `true` by default): turn a device class off to tell players on it that the game is not available there. At least one must stay on.
- **`chromebookEnabled`, `androidEnabled`, `iosEnabled`** (booleans, all `true` by default): the per-platform switches (Chromebook, Android, iPhone and iPad). A player on a switched-off platform sees the same "not available on this device" message on the game page and in embeds. They are returned by the read API as `devices.chromebook`, `devices.android` and `devices.ios`, next to `devices.desktop`, `devices.phone` and `devices.tablet`.
- **`hosting`** (`"hosted"` or `"external"`) and **`externalUrl`**: a game hosted on your own server is framed from `externalUrl`. The address must be `https`, at most 500 characters, a public host name, and carry no username or password. Addresses on the portal itself are refused (the site, the docs, blog and other section hosts, the SDK and image hosts; only a hosted-build address `g-<slug>.zokogames.com` is allowed), and so are `localhost`, IP numbers and internal names. Your server must allow being embedded in a frame from zokogames.com.

Staff can set the same fields from the admin editor.

## Next steps

- [Webhooks](https://docs.zokogames.com/guides/webhooks)
- [Analytics and metrics reference](https://docs.zokogames.com/guides/analytics-metrics)

---

Source: https://docs.zokogames.com/guides/multiplayer-rooms

# Multiplayer rooms

This page shows how to make the players of one room talk to each other with `SDK.game.room`, without running your own server. It covers how a room starts and ends, the limits, the events you receive, what changes in local mode, and a small two-player example you can run. The short reference is in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel); invite links and the friend tray are in [multiplayer and invites](https://docs.zokogames.com/guides/multiplayer-invites); the rules a multiplayer game must meet are in the [multiplayer requirements](https://docs.zokogames.com/requirements/multiplayer).

## What a room is

A room is a small group of signed-in players who are in the same game and share a room id. The portal keeps the list of members, picks one of them as host, and relays your messages between them. It does not run game logic, check moves or store anything. For physics, matchmaking beyond a lobby, or anti-cheat you still need your own server.

There are three pieces:

| Piece | What it is | Who can write |
| --- | --- | --- |
| Messages | Small JSON values sent with `send`, to everyone else or to one member. No history, no replay. | Any member |
| Shared state | A key-value object the whole room can read. A new member receives the current copy first. | The host only |
| Members | The list of players with `id`, `username` and `profilePictureUrl`, plus the host id. | The platform |

The channel is a game data channel, not a text chat. Do not use it to move free text between players; if you do, the [chat rules](https://docs.zokogames.com/requirements/multiplayer#chat-and-user-content) apply to your game.

## Start and end a room

A room starts when your game calls `SDK.game.updateRoom({ roomId, isJoinable, inviteParams })`, or when the player joins from an invite and your game then calls `updateRoom` with the room id it was given. It ends for a player when your game calls `SDK.game.leftRoom()`, when the player closes the game, or when their connection stays down for more than 30 seconds.

```js
const SDK = window.ZokoGames.SDK;
await SDK.init();

// Host: create a room and make it joinable.
await SDK.game.updateRoom({ roomId: "lobby-7", isJoinable: true, inviteParams: { room: "lobby-7" } });

// Guest: the room id arrives in the invite parameters.
const roomId = SDK.game.getInviteParam("room");
if (roomId) await SDK.game.updateRoom({ roomId });
```

Facts about `updateRoom` that matter here:

- If you leave out `roomId`, the portal makes one up. Room ids are letters, digits, `_`, `.` and `-`, at most 64 characters; other characters are replaced by `_`.
- The first player into a room is its host. Only the host changes `isJoinable` and `inviteParams` for the room.
- A new room holds as many players as the maximum lobby size you entered at upload, but never more than 100. If the game has no lobby size, the portal uses 8.
- A player who joins a full room, or a room whose host set `isJoinable: false`, is refused. Show your own "room full" message; the refusal is not an SDK error code.
- The same account in two browser tabs counts as one member.
- An empty room is deleted one minute after its last member left. Its shared state is deleted at once.

From SDK 1.6.0, the host can call `updateRoom({ isPublic: true })` to let friends join the room from their friends list; rooms are private by default, and in kids mode they always stay private. Call it after `onHostChange` reports that this player is the host; a call made before the first `onHostChange` is ignored.

### When rooms are not available

Rooms need a realtime identity, which only a signed-in player has. In these cases `updateRoom` still resolves, but nothing is announced and the channel does not work:

| Situation | What your game sees |
| --- | --- |
| Guest | `send` and `setState` reject with `roomUnavailable`. |
| Kids mode, or a game made for children | The portal never opens realtime for the visitor, so `send` and `setState` fail. Do not offer multiplayer there; see [kids mode](https://docs.zokogames.com/guides/kids-mode). |
| Signed-in account with no 13+ birthday on file, or an account scheduled for deletion | Same as a guest on the portal side. Calls fail with `notInRoom` or `roomUnavailable`. |
| Realtime switched off on the portal | `roomUnavailable`. |

Offer a sign-in button before you offer a room, with `SDK.user.showAuthPrompt()`, and let guests play a single-player mode.

In kids mode `send` and `setState` always reject with `roomUnavailable`. `SDK.user.isUserAccountAvailable` is `false` there, so use it to hide your multiplayer entry points; see [kids mode](https://docs.zokogames.com/guides/kids-mode#calls-in-kids-mode).

## Limits

| Limit | Value | When it is broken |
| --- | --- | --- |
| Message size (`send`) | 8 KB of JSON | `send` rejects with `payloadTooLarge` before anything is sent. |
| State patch size (`setState`) | 8 KB of JSON | `setState` rejects with `payloadTooLarge`. |
| Keys in one patch | 64 | `invalidArgument`. |
| State key | 1 to 40 characters of `A-Z a-z 0-9 _ . : -` | `invalidArgument`. |
| Shared state, total | 64 KB of JSON | `stateTooLarge`, reported through `onError`. |
| Message rate | 20 per second per player, burst of 20 | `rateLimited`; the extra messages are dropped. |
| Players in a room | Your maximum lobby size, at most 100 (8 if none was set) | The join is refused. |
| Room lifetime | While anyone is in it; deleted 1 minute after the last member leaves | Nothing is kept. |
| Reconnect window | 30 seconds | After that the player leaves the room. |

Both `send` and `setState` count against the 20 per second. If a player keeps sending more than that, 10 rejected messages inside 10 seconds close their realtime connection; the portal reconnects and rejoins the room, but messages sent meanwhile are lost.

Send less, not faster. Position updates at 10 per second are plenty for most games; send changes, not the whole world.

## Events

Every `on*` method returns a function that removes the listener. Each also has an `add...Listener` and `remove...Listener` form (`addMessageListener`, `removeMessageListener`, and so on); both forms do the same.

| Method | Fires when | Arguments |
| --- | --- | --- |
| `onMessage(cb)` | Another member sent a message. Never for your own. | `{ from, data, direct, seq, ts }`. `from`, `seq` and `ts` are set by the platform. |
| `onMembers(cb)` | A player joined or left, or a profile changed. | The full list of `{ id, username, profilePictureUrl }`. |
| `addLeftListener(cb)` | The portal ended your membership without you asking (SDK 1.7.0). | `{ reason, roomId? }`, `reason` one of `left`, `kicked`, `closed`, `disconnected`. There is no `onLeft`; use `addLeftListener` / `removeLeftListener`. |
| `onHostChange(cb)` | The host changed, including the first assignment. | `hostId` (or `null`) and `isHost` (true when it is you). |
| `onState(cb)` | The shared state changed, or you received it in full after joining. | The whole state, and `{ keys, rev, by? }` describing the change. |
| `onError(cb)` | The platform refused something after the call had already returned. | `{ code, message }`. |

**When `addLeftListener` fires.** It reports a membership that ended on the portal side. `left`: the server dropped the player from the room without your `leftRoom()` (the player left from another place, or the portal ended the session, for example a sign-out). `kicked`: the room goes on but the player is no longer a member. `closed`: the room service refused the room your `updateRoom` announced because it is closed. `disconnected`: the connection to the room service is gone for good (signed out, or the connection was taken over by another one; a short drop that reconnects fires nothing). Before the event, `onMembers` listeners get an empty list and `selfId` is `null`, so a game that only watches members already goes back to its lobby; use the event to tell the player why. **It is never sent for a `leftRoom()` your game made itself** (your code already knows, and the call's promise is the answer), and it fires once per room. Call `updateRoom` again to start or join a room after it. Not sent in kids mode, where there are no rooms.

Reading is synchronous: `members()`, `getState()`, `isHost()` and `selfId` give the current values. The host's own `setState` is applied when the platform confirms it, so read the result from `onState` or `getState()`, not straight after the `await`.

`seq` rises for every message in the room. Gaps are possible; order by it, and do not wait for a missing number.

### Host changes

The first player in is the host. When the host leaves, the member who has been in the room longest becomes host and `onHostChange` fires for everyone. The shared state stays. Put host duties (starting a round, advancing a counter) behind `isHost()` and re-check it inside `onHostChange`, so the game keeps going when the host closes the tab.

## Errors

| Code | Cause | Fix |
| --- | --- | --- |
| `notInRoom` | `updateRoom` was not called yet, or the player has no realtime identity. | Call `updateRoom` first; check sign-in. |
| `notHost` | A non-host called `setState`. | Guard with `isHost()`. |
| `payloadTooLarge` | A message or patch over 8 KB. | Send a smaller value. |
| `stateTooLarge` | The patch would push the state over 64 KB. | Remove keys with `null`, or keep bulky data elsewhere. |
| `unknownMember` | `to` is not a member of the room, or is yourself. | Take `to` from `members()`. |
| `rateLimited` | More than 20 messages per second. | Throttle, or merge updates into one message. |
| `roomUnavailable` | Guest, kids mode or realtime off. | Offer sign-in or a single-player mode. |
| `invalidArgument` | A value that cannot be turned into JSON, a bad state key or an empty patch. | Fix the call. |

`payloadTooLarge`, `notHost`, `invalidArgument` and `roomUnavailable` can reject the call itself. `rateLimited`, `unknownMember` and `stateTooLarge` usually arrive later through `onError`. Catch both. Errors are plain `{ code, message }` objects, not `Error` instances.

## A minimal two-player example

Each player has a tap counter. Everyone sees every counter, and the host sets the target score. Save it as `index.html`, serve it from `localhost` and open it in two tabs; the steps are under [test with two tabs](#test-with-two-tabs).

```html
<!doctype html>
<meta charset="utf-8">
<title>Tap race</title>
<button id="tap">Tap</button>
<button id="copy">Copy invite link</button>
<pre id="out">Starting...</pre>
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script>
(async () => {
  const SDK = window.ZokoGames.SDK;
  await SDK.init();
  const room = SDK.game.room;
  const out = document.getElementById("out");
  const taps = {};
  let mine = 0;

  const draw = () => {
    const target = room.getState().target ?? "?";
    const lines = room.members().map((m) => {
      const tag = m.id === room.selfId ? " (you)" : "";
      return `${m.username}${tag}: ${taps[m.id] ?? 0}`;
    });
    out.textContent = `Target ${target}${room.isHost() ? " (you are host)" : ""}\n` + lines.join("\n");
  };

  room.onMembers(draw);
  room.onState(draw);
  room.onHostChange((hostId, isHost) => {
    if (isHost && room.getState().target === undefined) room.setState({ target: 20 }).catch(console.warn);
  });
  room.onMessage(({ from, data }) => {
    if (data.type === "taps") { taps[from] = data.count; draw(); }
  });
  room.onError((e) => console.warn("room error", e.code, e.message));

  const roomId = SDK.game.getInviteParam("room")
    ?? (SDK.environment === "local" ? "demo" : crypto.randomUUID().slice(0, 8));
  await SDK.game.updateRoom({ roomId, isJoinable: true, inviteParams: { room: roomId } });

  document.getElementById("tap").onclick = () => {
    mine += 1;
    taps[room.selfId] = mine;
    room.send({ type: "taps", count: mine }).catch(console.warn);
    draw();
  };
  document.getElementById("copy").onclick = async () => {
    navigator.clipboard.writeText(await SDK.game.inviteLink({ room: roomId }));
  };
  window.addEventListener("pagehide", () => SDK.game.leftRoom());
  draw();
})();
</script>
```

In this example the host writes `target` once, every player broadcasts its own counter, and the display redraws on every member, state or message event. It does not handle a late joiner who missed earlier counters; to fix that, send your own counter again from `onMembers` when the member list grows, or keep each counter in the shared state through the host.

## Local mode

When you open the game from `localhost` (or add `?useLocalSdk=true`), `SDK.game.room` runs against a stand-in. Tabs of the same origin that call `updateRoom` with the same `roomId` are connected through a `BroadcastChannel`, so two tabs behave like two players. See [local testing](https://docs.zokogames.com/getting-started/local-testing) for how local mode starts.

What is the same as the portal: the 8 KB, 20 per second and 64 KB limits, the error codes, the first-in-is-host rule, host migration, direct messages and the full state a joiner receives.

What differs:

| Difference | Detail |
| --- | --- |
| Players | The local player is signed in as a mock user (`?user_response=logged_out` makes it a guest, and then `send` fails with `roomUnavailable`). Every tab is its own member, with id `<user id>:<tab id>`. |
| Room id | If you omit `roomId`, the page address `roomId` parameter is used, else `local-room`. |
| Host | The tab that joined first. A tab that goes silent for about seven seconds is dropped from the member list. |
| `seq` | Counts what this tab received, not a room-wide number. |
| Lobby size | Not enforced, and `isJoinable: false` does not refuse anyone. |
| Invites | There are no friends. `addJoinRoomListener` never fires; pass the room id in the page address. |
| Realtime outages | Not simulated. |

Local mode is not the portal. Before you submit, run the same flow in the [Preview tool](https://www.zokogames.com/preview) or the build preview and then with two real accounts.

## Test with two tabs

1. Serve the example on `localhost` and open `http://localhost:8080/?sdk_debug=true`. `sdk_debug=true` logs every SDK call.
2. Open the same address in a second tab. In local mode both tabs use the room id `demo`.
3. Press **Tap** in each tab. Both lists should update. The first tab shows "you are host".
4. Close the first tab. Within about seven seconds the second tab's list drops the player, `onHostChange` fires and the second tab becomes host.
5. Paste a 9 KB string into a `send` call from the console and check that it rejects with `payloadTooLarge`.

## Before you submit

- [ ] The game handles `addLeftListener` (back to the lobby, with a message) as well as its own leave button.
- [ ] `updateRoom` is called when the player creates or joins a room, and `leftRoom` when they leave.
- [ ] The game starts and works for a guest (single player) and tells guests why multiplayer needs sign-in.
- [ ] Messages stay under 8 KB and well under 20 per second; the shared state stays small.
- [ ] Host duties move correctly when the host leaves; the room does not freeze when anyone drops.
- [ ] Both `send` and `setState` errors are caught, and `onError` is handled.
- [ ] The minimum and maximum lobby size in the submission match what the game allows.
- [ ] If players can read each other's text, they can report it with [`game.reportChat`](https://docs.zokogames.com/sdk/game#reporting-chat) (SDK 1.4.0).
- [ ] No free text travels through the room without moderation, and `disableChat` is respected for your own chat.

## Next steps

- [Multiplayer and invites](https://docs.zokogames.com/guides/multiplayer-invites) for join links and the friend tray.
- [Multiplayer requirements](https://docs.zokogames.com/requirements/multiplayer) for what a reviewer checks.
- [Kids mode](https://docs.zokogames.com/guides/kids-mode) for why rooms are off for children.
- [Launch checklist](https://docs.zokogames.com/guides/launch-checklist) for the full path to a published game.
- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting#multiplayer-rooms) if a call fails.

---

Source: https://docs.zokogames.com/guides/kids-mode

# Kids mode and games made for children

This page is for developers who make a game for young children, or whose game may be played by a child in kids mode. It explains what the portal does in that case, what the SDK reports to your game, what your game must do itself, and how to test it. The full content rules a reviewer applies are under [age rating](https://docs.zokogames.com/requirements/gameplay#age-rating) and in the [requirements checklist](https://docs.zokogames.com/requirements/checklist#made-for-children-when-ticked).

## Two things with one name

| Name | What it is | Who sets it |
| --- | --- | --- |
| **Made for children** (the kids flag) | A setting of your game. Tick it in the **Audience and distribution** card. The game is listed in the kids area and always runs with the restrictions below. | You, confirmed by a reviewer |
| **Kids mode** | A switch on the visitor's device (a host-only cookie named `__Host-zoko-kids`), or the kids site itself: every page served from the kids host `kids.zokogames.com` is in kids mode whatever the cookie says, and the kids area pages (`/kids`, `/parents`, `/embed`) are in kids mode for that request. A parent turns the cookie on in one tap; turning it off needs a multiplication question (the parent gate). While it is on, the visitor can only open the kids area, kids games, the parent pages and legal pages. | A parent, or the portal by host |

Inside the game frame the two behave the same way. The portal treats a player as a child when either is true: the game has the kids flag, or the visitor's kids mode is on. Games without the flag are not shown in kids mode; if a child opens one by address, the page sends them back to the kids area.

## What the SDK tells your game

The portal tells your game through `SDK.game.settings.kidsMode`, on every game: `true` in kids mode and for a game with the kids flag, `false` otherwise. In the same cases it sets `disableChat` to `true`. The field is typed from SDK 1.5.0; an older SDK build copies the settings object it receives, so the value is readable there too. Where it is `undefined` (an older SDK in local mode, for example), fall back to `disableChat`. Read it at start and in the settings listener, and hide chat, multiplayer, sign-in and shop screens when it is `true`. For everything else, write code that works when each feature is simply missing.

```js
const isKids = (s) => s.kidsMode ?? s.disableChat;
const applyKids = (s) => { multiplayerButton.hidden = isKids(s); };
applyKids(SDK.game.settings);
SDK.game.addSettingsChangeListener(applyKids);
```

| SDK call | In kids mode or for a kids game |
| --- | --- |
| `SDK.game.settings.kidsMode` | `true` in kids mode and for a game with the kids flag, `false` otherwise. Sent by the portal on every game; typed from SDK 1.5.0 and passed through untyped by older builds. |
| `SDK.game.settings.disableChat` | `true` from the start for a game with the kids flag, and for any player in kids mode on any game. Respect it: hide your own text input and incoming text. |
| `SDK.ad.requestAd` | A game with the kids flag: rejects with `adsDisabled`, because ads never run for a kids game and no ad network script is loaded. A game without the flag that runs under kids mode: the call is not refused because of kids mode. The game's normal ad settings and limits apply, but only contextual or house ads play, with no ad network script, no blocker check and no ad-free offer; if the game has no ads enabled it still rejects with `adsDisabled`. The embed on partner sites is not such a case: it runs no SDK (see [embedding](https://docs.zokogames.com/requirements/embedding)), so `requestAd` rejects with `sdkDisabled` there. |
| `SDK.banner.requestBanner`, `SDK.banner.requestResponsiveBanner` | A game with the kids flag: rejects with `bannersDisabled`. A game without the flag under kids mode: accepted as usual when the game has banners on, and shown as a house banner only, never from an ad network; otherwise `bannersDisabled`. |
| `SDK.ad.hasAdblock` | Resolves `false`. No blocker check runs. |
| `SDK.user.showAuthPrompt` | Rejects with `userCancelled`. No sign-in prompt appears. |
| `SDK.user.showAccountLinkPrompt` | Rejects with `userNotAuthenticated`. |
| `SDK.user.getUserToken` | Rejects with `userNotAuthenticated`. The portal refuses to issue an identity token in kids mode and for a kids game (the token request is answered `401`, which the SDK reports as no user), so your server never receives a verifiable identity for a child. |
| `SDK.user.submitScore`, leaderboard reads | `submitScore` resolves and records nothing, with or without `delayed`. Boards come back empty. The server API answers a score submission for a kids game with `403` and the reason `kids-game`. |
| `SDK.achievements.list` | Resolves an empty list. |
| `SDK.achievements.unlock` | Resolves `{ ok: false, reason: "guest" }`. |
| `SDK.game.room`, `updateRoom`, invites | Rooms are never opened: the portal refuses the realtime connection in kids mode, so `send` and `setState` fail. The realtime server also refuses to open, join or message a room of a game with the kids flag (its `room_closed` error, which your game does not receive). The share and invite buttons are hidden. See [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms#when-rooms-are-not-available). |
| `SDK.data` | Works. Progress stays on the device, like a guest's, kept apart from any account's save and never merged into one. |

The portal also does these things without your game being involved:

- Optional cookie categories are off and analytics-only events are not sent. Plays and anonymous counts still work. Play history is not kept, on the device or on a parent's account. Analytics events are not recorded: the portal's event endpoint treats kids mode and kids games as anonymous, whatever the page claims, and never stores a visitor id.
- Players report a problem only with preset reasons. There is no free text, so the `feedback.received` webhook is not sent for a kids game and "contact the developer" is closed.
- The game cannot be embedded on partner sites, and sharing is hidden.
- Saving the game for offline play is offered for kids games only while kids mode is on.
- Ads are never personalised: a kids game shows no ads, and any other game in kids mode gets contextual or house ads only, with no ad network script loaded.
- The game frame does not grant camera or microphone access. It also has no pop-ups and no downloads, even if **Needs popups** is ticked for the game.
- A kids game creates no recently played entries and no play streak for a signed-in player: the portal records nothing when it is played. Its game page shows no "Play on your phone" QR card.
- The store is not available: `SDK.store.isAvailable` is `false` and every purchase call is refused. The console refuses the kids flag on a game marked as having in-game purchases (`kids_no_iap`).
- A kids game needs an all ages or 7+ rating. The console refuses any other rating with the error `kids_rating`.

## Calls in kids mode

In kids mode the portal answers these calls itself, as it would for a signed-out player, so no account, store or room service is reached. Handle each answer as shown.

| SDK call | Answer in kids mode |
| --- | --- |
| `SDK.init()` | Resolves. The portal reports no user, `SDK.user.isUserAccountAvailable` is `false` and `SDK.store.isAvailable` is `false`. |
| `SDK.user.getUser` | Resolves `null`. |
| `SDK.user.getUserToken`, `SDK.user.listFriends`, `SDK.user.showAccountLinkPrompt`, `SDK.store.getPurchaseToken` | Reject with `userNotAuthenticated`. |
| `SDK.store.getPlayerInventory`, `SDK.store.buyItem`, `SDK.store.consumeItem` | Reject with `userNotAuthenticated`. |
| `SDK.store.getCatalogItems` | Rejects with `catalogFetchFailed`. |
| `SDK.user.showAuthPrompt` | Rejects with `userCancelled`. |
| `SDK.user.submitScore` | Resolves and records nothing, with or without `delayed`. |
| `SDK.ad.requestAd`, `SDK.banner.requestBanner` | Not answered by the portal itself: the rules in the table above apply (a kids-flagged game gets `adsDisabled` and `bannersDisabled`; any other game gets contextual ads only). |
| `SDK.game.room.send`, `SDK.game.room.setState` | Reject with `roomUnavailable`. |
| `SDK.game.room` | Reads as an empty room: not in a room, no members, no host. |
| `SDK.game.updateRoom`, `SDK.game.leftRoom`, `SDK.analytics.trackOrder` | Resolve with nothing; nothing is announced or counted. |
| `SDK.game.inviteLink` | Rejects with `unexpectedError`. |
| `SDK.data` | Works on the device only; nothing is uploaded to the portal, and the save never merges into an account. |

Do not branch on these error codes. Read the two flags once after `init()` and hide sign-in, friends and shop screens when `SDK.user.isUserAccountAvailable` or `SDK.store.isAvailable` is `false`. Keep the `catch` blocks as a safety net.

```js
await SDK.init();

// Branch on the flags once, not on error codes.
signInButton.hidden = !SDK.user.isUserAccountAvailable;
shopButton.hidden = !SDK.store.isAvailable;

// A refused call still settles; treat it like a guest.
try {
  await SDK.user.getUserToken();
} catch (e) {
  if (e.code !== "userNotAuthenticated") console.warn(e.code);
}
```

## What the console refuses

When you tick **Made for children** (or change a kids game later), the console refuses the save with a `409` and the error `kids_blocked` if the game has any of these. The response lists them in `blockers`, and a game that is already a kids game is refused only for what the edit adds.

- `popups`: **Needs popups** is on.
- `external_hosting`: the game is hosted on your own server instead of as an uploaded build.
- `store_links`: any store link is filled in.
- `chat`: **Moderated chat** is on.

Three more refusals have their own codes: `kids_rating` (a rating other than all ages or 7+), `kids_no_iap` (the game is marked as having in-game purchases) and `kids_no_leaderboard` (a leaderboard is switched on for a kids game). Turn the setting off, or untick **Made for children**, and save again.

## What your game must do

The portal does not enforce everything. Some rules are checked only by the reviewer, and a game that breaks them is sent back with the reason **Audience flag**. In particular:

- **No links out.** No URL the player can open, no store, social or community links. Links between kids games of the same series are the only exception.
- **No purchases.** The portal refuses store calls in kids mode, but show no real-money items and no "unlock" or "premium" prompts either.
- **No ad offers.** Do not show a "watch an ad" button; `requestAd` fails with `adsDisabled` for a kids game.
- **No text from players.** No chat, comments, names, free-text fields or user names on screen.
- **No personal data.** Do not ask for a name, email, age or location, and call no host other than your own build. The build report lists external hosts as `origin_*` findings.
- **No pressure.** No return timers, streaks that punish absence or last-chance prompts.
- **Easy to start.** Short plain instructions, with pictures where you can, and an easy first level.
- **Content.** Cartoon-level violence at most, nothing frightening, no gambling-like loops or chance-based rewards.

Your game must also work in each failure above. `submitScore` and `unlock` resolve without doing anything, `showAuthPrompt` rejects, and `requestAd` fails. If a feature depends on one of them, hide it.

```js
const SDK = window.ZokoGames.SDK;
await SDK.init();

// Chat input follows the portal setting, and follows it live.
const applyChat = (s) => { chatBox.hidden = s.disableChat; };
applyChat(SDK.game.settings);
SDK.game.addSettingsChangeListener(applyChat);

// An ad that cannot run is just a break that did not happen.
try {
  await SDK.ad.requestAd("midgame");
} catch (e) {
  if (e.code !== "adsDisabled") console.warn(e.code);
}
// Always continue the game here.
```

## Test it

1. **Build preview.** After a build passes validation, open **Preview** for the game in the console. In the **Simulate the player** card, tick **Kids mode**. The game restarts with `disableChat` set, no ad blocker check, and sign-in, leaderboards and multiplayer not offered. Every answer shows in the event log under **Portal replies**.
2. **Preview tool.** The [Preview tool](https://www.zokogames.com/preview) shows your SDK calls as the portal receives them. Check that none of your own features is left as a dead button after a rejected call. The **Kids mode (SDK 1.5.0)** switch sends a settings change with `kidsMode` and `disableChat` set to `true`, as the portal does.
3. **Local mode.** From SDK 1.5.0 add `?kidsMode=true`: `kidsMode` and `disableChat` become `true`, and nothing else changes. With an older SDK add `?disableChat=true`. Add `?ad_response=adsDisabled` to force the ad failure, and `?user_response=logged_out` for a guest. See [local testing](https://docs.zokogames.com/getting-started/local-testing).
4. **Your own build.** Search it for outside links, text inputs, purchase calls and requests to other hosts. Play the first level reading as little as possible.

The simulated kids mode works only in the console's build preview. Public pages never honour it.

## Before you submit

- [ ] The kids flag is ticked and the rating is all ages or 7+.
- [ ] The game works with `adsDisabled`, `userCancelled`, no leaderboard and no rooms, and shows nothing that depends on them.
- [ ] `disableChat` is applied at start and on change.
- [ ] Kids mode is read from `kidsMode`, with `disableChat` as the fallback.
- [ ] No link, text input, purchase, personal data or call to another host.
- [ ] Instructions are short and the first level is easy.

## Next steps

- [Age rating](https://docs.zokogames.com/requirements/gameplay#age-rating) and the [requirements checklist](https://docs.zokogames.com/requirements/checklist#made-for-children-when-ticked) for the exact rules.
- [Player features](https://docs.zokogames.com/guides/player-features#kids-mode-and-kids-games) for the portal side.
- [Launch checklist](https://docs.zokogames.com/guides/launch-checklist) for the full path to a published game.
- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting) when a call fails.

---

Source: https://docs.zokogames.com/guides/launch-checklist

# Launch checklist

Use this page to go from an empty studio to a live game without a round trip. It follows the checks the portal and the reviewers really run, in the order you meet them: studio setup, the listing, the build, the artwork, the submission, the review, and the two launch stages. Each section links to the page with the detail. The long lists are on [build validation](https://docs.zokogames.com/requirements/build-validation) and the [requirements checklist](https://docs.zokogames.com/requirements/checklist); this page is the path through them.

## 1. Set up the studio

The **Getting started** list on the console dashboard tracks these steps. A step is done when:

| Step | Done when | Required |
| --- | --- | --- |
| Profile | Country, contact name and contact email are filled in. | Yes |
| Payout | Legal name, country and method are set, the payout terms are accepted and the payout connection is connected. Only owners and admins see this step. | Yes |
| Team | A second member has joined or an invitation is pending. | No |
| Game | You created a game. | Yes |
| Build | A build is active (or, for an externally hosted game, the address is set). | Yes |
| Artwork | All three covers are uploaded. | Yes |
| Submit | The game left draft. | Yes |
| Live | The game reached a live stage. | Yes |

Payout is not needed to submit a game. Set it up before full launch so revenue can be paid; see [payouts](https://docs.zokogames.com/business/payouts). To bring teammates in, see [team, roles and studios](https://docs.zokogames.com/guides/team-and-roles).

## 2. Fill in the listing

The **Submit for review** button refuses until every required item below is true. A refused submit answers `not_ready` and names what is missing.

| Item | Rule | Step in the console |
| --- | --- | --- |
| Name | At least 2 characters, at most 60 | Basics |
| Category | One of the portal categories | Basics |
| Short description | 20 to 160 characters | Basics |
| Description | 80 to 5,000 characters of text (formatting does not count) | Basics |
| Controls | 5 to 2,000 characters of text | Basics |
| Tags | At most 10; at least one is advised, not required | Basics |
| Age confirmation | You confirm the game fits the age rating | Basics |
| English confirmation | You confirm all visible text is available in English | Basics |
| Age rating | All ages, 7+ or 12+. A rating of 16+ or 18+ is not accepted. | Technical |
| Languages | The list includes English | Technical |
| Lobby sizes | For a multiplayer game, both a minimum and a maximum (1 to 100 each; the minimum cannot exceed the maximum) | Technical |
| Build | A build that passed validation is active, or an external address is set | Build |
| Covers | All three covers | Artwork |
| Preview videos | Not required to submit; needed for full launch | Artwork |

A game made for children must be all ages or 7+; the console refuses anything else with `kids_rating`. Read [kids mode](https://docs.zokogames.com/guides/kids-mode) before you tick it.

## 3. Upload and validate the build

The validator unpacks the zip in memory and writes a report. Errors reject the build; warnings and notes do not. While a game is in review you cannot change its builds (`locked_in_review`).

| Limit | Value |
| --- | --- |
| Unpacked size | 250 MB |
| Files | 1,500 |
| Zip entries | 6,500 |
| Initial download | Error above 50 MB; warning above 20 MB (mobile) |
| Single file | Warning above 20 MB |
| Compression ratio | Error above 200 to 1 for one file over 1 MB, or 400 to 1 for the archive |

The error codes that reject a build:

| Group | Codes |
| --- | --- |
| Not a usable zip | `not_zip`, `corrupt`, `central_mismatch`, `size_mismatch`, `total_bytes`, `zip64`, `empty`, `compression`, `encrypted` |
| Unsafe contents | `unsafe_path`, `symlink`, `duplicate`, `blocked_type`, `compression_ratio`, `bad_precompressed` |
| Missing entry point | `no_index` |
| Size | `too_large`, `too_many_files`, `too_many_entries`, `initial_too_large` |

The warnings most likely to cost you a review are `missing_reference`, `case_mismatch`, `absolute_path`, `mixed_content`, `no_sdk`, `sdk_bundled`, `third_party_sdk`, `external_url` and the `origin_*` codes. Every code, its meaning and its fix are on [build validation](https://docs.zokogames.com/requirements/build-validation). A build with no error is accepted, but a reviewer sees the same report.

Then:

- [ ] The report has no errors, and you read every warning.
- [ ] You opened the build in **Preview** and the checklist there ticked; the first `gameplayStart` came within 20 seconds.
- [ ] You activated the build you want players to get.

## 4. Add the artwork

| Asset | Requirement |
| --- | --- |
| Landscape cover | Exactly 1920 x 1080 px (16:9) |
| Portrait cover | Exactly 800 x 1200 px (2:3) |
| Square cover | Exactly 800 x 800 px (1:1) |
| Cover file | PNG, JPG or WebP, at most 5 MB |
| Preview videos | MP4, no audio, 15 to 20 seconds, at most 50 MB; landscape 1920 x 1080 and portrait 720 x 1080 |

A live game must always keep all three covers, and a game in review cannot change them. Details are on [covers](https://docs.zokogames.com/requirements/covers). A refused file is reported as `cover_invalid` or `video_invalid` with the reason.

## 5. Submit

Press **Submit for review**. The game goes from draft to submitted, and your studio gets a notification when a reviewer decides. You can withdraw a submission that nobody has picked up yet.

## 6. What the reviewer checks

A reviewer plays the build and answers every line below with pass, fail or not applicable. Lines that do not apply to your game are left out: ad lines only when ads are on, the account lines when you use the data module or a leaderboard, the multiplayer lines for a multiplayer game, and the touch line when you tick mobile.

Each line word for word, with how to check it yourself before you submit, is on the [testing checklist](https://docs.zokogames.com/getting-started/testing-checklist).

| Group | What is checked |
| --- | --- |
| Technical | Loads in the portal frame without blocking console errors; loads in about 10 seconds or less on 4G; initial download within the size budget; fullscreen and resize work and nothing breaks at 360 px wide; touch controls work (mobile); no unapproved external requests, popups or redirects; audio starts only after interaction and can be muted |
| Gameplay | A new player can start within 30 seconds; the controls match the description and are explained in game; no soft-locks in the first 10 minutes; the game pauses on blur and during ad breaks |
| Ads | Breaks use the SDK and never block the start; rewards are granted only after a finished ad; banners use approved sizes and stay off the controls; no third-party ad code or house ads |
| Accounts and saves | Playable as a guest; progress saves through the data module; leaderboard scores submit and display |
| Multiplayer | Lobby, invites and join links work; a player leaving does not freeze the room; the lobby sizes match the listing |
| Quality | Original or licensed work; content suits the declared audience, including the kids flag; covers and video meet the specs; title, descriptions and controls text are accurate and free of spam; quality is competitive for the category |

A reviewer can approve only when every line is answered and none is failed. If one fails, the reviewer asks for changes instead.

### The three outcomes

| Outcome | What happens | What you do |
| --- | --- | --- |
| Approved | The game goes to basic launch. | Watch the numbers (below). |
| Changes requested | The game returns to you with numbered reasons and a note. | Fix each reason and submit again. |
| Rejected | The submission ends and the game can be reopened as a draft. A final reason (copyright, copy, content, security) says the game cannot be published. | Read the reasons before you reopen it. |

Every request for changes or rejection carries at least one reason or a written note. The reasons come from a fixed list:

| Reason | Fixable |
| --- | --- |
| Game does not run | Yes |
| Performance | Yes |
| Ad integration | Yes |
| External links or popups | Yes |
| Controls unclear | Yes |
| Quality below bar | Yes |
| Artwork does not meet specs | Yes |
| Listing information | Yes |
| Audience flag | Yes |
| Copyright or brand misuse | No |
| Copy of another game | No |
| Inappropriate content | No |
| Security | No |

The meaning of each is on [quality guidelines](https://docs.zokogames.com/requirements/quality#reasons-a-submission-is-sent-back-or-rejected).

## 7. Basic launch, then full launch

In **basic launch** the game is live with ads off and no revenue. The window ends after at least 7 days and 500 plays, or after 21 days at most. A reviewer then promotes, extends or ends it; the score is advice, not the decision. These numbers are defaults: the portal team may adjust the window, and the console shows the values that apply to your game.

| KPI | Full marks | Weight |
| --- | --- | --- |
| Average play time | 10 minutes | 30 % |
| Day-1 retention | 15 % | 30 % |
| Conversion (views that last a minute) | 80 % | 20 % |
| Tile click-through, versus the category | 50th percentile | 20 % |

Fewer than 200 plays is too little data to decide. In **full QA** a second review checks the full SDK integration, ads included; after that the game goes to **full launch** with ads and revenue share. See [launch stages](https://docs.zokogames.com/getting-started/launch-stages).

Before full launch:

- [ ] `gameplayStart` and `gameplayStop` are in the right places.
- [ ] Ads follow the [advertisement rules](https://docs.zokogames.com/requirements/advertisements).
- [ ] Both preview videos are uploaded.
- [ ] Payout details are complete.

## 8. After launch

Updates and artwork changes on a live game go through review as an update or artwork submission; the game stays live meanwhile. Only one update can wait for review at a time (`update_pending`). To change what players get, activate another build; see [updating a game](https://docs.zokogames.com/getting-started/updating-a-game).

## Next steps

- [Requirements checklist](https://docs.zokogames.com/requirements/checklist) and [build validation](https://docs.zokogames.com/requirements/build-validation) for every rule in full.
- [Kids mode](https://docs.zokogames.com/guides/kids-mode) and [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms) if either applies.
- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting) for error codes from the SDK, the console and webhooks.

---

Source: https://docs.zokogames.com/guides/promoting-your-game

# Promoting your game

The **Promote** tab of a game in the console books a **sponsored placement**: your game's tile is shown on the portal's home and category rows for the days you choose, always labelled **Sponsored**. It is paid advertising, separate from the launch stages: "promoting" a game from Basic Launch to Full QA is a reviewer's decision and has nothing to do with this tab. You need no SDK code.

## Who can book

- Owners and admins of the studio. Other roles can see the campaigns of the game but not book, pay or cancel.
- The game must be in **Full QA** or **Full Launch**. A game in Basic Launch is still being measured against organic traffic, and paid traffic would skew that measurement, so the tab says it cannot be promoted yet and opens once the game reaches Full QA.
- The game must not be a kids game, must not be a test game, and the studio must not be suspended. If a running campaign's game stops qualifying, the campaign is paused automatically and the list says so. The booked days keep passing while it is paused and are not refunded. A paused campaign does not restart by itself: once the game qualifies again, contact support to have it resumed, or stop the campaign to get the remaining days back.
- Booking can also be closed for studios, or payments not set up yet. The tab then says so in plain words; campaigns you already have keep running.

## Book a campaign

1. Open the game and select **Promote**.
2. Choose the **first day** and **last day**. Both days count, days are UTC, the first day must leave time for review, and a campaign has a minimum and maximum length. The hints under the fields show the exact dates and limits.
3. The **price** shows live as days times the daily rate. It is computed on the server from the rate card, never taken from your browser.
4. Accept the sponsored placement terms and select **Create campaign**. Nothing is charged yet: the campaign is a draft.
5. Select **Pay**. You may be asked to confirm it is you (a passkey or authenticator app is needed to pay or cancel). After a successful payment the campaign goes to review. If you close the payment page, the draft is kept and you can pay it from the list.

Only a limited number of campaigns can run on any one day, and the console does not show which days are free. Creating and paying a campaign does not check this: a reviewer does, when approving. A campaign for days that are already full cannot be approved for those days: it is then declined, or it expires on its first day, and in both cases it does not run and its payment is refunded in full.

## What the statuses mean

| Status | Meaning |
| --- | --- |
| Draft / Awaiting payment | Created, not paid. Nothing is charged until you pay. |
| In review | Paid, waiting for a reviewer. It runs only once approved. |
| Approved | Approved, waiting for its first day. |
| Running | Showing today. |
| Ended | Finished its days. |
| Rejected | A reviewer refused it. The review note says why, and the payment is refunded in full. |
| Cancelled | You cancelled it before its first day. |

A campaign nobody reviewed before its first day does not run and is refunded in full. A campaign shown as **Test** was paid in test mode: no real money moved.

## Stop or cancel

- **Cancel** before the first day: the full payment is refunded to the card it was paid with.
- **Stop** a running campaign: it stops showing today, today counts as used, and the days it did not use are refunded.

Both need the confirmation step, and the refund amount is shown before you confirm. The terms you accepted when booking are the binding text; the amounts and timing of refunds are shown in the console.

## Read the report

In the campaign list, **Budget** is the price you paid, **Spent to date** is the part of it for the days that have passed since the first day, including days it was paused (the rest is what a stop today would give back) and **Refunded** is what has been returned to your card; a refund the card provider has not confirmed yet shows as on its way. Select **Report** on a campaign for impressions, clicks and click-through per day (UTC), updating during the day. **Impressions** count how often the sponsored tile was shown, **clicks** how often it was opened, and **CTR** is clicks divided by impressions. Numbers appear from the first day it runs. A day with few impressions has a noisy CTR; compare whole campaigns rather than single days.

## Related

- [Launch stages](https://docs.zokogames.com/getting-started/launch-stages) for Basic Launch, Full QA and Full Launch.
- [Artwork experiments](https://docs.zokogames.com/guides/artwork-experiments) to test which cover gets more clicks before you pay for exposure.

---

Source: https://docs.zokogames.com/guides/team-and-roles

# Team, roles and studios

A studio is one shared workspace: its games, builds, statistics and settings belong to the studio, not to a person. This guide covers who can do what, how people join and leave, and the second sign-in step some actions ask for. Everything here is on the **Team** page of the console.

## The three roles

| Can do | Member | Admin | Owner |
| --- | --- | --- | --- |
| Create and edit games, upload artwork, upload and activate builds, submit for review | Yes | Yes | Yes |
| Read and answer player feedback, read game statistics | Yes | Yes | Yes |
| See revenue, eCPM and ad fill | No | Yes | Yes |
| Receive studio notifications (review results, builds, player messages, payouts) | No | Yes | Yes |
| Change the kids setting, embedding, allowed sites, device switches, pop-ups or address of a live game | No | Yes | Yes |
| Delete games and builds, unpublish a live game, send new artwork of a live game for review | No | Yes | Yes |
| Artwork experiments, achievements, leaderboards, in-game store, promotions | No | Yes | Yes |
| API tokens and webhooks | No | Yes | Yes |
| Edit studio settings and the public studio page, upload the studio logo | No | Yes | Yes |
| Read statements, payouts and the audit trail | No | Yes | Yes |
| Invite members and remove members | No | Yes | Yes |
| Invite admins, make a member an admin, change roles | No | No | Yes |
| Change the payout profile, payout wallet, tax details and payment provider connection | No | No | Yes |
| Accept updated developer terms, transfer ownership, name the owner of record, delete the studio | No | No | Yes |

The server checks the role on every request, so a hidden button is not the only thing in the way: a member who opens a link to an admin page is sent back to the start page.

## Invite a person

1. Open **Team**, enter the person's email or username and choose a role. Admins can only invite members; only owners can invite admins.
2. They join when they **accept** the invitation. It is valid for **14 days**.
3. An email address with no ZokoGames account still gets the email: they create an account with that same email, then open the link and accept. A username must already belong to an account.

Under **Pending invitations** you see every unanswered invitation. One that expired stays in the list for 30 days so you can **Resend** it; resending replaces the link, and the earlier link stops working. **Revoke** cancels an invitation at any time. To protect inboxes, the same address can be mailed at most three times a day per studio.

## Change a role, remove a person, leave

- An owner changes a member to admin or back from the **Role** column. Making someone an admin asks for the second step (below). Making an admin a member asks you to confirm first, because it revokes every API token that person created.
- Admins can remove members. Owners can remove members and admins. The person loses access at once and is told by email. Their past work stays with the studio. Every API token they created is revoked at once (a build script or dashboard that used one gets `401 invalid_token` until a teammate creates a new token), so check the **API tokens** page before removing someone.
- You can **Leave** a studio yourself. The only owner cannot leave: transfer ownership first. The API tokens you created for the studio are revoked when you leave, as when you are removed or changed from admin to member, so hand scripts that use them to a teammate first.

Every one of these changes is written to the **audit trail** on the **Settings** page, which only owners and admins can open. Each entry says what happened, which game or member it was about, who did it and when, and a row reads like "Changed the role of Ben from member to admin". Actions by ZokoGames staff on your studio (approving a promotion, sending a tax form back) appear as "ZokoGames staff" without a name, and the actions of a member whose account no longer exists appear as "Former member". Times are in UTC. You can filter by member, game, action group and date, search by a member's or a game's name, and **Download as CSV** (up to 5,000 rows for the filters you chose). Ordinary entries are kept for 24 months, and payout, tax and store order records for 7 years.

## Transfer ownership and the owner of record

**Make owner** on a teammate's row hands the studio to them. You type the studio's URL name to confirm and pass the second step. You become an admin, and only the new owner can undo it. Payout and tax details and statements stay with the studio unchanged.

A studio can have more than one owner. One of them is the **owner of record**, the studio's main contact for ZokoGames staff. An owner can name another owner as the owner of record without changing any role. The owner of record cannot delete their account until someone else holds that place.

## Working in more than one studio, and with many games {#working-in-more-than-one-studio}

If you belong to several studios, a switcher in the console header shows the selected one. Studio-wide pages (games, analytics, team, settings, payouts, tokens) show the selected studio and stay on the same page when you switch. A link to one game always opens that game under the studio it belongs to, with your role in that studio; when that is not the selected studio, a note at the top of the game says so and offers **Switch to** that studio, because the team, notices, statements and settings around the game still follow the selected one. A link to a payout statement of another studio asks you to switch first.

In the notifications list every notice carries the name of its studio once you belong to two or more, so two games with the same name in different studios are told apart.

To start another studio, use **Create another studio** on the Settings page. You stay a member of the studios you already have. While studio sign-up is by invitation, a further studio needs an invitation too: apply to publish and say which studio you already run.

**Many games.** The **Games** page is built for large catalogues:

- Search by game name or by its URL name (the part after `/game/`).
- The status filter shows how many games are in each status, and **Needs attention** lists the games sent back for changes or declined in one view.
- Sort by last update, plays or name. The list shows 50 games a page.
- The dashboard shows the games that need you first and links to the rest, so it stays short however many games you have.

On the **Team** page, from eight members on, a search box finds a person by name or email, and owners and admins are listed first.

**Moving a game to another studio.** A game belongs to one studio, and only ZokoGames staff can move it to another. To ask for it, open **Support** in the console, choose the game, and write the URL name of the studio it should move to. Send the request as an owner or admin of the studio that holds the game. Staff move it and the owners of both studios get a notice.

What happens to the game:

- Its builds, listing, leaderboards, achievements and history stay with it.
- Ad revenue follows the days each studio owned the game: statements that were already cut stay with the earlier studio, and later days go to the new one.
- API tokens and webhooks belong to a studio, not a game: the earlier studio's stop seeing the game and the new studio's start.
- A kids game keeps its kids rules, but a staff allow-list of extra sites granted to the earlier studio is cleared, so the new studio starts without one.

The people who work on the game are not moved: invite them to the new studio from **Team**.

## The second sign-in step

These actions ask you to confirm with a passkey or an authenticator code, even though you are signed in:

- inviting an admin, making a member an admin, transferring ownership and naming the owner of record;
- deleting an empty studio, deleting a game that was never published, and unpublishing a live game;
- changing payout details;
- creating, rotating or revoking API tokens and webhook secrets, and some promotion and money settings.

The confirmation covers the next five minutes. If your account has no passkey or authenticator app yet, the console says so and links to the security settings of your player account on **www.zokogames.com** (account menu, Settings, Account, Two-factor authentication). After you set one up, use the link back to the console and repeat the action: what you typed is not carried over.

## Related

- [Launch checklist](https://docs.zokogames.com/guides/launch-checklist)
- [Notifications](https://docs.zokogames.com/guides/notifications) for who receives which studio notice.
- [Developer API](https://docs.zokogames.com/guides/developer-api) for API tokens.

---

Source: https://docs.zokogames.com/business/revenue-share

# Revenue share overview

ZokoGames shares the revenue earned by your game with you. This page describes how that works in the portal. **The binding terms are the developer terms you accepted and any agreement we made with you**, see the [developer terms summary](https://docs.zokogames.com/business/developer-terms); the share rate shown in your console is the one applied. Terms such as **studio**, **basic launch** and **full launch** are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## What earns revenue

| Source | Status | How it reaches you |
| --- | --- | --- |
| **Advertising** served through the SDK: midgame ads, rewarded ads and banners, on games in full launch | In testing: no real money yet | Gross ad revenue per game and day, times your share rate. Only SDK-served ads count, so ads from other networks are not allowed. Today the ads shown are the portal's own house ads, because no ad network is connected yet, so no ad revenue is earned. |
| **Ad-free membership playtime pool** | Planned | Players who are ad-free members see no midgame ads, so they produce no ad revenue for the games they play. A pool funded by membership revenue replaces it. The membership is built but new sign-ups are switched off for the public, so the pool pays nothing yet. See below. |
| **In-game purchases** | In testing: no real money yet | Stripe is connected as the payment provider, but real-money sales stay off until the portal team switches them on, so only test (sandbox) purchases exist and no purchase revenue is paid. See [in-game purchases](https://docs.zokogames.com/sdk/purchases). |

The statuses are defined once in [feature status](https://docs.zokogames.com/business/faq#feature-status).

### The membership playtime pool

This is the rule as decided; it is behind a provider switch and is not paying out yet, because no real membership payment provider is connected. The membership itself is planned: it is switched off and not offered to players.

1. **Measure.** When a signed-in player who is an ad-free member starts a play, the portal records that on its servers (never from the client). The sessions' playtime, with the same 30-minute cap as normal playtime, is added up per game per day as ad-free playtime.
2. **Pool.** For a payout period, the pool is the membership revenue after provider fees, taxes and refunds, times the platform's developer share for ad revenue.
3. **Split.** Each game gets the pool multiplied by its share of all ad-free playtime on the portal that period. Games with no ad-free playtime get nothing. Parts add up to the pool exactly, in whole micro-units.
4. **Statement.** The amount is credited to the game's studio as a **separate line**, so it never mixes with ad revenue.

Wiring this line into statements comes once a real provider is connected and there is revenue to share. Until then, nothing in your statements comes from it. Ad-free playtime depends on recorded play sessions, so see [analytics and metrics](https://docs.zokogames.com/guides/analytics-metrics) for what is measured.

## Payments status

- **No ad revenue is earned today**, because only house ads run: no ad network is connected yet.
- **Ad revenue** is recorded and statements are prepared and invoiced. Payouts are made by hand: once the owner has confirmed manual payouts, the portal team pays each invoiced statement to the method in your payout profile and records the transfer reference; a paid statement is one the portal team has transferred and recorded. Nothing is paid automatically. See [payouts](https://docs.zokogames.com/business/payouts).
- **In-game purchases** are sandbox only until the portal switches real-money sales on, and the **membership pool** until a membership payment provider is connected, so they produce no revenue for you yet.
- Revenue is paid to the studio. Ownership and exclusivity are in the [developer terms summary](https://docs.zokogames.com/business/developer-terms): you keep ownership and the licence is non-exclusive.

## When revenue starts

- During **basic launch** the game runs without ads. There is no advertising revenue and no revenue share.
- During **Full QA** the game is being reviewed for Full Launch.
- From **full launch** ads run and your share accrues. Ads never run for games the portal marks as kids' games, or if ads were not enabled for the game.
- Today the ads in full launch are the portal's own house ads, so no share accrues yet.

See the [introduction](https://docs.zokogames.com/getting-started/introduction) for the stages.

## How it is calculated

1. Gross revenue is recorded per game and per day from the ad provider's figures. The **Revenue** page in the console shows it by day, game or country, together with your share, as an estimate until the month closes.
2. After each month ends, a **statement** is prepared for your studio: the sum of gross revenue of all your games for that month.
3. Your share is the gross multiplied by the share rate in your payout profile. The console shows the rate on the Revenue page ("Your share (X %)"). New studios start at **50 percent**, the standard rate. A different rate, for your studio or for one of its games, applies only where it was agreed with your studio in writing, and it is the rate the Revenue page shows; when rates differ by game, the Revenue page notes that your share differs by game. Amounts are calculated in whole micro-units with no floating-point rounding; the fraction of a micro-unit that is left over stays with the portal.
4. The statement adds any balance carried over from earlier months that was below the minimum. See [payouts](https://docs.zokogames.com/business/payouts). For a new studio, 20 percent of each of its first 3 paid statements is held back and paid as a line on the first statement prepared after 90 days.
5. When a statement is created you get an email and a push notification, and a `statement.created` [webhook](https://docs.zokogames.com/guides/webhooks) fires if you subscribed. A statement is **held** instead of invoiced while the tax form is not approved or the terms are not accepted, or when the portal team places a hold; payouts are then released together once it is lifted. When a statement is paid, held or released, a `statement.updated` [webhook](https://docs.zokogames.com/guides/webhooks) fires.

If a figure looks wrong, contact [support](https://docs.zokogames.com/business/support) with the game and the period: email developer support, or use the contact form.

## Things that affect it

- Impressions and ad quality, which depend on your player count, geography and device mix.
- Whether the SDK is correctly integrated: games that never send gameplay events or that fail ads often earn less.
- Policy compliance. Revenue from traffic generated by prohibited practices (incentivised clicking, pretend reward ads) is not shared.

## What you do not pay

There is no fee to submit or to host a game on ZokoGames. Our revenue comes from our share.

## Multiple team members

A studio can have owners, admins and members. Revenue goes to the studio, not to individuals; how you split it inside your team is up to you.

## Changes

If the revenue share terms change, the [changelog](https://docs.zokogames.com/business/changelog) and your agreement will say so. We do not change them for past periods.

## Next steps

- [Payouts](https://docs.zokogames.com/business/payouts)
- [Statements, PDFs and sandbox payouts](https://docs.zokogames.com/guides/statements-and-pdf)

---

Source: https://docs.zokogames.com/business/payouts

# Payouts

Earnings accrue per calendar month and are settled after the month closes. The **Payouts** page in the developer console shows your payout profile, the current minimum, and every statement. Terms such as **studio**, **basic launch** and **full launch** are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## Set up

Your payout profile starts in the onboarding form and is finished on the **Payouts** page:

1. Enter your legal name and country.
2. Pick a payout method: bank wire, ACH (US) or PayPal.
3. Pick a payout currency, USD or EUR. Revenue is recorded in USD and a EUR statement is converted with a rate the portal sets. Payment in another currency may incur exchange fees.
4. Accept the developer terms (done during onboarding).
5. Confirm how you are paid. Studios are paid by hand: the owner chooses **Use manual payouts** on the **Payouts** page. There is no payout provider account to connect, and bank details are never entered in the console: our team confirms them with you directly before your first payout.

Only the studio **Owner** can change the payout profile and connect the payout provider, because both decide who receives the studio's money. Admins see the **Payouts** page read-only, with a note to ask the owner; members have no access to it.

Every change to the payout details, and every connection of a payout account, notifies the studio's owner and admins in the console and by push: who made the change and when (UTC), for new details the payee masked to the first letter of each word, and a link to the studio's audit trail in **Settings**. Payout details cannot be removed on their own: correct them by saving new ones; they are removed when the studio is deleted.

> [!NOTE]
> **How payouts work today: by hand** (status: available now, see [feature status](https://docs.zokogames.com/business/faq#feature-status)). No payout provider is connected. Once the owner has confirmed manual payouts, the portal team pays each invoiced statement by hand to the method in your payout profile (bank wire, ACH or PayPal) and marks it **Paid** with the transfer reference. Nothing is paid automatically. A studio whose payout account is still the earlier built-in test provider (a reference starting with `stub_`) is not connected: its owner confirms manual payouts once, and until then its statements carry the **SANDBOX** watermark. A payout needs revenue; [revenue share](https://docs.zokogames.com/business/revenue-share) says which revenue counts today.

Set this up early. A statement is **held** instead of invoiced while the tax form is not approved or the terms are not accepted.

## Statements and schedule

| Item | Value |
| --- | --- |
| Period | One calendar month |
| Preparation | Automatically on the second day of the following month |
| Minimum payout | 50 in your payout currency (USD 50 or EUR 50), also shown on the Payouts page |
| Payment terms | 45 days after the end of the month a statement covers, as the console states |
| Below the minimum | The amount rolls over into the next month |
| Holdback for new studios | 20 percent of each of a studio's first 3 paid statements is held back and paid as a line on the first statement prepared after 90 days |

Each statement shows gross revenue, your share, any amount carried in and its state:

| State | Meaning |
| --- | --- |
| Open | Still being prepared. |
| Invoiced | A self-billing invoice was issued; the amount is due under the payment terms. |
| On hold | Held because the tax form or terms are missing, or by review. It is released, together with later statements, in a single payment. |
| Paid | The portal team made the transfer outside the console and recorded its reference. Payment is not automatic. |
| Rolled over | The balance was below the minimum, so nothing is invoiced; the whole amount moves into the next statement. |

Invoice numbers are deterministic (`ZG-YYYYMM-` plus a short studio code), so a re-run of the same month gives the same number. You get a notification when a statement is invoiced.

## Invoices

For each invoiced period a PDF invoice is available in the console under **Payouts**. Use it for your accounting. If you disagree with a figure, tell [support](https://docs.zokogames.com/business/support) before the payment date.

## Disputes and support

If a figure or a state looks wrong, email developer support with the studio, the period and the figure you expected; see [support](https://docs.zokogames.com/business/support).

## Taxes

You are responsible for your own taxes. Send your tax form to our team (W-9 for US payees, W-8BEN or W-8BEN-E otherwise), then choose **I have filed my tax form** on the **Payouts** page so it can be reviewed; statements stay on hold until it is approved. ZokoGames does not give tax advice.

## Troubleshooting

| Problem | What to do |
| --- | --- |
| Statement is "On hold" | Open the Payouts page; a missing tax form or unaccepted terms is shown there. |
| Amount is lower than expected | Compare the monthly report with the Revenue page: your share is gross revenue times the share rate. |
| No statement for a month | A statement only exists when your games had revenue (or a carried balance). Games in basic launch earn nothing. Revenue earned before you set up a payout profile stays as a rolled-over balance until you do. |
| I changed bank details | Tell [developer support](https://docs.zokogames.com/business/support) before the payment date; our team confirms the new details with you directly. Bank details are never entered in the console. |

For the statement PDF and CSV downloads, see [statements and PDF](https://docs.zokogames.com/guides/statements-and-pdf).

## Next steps

- [Statements, PDFs and sandbox payouts](https://docs.zokogames.com/guides/statements-and-pdf)
- [Support and contact](https://docs.zokogames.com/business/support)

---

Source: https://docs.zokogames.com/business/developer-terms

# Developer terms summary

Terms used on this page, such as **studio**, **build**, **basic launch** and **full launch**, are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!IMPORTANT]
> This page summarises the developer terms you accept when you create a studio. It is **not** the agreement. The text you accept in the onboarding form (identified by a version, currently `2026-11-21`) and your payout profile are the binding sources. If this page and the agreement disagree, the agreement wins.

## What you agree to

**Ownership and licence.** You keep ownership of your game. You grant ZokoGames a non-exclusive licence to host, distribute and promote it on the portal and related surfaces. The licence is non-exclusive, so nothing in the terms stops you from publishing the game elsewhere; what the [requirements](https://docs.zokogames.com/requirements/gameplay#cross-promotion) do restrict is promoting other portals or running other ad networks inside the build you upload here.

**SDK and no other monetisation.** Games must use the ZokoGames SDK for ads, saves and accounts, and must not include other ad networks, tracking or portal branding. See the [advertisement rules](https://docs.zokogames.com/requirements/advertisements) and [cross-promotion rules](https://docs.zokogames.com/requirements/gameplay#cross-promotion).

**No paid random rewards.** A game that sells items must not sell anything bought with money or coins whose content is decided by chance, such as loot boxes, card packs, spins or mystery items. Prizes of money or other real-world value are not allowed, and items and in-game currency must not be cashed out, traded or sold outside the game.

**Rights and audience.** You confirm that you hold the rights to everything in your game, that it is suitable for a general audience (a PEGI 12 rating) and that its text is available in English. Copyright or brand misuse and copies of other games cannot be published.

**Revenue.** Revenue from ads served through the SDK is shared as shown in your payout profile. The standard terms are a 50 percent share for new studios and payment 45 days after the end of the month a statement covers; a different share or payment term applies only where it was agreed with your studio in writing. The console shows the terms in force: the share rate on the **Revenue** page and the payment term on the **Payouts** page. Net revenue from items sold through the ZokoGames store in your game (without the tax in the price, and after payment fees, refunds and chargebacks) is shared at the same rate unless the console shows a separate store rate; ZokoGames is the seller of those items to the player. Statements are monthly. A statement below the minimum balance rolls into the next month, and one is held while the tax form is not approved or the terms are not accepted. See [revenue share](https://docs.zokogames.com/business/revenue-share) and [payouts](https://docs.zokogames.com/business/payouts).

**Review and removal.** Every game and every update may be reviewed. We can request changes, reject or remove a game that breaks the terms, and a terms violation in an update can lead to immediate removal. See [how review works](https://docs.zokogames.com/requirements/quality#how-review-works) for the process and the fixed list of reasons.

**Ending the agreement.** Either side can end it. After removal, revenue you already earned is still paid under the normal rules.

## Takedown

- **By ZokoGames.** A game that breaks the terms can be rejected or removed. Reasons that end a submission (copyright or brand misuse, a copy of another game, inappropriate content, unsafe code) are final, see [typical reasons](https://docs.zokogames.com/requirements/quality#reasons-a-submission-is-sent-back-or-rejected). Repeat infringers can lose publishing access.
- **By a rights holder.** Anyone can send a notice through the [copyright form](https://www.zokogames.com/dmca); we review a complete notice and remove content that infringes.
- **By you.** The console deletes only drafts that were never published. To take a live game down, email developer support with the game name; to close a studio, use **Request deletion** in the studio settings. Nothing is removed until the team confirms with you. See [support](https://docs.zokogames.com/business/support).

## What data you see

- **Your studio's own data.** Every member of your studio sees its games, their statistics and feedback. Only owners and admins see the **Revenue** and **Payouts** pages and statements, and manage API tokens, webhooks and leaderboard keys. Staff of the portal can also see studio data.
- **Player details through the SDK.** Your game receives the user id, username and avatar of a signed-in player, and the verified token for your server. Use them to run your game, and not for your own tracking. Not shared with you: the player's email address.
- **Aggregates in the console.** Plays, views, playtime, retention, click-through and ad figures are counts per game and day, not lists of people. See [analytics and metrics](https://docs.zokogames.com/guides/analytics-metrics).
- **Player feedback.** Reasons and messages players send about your game appear on the console's Feedback page. A player's email is visible to staff only, and your reply is emailed only to the verified address of a signed-in account.

## Things the console enforces for you

- Acceptance is recorded with the terms version and a timestamp when you create the studio. Terms are versioned; the payouts page shows which version you accepted.
- Bank and card details are never entered on ZokoGames. A payout provider collects them, and we keep only an opaque reference.
- Owners and admins open the **Revenue** and **Payouts** pages and statements, manage API tokens, webhooks and leaderboard keys, and invite or remove members; members work on games. Only the owner changes the payout profile and the tax form, adds admins, changes roles and accepts the terms. Revenue is paid to the studio, not to individuals.

## Things that are not in the terms

- Promotion. Being live does not guarantee placement; see the [introduction](https://docs.zokogames.com/getting-started/introduction) for how promotion works.
- Tax advice. You are responsible for your own taxes; the payout provider's wizard picks the right form for your country.

Questions about the terms go to [support](https://docs.zokogames.com/business/support): the **Request help** button in the dashboard checklist callout, the developer support email, or the [contact form](https://www.zokogames.com/contact).

## Next steps

- [Revenue share overview](https://docs.zokogames.com/business/revenue-share)
- [Payouts](https://docs.zokogames.com/business/payouts)

---

Source: https://docs.zokogames.com/business/support

# Support and contact

## Before you write

Most problems can be diagnosed in two minutes:

1. Open the game in the [Preview tool](https://www.zokogames.com/preview) with the browser console open and `?sdk_debug=true`.
2. Look for the first red error. Note its message.
3. Search this documentation and the [FAQ](https://docs.zokogames.com/business/faq). Check the [error code lists](https://docs.zokogames.com/sdk/introduction#errors).
4. Try the game in an incognito window with extensions off, in a second browser.

## What to include

A request with these details is answered fastest:

- The game name and the build version or upload time.
- A preview link, or the exported event log from the [Preview tool](https://www.zokogames.com/preview).
- What you did, what you expected and what happened.
- The `code` and `message` of any SDK error, and the `environment`.
- Browser, operating system and device.
- A link to a screenshot or a short screen recording (the form takes no attachments, so upload it somewhere you can share and paste the link).
- For payout questions: the period and the figure you expected.

Do not send passwords, API keys or tokens. If you pasted a token or leaderboard key by accident, tell us so we can rotate it.

## Getting help: where to write

There are three routes, and all reach people who read them. Terms such as **studio**, **build** and **basic launch** are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

1. **The Request help button.** The dashboard's checklist shows a highlighted callout, "Next: upload your first build", with three links (quick start, starter kits, Preview tool) and a **Request help** button. It appears while the next unfinished step is creating your first game or uploading its first build, so it is not always on screen. Describe what you need (at least 10 characters). The request opens a thread in the support inbox tagged with your studio and its role, so the team knows who asked, and the team replies by email. It is limited to five requests per hour.
2. **The Support page and email.** The **Support** page in the developer console (left menu, `/developer/support`) has a request form and shows the address, `developers@zokogames.com`, with a short checklist. In the form, choose a topic (a review decision, build validation or upload, revenue and payouts, account access or your team, moving a game, a bug in the portal, an SDK question or something else): three documentation pages for that topic appear before you send, and the game, its build numbers, your browser and the topic are added to the request for you. Links from a rejected upload, a sent-back game or an error screen open the form with the topic, the game and the validation finding already filled in. Attachments are not supported, so paste links to screenshots or to the event log you exported from the Preview tool. When the request is sent you get a reference such as `0A1B2C3D`; quote it if you write again. The request is listed under **Your requests** on the same page with its status (open, answered or closed), and the answer goes by email to your account address. Every role in a studio can send a request, and only you and the support team can read it; a request you send from your own mail app is not listed on the page. Replies usually arrive within a working day. Email is the route that is always available, for studio, build, review, SDK and payout questions.
3. **The [contact form](https://www.zokogames.com/contact).** It works signed in or out. Pick a subject (for example "Bug or technical problem" or "Partnership or business"), enter your name, your email and a message of at least 10 characters. It is limited to five submissions per hour per network address.

There is no live chat. Replies to **player feedback** about your game are a different thing: you write those yourself from the **Feedback** page of the console (see [player features](https://docs.zokogames.com/guides/player-features)). Review decisions arrive in the console and by [notification](https://docs.zokogames.com/guides/notifications), with the reviewer's reasons; if you disagree with one, send a request from the Support page (topic: a review decision) with what you changed or want reconsidered. The form allows five requests an hour; when you reach that, the message says how long to wait, and email still works.

## Statuses and answer time

Each request on the **Your requests** list (the ten newest) shows one of three statuses:

| Status | Meaning | What you do |
| --- | --- | --- |
| Open: waiting for our team | We have it and nobody has answered yet. | Wait; replies usually arrive within a working day. |
| Answered: look in your email | We replied by email to your account address. | Read the answer, check your spam folder if it is not there, and try what it says. |
| Closed | We consider it settled. | If it is not settled, send a new request from the form and write the earlier reference in the message. |

The page does not show the text of the answer; it is in your email.

Copyright holders who want content removed use the [copyright form](https://www.zokogames.com/dmca) instead, and a studio deletion is requested from the studio settings; see [developer terms](https://docs.zokogames.com/business/developer-terms#takedown).

## Security reports

If you find a security problem in the portal or the SDK, report it privately by email to the developer support address shown on the console's Support page, and say in the first line that it is a security report. Please give us reasonable time to fix it before you disclose it.

## What support cannot do

Support does not debug your game code, but we will tell you what the portal sees. We do not provide tax advice. We cannot promote a game on request; see the [introduction](https://docs.zokogames.com/getting-started/introduction) for how promotion works.

---

Source: https://docs.zokogames.com/business/faq

# FAQ

## Feature status {#feature-status}

Every page of these docs uses the same three words for what works today. A page that names a status means exactly this:

- **Available now**: works in production for every studio.
- **In testing: no real money yet**: built and usable, but it runs on a test provider or in test mode, so no money is earned, charged or paid.
- **Planned**: built but switched off, so players and studios cannot use it yet. We do not promise a date.

| Feature | Status | What that means today |
| --- | --- | --- |
| Submission, review, hosting, launch stages, the JavaScript SDK, cloud saves, leaderboards, multiplayer, analytics, webhooks and the developer API | Available now | |
| Engine plugins | Available now | Published at 1.6.1. The Godot addons ran in the official editors and the Defold library was built with Defold's own build tool; the Unity, Cocos, Construct 3 and GameMaker plugins were compiled or checked, but not opened in their editors. Tell us if you hit a problem. |
| Advertising revenue | In testing: no real money yet | Games in full launch show the portal's own house ads. No ad network is connected, so no ad revenue is earned for any game yet. |
| Revenue share and payouts | Available now | The share rate in your console is the one that applies, and statements are prepared and invoiced. Payouts are made by hand: once the owner has confirmed manual payouts on the Payouts page, the portal team pays each invoiced statement to the method in your payout profile and records the transfer reference. Nothing is paid automatically, and a payout needs revenue (see the advertising and in-game purchase rows). |
| In-game purchases and coins | In testing: no real money yet | In-game purchases are built and Stripe is connected as their payment provider, but real-money sales stay off until the portal team switches them on, so only test purchases exist and nothing is charged. The coin store is off: players cannot buy coins. |
| Paid promotion of a game | In testing: no real money yet | No payment provider is connected for promotion: campaign payments are test payments and no money moves. |
| Ad-free membership and its playtime pool | Planned | The membership is built and sold through Stripe Managed Payments, with Link (a Stripe company) as the seller of the payment. New sign-ups are switched off for the public, so no player is ad-free today and the pool pays nothing. |
| Licensed games from distribution feeds | Planned | The catalogue holds only games published on ZokoGames. |
| Sign-in with Apple and Facebook | Planned | Players sign in with email, a passkey or the other sign-in providers shown on the sign-in page. |

When a status changes, the [changelog](https://docs.zokogames.com/business/changelog) says so.

## Submission and review

**Which engines work?** Anything that exports to HTML5/WebGL: Unity, Godot, Phaser, Construct 3, GameMaker, Cocos, Defold, PlayCanvas, Pixi, Babylon and plain JavaScript. See [engines](https://docs.zokogames.com/engines/overview).

**How do I submit?** Create a studio at `/developer/onboarding`, create a game, fill in the wizard, upload a zip and press **Submit for review**. See the [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).

**How long does review take?** The console shows the state of your submission and emails you the outcome. Review time depends on the queue, so we do not promise a number. A complete listing, a clean build and a note for the reviewer help.

**Why was my game rejected or sent back?** The decision lists reasons picked from a fixed list: game does not run, performance, ad integration, external links or popups, unclear controls, quality below the bar, artwork not meeting specs, inaccurate listing, audience flag. Some reasons are final (copyright or brand misuse, a copy of another game, inappropriate content, unsafe code): the message says the game cannot be published. See [how review works](https://docs.zokogames.com/requirements/quality#how-review-works) and the [typical reasons](https://docs.zokogames.com/requirements/quality#reasons-a-submission-is-sent-back-or-rejected).

**What does the build report mean?** Every upload produces a report with a code per finding. Errors block the build; warnings and notes do not. Each code, with its exact limit and fix, is on [build validation](https://docs.zokogames.com/requirements/build-validation).

**How does a game move from basic launch to full launch?** A basic launch starts ads-off and is due for a decision after at least 7 days and 500 plays, or after 21 days (defaults the portal team can change). A reviewer looks at average play time, day-1 return, conversion and click-through, and decides: promote, extend or end. See [launch stages](https://docs.zokogames.com/getting-started/launch-stages).

**Can I update a live game?** Yes, upload a new build at any time. During basic launch it goes live immediately; in full launch a reviewer approves it first. Games in review are locked until the decision.

**Can I host the game on my own server?** Hosting on ZokoGames is recommended: it is served from a global network under versioned paths. A game on your own `https` server is supported, must allow being framed from zokogames.com, and only earns when it uses the SDK.

**Do I have to use the SDK?** It is optional to submit and for basic launch, and required for full launch.

**Is there a size limit?** 250 MB unpacked, 1,500 files and an estimated initial download of 50 MB (20 MB for mobile). See [technical requirements](https://docs.zokogames.com/requirements/technical).

## Testing

**How do I test without uploading?** Run the game on `localhost` (the SDK mocks the portal), then open the [Preview tool](https://www.zokogames.com/preview), enter your address and play inside the real portal frame. No account is needed. See [testing](https://docs.zokogames.com/getting-started/local-testing).

**Is there a starting point?** Yes, five [starter kits](https://docs.zokogames.com/getting-started/starter-kits): plain HTML5, Vite with TypeScript, Phaser 4, PlayCanvas 2 and GDevelop 5.

## SDK

**Why does every call fail with `sdkDisabled`?** The page is not inside the portal and not on `localhost`. Add `?useLocalSdk=true` for testing. See [environments](https://docs.zokogames.com/getting-started/environments).

**Can I call the SDK before `init()` resolves?** No. You get `sdkNotInitialized`.

**Why is my ad not showing in local mode?** It is: local ads are a three-second overlay. If nothing shows, check the console with `?sdk_debug=true`, and check whether a midgame ad ran within the last three minutes.

**Why do I get `adsDisabled` in the portal?** Ads only run for games in full launch with ads enabled, and never for kids' games. Your code must treat it like any other ad error: resume the game and continue without an ad.

**Do I need to implement the user module?** Only if you use accounts, friends or leaderboards. If you do, follow [accounts](https://docs.zokogames.com/requirements/accounts).

**Is the player's id safe to use?** `__dangerousUserId` is client-provided and can be forged. Verify the token on your server and use its claims. See [player accounts](https://docs.zokogames.com/guides/player-accounts).

**How big can cloud save be?** 1 MiB for the whole save. See [data](https://docs.zokogames.com/sdk/data) and [cloud saves](https://docs.zokogames.com/guides/cloud-saves).

## Monetisation

**Where do I add my own ad network?** You cannot. Only SDK-served ads are allowed.

**Can I sell items in my game?** Real-money purchases are not available yet: real-money sales are switched off on the portal for now, so purchases run only as sandbox test purchases. See [in-game purchases](https://docs.zokogames.com/sdk/purchases).

**Why do I see no ad revenue?** No ad network is connected yet: games in full launch show the portal's own house ads, which earn nothing, so every game's ad revenue is zero today (see feature status above). Basic launch has no ads. After full launch check that you call `requestAd` at natural breaks and what `adError` codes you receive. Games marked as made for children never show ads.

**What is the revenue share?** New studios start at the standard rate of 50 percent. A different rate, for your studio or for one of its games, applies only where it was agreed with your studio in writing, and it is the rate the console shows on the Revenue page; see [revenue share](https://docs.zokogames.com/business/revenue-share) and the [developer terms summary](https://docs.zokogames.com/business/developer-terms).

**Who owns my game, and is it exclusive?** You own it. You grant ZokoGames a non-exclusive licence to host, distribute and promote it on the portal, so the terms do not stop you from publishing elsewhere. See [developer terms](https://docs.zokogames.com/business/developer-terms).

**Can I reuse the SDK and plugin code?** Yes. The SDK, the engine plugins and the starter kits are under the MIT licence; see [licences](https://docs.zokogames.com/business/licences).

**How do I take a game down?** In the console, an admin or owner can **Unpublish** a live game from its **Overview** tab at once (it goes offline and its builds, covers and stats stay), and can delete a draft that was never published. A studio with no games or statements can be deleted by its owner from the studio settings; for any other studio use **Request deletion** there, and nothing is removed until the team confirms with you. Copyright holders use the [copyright form](https://www.zokogames.com/dmca).

## Content

**Can I have chat?** Yes if it is moderated (at least a profanity filter and report option) and you honour `disableChat`.

**Can I link to my store page?** Add store links in the submission's metadata fields, not inside the game.

**Which age rating?** Games must fit PEGI 12. See [gameplay requirements](https://docs.zokogames.com/requirements/gameplay#age-rating).

## Account and payouts

**Who can see my game's data?** Every member of your studio sees your games' statistics and feedback. Only owners and admins see the **Revenue** and **Payouts** pages and statements, and manage API tokens, webhooks and leaderboard keys. Owners and admins invite or remove members on the Team page; only the owner adds admins and changes roles.

**When do I get paid?** Statements are prepared automatically on the second day of the following month and invoiced above a minimum balance, and payable 45 days after the end of the month they cover. That is the standard term; a different one applies only where it was agreed with your studio in writing, and the **Payouts** page in the console shows the term in force. Payment is made by hand: the portal team pays each invoiced statement to the method in your payout profile (bank wire, ACH or PayPal) and records the transfer reference; nothing is paid automatically. See [payouts](https://docs.zokogames.com/business/payouts).

**What can I see about my players?** Aggregate figures per game and day in the console, and for a signed-in player the user id, username and avatar through the SDK. Not their email address. See [developer terms](https://docs.zokogames.com/business/developer-terms#what-data-you-see).

**How do I get help?** Open **Support** in the console menu, choose a topic and describe the problem: the game, its build numbers and your browser are added for you, and when you send it you get a reference number. The answer goes by email to your account address, and the request is listed under **Your requests** on the same page. Attachments are not supported: in the Preview tool press **Download log file**, put the file somewhere you can share and paste the link into the message. You can also use the **Request help** button in the dashboard checklist callout, email the developer support address shown on the Support page, or use the [contact form](https://www.zokogames.com/contact). See [support](https://docs.zokogames.com/business/support).

**Why does the console ask for a second step before I make a key, token or webhook?** Creating, rotating or revoking a key or secret, inviting an admin and transferring ownership need your passkey or authenticator app. Add one in your account security settings first; until then the console answers that the action needs a second step and changes nothing.

**I uploaded a new build and players still see the old one. Why?** Before launch each new valid build becomes active at once. In basic launch players keep the current build until you press **Activate** on the new one; in full launch a reviewer approves the update first, and a build the safety scan flags as needs review also waits for a moderator. The current version stays live until then.

**My game was sent back or rejected. Is it still online?** In basic launch it stays playable. A game in Full QA that gets changes requested or a rejection goes offline until you fix it and submit it again; a rejection leaves it unpublished.

**Can I move a game to another studio?** Only ZokoGames staff can. Open Support, choose the topic about moving a game and the game, write the URL name of the studio it should go to, and send it as an owner or admin of the studio that holds the game.

**Can I change my studio's URL name?** Not in the console, because it is part of your public address. Ask through Support and give the new name you want.

**My studio is suspended. Can I still reach you?** Yes. The Support form keeps working while a studio is suspended, so you can appeal there. Build uploads are refused until the suspension ends.

Terms such as **build**, **studio**, **basic launch** and **full launch** are in the [glossary](https://docs.zokogames.com/getting-started/glossary). Not here? See [support](https://docs.zokogames.com/business/support).

## Next steps

- [Troubleshooting](https://docs.zokogames.com/guides/troubleshooting)
- [Support and contact](https://docs.zokogames.com/business/support)

---

Source: https://docs.zokogames.com/business/changelog

# Changelog

## SDK v1.7.0

Additive, no change to your code. New calls: `SDK.analytics.track(name, params?)` records a custom game event (fire-and-forget; an invalid or over-limit call is dropped silently). `SDK.data.mirrorIndexedDB(options?)` mirrors IndexedDB databases into the cloud save, for engines that save there (Unity, Godot, GameMaker); await it before the engine starts. `SDK.game.room.addLeftListener(cb)` and `removeLeftListener(cb)` tell the game when the portal ended the player's room membership (`left`, `kicked`, `closed`, `disconnected`). `showInviteButton(params, { portalOnly: true })` and `hideInviteButton({ portalOnly: true })` show or hide the portal's invite button without creating or changing a room. The engine plugins moved to 1.7.0 with the room left event and a `track` binding in every engine; `mirrorIndexedDB` is not bound in the plugins yet. See [versioning](https://docs.zokogames.com/sdk/versioning#migration-notes).

## SDK v1.6.4

Additive, no change to your code. `SDK.user.submitScore` takes an optional `delayed` field, so a score earned offline is not lost: a second copy of the score, sealed at the end of the run, that the portal keeps on the device for a signed-in player and sends when they are back online, within 72 hours. It counts for the all-time board only, not the weekly board, applies to boards with an encryption key, and is never kept in kids mode or for guests. A malformed `delayed` is dropped and the normal score still goes through, and a portal older than 1.6.4 ignores it. See [leaderboards](https://docs.zokogames.com/sdk/leaderboards#offline-scores). Local mode changed too, and you will notice it when you test: it now refuses a midgame ad with `adCooldown` until the game has called `gameplayStart()` (or 30 seconds of visible page time have passed), as the portal does, and it shows "Score saved offline" for an offline signed-in `submitScore` that carries `delayed`. Three small additions: every `add<Thing>Listener` method returns a function that removes the listener, `window.ZokoGames.SDK_VERSION` holds the version string, and `SdkError.code` autocompletes the known codes. The engine plugins need no update (they do not pass `delayed` yet). `https://sdk.zokogames.com/zokogames-sdk-v1.js` serves 1.6.4 automatically. Pinned: `https://sdk.zokogames.com/1.6.4/zokogames-sdk-v1.js`.

## SDK v1.6.3

Clearer messages, no change to your code: no name, type, error code, return value or timing changes. The `sdkDisabled` message now says why the SDK is disabled and links the local testing page, and the one-time "Disabled" console line tells you to add `?useLocalSdk=true` to the page address when local mode is the way out. `invalidArgument` messages say what was received (for example `got "interstitial"`), and the banner `invalidSize` message lists the allowed sizes. Three new one-time console warnings, which never throw: `ad.requestAd` called with callbacks that can never run (a bare function, a misspelled name such as `onFinished`, or a value that is not a function), `user.getUserToken` called with something other than an options object, and, in local mode, a misspelled scenario switch value such as `?user_response=guest`. Local mode also logs each `user.submitScore` call, and its start-up line now says submitted scores are only logged. One fix: `ad.requestAd` now resolves when the callbacks object cannot be read (for example a revoked `Proxy`); before, such a request stayed pending for ever. `https://sdk.zokogames.com/zokogames-sdk-v1.js` served 1.6.3 automatically until 1.6.4 was released. Pinned: `https://sdk.zokogames.com/1.6.3/zokogames-sdk-v1.js`.

## SDK v1.6.2

Additive, no change to your code. `SDK.game.gameId` is a new read-only string with the portal's id for your game (`"local-game"` in local mode). The SDK now writes one-time console notices (once per page each, no player data): why it ended up `disabled`, a member used before `init()` resolved, and a cloud save that failed to sync and will be retried. Host names with a reserved label at any depth (for example `x.g-<slug>.zokogames.com`) no longer count as the portal. Two fixes: an ad request that already ended (timeout, error or finished) now ignores later host events, so a late `adStarted` no longer keeps banners refused with `videoAdPlaying`; and `showAuthPrompt()` asks the portal who is signed in, so it opens the sign-in dialog after a sign-out in the portal instead of rejecting with `userAlreadySignedIn`. Games on the portal need no change, and the engine plugins need no update (they do not wrap `gameId` yet). `https://sdk.zokogames.com/zokogames-sdk-v1.js` served 1.6.2 automatically until 1.6.3 was released. Pinned: `https://sdk.zokogames.com/1.6.2/zokogames-sdk-v1.js`.

## SDK v1.6.1

Security hardening, no change to your code. The SDK now accepts the start-up handshake only from a ZokoGames page (not a game host `g-<slug>` or the preview runner), from a local host when the game itself runs locally, or from the game's own origin, so a site that frames your game can no longer pose as the portal. One trailing dot on a host name is tolerated. Also fixed: `SDK.ad.requestAd(type, null)` no longer throws, and the descriptions of the banner errors `missingId` and `notCreated` are corrected. Games on the portal need no change, and the engine plugins need no update. `https://sdk.zokogames.com/zokogames-sdk-v1.js` serves 1.6.1 automatically. Pinned: `https://sdk.zokogames.com/1.6.1/zokogames-sdk-v1.js`.

## SDK v1.6.0

Rooms open to friends, no change to existing code. The room host can call `SDK.game.updateRoom({ isPublic: true })` so friends can join from their friends list without an invite; rooms are private by default, and in kids mode they always stay private (see [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms)). The engine wrappers move to 1.6.0 together: Construct 3 adds the action **Set room public**, Unity `ZokoRoomUpdate.IsPublic`, and the other wrappers pass `isPublic` through their room update. Pinned: `https://sdk.zokogames.com/1.6.0/zokogames-sdk-v1.js`.

## SDK v1.5.1

Local-mode test events, no change to your code. Local mode fires `settingsChange`, `joinRoom` and `offlineChange` when the page dispatches `zokogames:local-settings`, `zokogames:local-join-room` or `zokogames:local-offline` on `window`, so those listeners can be tested without the portal (see [local testing](https://docs.zokogames.com/getting-started/local-testing#simulating-portal-events)). Nothing changes outside local mode, and the engine wrappers stay at 1.5.0. The [Preview tool](https://www.zokogames.com/preview) can now also run a build zip from your computer without uploading it. Nothing to do: `https://sdk.zokogames.com/zokogames-sdk-v1.js` serves 1.5.1 automatically. Pinned: `https://sdk.zokogames.com/1.5.1/zokogames-sdk-v1.js`.

## SDK v1.5.0

Kids mode and a leaderboard row type, no change to existing code. `SDK.game.settings.kidsMode` is typed: `true` when the game runs in kids mode, also in the settings listener; where it is `undefined`, fall back to `disableChat`. Local mode reads `?kidsMode=true`, and the [Preview tool](https://www.zokogames.com/preview) has a kids-mode switch. The new type `LeaderboardEntry` describes one row of the [leaderboard](https://docs.zokogames.com/sdk/leaderboards) JSON endpoints, with `isYou` and the opaque per-game `userId` (a type only; the SDK has no leaderboard read call). Every engine wrapper 1.5.0 exposes `kidsMode`. See [versioning](https://docs.zokogames.com/sdk/versioning). Pinned: `https://sdk.zokogames.com/1.5.0/zokogames-sdk-v1.js`.

## SDK v1.4.1

Robustness fixes, no changes to your code and no API change. Inside the portal the SDK now waits up to 15 seconds for the portal's answer to `init()` instead of 1.5 seconds, so a slow connection no longer leaves the game `disabled`. `gameplayStart`, `gameplayStop`, `happytime`, `loadingStart`, `loadingStop` and `leftRoom` resolve with a console warning instead of rejecting when the portal does not answer in time. Cloud saves write faster and a failed sync is retried on its own. `getUserToken` keeps one token per key type and forgets it when the player signs in. A few invalid arguments (`NaN` in `setGameContext`, sizes given as strings, values that cannot be copied) are refused with `invalidArgument` or `invalidSize`. The compatibility shim no longer rejects `requestAd` when an `adError` callback throws. Nothing to do: `https://sdk.zokogames.com/zokogames-sdk-v1.js` serves 1.4.1 automatically. The engine wrappers move to 1.4.1. Pinned: `https://sdk.zokogames.com/1.4.1/zokogames-sdk-v1.js`.

## SDK v1.4.0

Chat reports, feedback screenshots and a localStorage bridge. Adds `SDK.game.reportChat({ reportedName, message, reason, reportedUserId, roomId, context })`, which sends a chat message to the portal's moderators (limits and error codes under [reporting chat](https://docs.zokogames.com/sdk/game#reporting-chat)); `SDK.game.onScreenshotRequest(handler)`, which lets your game supply an image when the player opens the portal's feedback form (scaled to 1280 px and 1.5 MB by the SDK; see [feedback screenshot](https://docs.zokogames.com/sdk/game#feedback-screenshot)); and `SDK.data.mirrorLocalStorage({ keys, prefix })`, an opt-in switch that copies a ported game's `localStorage` saves into the cloud save and restores newer cloud values (see [mirroring](https://docs.zokogames.com/sdk/data#mirroring-localstorage-ported-games)). Additive: nothing runs unless you call it, older games are unaffected, and the script grows by about 9 KB. Nothing to do: `https://sdk.zokogames.com/zokogames-sdk-v1.js` serves 1.4.0 automatically once released. Pinned: `https://sdk.zokogames.com/1.4.0/zokogames-sdk-v1.js`.

## SDK v1.3.1

Reliability fixes, no changes to your code. An ad request (`requestAd`) now ends with `adError` and the code `timeout` when the portal neither answers nor starts the ad within 30 seconds, so your game can resume instead of waiting forever; once an ad has started there is still no time limit. A malformed message from the portal is ignored instead of throwing an error in your game. Calling `SDK.init()` on a page that has no browser window (for example while a server renders the page) resolves as `disabled` instead of failing. If the script tag is loaded twice, the first copy is kept and `window.ZokoGames.SDK` is no longer replaced. The module build also exports `ERROR_CODE_DESCRIPTIONS`, one plain-language line for every error code. In local mode the console prints one hint that says what is simulated. Nothing to do: `https://sdk.zokogames.com/zokogames-sdk-v1.js` serves 1.3.1 automatically, and the 1.3.0 files stay available at their pinned address. The engine wrappers move to 1.3.1 with no API change. Pinned: `https://sdk.zokogames.com/1.3.1/zokogames-sdk-v1.js`.

## SDK v1.3.0

Room data channel. Adds `SDK.game.room`: `send(data, { to })`, `onMessage`, `setState`, `getState`, `onState`, `members`, `onMembers`, `isHost`, `onHostChange`, `selfId` and `onError` (each `on*` also has an `add<Thing>Listener` / `remove<Thing>Listener` pair), so the players of one room can exchange small JSON messages (8 KB, 20 per second per player) and share a host-written state (64 KB) through the platform. The platform assigns the sender, a sequence number and a timestamp; the first player is the host and the role migrates when the host leaves. New error codes `notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember` and `roomUnavailable`. Local mode connects tabs of the same origin through a `BroadcastChannel`. Additive: older SDKs and portals keep working; on a portal without the channel `game.room.send` rejects with `unexpectedError`. The engine wrappers move to 1.3.0 with `game.room` bound in Phaser and Cocos Creator and JS-only in the others. Pinned: `https://sdk.zokogames.com/1.3.0/zokogames-sdk-v1.js`.

## SDK v1.2.0

Offline awareness. Adds `game.isOffline`, `game.addOfflineListener(fn)` and `game.removeOfflineListener(fn)`; local mode mirrors `navigator.onLine` and accepts `?offline=true`. Additive: older SDKs and older portals keep working, and `isOffline` is `false` when the portal does not send the flag. Pinned: `https://sdk.zokogames.com/1.2.0/zokogames-sdk-v1.js`.

## SDK v1.1.1

Fixes only. The banner refresh floor (30 s) and session cap now hold when a banner is cleared and requested again, and local mode reads `instantJoin=true` and invite parameters from the page URL. Pinned: `https://sdk.zokogames.com/1.1.1/zokogames-sdk-v1.js`.

## SDK v1.1.0

Additive release; nothing from 1.0 breaks. Latest alias: `https://sdk.zokogames.com/zokogames-sdk-v1.js`; pinned: `https://sdk.zokogames.com/1.1.0/zokogames-sdk-v1.js`.

- New `SDK.store` module (`isAvailable`, `getCatalogItems`, `getPlayerInventory`, `buyItem`, `consumeItem`, `setSandbox`, `getPurchaseToken`) and its error codes.
- `store.getPurchaseToken()` returns the purchase token; `user.getXsollaUserToken()` arrived with it as a deprecated alias for ported code. See the [migration note](https://docs.zokogames.com/sdk/versioning#10-to-11).
- New `SDK.game.loadingProgress(0..100)`, `?ad_response=` in local mode, and the exported `ERROR_CODES` table.
- `user.getUserToken({ signingKeyType })` now sends the key type to the portal; `submitScore` accepts an empty `encryptedScore` for boards without an encryption key.
- Docs: a complete runnable [quick start](https://docs.zokogames.com/getting-started/quick-start), exact [local mode rules](https://docs.zokogames.com/getting-started/local-testing) and an expanded [troubleshooting](https://docs.zokogames.com/guides/troubleshooting) page.

## SDK v1.0.0

First release of the ZokoGames SDK and developer portal.

**SDK**

- Script URL `https://sdk.zokogames.com/zokogames-sdk-v1.js`, global `window.ZokoGames.SDK`.
- Environments `zokogames`, `local` and `disabled`, with query overrides for local testing and `sdk_debug` logging.
- **Ad**: `requestAd` (midgame, rewarded) with `adStarted`, `adFinished`, `adError`; `hasAdblock`.
- **Banner**: static and responsive banners, `clearBanner`, `clearAllBanners`; 30 second refresh interval and a 60 refresh session cap.
- **Game**: `gameplayStart/Stop`, `loadingStart/Stop`, `happytime`, `reportGameCompletedPercentage`, game context, settings with change listener, rooms, invite links and join listener.
- **User**: `getUser`, `systemInfo`, `listFriends`, signed `getUserToken` with JWKS at `https://www.zokogames.com/.well-known/jwks.json`, `showAuthPrompt`, `showAccountLinkPrompt`, auth listener, `submitScore`.
- **Data**: cloud save with a `localStorage`-shaped API, 1 MiB limit, background sync.
- **Analytics**: `trackOrder`.
- Error codes including `dataLimitExceeded`, `bannerCooldown` and `adCooldown`.

**Compatibility shim**

- `zokogames-compat-v1.js` lets a game written against another portal's v3-style SDK keep its call sites. See [migrating](https://docs.zokogames.com/guides/migrating).

**Engines**

- Wrappers for Unity, Godot 4, Construct 3, GameMaker, Cocos Creator, Defold and Phaser 3, built from one shared bridge. They have not yet been compiled against every engine release, so expect small fixes on first import and report them through [support](https://docs.zokogames.com/business/support).

**Not in v1.0.0**

- In-game purchases (added later, sandbox only today, see [in-game purchases](https://docs.zokogames.com/sdk/purchases)).

## What changed in the docs

Short list, newest first. Every page also shows its own last-updated date.

- **23 November 2026, SDK 1.7.0 documented.** The [analytics](https://docs.zokogames.com/sdk/analytics), [data](https://docs.zokogames.com/sdk/data#mirroring-indexeddb-unity-godot-gamemaker), [game](https://docs.zokogames.com/sdk/game) and [multiplayer](https://docs.zokogames.com/guides/multiplayer-rooms) pages describe the four additions; the engine plugins are at 1.7.0.
- **23 November 2026, SDK 1.6.4 documented.** The [leaderboards](https://docs.zokogames.com/sdk/leaderboards#offline-scores) and [user](https://docs.zokogames.com/sdk/user#submitting-scores) pages describe `delayed` (what it is, how to seal it, which boards and players it applies to, the 72 hours), the [offline play](https://docs.zokogames.com/guides/offline-play) and [leaderboard setup](https://docs.zokogames.com/guides/leaderboard-setup) guides say what happens to a score offline, and [local testing](https://docs.zokogames.com/getting-started/local-testing) and [ads](https://docs.zokogames.com/sdk/ads#gameplay-first) say that local mode now applies the midgame rule and shows "Score saved offline". The [game](https://docs.zokogames.com/sdk/game) and [user](https://docs.zokogames.com/sdk/user) pages show that the listener methods return a remover, and [versioning](https://docs.zokogames.com/sdk/versioning) has the release notes.
- **22 November 2026, midgame ads wait for `gameplayStart`.** A change on the site, not in the SDK (no SDK version changes): the portal refuses a midgame ad request with `adCooldown` until the game has called `SDK.game.gameplayStart()` once in that game window. A game that never calls it gets midgame ads 30 seconds after play begins. Rewarded ads are not affected. Local mode did not apply the rule until SDK 1.6.4; from 1.6.4 it does. See [Gameplay first](https://docs.zokogames.com/sdk/ads#gameplay-first) and the [advertisement rules](https://docs.zokogames.com/requirements/advertisements). The pages for kids mode, the Unity and Defold version constants and the `order` analytics event were corrected in the same pass.
- **22 November 2026, SDK 1.6.3 documented.** The SDK pages show the new error and console messages (what was received, and what to do), [troubleshooting](https://docs.zokogames.com/guides/troubleshooting) lists each new console line with its fix, and [versioning](https://docs.zokogames.com/sdk/versioning) has the release notes. New guide: [team and roles](https://docs.zokogames.com/guides/team-and-roles).
- **22 November 2026, SDK 1.6.2 documented.** The SDK pages describe `SDK.game.gameId`, the one-time console notices and the reserved-label rule, the local-testing page lists the notices, the data page names the reserved `__zoko_ls_mirror_ts` key that `mirrorLocalStorage` writes, and the game, user and leaderboards pages are corrected (`updateRoom` takes a boolean `isPublic`; the game id is readable as `SDK.game.gameId` from 1.6.2).
- **21 November 2026, one text editor and Markdown in the API.** Description, controls, FAQ answers, release notes and the studio description now use one Markdown editor with a fixed set of formatting; see [text formatting](https://docs.zokogames.com/requirements/text-formatting). The [developer API](https://docs.zokogames.com/guides/developer-api) returns Markdown for `description` (game detail) and `release_notes` (builds). Older values stay HTML (plain text for release notes) until they are saved again, so sanitise what you render.
- **20 November 2026, engine plugins 1.6.1.** Every engine plugin moves to 1.6.1 and still targets SDK 1.6.0; game code needs no change. The plugins were checked against each engine's official documentation and fixed: Unity (runtime assembly references uGUI, static state reset when Domain Reload is off, `.meta` files shipped), Godot 4 (loads again in 4.0 and 4.1, the autoload survives closing the editor; portal builds need 4.3 or newer), Construct 3 (the addon loads, its DOM script is registered, every action can be awaited; r397 or newer), GameMaker (the simulator uses the extension `#define` format, events never arrive while a call is still running), Defold (Lua callbacks run with their script instance). Cocos, Godot 3 and Phaser have no code change. Download the new files from each engine page; each plugin's CHANGELOG lists the details.
- **20 November 2026, paid and held-back amounts.** The `statement.updated` [webhook](https://docs.zokogames.com/guides/webhooks) has two new fields for a paid statement: `paidMicros`, the amount actually sent, and `heldBackMicros`, the part the new-studio holdback kept back. The statements list of the [developer API](https://docs.zokogames.com/guides/developer-api) has the same two amounts as `paid_minor` and `held_back_minor`. `payableMicros` and `payable_minor` keep their meaning, the full payable amount. The new fields are `null` until the statement is paid. Nothing else in the payloads changed. Clients that validate responses strictly against the published OpenAPI document (objects closed with `additionalProperties: false`) must allow the new fields, for example by regenerating from the current document. Webhook handlers should ignore fields they do not know.
- **20 November 2026, amounts too large to state exactly.** The `statement.updated` [webhook](https://docs.zokogames.com/guides/webhooks) can carry `payableMicros: null`, and the [developer API](https://docs.zokogames.com/guides/developer-api) statements endpoints can answer `409 amount_unsafe`, for a statement whose amount is outside the exactly representable range and is settled by hand. Treat `null` as unknown, never as `0`. See [statements, PDFs and sandbox payouts](https://docs.zokogames.com/guides/statements-and-pdf).
- **19 November 2026, SDK 1.5.0–1.6.0.** New pages [Build a minimal game in 15 minutes](https://docs.zokogames.com/getting-started/first-game), [Testing checklist before you submit](https://docs.zokogames.com/getting-started/testing-checklist) and [Audio, pausing and ads](https://docs.zokogames.com/guides/audio-and-ads). In local testing, [simulated portal events](https://docs.zokogames.com/getting-started/local-testing#simulating-portal-events) and [running a build zip from your computer](https://docs.zokogames.com/getting-started/local-testing#run-a-build-zip-from-your-computer); rooms open to friends (`isPublic`) in [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms); versioned [engine downloads](https://docs.zokogames.com/engines/overview#getting-the-plugin) with checksums; the 1.5.0, 1.5.1 and 1.6.0 notes in [versioning](https://docs.zokogames.com/sdk/versioning).
- **19 November 2026, confirming it is you.** Creating or revoking an API token, adding a webhook endpoint or rotating its secret, changing payout details, making someone an admin, transferring studio ownership and deleting a studio now ask you to confirm it is you with a passkey or an authenticator app. See the [developer API reference](https://docs.zokogames.com/guides/developer-api), [webhooks](https://docs.zokogames.com/guides/webhooks) and the [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- **19 November 2026, SDK 1.4.0.** [Reporting chat](https://docs.zokogames.com/sdk/game#reporting-chat) and the [feedback screenshot](https://docs.zokogames.com/sdk/game#feedback-screenshot) in the game module, [mirroring localStorage](https://docs.zokogames.com/sdk/data#mirroring-localstorage-ported-games) in the data module, a pointer from the [cloud saves guide](https://docs.zokogames.com/guides/cloud-saves) and the [multiplayer rooms guide](https://docs.zokogames.com/guides/multiplayer-rooms), and a 1.3 to 1.4 note in [versioning](https://docs.zokogames.com/sdk/versioning).
- **18 November 2026, read-through for newcomers.** [Your first game live in 30 minutes](https://docs.zokogames.com/getting-started/quick-start) is now the single path from zero to a submitted build. New [glossary](https://docs.zokogames.com/getting-started/glossary) and a reorganised [troubleshooting](https://docs.zokogames.com/guides/troubleshooting) page (blank frame, mixed content, CORS, audio, fullscreen, saves, ads in preview). The docs now say how switching builds really works (**Activate** and **Roll back to this**) and that studios may be onboarded by invitation.
- **18 November 2026, earlier updates.** [Analytics and metrics reference](https://docs.zokogames.com/guides/analytics-metrics), [build validation reference](https://docs.zokogames.com/requirements/build-validation), [notifications](https://docs.zokogames.com/guides/notifications), [player features](https://docs.zokogames.com/guides/player-features), [webhooks](https://docs.zokogames.com/guides/webhooks), the [purchases](https://docs.zokogames.com/sdk/purchases) rewrite (sandbox only), embedding on partner sites, and age rating and languages as required submission fields.
- **17 November 2026.** [Submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough), [starter kits](https://docs.zokogames.com/getting-started/starter-kits), the public [Preview tool](https://www.zokogames.com/preview), [requirements checklist](https://docs.zokogames.com/requirements/checklist), [launch stages](https://docs.zokogames.com/getting-started/launch-stages), [updating a live game](https://docs.zokogames.com/getting-started/updating-a-game), [engine pages](https://docs.zokogames.com/engines/overview) and the [SDK playground](https://docs.zokogames.com/sdk/playground).

---

Source: https://docs.zokogames.com/business/licences

# Licences

## SDK, plugins and starter kits

The ZokoGames SDK, the compatibility shim, the [engine plugins](https://docs.zokogames.com/engines/overview) and the [starter kits](https://docs.zokogames.com/getting-started/starter-kits) are published under the MIT licence, copyright 2026 APIDLY LTD. Every download contains a `LICENSE` file with the full text (`LICENSE.md` in the Unity package), and the SDK script starts with a one-line licence header.

## What the licence allows

- Use, copy and change the code in any game, free or paid, on ZokoGames or anywhere else.
- Ship it inside your build. When you pass on a copy of the code, keep the copyright line and the licence text with it.
- The code comes without warranty, as the licence text says.

The licence covers our code only. Your game stays yours, and publishing it on ZokoGames is governed by the [developer terms](https://docs.zokogames.com/business/developer-terms).

## Open-source software in the portal

The ZokoGames website is built with open-source packages and fonts. Their copyright notices and licence texts are listed in the [third-party notices](https://www.zokogames.com/third-party-notices.txt).
