npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@milkywaygaming/rgs-player-sdk

v0.1.0-alpha.97

Published

The framework-free player SDK for Milkyway Gaming games in a casino's own frontend: the launch, the player API, the game session with browser client seeds and replay-safe bets, reveal checks and verify links.

Readme

@milkywaygaming/rgs-player-sdk

The player SDK for Milkyway Gaming games in a casino's own frontend: framework-free TypeScript, ESM with type declarations, and two dependencies: SignalR's client (@microsoft/signalr), loaded only when the hub first connects, and FingerprintJS (@fingerprintjs/fingerprintjs, MIT), loaded only for the device report once a session is ready. A React or Next.js app builds its game UI on it. It passes two things: the API origin Milkyway Gaming gives the casino (https://player.<domain>), and the session's token, which the casino's backend gets from the launch and hands to its frontend. The SDK does the rest:

  • the player API over the platform's player hub (createHubPlayerApi: one WebSocket per session, a fresh connect ticket on every connect and reconnect, pushed balances), behind the PlayerApi port, with typed errors (PlayerApiError, whose message is a stable code, never server text);
  • the balance: the game asks the casino's wallet for the balance at most once every 30 seconds, and never because of a bet (BALANCE_READ_MIN_INTERVAL_MS). A bet or a win shows the balance the casino's answer, or its pushed event, carries, and the newest by asOf wins;
  • the game session (createGameSession): a browser client seed on every active pair, kept across launches when this browser set it, bets with replay-safe retries under one idempotency key, reveal checks, and verify links (buildVerifyLink); the game state the hub pushes as it connects (the settings, the balance, the player's earlier bets), with older bets and their verify links on request; and, on a step game's session, bets that stay open across the player's moves (placeOpenBet, placeOpenFreespin, act), resumed from the game state;
  • round replays: a settled round shared as a public link (session.createShareLink), and a shared round read with no session at all (loadReplay), with no amount and no currency when the share hides them, and each item's price either way;
  • amount text that is never parsed into a float (amountFromInput, addAmounts, compareAmounts, multiplyAmount), shown exactly in one standard format, 1,234.56, in every language (formatAmount); multipliers in the same format at two decimals (formatMultiplier); and plain numbers and percentages (formatNumber, formatPercent);
  • a table game's payout tables, read from the session's settings and never worked out (findPaytable, paysAt, chanceAt), and their chances at two decimals (formatChance).

readLaunch and siteOrigins serve Milkyway Gaming's own play pages, which read the token from their launch URL and derive the API origin from their host; a casino's app doesn't use them. So do readReplayLaunch and createReplaySession: a play page opened from a replay link (#replay=<code>) shows the round in replay mode, with no session, and refuses every bet, move, rotation and share with replay_mode.

Importing it touches no browser global, so any module of a Next.js app may import it. But Next.js renders client components ('use client') on the server too, and a session must start in the browser: its client seed is the player's, made in the page, never on the casino's server. So create and start the session in useEffect or an event handler, never during render; or load the game component with next/dynamic and { ssr: false }. A session on systemRuntime started where there is no window ends at once with browser_required and sends nothing. The client seed needs crypto.subtle, which a browser offers only on HTTPS.

A game in your page

A React or Next.js component for Dice, whole. Another game's has its own engineId, paramOrder, paramKinds and params, from that game's page.

'use client';

import { useEffect, useState, useSyncExternalStore } from 'react';
import { createGameSession, createHubPlayerApi, type GameSession, systemRuntime } from '@milkywaygaming/rgs-player-sdk';

// Milkyway Gaming gives the casino these two origins.
const API_ORIGIN = 'https://player.example-rgs.com';
const VERIFY_ORIGIN = 'https://verify.example-rgs.com';

export function DiceGame({ token }: { readonly token: string }) {
  const [session, setSession] = useState<GameSession | null>(null);

  useEffect(() => {
    // In the browser only: the hub connection and the client seed are made here, never during render.
    const api = createHubPlayerApi({ apiOrigin: API_ORIGIN, token });
    const game = createGameSession({ api, engineId: 'dice', paramOrder: ['Target', 'Over'], paramKinds: { Target: 'integer', Over: 'boolean' }, verifyOrigin: VERIFY_ORIGIN, runtime: systemRuntime });
    setSession(game);
    void game.start().then(() => game.gameShown()); // never rejects: the snapshot says how it went
    return () => {
      game.dispose();
      void api.close();
    };
  }, [token]);

  return session === null ? <p>Loading…</p> : <DiceTable session={session} />;
}

function DiceTable({ session }: { readonly session: GameSession }) {
  const snapshot = useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot);
  if (snapshot.status === 'starting') return <p>Starting…</p>;
  // 'closed' comes with every end: nothing comes back by itself (endedCode says why).
  if (snapshot.connection === 'closed') return <p>Session closed. Reopen the game. ({snapshot.endedCode})</p>;
  // 'reconnecting': the SDK reconnects by itself; stop betting until it is back.
  const reconnecting = snapshot.connection === 'reconnecting';
  // The stakes a bet is checked against, in the session's currency: never constants of your own (null until known).
  const stake = snapshot.settings?.minStake ?? null;

  const roll = async () => {
    if (stake === null) return;
    // Amounts are strings at the currency's scale; never numbers.
    const outcome = await session.placeBet({ items: [{ itemId: 'main', stake }], params: { Target: 5000, Over: true } });
    if (outcome.kind === 'refused') console.warn(outcome.code, outcome.reason, outcome.roundId);
    // 'unresolved': the SDK couldn't confirm the bet; offer session.resolvePendingBet().
  };

  return (
    <div>
      {reconnecting && <p role="status">Connection lost. Reconnecting…</p>}
      <p>Balance: {snapshot.balance === null ? '—' : session.formatAmount(snapshot.balance.amount)}</p>
      <button type="button" onClick={() => void roll()} disabled={stake === null || reconnecting || snapshot.busy !== null || snapshot.pending !== null}>
        Roll over 50.00
      </button>
      {snapshot.pending !== null && (
        <button type="button" onClick={() => void session.resolvePendingBet()} disabled={reconnecting}>
          Check bet
        </button>
      )}
      <ul>
        {snapshot.bets.map(({ bet, verifyLink }) => (
          <li key={bet.betId}>
            {session.formatAmount(bet.stake)} paid {session.formatAmount(bet.payout)} {verifyLink !== null && <a href={verifyLink}>Verify</a>}
          </li>
        ))}
      </ul>
    </div>
  );
}
  • start() never rejects. It resolves once status is 'ready' or 'ended' (endedCode says why), and also once you call dispose(), which stops it at once: check status after it, never that it resolved.
  • start() has no time limit during a network fault. While the platform can't be reached (network_error, request_timeout, gateway_error, service_unavailable) status stays 'starting' and connection reads 'reconnecting', for as long as it takes. Give it a wait of your own (30 s, say), then show your message with a Try again button that calls dispose() and the adapter's close() and creates both again with the same token.
  • A connection the hub closes with rate_limited and a wait is waited out, at start as later: a connection past its address's connection limit is closed with retryAfterSeconds (10). So is a connect ticket refused rate_limited with a Retry-After. connection reads 'reconnecting' meanwhile, nothing connects and no ticket is asked for before the wait is over (a wake doesn't make it sooner), and the session then connects anew by itself. It never ends the session. A ticket refused rate_limited with no Retry-After still ends a start with rate_limited.

