> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nodeloc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK reference

> Every nl.* method in @nodeloc/game-sdk, with parameters, return values, errors, and web version behavior

## Include the SDK

```html theme={null}
<script src="nl-game-sdk.js"></script>  <!-- global nl -->
```

```javascript theme={null}
import nl from "@nodeloc/game-sdk";       // ES module
const nl = require("@nodeloc/game-sdk");  // CommonJS
```

The SDK needs no build step. Put `nl-game-sdk.js` in the game package when you pack it. Type definitions are in `index.d.ts` in the package.

## Conventions

* Async methods return a Promise with a default timeout of 5 seconds. Methods that wait for the user have no timeout: `energy.requestPayment`, `energy.deposit`, `energy.withdraw`, `energy.claimDaily`, `energy.confirmStake`, `share.invite`, `auth.login`.
* On failure the Promise rejects with an `NLError` whose `code` is one of the following:

| code | Meaning | What the game should do |
| - | - | - |
| `NOT_SUPPORTED` | The current host does not have this capability | Hide the feature |
| `SCOPE_DENIED` | The game was not approved for this scope | Hide the feature |
| `USER_CANCELLED` | The user cancelled in a panel or pop-up | Not an error; return silently |
| `AUTH_REQUIRED` | The user is not signed in to the forum, or the session expired | Show "Please sign in" and a button that calls `nl.auth.login()` |
| `INVALID_PARAMS` | Invalid parameters | Fix the code |
| `RATE_LIMITED` | Too many calls | Retry later |
| `NETWORK` | Network or server error | Offer a retry |
| `INTERNAL` | Internal host error | Offer a retry |

* `nl.system.getInfo().capabilities` lists the methods the current host actually supports. Use it to decide on fallbacks.

## Startup

| Method | Description |
| - | - |
| `nl.setLoadingProgress(p)` | Loading progress, 0–1. Shown on the host loading screen |
| `nl.ready(): Promise<void>` | Closes the host loading screen. Call it as soon as enough is loaded to start playing. If it is not called within 15 seconds, the host shows "Retry / Exit" |
| `nl.exit(): Promise<void>` | Exits the game |

## System

| Method | Returns |
| - | - |
| `nl.system.getInfo()` | `{platform, osVersion, clientVersion, sdkProtocol, locale, safeArea, pixelRatio, capabilities, launch?, gameService?}`. `platform` is `ios`, `android`, or `web`; `gameService` is the WebSocket URL of the real-time game service |
| `nl.system.getLaunchOptions()` | Synchronously returns `{room?}`: the room code when the game was opened from an invite link |

## UI

| Method | Description |
| - | - |
| `nl.ui.getCapsuleRect(): Promise<{x, y, width, height}>` | Position of the "Exit" capsule in the top-right corner. Keep the title bar and buttons clear of it |
| `nl.ui.toast(text)` | Shows a brief message |
| `nl.ui.requestFullscreen(): Promise<void>` | Web version: enters full screen and, on phones, locks the screen to the manifest orientation |

## Lifecycle

| Method | Description |
| - | - |
| `nl.lifecycle.on(event, cb)` | `event` is `pause`, `resume`, `back`, or `memoryWarning`. Returns an unsubscribe function |
| `nl.lifecycle.setExitGuard(on, message?)` | When on, the user confirms before exiting. Recommended during a match |

When the game goes to the background (`pause`), pause timers and stop background music.

## Audio

| Method | Description |
| - | - |
| `nl.audio.preload(keys): Promise<void>` | Preloads audio paths in the package |
| `nl.audio.play(key, {volume?, loop?, rate?}): number` | Plays a sound and returns a handle. Does not wait for a reply |
| `nl.audio.stop(handle)` | Stops a sound |
| `nl.audio.bgm.play(key)` / `pause()` / `resume()` / `stop()` | Background music |
| `nl.audio.setMasterVolume(v)` / `setMuted(muted)` | Master volume and mute |

The app uses native audio, and the host handles the mute switch and call interruptions. The web version uses Web Audio, which unlocks after the first tap.

## Haptics

| Method | Description |
| - | - |
| `nl.haptics.impact(style?)` | `light`, `medium`, `heavy`, `rigid`, `soft` |
| `nl.haptics.notify(type?)` | `success`, `warning`, `error` |
| `nl.haptics.selection()` | Selection feedback |

Haptics fire at most once every 50 milliseconds, and extra calls are dropped. The web version uses `navigator.vibrate` and skips silently where iOS Safari does not support it.

## Identity

| Method | Returns | Description |
| - | - | - |
| `nl.auth.getUser()` | `{id, username, name, avatar, tier?}` | `id` is an anonymous per-game ID, not the forum user ID |
| `nl.auth.getToken()` | `{token, expiresAt}` | The game token for connecting to the game service. `expiresAt` is Unix milliseconds; the token renews automatically 60 seconds before it expires |
| `nl.auth.login()` | `Promise<void>` | Asks the user to sign in to the forum. Must be called from a click handler |

