# Bitey Games SDK — HTML5 Developer Guide (v1.3)

> **Update (Nov 2026):** If you copied the kit into your game (e.g. `src/vendor/biteygames-sdk/index.mjs`),
> the app now works without changes, but please replace that file with the latest
> [`biteygames-sdk.mjs`](https://biteygames.com/downloads/biteygames-sdk.mjs) so you get future fixes.
> New games: nothing extra for the app — call `connect({ gameKey })`, start a session, use wallet/save/score
> through the kit, and call shut-down on Exit.


For HTML5/JavaScript games (Phaser, Cocos, Construct, raw HTML, Vite/webpack).

**New in v1.3:** games now recognise the player inside the Bitey Games mobile app. Games loading the SDK from `https://biteygames.com/sdk` get this automatically; games bundling the SDK must rebuild with the latest version (no code changes). Your Exit button must call `gv.shutdown()` so the app can close the game screen.


Version `0.2.0` moves every call onto a single opaque gateway endpoint. Your game no longer
knows (or ships) any platform endpoint paths, and **no API secret ever ships in your bundle**.

---

## Install

### Bundled copy (Vite, webpack)

```bash
# Not on npm yet: download https://biteygames.com/downloads/biteygames-sdk.js
# and add it to your project
```

```ts
import { BiteyGames } from "./biteygames-sdk.js";
```

### CDN script tag (Cocos, Construct, raw HTML — no bundler needed)

```html
<script src="https://biteygames.com/sdk"></script>
<script>
  // global window.BiteyGames is available
  const gv = await BiteyGames.connect({ gameKey: "gk_..." });
</script>
```

## Quick start

```ts
import { BiteyGames } from "./biteygames-sdk.js";

const gv = await BiteyGames.connect({
  gameKey: "gk_542fa347d208717a",        // public identifier, safe in your bundle
  devToken: import.meta.env.VITE_BITEY_DEV_TOKEN, // localhost only, optional
});

const session = await gv.session.start();
console.log(session.session_id, session.wallet_balance);

// Persist progress
gv.state.set({ level: 3, unlocked: ["jetpack"] });
await gv.state.save();

// Reward the player
await gv.wallet.credit(100, "run_complete");

// Submit a score
await gv.scores.submit(12_400);

// On exit
await gv.shutdown();
```

## How authentication works

| Where the game runs | Token used |
| --- | --- |
| Inside the platform iframe | Short-lived session token delivered by the `gv:auth` handshake |
| Localhost / standalone | `bdt_...` dev token you mint in the Developer Dashboard |

`BiteyGames.connect()` handles both: it posts `gv:ready` to the parent, waits briefly for
`gv:auth`, and falls back to `devToken` when there is no parent frame.

You send two things on every request:

- `x-game-key` — your **public** game key (identifier only, not a credential)
- `Authorization: Bearer <token>` — the session or dev token

The old `API_SECRET` must **not** be shipped in a game bundle. Legacy games using
`x-api-key` continue to work through compatibility shims, but should migrate.

## Local usage without npm

The SDK is not yet published to the npm registry. Until it is, use one of the three
methods below. All produce the same `import { BiteyGames } from "./biteygames-sdk.js"` API —
only the installation step differs.

> **Prerequisite:** You need a copy of the SDK source. It lives in the platform repo at
> `packages/sdk/`. Clone or download that folder to your machine.

### Method 1 — Build and install from a local folder (recommended)

Build the SDK once, then point your game's `package.json` at the local `dist/` output.

```bash
# 1. Build the SDK (run inside the platform repo)
cd packages/sdk
bun install          # or: npm install
bun run build        # produces dist/index.mjs, dist/index.cjs, dist/index.d.ts

# 2. In your game project, install from the local path
cd /path/to/your-game
npm install /path/to/platform/packages/sdk
# or add this to package.json dependencies:
#   "@biteygames/sdk": "file:/path/to/platform/packages/sdk"
```

Your game code stays identical:

```ts
import { BiteyGames } from "./biteygames-sdk.js";   // resolves to the local build
```

### Method 2 — npm link (iterative development)

Best when you're editing SDK source and want changes picked up instantly without
re-installing.

```bash
# Terminal 1 — in the SDK folder
cd packages/sdk
bun install && bun run build
npm link

# Terminal 2 — in your game project
cd /path/to/your-game
npm link @biteygames/sdk
```

Rebuild the SDK (`bun run build`) after code changes; your game picks them up on the
next dev-server restart.

### Method 3 — CDN script tag (requires deployed platform)

If the platform is already live (e.g. `https://biteygames.com`), you can skip the
local build entirely and load the SDK from the platform's CDN route:

```html
<script src="https://biteygames.com/sdk"></script>
<script>
  const gv = await BiteyGames.connect({ gameKey: "gk_..." });
</script>
```

This works from localhost — the script is fetched from the deployed platform, but your
game runs locally. No bundler or build step needed.

> The CDN is only available once the platform is deployed. The local build methods
> (1 and 2) work regardless of whether the platform is hosted.

## Local development

1. Developer Dashboard → your game → **Local development** → *Generate dev token*.
2. Copy the `bdt_...` value into a local env var (e.g. `VITE_BITEY_DEV_TOKEN`) — never commit it.
3. Run your game on `http://localhost:...`; `connect()` picks up the dev token automatically.

Dev tokens are valid for 8 hours, are bound to one game, and act as a **sandbox player**:
a separate wallet and stats that are excluded from all public leaderboards. Revoke a token
any time from the same panel.

> **Note:** Dev tokens authenticate you, but the SDK still needs the platform API to be
> reachable (localhost preview, staging, or production) for calls to succeed. The SDK
> package itself installs and imports fine without a running platform.

## Transport

Every method is one `POST` to `<apiBase>/rpc`:

```http
POST https://biteygames.com/api/v1/sdk/rpc
x-game-key: gk_...
Authorization: Bearer <token>
content-type: application/json

{ "op": "wallet.credit", "payload": { "amount": 100 }, "nonce": "..." }
```

Response envelope:

```json
{ "success": true, "data": { "balance": 1250 }, "request_id": "req_..." }
```

Use `gv.call<T>(op, payload)` for any operation without a typed helper.

## Operations

| Area | Operations |
| --- | --- |
| Session | `gameplay.session.start`, `gameplay.session.end` |
| State | `gameplay.state.load`, `gameplay.state.save` |
| Scores | `gameplay.submit_score`, `leaderboard.top` |
| Wallet | `wallet.balance`, `wallet.bites`, `wallet.credit`, `wallet.debit` |
| Tournaments | `tournament.list`, `tournament.join` |
| Player | `player.profile`, `player.progress`, `progression.get`, `progression.xp` |
| Achievements | `achievements.list`, `achievements.claim` |
| Rewards | `rewards.center`, `rewards.request`, `spin.status`, `spin.play` |
| Retention | `retention.daily_login.*`, `retention.comeback.*`, `retention.missions.*` |
| Store | `store.list`, `store.purchase`, `offers.list`, `offers.claim` |
| Analytics | `analytics.track`, `analytics.event` |

## API reference

### `BiteyGames.connect(options)`

| Option | Type | Notes |
| --- | --- | --- |
| `gameKey` | `string` | Required. Public game key. |
| `devToken` | `string` | Optional localhost fallback. |
| `apiBase` | `string` | Defaults to `https://biteygames.com/api/v1/sdk`. |
| `schemaVersion` | `number` | Schema version your build writes. |
| `onStateReload` | `(state) => void` | Called after a `STATE_CONFLICT` reload. |
| `autosaveDebounceMs` | `number` | Default `5000`. |
| `handshakeTimeoutMs` | `number` | Default `3000` before falling back to `devToken`. |

### Instance

- `session.start() / session.end() / session.id()`
- `state.get() / state.set(patch) / state.replace(obj) / state.save() / state.load() / state.flush()`
- `wallet.balance() / wallet.credit(amount, reason?, metadata?) / wallet.debit(...)`
- `scores.submit(score, { tournament_id?, metadata? })`
- `leaderboard.top(period?, limit?)`
- `player.profile() / player.progress()`
- `analytics.track(event, value?, metadata?)`
- `call<T>(op, payload)` — any operation
- `shutdown()` — flush autosave, end session, notify the platform

## Errors

All failures throw `BiteyGamesError` with `code`, `message`, `status`, `request_id`.
Notable codes: `STATE_CONFLICT` (reload and merge), `INSUFFICIENT_FUNDS`,
`RATE_LIMITED`, `UNAUTHORIZED` (token expired — re-run `connect()`).

## Migrating from 0.1.x

| 0.1.x | 0.2.0 |
| --- | --- |
| `apiKey: "<key>.<secret>"` | `gameKey: "gk_..."` (no secret) |
| `BiteyGames.init({ apiBase, apiKey, token })` | `await BiteyGames.connect({ gameKey })` |
| `fromParentHandshake()` | `connect()` (or `waitForHandshake()` for the raw message) |
| Per-endpoint REST paths | Single `/rpc` endpoint, `op` names |

## License

MIT — see [LICENSE](./LICENSE).

## Update (Oct 2026): tournament scores
- Call score submit at the end of every round. Passing the tournament id is recommended, but no longer required: if it is missing, the score is credited to the player's live tournament for this game.
- Only scores sent between a tournament's start and end count; the player's highest score is kept.
- Game leaderboards (daily, weekly, monthly, all-time) are now built from saved scores and update within about 15 seconds.

## Update (Oct 30 2026): browsing without sign-in + "game not connected" checklist

### Public browse endpoints (no token needed)
These now work with **no** `Authorization` header, so the app can show content before sign-in:
`GET /home`, `/games`, `/games/:gameId`, `/genres`, `/upcoming`, `/tournaments`, `/tournaments/recommended`, `/tournaments/:id`, `/tournaments/:id/standings`.
If a token is sent, personal fields (wallet, missions, joined, recommendations) are filled in. Without one, `/home` returns `signed_in: false` with featured games, and tournaments return `is_guest: true`, `joined: false`.
Everything else (launch, play, wallet, missions, rewards, join, profile) still needs a token. To let users play straight away, the app can call `POST /auth/guest` silently on first launch.

### `:id` in `POST /games/:id/launch`
`:id` is the game's `id` from `GET /games` (e.g. Galactic Dash = `99c352b1-b6e3-4ae1-a3bf-364f4f808a70`).

### Game not spending/earning coins or losing purchases — check these
1. **The game must call the kit.** Spending: `await gv.wallet.debit(amount, "warship")`. Earning: `await gv.wallet.credit(amount, "run_reward")`. Keeping items: `gv.state.set({ ships: [...] })` then `await gv.state.save()` (load it back with `await gv.state.load()` on start). Items held only in game memory are lost on exit.
2. **The app must open `launch_url`**, not `play_url`. `launch_url` carries the player identity.
3. **Use the current kit.** Load it from `https://biteygames.com/sdk` or rebuild a bundled copy with the latest version.
4. **On Exit:** `await gv.shutdown()` (it saves state and ends the session) — and wait for it before the app closes the WebView. The app should close on the `gv:exit` message, not immediately on tap.
5. **Look at the browser console.** `[BiteyGames] NOT CONNECTED` means no identity reached the game (see item 2/3).

Quick test: play once in the app, buy something and finish a run, then check the player's wallet history — it should show one spend and one reward line for the game.

## Update (Nov 9 2026): fit the player's screen
Inside the mobile app the game fills the phone's screen in portrait or landscape. Make sure your game:
- sizes itself from the window (`window.innerWidth/innerHeight` plus a `resize` listener) instead of a fixed pixel width
- for Unity WebGL, uses the Bitey Games template and a Canvas Scaler set to "Scale With Screen Size"

A fixed-width game spills off the right side of the screen on phones.