A Home button

snapshot.session.returnUrl is the address your launch gave for going back, such as your lobby, or null when it gave none. Offer the button only with one, and only navigate with it, on the player's press:

'use client';

import { useSyncExternalStore } from 'react';
import type { GameSession } from '@milkywaygaming/rgs-player-sdk';

/** Goes back to the casino: the top window, or the game's own window where the browser refuses the top one. */
function goHome(returnUrl: string): void {
  try {
    (window.top ?? window).location.href = returnUrl;
  } catch (error) {
    // The browser refused the top window (a sandboxed frame): leave from the frame.
    if ((error as { name?: unknown } | null)?.name !== 'SecurityError') throw error;
    window.location.href = returnUrl;
  }
}

export function HomeButton({ session }: { readonly session: GameSession }) {
  const snapshot = useSyncExternalStore(session.subscribe, session.getSnapshot, session.getSnapshot);
  const returnUrl = snapshot.session?.returnUrl ?? null;
  if (returnUrl === null) return null;
  return (
    <button type="button" onClick={() => goHome(returnUrl)}>
      Home
    </button>
  );
}

A step page: import the step entry

A step game's own code (what places its open bets and Freespins, reads their answers and moves them on, with the moves' resend rule) is a module of its own, so a page that plays no step game never carries it. A step session needs it: a step page imports it from the SDK's step entry and passes it to the session with mode: 'step', so the session has it from the start, with your page's own code, and connects at once:

import { stepCode } from '@milkywaygaming/rgs-player-sdk/step';

const step = createGameSession({ api, gameId, paramOrder: ['Difficulty'], verifyOrigin: VERIFY_ORIGIN, runtime, stateful: true, mode: 'step', stepCode });
void step.start();

In TypeScript, mode: 'step' without stepCode doesn't compile, nor does stepCode without mode: 'step', unless your tsconfig sets exactOptionalPropertyTypes and you add them as optional members; the TypeError still catches a step session without the code. In plain JavaScript, a step session made without it throws a TypeError at once, naming the import. A session of another kind refuses placeOpenBet, placeOpenFreespin and act, and their Check bet and Check move, with game_mode_not_supported, sending nothing. stateful: true is a step session's alone: on a session of another kind it doesn't compile, and in plain JavaScript a session left in single mode throws a TypeError at once, naming the step entry. Import the step entry on step pages only.

A crash page: import the crash entry

A crash game's room code (what follows the room's events, its round's live bets list and the player's own bets in it, and what places, cashes out and cancels the player's crash bets) is a module of its own, so a page that plays no crash game never carries it. A crash session needs it: a crash page imports it from the SDK's crash entry and passes it to the session, so the session has it from the start, with your page's own code, and connects at once:

import { crashRoomCode } from '@milkywaygaming/rgs-player-sdk/crash';

const crash = createGameSession({ api, gameId, paramOrder: ['AutoCashOut'], verifyOrigin: VERIFY_ORIGIN, runtime, mode: 'crash', crashRoomCode });
void crash.start();

In TypeScript, mode: 'crash' without crashRoomCode doesn't compile, nor does crashRoomCode without mode: 'crash', unless your tsconfig sets exactOptionalPropertyTypes and you add them as optional members; the TypeError still catches a crash session without the code. In plain JavaScript, a crash session made without it throws a TypeError at once, naming the import. Import the crash entry on crash pages only.

A crash round's betting

A page bets on a crash round (createGameSession({ ..., mode: 'crash', crashRoomCode })) while snapshot.crash.phase is 'betting' and snapshot.crash.closing isn't true. Closing comes between the two: the window has closed, the round waits for the debits still on their way, and it starts as soon as they are answered. Show "Starting…" then, with the bet buttons off: a bet placed in it is refused round_closed, and a cancel round_started.

const { crash } = session.getSnapshot();
const open = crash?.phase === 'betting' && crash.closing !== true; // null: a platform that doesn't say
const starting = crash?.phase === 'betting' && crash.closing === true;

A crash bet after a reload

A reload, a new tab or another device launches the game again: a new session, which never placed the player's bets on the running round. The game state lists them, and snapshot.crash.bets shows them beside this page's own, each bet once, so the player can still cash a running bet out. Show them as any bet of the page's, and offer Cash out (session.cashOut(bet.id)) for a 'placed' bet that stakes main while the round runs: a bet of only red, green or moon has nothing to cash out (nothing_to_cash_out). A bet the state lists cashed out shows cashedOutAt and cashOutPayout; one of a voided round shows in that round; a lost one stays 'placed', and its record says how it ended. A cancel takes a bet out of play, 'cancelled', whichever of the player's pages cancelled it, this page's own bets included, and a cancelled bet never comes back; a bet still being placed that is cancelled first ends bet_cancelled. A bet the state doesn't list is never dropped. A reconnect can bring a later round: a bet of an earlier round is never cashable (cashOut refuses it, sending nothing), so compare its roundId with the room's. Such a bet's accepted has no balanceAfterDebit or asOf, and its variant may be null (RebuiltCrashBet). Never place a bet again because it is listed. A platform that doesn't list them, and a demo session, leave the bets as they are.

const { crash } = session.getSnapshot();
const running = crash?.phase === 'running';
const cashable = (crash?.bets ?? []).filter(
  (bet) => running && bet.roundId === crash?.round?.roundId && bet.state === 'placed' && bet.items.some((item) => item.itemId === 'main'),
);

What it keeps on the device

Seed pairs are per game: every game has its own, a title included, and another game's bets, rotations and open rounds never change them. A session start reads the player's pairs in the session's game. When the active pair is one this browser set, in an earlier launch of the game or another tab, the session keeps it: nothing is rotated, and the pair's nonce counter goes on. Otherwise it rotates once with a fresh browser client seed: the first time the player opens a game (its new pair carries a client seed the platform chose), on a new device, after cleared browser data, on a pair another device set, and after the platform's own rotation at the nonce cap. A player's own rotation is remembered too.

To know which pairs it set, the session keeps a short list in SdkRuntime.storage, under the one key rgs.seed-pairs.v1: each pair's id, its commitment and the client seed it sent, newest first by when this browser set it, at most 10 for every player and game on the device. Once 10 newer pairs have been set there, the game whose pair was set longest ago rotates once more at its next launch, however recently it was played, and nothing else changes. A pair it sees leave the active slot is forgotten, and so is one a read shows as the next pair, or one that fails the nonce counter check or shows its commitment under another id. A pair from the list that the platform shows as active with another commitment or client seed ends the session with fairness_check_failed. Nothing in it is secret: those three are on every bet the player sees. The launch token is never stored.