When the user is signed out, the first two methods return `AUTH_REQUIRED`. In the app, the host prompts the user to sign in and reloads the game afterward. In the web version, if there is no token, the SDK redirects the whole page to the forum authorization page. On first use, the user confirms they are 18 or older and grants authorization.

## Game energy

| Method | Returns | Scope |
| - | - | - |
| `nl.energy.getWallet()` | Wallet, see below | Any game energy scope |
| `nl.energy.getHistory({cursor?, limit?, kinds?, allGames?})` | `{entries, nextCursor}` | Any game energy scope |
| `nl.energy.claimDaily()` | `{granted, balance}` | Any game energy scope |
| `nl.energy.deposit()` | `{deposited, balance}` | `game.energy.stake` or `game.energy.pay` |
| `nl.energy.withdraw()` | `{withdrawn, balance, withdrawable}` | Any game energy scope |
| `nl.energy.confirmStake({base, cap, table?, title?})` | `{confirmed: true, remembered}` | `game.energy.stake` |
| `nl.energy.requestPayment(orderToken)` | `{status: "paid", orderId}` | `game.energy.stake` or `game.energy.pay` |

The game energy scopes are `game.energy.read`, `game.energy.stake`, and `game.energy.pay`; the last two include read access. `claimDaily`, `deposit`, and `withdraw` open a host panel where the user chooses the amount.

Wallet:

```typescript theme={null}
{
  balance: number;
  withdrawable: number;          // the part that can be withdrawn to community energy
  dailyFreeClaimable: boolean;
  limits: {
    stakeToday, stakeCap, netLossToday, netLossCap,
    depositToday, depositCap, withdrawToday, withdrawCap,
    withdrawMin, withdrawEnabled, withdrawLockDays
  };
  remaining: { stake, netLoss, deposit, withdraw };  // allowance left today
}
```

Each history entry: `{id, createdAt, kind, label, amount, balanceAfter, withdrawableDelta, withdrawableAfter, game, roomId?, orderId?}`. `label` is already translated into the user's language. A positive `amount` is income. A `game` of `null` means an entry of the wallet itself (deposit, withdrawal, claim). A `nextCursor` of `null` means there are no more entries. By default only this game's entries and the wallet's own entries are listed; `allGames` is available only in the app.

`kind` can be `deposit`, `withdraw`, `daily_grant`, `relief_grant`, `stake_hold`, `stake_release`, `win`, `loss`, `bot_win`, `bot_loss`, `rake_burn`, `cap_burn`, `ticket`, `prize`, `bonus`, `item`, `refund`.

See [Game energy and payments](https://docs.nodeloc.com/en/minigames/energy.md) for rules and limits.

## Sharing

| Method | Description |
| - | - |
| `nl.share.invite({title, text?, roomCode?, image?})` | Returns `{shared}`. The invite link is `https://www.nodeloc.com/games/{slug}?room=…` |
| `nl.share.onInvite(cb)` | Fires when the user taps another invite to the same game while it is running, with `cb({room})`. Returns an unsubscribe function |

## Debugging and configuration

| Method | Description |
| - | - |
| `nl.debug.log(...args)` | Visible in the app debug panel |
| `nl.configure({slug?, site?, gameService?, orientation?, capsule?, loading?})` | Needed only in the web version or for local debugging. `capsule: false` hides the exit button, and `loading: false` hides the loading layer |

The host reports startup time, crashes, frame rate, and connection quality automatically. The game does not need to handle them.

## Web version behavior

| Capability | Web version |
| - | - |
| Identity | Forum authorization (PKCE). The token and refresh token are stored in `sessionStorage`; the refresh token is valid for 7 days |
| Balance and history | Read from the forum's read-only API with the game token (request header `X-Game-Token`). Only this game's history is visible, and `allGames` returns `SCOPE_DENIED` |
| Claim, deposit, withdraw, pay | Opens a forum pop-up where the user confirms on the forum page. Must be called synchronously from a click handler. Returns `USER_CANCELLED` if the pop-up is blocked or closed |
| Stake confirmation | The SDK draws a confirmation dialog on the page. It is only a reminder; the actual charge is enforced by server rules and payment confirmation |
| Sharing | `navigator.share`; where unsupported, the link is copied and a message is shown |
| Lifecycle | `visibilitychange` maps to pause / resume; `setExitGuard` uses `beforeunload` |
| Capsule, loading screen, orientation | The SDK draws the exit button and loading layer. On phones in the wrong orientation it shows "Please rotate your phone to landscape" |
| Version | When an old build is opened, the SDK redirects to the current version |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.