# 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)