systemRuntime's storage is the browser's localStorage, for that key, the player settings' browser copy (rgs.settings.v1.all and rgs.settings.v1.game.<gameId>, "Player settings", below) and one more per game only: any other key reads as nothing and is never written, so nothing else reaches the device through it. Where localStorage is missing, blocked (a sandboxed frame, storage switched off) or full, the list lives in memory for the page's life, and each launch rotates as on a new device. A write that fails removes the key from localStorage, so a later launch never reads a list that still holds a pair the page saw revealed.

The one more key is a game's intro opt-out, rgs.intro-optout.v1.<gameId>: a slot intro's "Don't show again", which the game keeps through the runtime's storage rather than localStorage itself, so a casino's own storage (scoped to its player, below) keeps it too. It is the older way: the session now keeps the choice as the player setting intro.opt-out, and reads this key as that setting while the game's browser copy lacks it.

  • Its value is "1", or the key is absent. Set "1" when the player opts out and remove the key to show the intro again. Any other value is never written, and one another script left there reads as null.
  • <gameId> is the game's ID as the platform writes it (snapshot.session.gameId, a title's own ID for a title): lower-case letters, digits and single hyphens, at most 63 characters. A key with anything else after rgs.intro-optout.v1. (a capital, a dot, a space, a slash, an accented letter) is refused, never encoded: it reads as null and is never written.
  • Like the list, it lives in memory for the page's life where localStorage is missing, blocked or full: the intro then shows again at the next launch.
import { INTRO_OPT_OUT_VALUE, introOptOutKey } from '@milkywaygaming/rgs-player-sdk';

const key = introOptOutKey(gameId); // null for a game ID the storage would refuse
if (key !== null) {
  const optedOut = runtime.storage?.getItem(key) === INTRO_OPT_OUT_VALUE;
  runtime.storage?.setItem(key, INTRO_OPT_OUT_VALUE); // "Don't show again" ticked
  runtime.storage?.removeItem(key); // and unticked
}

To keep it elsewhere, pass a runtime with a storage of your own (KeyValueStorage): an object with getItem(key), setItem(key, value) and removeItem(key), as Web Storage has. When a write that forgets a pair fails, the session removes the whole list with removeItem, which only costs rotations. Only a storage that refuses that too can keep a pair the session saw revealed.

import { type KeyValueStorage, type SdkRuntime, systemRuntime } from '@milkywaygaming/rgs-player-sdk';

const storage: KeyValueStorage = {
  getItem: (key) => window.localStorage.getItem(`${playerId}:${key}`),
  setItem: (key, value) => window.localStorage.setItem(`${playerId}:${key}`, value),
  removeItem: (key) => window.localStorage.removeItem(`${playerId}:${key}`),
};
const runtime: SdkRuntime = { ...systemRuntime, storage };

The session doesn't name the player or the casino, so the list is the device's. Seed pair ids are unique to a player's pair, so on an honest platform another player's pair never matches. Scope your storage to your player, as above, to keep their lists apart. That matters on a shared device: a dishonest platform could show a player any of the up to 10 pairs remembered there, choosing among pairs whose outcomes it knows. It could never pick a server seed after seeing a client seed, since each pair's commitment came first. The same holds for a pair the player left behind by rotating on another device. A storage that throws is never an error: it only means rotations. A runtime of your own without storage remembers nothing, and rotates at each start, as before.

The session keeps one more thing on the device, in a storage of its own: the device report's device ID ("The device report", below).

The device report

A real session sends one device report, once it is ready and your game is shown. The platform's game state asks for it (deviceReport: true, never for a demo session); your frontend's one part is to say when the game is shown:

await session.start();
// ...your loader shows the scene; once it is gone and the game is playable:
session.gameShown();
  • When. Only after start() has reached ready and you have called session.gameShown(): the collector's chunk isn't even requested before, so nothing of it competes with your game's loading. Call it once your loader is gone and the game is playable; a call before start() resolves is kept until the session is ready, and a second call changes nothing. Where a frontend never calls it, the report begins 20 s after the session first became ready. Either way it then waits for a quiet page: two idle periods with 40 ms or more left, or 10 s where none comes.
  • Only in idle time. The SDK works only while the browser is idle (requestIdleCallback) and no call of the session is out, and only where the idle period has room for the step it takes next: steps are sized from measurements on a mid-range phone, so your frames don't wait for them. An idle period's room counts only in its own callback: once an answer comes from off the page (the worker, a frame's load, a render, a hash), the next step waits for a new idle period, however much time the last one still shows. fontPreferences and audio, which only your page can read, take short steps like the rest, none larger than two idle periods of a page that draws every frame, so a game that always animates still gets them; each step over 8 ms begins in an idle period of its own, so no idle period runs two of them back to back. A few steps can't be split: the page's first time zone format (where the worker can't read it) and domBlockers (Android and WebKit). Each runs only in an idle period the browser gives whole (45 ms or more left), which it gives only when it has no frame to draw soon; where there is none at once, that reading waits until the others are read. On a page that animates all the time no such period comes, and 60 s after the collection began those readings are sent as { error: 'busy' }: the report costs readings, never your frames. On a still page these steps do run, each once a session and only in a whole idle period, and domBlockers takes longer than 50 ms (97 ms measured at 4x slower CPU on a loaded build server): the budget's recorded exception. Where the browser can't say when it is idle (no requestIdleCallback, as in Safari and every browser on iOS), it waits 2 s before the first step and 250 ms before each after it, takes a step only where 16 ms of work each time has room for it (a single call of the browser's can run longer: putting fontPreferences' frame in the page, 17 to 27 ms at 4x slower CPU), and sends the steps that can't be split as busy at once. A bet placed meanwhile is sent at once, and the next step waits for its answer. A reading may take 300 ms of the page's time and the whole report 1.5 s: once that is spent, no reading or step starts, and what was read is sent. After 90 s nothing more is read, and the report is sent with what it has.
  • A worker of its own. What can't be split into short steps runs in a dedicated worker, off your page's thread: the canvas images, the font check, both WebGL readings, the time zone readings and the library's visitor ID. Your bundler emits the worker as a file of its own beside the collector's chunk (Vite, webpack and Parcel do it for new Worker(new URL('./device-worker.js', import.meta.url), { type: 'module' })); serve it from your page's own origin, as your other chunks. Your page's Content-Security-Policy must admit it: worker-src 'self', or script-src 'self' where it has no worker-src. Where the worker can't run (a policy that refuses it, a bundler that doesn't emit it, assets served from another origin than your page's, a browser without workers or OffscreenCanvas), the report goes on without it: canvas, webGlBasics and webGlExtensions are sent as { error: 'unsupported' }, fonts is measured on your page in short steps (your page's canvas also sees the web fonts your page loaded, so its list can differ from the worker's), the time zone is read by the library in a step that can't be split, and the report names no visitor ID.
  • In this order. The components listed below first, in the library's own order, then the SDK's own device data, then the library's other components: a slow device that runs out of the 1.5 s leaves out the others first. The collector and FingerprintJS are in a chunk of their own (a dynamic import()): nothing of them is in your start path.
  • Once. It is sent at most once a session, over the hub (ReportDevice): when the connection is down it waits for the next one; once sent it is never sent again, answered or not.
  • Silently. Whatever becomes of it, nothing reaches the game, the snapshot or the page: no event, no error, no postMessage. It makes no request but the hub call and its two files.
  • Named for a perf check, when asked. A perf harness's runtime may set deviceReportMarks: true (for example { ...systemRuntime, deviceReportMarks: true }). Each step of the report is then marked on the page's performance timeline as it begins and measured from that mark as it ends, at its next step, a wait (for an idle period or the worker) or its reading's end: the measure is the step's own work. Both are named rgs.device:<reading>:<step>. <reading> is a component by the library's name (fonts), the SDK's own device readings as device.<name> (device.basics), the device ID's pieces as deviceId, and the rest of the report as report. <step> is 0 for what a reading does in the idle period it starts in, then one more for each step, from 0 again for a reading read again after the others. Without it (the default, and systemRuntime's) nothing is marked.

