# 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
