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