The report holds:

  • v (1) and sdk, the SDK's version;
  • deviceId and deviceIdSource: the device ID (below) and where it came from, cookie, storage or new; none, with no deviceId, when the browser keeps it nowhere;
  • library: the library's name and version (fingerprintjs, the pinned @fingerprintjs/fingerprintjs, MIT) and its own visitor ID, made in the worker (none without it);
  • components: every component the library reads, under its own name, as { value, duration }, or as { error, duration } with a code when it failed, ran out of its time (timeout) or of the collection's (budget), found no idle period with room for a step that can't be split (busy), or can't be read without a long task (unsupported). duration is the reading's own work on your page, in ms: the time it waited for idle periods or for the worker isn't in it. screenFrame is never read while an element is in fullscreen ({ error: 'fullscreen' }), as reading it then could take the player out of fullscreen, and audioBaseLatency is never read ({ error: 'skipped' }), as it would open an audio context beside your game's own sound, and making a page's first one can take longer than 50 ms;
  • device: the SDK's own reading: the high-entropy client hints (Chromium only), screen and viewport, languages and time zone, hardware concurrency, device memory and touch points, pointer and hover, the WebGL vendor and renderer, five automation signs, the frame's origins (never a path) and the connection type;
  • timings.collectMs: how long the collection worked on your page.

Most components are the library's own sources, run as the library runs them. Four are read the SDK's way, each the same way every time in one browser: fonts measures the library's test string in each of its fonts with a canvas's measureText (in the worker, or on the page where the worker can't), where the library lays out text in a hidden frame; canvas draws the library's two images in the worker and encodes them with OffscreenCanvas.convertToBlob, whose bytes can differ from toDataURL's; webGlBasics and webGlExtensions are read from a WebGL context in the worker; and timezone and dateTimeLocale come from the worker's Intl. fontPreferences is the library's own reading, a preset at a time, to the library's values, in the library's hidden frame: made empty and given the library's viewport, where the library loads it with a srcdoc (Firefox keeps the srcdoc), so the browser has nothing to load for it in your page. The frame, once emptied, stays in your page until the session ends, as taking it down is as long a task as making it. audio is the library's own source, given an offline context of the size it asks for that the SDK made a step at a time beforehand (the context, then its two waves), for that one call; where the library makes none (Safari 17 and later, Samsung Internet 26 and later), the SDK makes none either.

Every image a component returns (canvas data URLs) and every string over 1 KiB is sent as the SHA-256 of its text (sha256:<hex>): the rendered output never leaves the browser. These components are sent the same way every time (hashed when over 2 KiB, as the SHA-256 of their JSON, decided from each value alone): architecture, audio, canvas, colorDepth, colorGamut, deviceMemory, fontPreferences, fonts, hardwareConcurrency, hdr, languages, math, pdfViewerEnabled, platform, plugins, screenResolution, timezone, touchSupport, vendor, vendorFlavors, webGlBasics and webGlExtensions (in Chromium, webGlExtensions alone is about 14 KB, so it is always a hash there). The report is at most 16 KiB of UTF-8 as sent: a larger one has its largest parts replaced by their SHA-256 until it fits, the other components and the device data first, and is not sent if it still doesn't.

The device ID

A random UUID, made the first time the SDK finds none, kept in SdkRuntime.deviceStorage under rgs.device.v1: systemRuntime's is the browser's localStorage, for that key and a device ID alone. Never in SdkRuntime.storage, so a storage you scope to your player doesn't give each player on a shared device an ID of their own; a runtime of your own that spreads systemRuntime keeps it. On Milkyway Gaming's own play pages it is also kept in a cookie, rgs_did, on the domain the platform names (deviceCookie), and only when the page's host is that domain or under it; the SDK removes it where the platform names none. On your own frontend the SDK sets no cookie of its own; the library's cookie check writes and removes cookietest at once. A storage or cookie that throws is never an error: the report then names no device ID.

Showing amounts and multipliers

formatAmount and formatMultiplier turn the amount and multiplier text the platform sends into what the player reads. Both are for display only: a stake field keeps what the player typed, and what you send, compare or copy keeps the text as it came.

import { formatAmount, formatMultiplier } from '@milkywaygaming/rgs-player-sdk';

const { session, balance } = game.getSnapshot(); // session is null until it is read, balance until one came
if (session !== null && balance !== null) {
  formatAmount(balance.amount, session.currency, { locale: session.locale }); // '$1,234.56' in every language
}
formatMultiplier('4.8504'); // '4.85×' in every language
formatMultiplier('4.8504', { exact: true }); // '4.8504×', where the exact figure is the point
  • One standard format, in every language (from 0.1.0-alpha.57): numbers are always written 1,234.56: a comma for thousands, a point for decimals, Latin digits, a plain minus sign. The player's language never changes them, so a player on a de, es, tr, ru, ka, ar, fr or pt-BR launch sees 3,560.00 USDT, never 3.560,00 USDT. The locale option (session.locale, a BCP 47 tag such as pt-BR) is still accepted, so no call changes, and it is ignored.
  • The decimals come from the text: the zeros past two are dropped (5.00000000 shows 5.00, 0.00012300 shows 0.000123), an amount with no decimals shows none (1500 shows 1,500), and nothing is ever rounded. A game screen passes decimals to show fewer ("On a game screen", below).
  • At least N decimals (from 0.1.0-alpha.59): minDecimals pads what shows with zeros up to that many, so never pad the text yourself. formatAmount('5', 'USD', { minDecimals: 2 }) shows $5.00, '5.5' shows $5.50, and formatAmount('1.5', 'BTC', { minDecimals: 8 }) shows 1.50000000 BTC. It only appends zeros: it never cuts, never rounds and never changes a digit or the grouping (1234.5678 at 2 stays $1,234.5678). A whole number from 0 to 100; left out or 0, nothing changes.
    • With decimals, the cut comes first and the padding after, never past decimals: the smaller wins. { decimals: 6, minDecimals: 4 } shows 5.00000000 BTC as 5.0000 BTC, { decimals: 6, minDecimals: 8 } shows 1.2 BTC as 1.200000 BTC, and { decimals: 2, minDecimals: 2 } shows 1.999 USD as $1.99. A small amount still shows up to its first significant digit (0.00412345 USDT at 2 shows 0.004 USDT).
    • A fiat currency pads only up to its own standard decimals, as the runtime's Intl gives them: JPY and KRW have none, USD and EUR 2, BHD 3. So formatAmount('1500', 'JPY', { minDecimals: 2 }) stays ¥1,500, formatAmount('5', 'USD', { minDecimals: 4 }) shows $5.00 and formatAmount('1.5', 'BHD', { minDecimals: 4 }) shows BHD 1.500: a list in many currencies can ask for 2 throughout. It caps the padding only: an amount with more decimals than its currency has still shows them (1500.5 JPY stays ¥1,500.5). A crypto code or any other code pads as asked (1500 USDT at 2 shows 1,500.00 USDT).
  • The currency: a fiat currency shows its symbol before the number, as in English, in every language: $1,234.56, €1,234.56, R$1,234.56. Every crypto currency shows its code after the amount, never a symbol (100.00 USDT, 0.5 ETH, 0.000123 BTC). display: 'code' always shows the code (1,234.56 USD), and display: 'none' only the number, for a balance beside a currency icon of your own. An amount and its code are joined by a no-break space (U+00A0), so a line never breaks between them. A right-to-left language (ar, he, fa, ur) gets no direction marks: the text is the same as in English.
  • A negative amount gets a plain minus sign (-). A positive one never gets a +.
  • A multiplier shows exactly two decimals (from 0.1.0-alpha.71): formatMultiplier pads fewer and cuts more, never rounding: 2 shows 2.00×, 4.8504 shows 4.85×, 1.999 shows 1.99×, 112.73333333 shows 112.73×. A non-zero multiplier under 0.01 shows <0.01×, so a win never reads as 0.00×; zero shows 0.00×.
    • { exact: true } shows every significant decimal, at least two, with no zeros past them (4.8504×, 0.0099×): for a fairness check, a help text that states a game's own odds, and an accessible name or tooltip that says the full figure. Everywhere else a player reads a multiplier, leave it out. Where a game's own price has more decimals (a Dice multiplier has four), the button shows two, and the exact figure goes where the player reads what a bet pays.
  • It never guesses. An amount or a multiplier that isn't decimal text (a number, 1e5, +5, 1,234.56), a currency that isn't a code, an unknown display and a minDecimals outside 0 to 100 throw a TypeError.
  • A cost of several bets, such as a bought bonus at its BetItemTerm.price, is multiplyAmount(bet, price, session.currencyScale): exact, and null when the currency's scale can't hold the product (0.10 times 1.25). Show the result with formatAmount, and stake exactly that text.
  • Which multiplier to show. A bet item's multiplier is the round's win as a multiple of the bet: show it as the round's multiplier, and the item's payout as the win, both as sent. On an item with a price the bet is the stake ÷ the price: an ante at 1.5 bets on a bet of 1.00 stakes 1.50, and a round that wins 10 bets reads multiplier: "10.0000" (10.00×), payout: "10.00" and price: "1.50". A finished move's answer (ActFinished) also has the bet's own multiplier, its payout ÷ its total stake (6.66666666 there): what it returned on its cost, not the round's multiplier. PlaceBet's answer and history bets have no bet multiplier. multiplyAmount is for an item's cost only, never for a payout: the platform rounds a payout down and cuts it at the max win, so never work one out. Before a bet, show what it would pay from session.quoteBet's amounts; after it, the answer's payout.

On a game screen

A game screen shows at most as many decimals as the game's stakes and costs need, so a USDT balance at the platform's scale of 8 reads 6,187.41 USDT, not 6,187.41366328 USDT. The session works the number out and formats with it:

const snapshot = game.getSnapshot(); // game: the GameSession
if (snapshot.balance !== null) game.formatAmount(snapshot.balance.amount); // '6,187.41 USDT': the session's currency and decimals
snapshot.displayDecimals; // 2 on USDT levels of 0.10 to 100, 6 on BTC levels from 0.000001, undefined without levels
  • How many: displayDecimals(stakeLevels, betItems?) covers every amount a player can be debited: the most decimals among the levels and each level's cost on each priced bet item (the level times the item's price), once their trailing zeros are dropped, never fewer than 2 and never more than the currency's scale. 2 for USDT levels of 0.10 to 100.00, 6 for BTC levels from 0.000001, and 3 for USDT levels from 0.05 with an ante at 1.5 bets, whose cost of 0.075 then shows whole. A currency with no decimals shows none (0 for levels of 1, 2, 5 and up). Pass the levels and items as the settings give them, at the currency's scale: displayDecimals(settings.stakeLevels, settings.betItems). It works on the texts exactly, never on numbers. With no levels (undefined or []), or levels or prices it can't read, it is undefined, so formatAmount(amount, currency, { decimals: displayDecimals(...) }) shows every decimal then.
  • The session's number: snapshot.displayDecimals is displayDecimals(snapshot.settings.stakeLevels, snapshot.settings.betItems). While there are no levels (before the first game state, settings refused, or settings without them) it is undefined, and game.formatAmount cuts nothing: every significant decimal shows, so a crypto amount never loses digits for want of levels (1.23456789 BTC stays whole). Every game sends its levels with its first game state. The number changes with the levels (outside USD they follow the live rate), and the new snapshot redraws the screen as any change of the settings does.
  • Cut, never rounded: formatAmount(amount, currency, { decimals }) cuts the amount toward zero to at most that many decimals, so it never shows a larger amount than it is (1.999 shows 1.99); a loss is cut toward zero too (-1.999 shows -1.99). The zeros past two are then dropped as before (5.00000000 shows 5.00), and an amount never shows more decimals than it has (12.50 stays 12.50 at 6).
  • A small amount never reads as 0: a non-zero amount the cut would show as 0 shows its digits up to its first significant one: a win of 0.00412345 USDT shows 0.004 USDT. Zero shows 0.00.
  • game.formatAmount(amount, options?) is formatAmount with the session's currency (session.currency), the one standard number format (session.locale is accepted and ignored) and snapshot.displayDecimals, read when it is called; an option you pass wins. Without levels it is formatAmount with every decimal. An amount in another currency ({ currency: 'BTC' }) keeps every decimal unless you pass decimals: the session's levels say nothing of that currency. minDecimals is passed on, so it pads after the session's cut and never past it: game.formatAmount('5', { minDecimals: 2 }) shows 5.00 USDT at 2, and once the stake levels are read a scale-0 currency's displayDecimals of 0 keeps its amounts whole (before them, a fiat code still pads no further than its own decimals). Before the session is read it has no currency: pass one, or it throws a TypeError.
  • What uses it: the balance, wins, the history, totals and big-win screens. Bet level labels and priced costs are within the decimals already.
  • A count-up (a win counting from 0 to its amount) steps in display units: every frame is a multiple of 10^-displayDecimals (0.01 at 2), starting at the first one, and the last frame is the win itself. A frame such as 0.00012 would show its digits up to the first significant one, so a count-up that starts below one display unit shows long numbers in its early frames.
  • What doesn't: a stake field keeps what the player typed; what you send, compare or sort keeps the text as it came; and a copy of an amount copies its full text. Without decimals, formatAmount shows every significant decimal, as it always has.

Plain numbers and percentages

A number that is neither money nor a multiplier, such as a Dice roll or target, shows with formatNumber, and a percentage, such as a win chance or the RTP, with formatPercent (from 0.1.0-alpha.46):

import { formatNumber, formatPercent } from '@milkywaygaming/rgs-player-sdk';

const locale = game.getSnapshot().session?.locale;
formatNumber('79.19', { locale }); // '79.19' in every language
formatNumber('50', { locale, fixedDecimals: 2 }); // '50.00' in every language
formatNumber('2', { locale, minDecimals: 2 }); // '2.00' in every language
formatPercent('96.03', { locale }); // '96.03%' in every language
  • Exact, as formatAmount is: the text is read as text, never through a float, in the one standard format (1,234.56), whatever the language. Without fixedDecimals the decimals the text has show, the zeros past two dropped (0.9700 shows 0.97), never padded and never rounded.
  • fixedDecimals is exact: always that many decimals, padded with zeros (49.5 shows 49.50) or cut toward zero, never rounded up (96.0396 shows 96.03), so a target or a chance keeps its width as it changes. A whole number from 0 to 100. It isn't formatAmount's decimals, the most to show, which never pads: decimals given to these two throws a TypeError that names fixedDecimals.
  • minDecimals is a least (from 0.1.0-alpha.59), as formatAmount's: padded with zeros up to that many (2 at 2 shows 2.00, 0.97 at 4 shows 0.9700), never cut and never rounded (79.1234 at 2 stays 79.1234). With fixedDecimals, exactly fixedDecimals show: the cut wins, and minDecimals adds nothing. A whole number from 0 to 100. formatPercent takes it too (97 at 2 shows 97.00%).
  • A percentage is the percentage itself, never a ratio: formatPercent('97.00') shows 97.00%. The settings' RTP is a ratio ("0.9700"): pass 97.00, worked out on the text. The percent sign always follows the number with no space (96.03%), in every language, and the grouping is in thousands.
  • A negative number gets a plain minus sign, and a positive one no +. A number the cut shows as zero has no sign (-0.004 at 2 decimals shows 0.00).
  • It never guesses: text that isn't decimal text (a number, +5, 1e3, 79,19, 1,234.5), and fixedDecimals or minDecimals outside 0 to 100, throw a TypeError.
  • A payout table's chance (a Plinko bucket's, a Keno hit count's) shows with formatChance, not formatPercent ("Payout tables", below).

Common mistakes in showing amounts

| Mistake | What you see | Fix | | --- | --- | --- | | Number(amount) or parseFloat(amount) before showing it | Long amounts change: 12345678901234567.5 shows as 12,345,678,901,234,568, and a coin's 18th decimal is lost | Pass the amount text to formatAmount as it came | | toFixed(2) to cut the decimals | 0.999 shows as 1.00: the player sees more than they have | formatAmount, which drops only zeros and never rounds; on a game screen game.formatAmount, which cuts to the game's decimals | | Padding the text yourself (`${amount}.00`, padEnd, toFixed) before formatting it | 5.50 turns into 5.50.00, which throws a TypeError; zeros past two you added are dropped again (1.5000 shows 1.50); and toFixed rounds | formatAmount(amount, currency, { minDecimals: 2 }), or formatNumber(text, { minDecimals: 2 }) for a number: it only appends zeros | | formatAmount(amount, currency) for a game screen's balance or win | 6,187.41366328 USDT: eight decimals, and a count-up or big-win box that grows past its frame | game.formatAmount(amount), at the session's displayDecimals | | A fixed decimals: 2 for every currency | A BTC win of 0.01234567 shows 0.01 BTC | snapshot.displayDecimals, which follows the game's levels (6 there) | | Expecting localized separators (1.234,56 for a German player) | Every language shows 1,234.56: the locale option is accepted and ignored | Nothing: one standard format is intended. Never swap the marks yourself, and never format an amount with toLocaleString or Intl beside the SDK, or the screen mixes two formats | | A symbol of your own for a coin (₿, Ł, $ for USDT) | Your lobby and the game disagree, and a stablecoin reads as dollars | Show formatAmount's text, or display: 'code' | | A number instead of the text (formatAmount(1.5, 'USD')) | A TypeError | Pass the text the SDK gave you | | Payout ÷ stake, or the bet's own multiplier, as a priced round's multiplier | An ante round that won 10× the bet shows 6.66× | Show the item's multiplier | | `${multiplier}×`, or { exact: true } on a game screen | 112.73333333×, or a multiplier whose width changes from round to round | formatMultiplier(multiplier): two decimals, cut | | toFixed(2) on a multiplier | 1.999 shows as 2.00×, more than the round paid, and a win of 0.004 shows as 0.00× | formatMultiplier(multiplier), which cuts and shows <0.01× | | The item's multiplier times its stake as the win | A 10× ante round staked at 1.50 shows 15.00 | Show the item's payout as sent | | toFixed(2) or toLocaleString() on a roll, a target or a chance | toFixed rounds a chance of 96.0396 up to 96.04, and adds no grouping, no zero trimming and no stake decimals; toLocaleString writes the browser's own separators, not the SDK's 1,234.56 | formatNumber(text, { locale, fixedDecimals: 2 }), or formatPercent for a percentage | | formatNumber(target, { decimals: 2 }), as for formatAmount | A TypeError that names fixedDecimals | { fixedDecimals: 2 }, which shows a target of 50 as 50.00 | | `${formatNumber(chance)}%` | Works today, but the percent text is the SDK's to write | formatPercent(chance, { locale }) | | formatPercent(settings.rtp) | 0.97% for an RTP of 97% | Pass the percentage, 97.00, worked out on the text, never Number(rtp) * 100 |

Payout tables

A table game (Plinko, Keno) shows what each outcome pays, and its chance, before the bet: Plinko's buckets, Keno's hits. Those figures are the game's, and a new version, RTP variant or title may change them. The session's settings carry them (snapshot.settings.paytables), and three helpers read them, computing nothing:

import { chanceAt, findPaytable, formatChance, formatMultiplier, paysAt } from '@milkywaygaming/rgs-player-sdk';

// The params your screen will bet with: Plinko's risk and rows here, Keno's picks and risk in Keno.
const table = findPaytable(snapshot.settings, 'main', { Risk: 1, Rows: 8 }); // null: show no table
const buckets =
  table === null
    ? []
    : table.pays.map((_, index) => {
        const pays = paysAt(table, table.first + index); // '9.0000'
        const chance = chanceAt(table, table.first + index); // '0.3906', or null: the game declares no chances
        return { pays: pays === null ? '' : formatMultiplier(pays), chance: chance === null ? '' : formatChance(chance) };
      });
  • snapshot.settings.paytables (GameSettings.paytables): every table of the version and RTP variant a new bet plays, every bet item and key, in the game's order. Each Paytable is { itemId, key, outcome, first, pays, chances }:
    • key names the bet params that choose the table, each by its params name: an integer param's value, or a list param's length (Plinko { Risk: 1, Rows: 8 }; Keno { Picks: 5, Risk: 2 }, Picks the number of numbers picked);
    • outcome says what an outcome counts (Plinko's Bucket, Keno's Hits), and first is the first entry's outcome (0 for both);
    • pays is what each outcome pays per unit staked, from first up, four-decimal multiplier text ("9.0000");
    • chances is each outcome's chance as a percent, cut to four decimals and never rounded up ("27.3437"), as long as pays, or null when the game declares none. "0.0000" is an outcome under 0.0001%, never one that can't happen.
  • null for a game that declares none (Dice, Limbo, Crash, slots, and a table game's version before it declared them), from a platform without them, and when they aren't a list: show no table then, never one of your own. An entry the SDK can't read is left out, and so are both of two entries with the same item and key, so only that key's lookup gives null. A title's fixedParams don't filter the list.
  • findPaytable(settings, itemId, params) gives the table a bet with these params plays for that item, or null. The settings' fixedParams are laid over your params first, as the platform plays a pinned value whatever a bet sends. A table matches when every member of its key matches the param of that name: an integer equal to it, or a list (Keno's picks) as long as it. Params the key doesn't name don't matter; a key member missing from your params, or a param of any other kind, is no match, never the nearest table. null settings (before the first game state) give null.
  • paysAt(table, outcome) and chanceAt(table, outcome) give an outcome's entry exactly as sent, counted from the table's first; null for an outcome with no entry, a table without chances (chanceAt), and a null table, so findPaytable's answer can be passed on as it is. Show a pay with formatMultiplier.
  • formatChance(chance, options?) shows a chance: exactly two decimals, cut and never rounded, so a chance never reads larger than it is (19.6380 shows 19.63%, 27.3437 shows 27.34%, 100.0000 shows 100.00%); a chance the cut shows as zero, 0.0000 included, shows <0.01%. { exact: true } shows every significant decimal, at least two (19.638%, 0.0015%), and <0.0001% for 0.0000: for a tooltip, an accessible name or a copy of the figure. The locale option is accepted and ignored, as the other formatters'. Anything but a chance at four decimals from 0.0000 to 100.0000 throws a TypeError.
  • They change with the settings: each game state carries the tables of the version and variant a new bet plays, so draw them from each new snapshot, as every setting. A bet in the history keeps its own multiplier.

Common mistakes with payout tables

| Mistake | What you see | Fix | | --- | --- | --- | | A payout table copied into your page | A new version or RTP variant pays otherwise, and your buckets show what the game no longer pays | findPaytable(snapshot.settings, …), then paysAt | | Working a chance out (0.5 ** rows, a binomial, a hypergeometric) | A float figure that disagrees with the game's own in the last decimal, and a rounded one that reads larger than it is | formatChance(chanceAt(table, outcome)) | | Looking a Keno table up by the numbers picked, not how many | No table, or the wrong one | Pass the bet's params as you send them: findPaytable counts a list by its length | | Laying a title's fixedParams over the params yourself, or leaving them out | The table of a value the game never plays | Pass the settings the tables came with: findPaytable lays fixedParams over your params | | formatPercent(chance, { fixedDecimals: 2 }) or toFixed(2) for a chance | 0.0000 shows as 0.00%, as if the outcome couldn't happen; toFixed rounds 27.3487 up to 27.35 | formatChance(chance) | | A table of your own when paytables is null or findPaytable gives null | Figures the platform never sent | Show no table |

Reading what the player types

amountFromInput(text, scale) reads an amount the player typed into a stake or limit field, at the currency's scale (session.currencyScale): { ok: true, amount }, the amount text to send, or { ok: false, code: 'invalid_stake' }.

  • It pads to the scale (1 reads 1.00 at 2) and refuses more decimals than the scale has (1.505 at 2): it never rounds. At most ten integer digits, no leading zero, no spaces, signs or exponents, and only the digits 0 to 9.
  • A lone comma is the decimal point (from 0.1.0-alpha.46): 5,50 reads 5.50. On a phone set to a comma region (most of Europe and Latin America), inputMode="decimal" opens a pad whose only decimal key is a comma. A comma has a point's rules: ,5 and 5, are refused as .5 and 5. are, and 5,505 is refused at scale 2.
  • No grouping is guessed: a comma with a point (1,234.50, 1.234,50) and two commas (1,2,3) are refused. A lone comma is always the decimal point, so 1,234 reads 1.234, never 1234. At scale 2 it is refused; at scale 3 and above (KWD, BHD, OMR, JOD and TND, and the coins) it reads, as 1.234. So show the amount read next to the field, as formatAmount writes it: a player who typed 1,234 meaning one thousand sees 1.234 before they bet.
  • The field keeps what the player typed. Show the text as typed and send the amount read from it: never write the amount back into the field, and never replace the comma.
  • An auto bet's percentage follows the same rules (from 0.1.0-alpha.46): isPercentText('12,5') is true, and a StakeChange with percent: '12,5' changes the stake by 12.5%. Pass the field's text as typed: the auto bet reads the comma itself. A comma with a point, or two commas, is refused, as for an amount.

Common mistakes in reading input

| Mistake | What you see | Fix | | --- | --- | --- | | Replacing the comma in the field (value.replace(',', '.')), or writing the amount read back into it | The player's 5,5 turns into 5.5 or 5.50 as they type, and the caret jumps | Keep the field's text; send amountFromInput's amount, and an auto bet's percent as typed | | formatPercent on the percentage the player typed | formatPercent('12,5') throws a TypeError: it reads decimal text with a point only, though isPercentText takes the comma | Show the field's text as typed; to show it formatted, pass its point form, formatPercent(text.replace(',', '.'), { locale }), and leave the field as typed | | parseFloat(text) or Number(text) | parseFloat('5,50') is 5, and Number('5,50') is NaN | amountFromInput(text, scale) | | type="number", or inputMode="numeric" | type="number" gives '' for 5,50, its value for text it can't read; numeric opens a pad with no decimal key | A text input with inputMode="decimal" |

When a bet is not placed

A bet's refusal (kind: 'refused') carries its code, and two more members when the platform sent them:

  • reason (BetNotPlacedReason), with bet_not_placed only: why the bet wasn't placed;
  • roundId, with a refusal the platform stored with its bet: the round the stake's debit named, the bet's own ID on a single-player game and the crash round's on Crash. Casinos find a round by this ID, so show it with the message, as text the player can copy.

Auto bet's stop carries them as notPlacedReason and roundId, and a refused crash bet in snapshot.crash.bets has reason beside its code. A refusal before any debit names no round. What each reason must get across (your page writes its own words):

| reason | Show | | --- | --- | | casino_no_answer | The casino didn't give an answer we could use, so the bet wasn't placed and any stake taken is coming back. Contact the casino's support with the round ID. | | game_error | Something went wrong in the game, and any stake taken is coming back. Try again; if it keeps happening, contact support with the round ID. | | round_closed | Betting closed for this round; bet on the next one. | | open_round | Finish the open round first (snapshot.openBet), or in the game it is in. | | freespin_other_round | A Freespin is still playing in another round (Crash): nothing moved and no Freespin was used. The player plays the next one once that round has ended. It names no round. | | another, or none | As game_error. |

The casino's own refusals (insufficient_funds, player_blocked, operator_limit_exceeded, wallet_rejected) carry roundId and no reason: send the player to the casino's support with the round ID for them too.

Freespins: the count to show

Each bonus in snapshot.freespins (bonuses, next and paused) carries two counts:

  • freespinsLeft: the platform's spins left, as its last answer, game state or push said. Decide with it: whether there is a Freespin to offer (next), when Freespin mode ends, the end summary, when autoplay stops.
  • freespinsLeftShown: the number to show the player. It drops by one as a spin starts, in the snapshot that marks the spin as sending (busy: 'bet', or the crash bet placing), so a screen shows "19 left" of 20 while the spin is on its way, rather than 20 until the answer. Two spins on their way (two crash bets on one round) show two fewer.
const bonus = snapshot.freespins.next;
const shown = bonus?.freespinsLeftShown ?? bonus?.freespinsLeft; // show this
const offer = bonus !== null; // decide with freespinsLeft: next is null once it is 0

The two agree again as the spin ends: its answer shows the platform's count, and so does a refusal (the spin wasn't used). A spin left unresolved (a lost reply, waiting for Check bet) keeps the drop until its Check bet's answer, or until the freespins are read again or pushed, which say the platform's count however the spin went. freespinsLeftShown is never below 0 and never above freespinsLeft. A relaunched page shows freespinsLeft: a step game's open Freespin is already out of it. On the last spin it is 0 while the spin is on its way, but next still names the bonus and the bonus stays in bonuses until the answer ends it, as before: end Freespin mode and show its summary from freespinsLeft and next, never from the count shown. Nothing sent to the platform changes.

freespinsLeftShown is optional only so a view built by hand still compiles: the session always sets it.

Freespins: the player's own choice

Some games let the player choose a Freespin's params: on Keno, the player picks the numbers of every Freespin, by hand or with auto pick, as for a cash bet. The bonus still fixes what the spin's return depends on (Keno's count of picks and its risk), and the stake and the item stay the bonus's.

const next = snapshot.freespins.next;
const chooses = next !== null && snapshot.settings?.freespinChoices.includes(next.freespinBet.id) === true;

// Keno: the bonus fixes the risk and how many numbers; the player picks which ten.
const picks = [3, 8, 11, 17, 20, 24, 29, 33, 36, 40];
const outcome = next !== null && chooses ? await session.placeFreespin({ ...next.freespinBet.params, Picks: picks }) : await session.placeFreespin();
  • snapshot.settings.freespinChoices lists the Freespin bets of the version a new bet plays whose params the player chooses: [] for none, and from a platform that doesn't send it. Offer a choice only when it lists the freespinBet.id of the bonus freespins.next names; otherwise draw the bonus's freespinBet.params and send none.
  • session.placeFreespin(params) sends { freespin: true, params }, and the spin plays exactly those params. Lay the settings' fixedParams over the choice, as for a cash bet: a title that pins a member plays it at that value, and another value is invalid_params. The params are read as you call it: changing the object afterwards changes nothing sent, and a resend under the spin's key (a lost answer, Check bet) sends the same body again. Each call is a spin of its own, under a key of its own.
  • session.placeFreespin() with no params sends { freespin: true }, as before, and plays the bonus's own params.
  • A refused choice keeps the bonus. invalid_params (a choice that changes what the bonus fixes, a number twice, or params on a bet that takes no choice) and the game's invalid_selection use no spin: freespins.next still names the bonus, at the count it had. Let the player choose again. Params no game takes (not an object, a fraction, over 16 KiB) are refused invalid_params at once, with nothing sent. Only the bonus's own refusals (freespin_bet_unavailable and the others) stop offering it, as before.
  • The accepted bet, the history and the verify link carry the params the spin played.

Common mistakes with chosen Freespins

| Mistake | What you see | Fix | | --- | --- | --- | | Params sent where freespinChoices doesn't list the bonus's bet | invalid_params, no spin used | Send none: placeFreespin() | | A choice that changes what the bonus fixes (Keno: another count of picks, another risk) | invalid_params, no spin used | Start from bonus.freespinBet.params and change only what the player picks | | The Freespin offer closed after invalid_params | The player loses the bonus on screen, though it is still there | Keep offering it while freespins.next names it, and let the player choose again |

Freespins: auto bet

Auto works in Freespin mode as it does for the player's own bets. createAutoBet({ session, freespins: true }) makes an auto bet whose every bet is the next Freespin of the bonus snapshot.freespins.next names as its run starts. Start it with the plan your Auto form gives:

const freespinRun = createAutoBet({ session, freespins: true });

const stop = await freespinRun.start({
  kind: 'steps',
  items: [],                                                     // not read: each round is the bonus's own bet
  params: {},
  count: null,                                                   // every Freespin the bonus has left
  stepActions: [12, 7, 18].map((tile) => ({ Move: 0, Tile: tile })), // the tiles the player marked
  cashOutAction: { Move: 1, Tile: 0 },
});
// stop.reason 'freespins_ended' once the bonus has no Freespin left, or another bonus is next.
  • Each bet is the bonus's next Freespin.
    • A step plan's round opens with placeOpenFreespin() and is then played with the plan's moves.
    • A one-shot plan's bet is placeFreespin(). It carries the plan's params as the player's choice only where settings.freespinChoices lists the bonus's freespinBet.id (Keno's picks).
    • A crash run's bet is placeCrashFreespin({ roundId }), one a round. It cashes out as the bonus's params say: at their AutoCashOut, or by the player's hand on a classic bet (session.cashOut with getState().betId).
  • On Keno, build params from the bonus. Start from next.freespinBet.params and add the player's picks ({ ...next.freespinBet.params, Picks: picks }). Params that change what the bonus fixes get each Freespin refused invalid_params: no spin is used, and the run stops at once. See "Common mistakes with chosen Freespins", above.
  • The bonus's bet plays, at its stake. The plan's items are never read or sent, and the player's own money is never bet. There is no balance check: a Freespin takes nothing of the player's.
  • staked stays '0.00', so net equals paid: what the Freespins won, as on every run, paid less staked.
  • It stops with 'freespins_ended' once the bonus it started on is no longer next with a Freespin left. That is its last one played, a cancel, its expiry, or another bonus next. It sends nothing more, and starts no Freespin of another bonus; a switch that lands while a Freespin is on its way can still play that one spin on the other bonus. Started with no bonus next, it stops so at once. count stops it first when it is lower.
  • A restriction pauses the bonus; it doesn't end it. While the casino's restriction holds the bonus (snapshot.freespins.paused names it, a Freespin credit in retry among the causes), the run stops 'refused', code freespin_restricted, with nothing sent. Keep Freespin mode and show the restri