SDK · API · Protocol

Developer docs

Add provably fair randomness to any game server in minutes.

Install

FairDice is a tiny library you run inside your own game server. It never calls fairdice.ir while a game is running. Three SDKs produce bit-for-bit identical results, checked against the shared test vectors.

npm install https://fairdice.ir/sdk/fairdice-latest.tgz
# or load it in a browser:
# <script type="module"> import { FairDice } from "https://fairdice.ir/sdk/fairdice.mjs" </script>

Files: fairdice.mjs (ESM) · fairdice.cjs (CommonJS) · fairdice.global.js (browser global FairDiceSDK) · fairdice.d.ts · FairDice.cs · fairdice.py

Quick start

The whole integration is three moments: create the dice and publish the commitment, roll during the game, publish the proof link at the end.

// npm i https://fairdice.ir/sdk/fairdice-latest.tgz
import { FairDice } from 'fairdice';

// 1. Before the match: create the dice, show players the commitment
const dice = new FairDice({ dice: '2d6', game: 'Backgammon', meta: { match: 'm-1842' } });
broadcast({ commitment: dice.commitment });

// optional: players send their own seeds before the first roll
dice.setPlayerSeeds([whiteSeed, blackSeed]);

// 2. During the match: roll offline, as often as you like
const [a, b] = dice.roll();          // e.g. [6, 6]

// 3. After the match: one link proves every roll
broadcast({ proof: dice.url() });    // https://fairdice.ir/v/eyJ2Ijox...

How a session works

  1. Server seed. new FairDice() generates 32 secure random bytes (64 hex characters). It stays secret until the end.
  2. Commitment. fd.commitment = SHA-256(serverSeed). Show it to the players before the game (lobby, first screen, chat). It locks the seed: a different seed would have a different hash.
  3. Client seed. Extra entropy the operator does not control: each player's seed (fd.setPlayerSeeds([...])) or a future beacon value (await fd.useBeacon()). It must be fixed after the commitment is shown and before the first draw; the SDK enforces the latter.
  4. Draws. Draw number k uses nonce firstNonce + k. Its bytes are HMAC-SHA256(serverSeed, clientSeed:nonce:block). The SDK counts every draw and records its type in a compact log, e.g. [["d",[6,2],57]] = "57 rolls of 2d6".
  5. Reveal. fd.url() packs seeds, first nonce and the log into one token: https://fairdice.ir/v/<token>. Anyone opening it recomputes every draw in their browser and checks the commitment. No database is involved: the link is the proof.
Use a new FairDice per match (or per table round). Revealing a seed makes every future draw of that seed predictable, so the SDK refuses to draw after reveal().

Options

OptionTypeMeaning
serverSeedstring64 lowercase hex chars. Omit to generate one (recommended).
clientSeedstring1-256 chars. Defaults to random; override with player seeds or a beacon value.
noncenumberFirst nonce (default 0). Useful when one seed pair spans several sessions.
dicestringDefault op for roll() in dice notation: "2d6" backgammon, "5d6" Yatzy, "d20".
presetstringDefault op from a preset: backgammon, yatzy, ludo, hokm, holdem, blackjack, lotto649, bingo75, roulette, lootbox, mapseed...
op[code, params]Default op given explicitly, e.g. ["dl", ["std52", 4, 13]].
gamestringLabel shown on the verification page (max 80 chars).
metaobjectUp to 20 short key/values (match id, table...). Displayed but not verified.
keepHistorybooleanKeep every draw in fd.history (default true).
baseUrlstringLink base (default https://fairdice.ir).

Methods

JSC#PythonReturns
roll()Roll()roll()the default op result (e.g. [3, 5])
dice(sides, count)Dice(sides, count)dice(sides, count)numbers 1..sides
d("3d8")--dice by notation
coin() / coins(n)Coin()coin()"H" or "T"
int(min, max) / ints(min, max, n)Int(min, max)int(min, max)inclusive integer
float()Float()float()[0, 1) with 53 bits
shuffle(deck)Shuffle(deck)shuffle(deck)whole deck in random order
deal(deck, hands, perHand)Deal(deck, hands, perHand)deal(deck, hands, per_hand){ hands, rest }
sample(n, k, offset=1)Sample(n, k, offset)sample(n, k, offset)k distinct numbers, in draw order
lotto(k, n)Lotto(k, n)lotto(k, n)k distinct of 1..n
pick(items) / pickMany(items, k)Pick(items)pick(items)element(s) of your array
shuffleArray(items)--your array, shuffled
weighted(weights) / weightedManyWeighted(weights)weighted(weights)index chosen by integer weights
roulette("eu" | "us")-roulette(variant)0-36 or "00"
bytes(length)Bytes(length)bytes(length)hex string
draw(code, params)Draw(code, params)draw(code, params)any op (see Draw types)
setClientSeed(s) / setPlayerSeeds([...])SetClientSeed / SetPlayerSeedsset_client_seed / set_player_seedsonly before the first draw
commitment, count, nonce, historyCommitment, Count, Nonce, Historycommitment, count, nonce, historysession state
state() / FairDice.restore(state)StateJson() / Restore(json)state()persist & resume (contains the secret!)
url() / token() / reveal()Url() / Token() / Reveal()url() / token() / reveal()proof link; ends the session
commitUrl()CommitUrl()commit_url()pre-game link that shows only the hash
verify(tokenOrUrl, { expectedCommitment })FairDiceProtocol.Verify(token, expected)verify(token, expected)recomputed draws

Draw types

Every draw is one op. The proof stores ops as run-length encoded entries [code, params, times].

CodeParamsResultAlgorithm
d[sides, count]number[]count x (1 + int(sides))
c[count]("H"|"T")[]int(2): 0 = H
i[min, max, count]number[]min + int(max - min + 1)
f[count]number[](uint32>>>5) * 2^26 + (uint32>>>6), / 2^53
s[deck]item[]forward Fisher-Yates over the deck
dl[deck, hands, perHand]{hands, rest}shuffle, then consecutive slices
p[n, k, offset]number[]first k steps of forward Fisher-Yates over 0..n-1, + offset
w[weights[], count]number[]r = int(sum); first index whose cumulative weight > r
r["eu"|"us", count](number|"00")[]int(37) or int(38); 37 = "00"
b[length]hex stringraw stream bytes

Decks & cards

The unshuffled order is part of the protocol. Cards are rank + suit: ranks A 2-9 T J Q K, suits S H D C (spades, hearts, diamonds, clubs).

std52A..K of S, then H, then D, then C (AS, 2S, ... KC)
std54std52 + XR (red joker) + XB (black joker)
std36A, 6..K of each suit (Durak)
std32A, 7..K of each suit (Piquet, Belote, Skat)
shoe:NN x std52 (N = 1..16), e.g. shoe:6 for blackjack
dom6 / dom9 / dom12domino sets "a-b" with a <= b (28 / 55 / 91 tiles)
n:Nthe numbers 1..N (turn order, tiles, seats, bingo)

Persistence

Game servers restart. fd.state() returns a JSON object you can store next to the match (it contains the secret seed, keep it server-side). FairDice.restore(state) replays the log and continues with the exact same next nonce.

await redis.set(`match:${id}:dice`, JSON.stringify(fd.state()));
// ...after a restart
const fd = FairDice.restore(JSON.parse(await redis.get(`match:${id}:dice`)), { dice: '2d6' });

Optional online helpers

Nothing here is required. They make a proof stronger or shorter.

const fd = new FairDice({ dice: '2d6', game: 'Backgammon' });
await fd.register();      // timestamp the commitment on fairdice.ir (notary)
await fd.useBeacon();     // client seed = next public beacon value -> no seed grinding possible
// ... play ...
const link = await fd.shortUrl();   // reveal + https://fairdice.ir/p/Ab3xY9k2

With register() followed by useBeacon() the verification page proves that the server seed was fixed before the client seed existed, without the players typing anything.

Recipe: backgammon

// one FairDice per match: two dice per roll
const dice = FairDice.backgammon({ meta: { match: match.id } });
match.send('commitment', dice.commitment);          // show it in the lobby

// both clients send a random seed when the match starts
const seeds = await match.collect('seed');           // e.g. crypto.randomUUID() on each client
dice.setPlayerSeeds(seeds);

on('roll', (player) => {
  const [a, b] = dice.roll();                         // [6, 6] = doubles, move four times
  match.broadcast('rolled', { player, a, b, n: dice.count });
});

on('gameOver', () => match.broadcast('proof', dice.url()));

The opening roll (one die each) can be dice.dice(6, 2) too: the verify page labels every draw, so mixing ops is fine.

Recipe: Yatzy & dice games

const fd = FairDice.yatzy();                     // roll() = five dice
let hand = fd.roll();                              // [2, 5, 5, 1, 6]
// keep the 5s, re-roll three dice
const fresh = fd.dice(6, 3);
hand = [5, 5, ...fresh];
// Ludo: FairDice.ludo().roll() -> [4]      D&D: fd.d('d20'), fd.d('3d8')

Recipe: Hokm, poker & card games

const fd = new FairDice({ game: 'Hokm', preset: 'hokm' });
const { hands } = fd.roll();          // 4 hands x 13 cards: [['AS','TH',...], ...]
hands.forEach((h, seat) => send(seat, h));   // each player only sees their own hand

// next deal in the same match: just call roll() again (next nonce)
// Texas hold'em for 6 seats: fd.deal('std52', 6, 2) -> rest[0..4] are the board cards
// Blackjack: const shoe = fd.shuffle('shoe:6')
The proof reveals every card, including other players' hands. Publish it after the hand / match is over, never during play.

Recipe: lotteries & giveaways

For public draws use Draws (UI) or POST /api/draws. The entry list is frozen and hashed first, and the winners are derived from a beacon round in the future:

curl -X POST https://fairdice.ir/api/draws -H 'content-type: application/json' -d '{
  "title": "Instagram giveaway - 3 winners",
  "organizer": "@mypage",
  "mode": "winners", "pick": 3,
  "entries": "@sara\n@reza\n@mina\n@ali\n@neda",
  "drawAt": "2026-12-24T18:00:00Z"
}'
# -> { "id": "k3Hq9xWb", "url": "https://fairdice.ir/d/k3Hq9xWb", "beaconRound": ..., "status": "scheduled" }

Modes: winners (pick k), order (random order of everybody, e.g. turn order or seeding), groups (split into k groups, e.g. tournament brackets). Instead of entries you can send a ticket range: "rangeStart": 1, "rangeEnd": 250000.

How a draw is computed (anyone can redo it): entriesHash = SHA-256(entries joined by "\n"), then a FairDice draw with serverSeed = beacon output of the round, clientSeed = draw:<id>:<entriesHash>, nonce 0, op p [n, k, offset].

Recipe: scratch cards & instant wins

Commit to the whole prize table before selling a single ticket, so nobody can move the winning tickets after the sale:

const fd = new FairDice({ game: 'Scratch series #12' });
await fd.register('Scratch series #12');      // timestamped before the sale
const prizes = [...Array(10).fill('1,000,000'), ...Array(200).fill('50,000'), ...Array(9790).fill('-')];
const tickets = fd.shuffleArray(prizes);      // ticket i has prize tickets[i]
// sell tickets... when the series ends, publish fd.url(): every buyer can check their ticket

Recipe: loot boxes & gacha

// publish the odds; weights are integers (60% / 30% / 9% / 1%)
const ODDS = [600, 300, 90, 10];
const RARITY = ['Common', 'Rare', 'Epic', 'Legendary'];
const item = RARITY[fd.weighted(ODDS)];
// a player's proof link shows every box they opened

Recipe: procedural map seeds

const fd = new FairDice({ game: 'Ranked map' });
fd.setPlayerSeeds(playerSeeds);
const mapSeed = fd.bytes(32);        // feed it to your terrain generator
// competitive players can verify nobody picked a favourable map

Verifying in the game client

The same library runs in browsers and JS game engines, so the client can verify the proof itself instead of trusting a web page:

import { verify } from 'https://fairdice.ir/sdk/fairdice.mjs';
const v = verify(proofUrl, { expectedCommitment: commitmentShownAtStart });
if (!v.commitmentMatches) alert('This proof does not belong to your match!');
const rolls = v.draws.map((d) => d.result);   // compare with what you saw

Trust model

  • Proven: every result follows from the seeds; the server seed is the one committed to; draws were not reordered, skipped or re-rolled (nonces are consecutive and the count is in the proof).
  • Requires: players see the commitment before the client seed is fixed. Player seeds or a future beacon round make seed grinding impossible; a commitment registered on the notary makes the timing provable later.
  • Not proven: that the game applied the results correctly (e.g. moved the right checker). Log your game moves next to the draw count if you need that.
  • Rooms are fair between the people at the table: fairdice.ir holds the seed and anyone can reveal it at any time.
  • Beacon: values are fixed one year ahead by a hash chain and mixed with drand (League of Entropy) at publication time, so neither fairdice.ir nor an operator can predict or choose them.

HTTP API

JSON over HTTPS, CORS enabled, no key needed. Please keep it under ~1 request/second per client; heavier use is rate-limited.

EndpointDescription
GET /api/verify?token=...&commitment=...Recompute a proof server-side (bots, backends without an SDK).
POST /api/proofs {token}Store a proof; returns a short link /p/<id>.
POST /api/commitments {hash, label?}Notary: timestamp a commitment (first registration wins, Ed25519-signed).
GET /api/commitments/<hash>Notary receipt.
GET /api/beacon/latestLatest beacon round.
GET /api/beacon/<round>A specific round (round r is due at unix time r*60).
GET /api/beacon?before=&limit=Recent rounds.
GET /api/beacon/infoPublic key, chain anchors, formulas.
POST /api/drawsCreate a public draw (see Lotteries).
GET /api/draws/<id>Draw state, entries and winners.
POST /api/rooms {name, preset}Create a dice room.
GET /api/rooms/<id>?after=<eventId>Room state and new events (poll ~1/s).
POST /api/rooms/<id>/roll {actor, preset | dice | range | pick}Roll in a room.
POST /api/rooms/<id>/reveal {actor}Reveal the room seed and start a new one.
curl https://fairdice.ir/api/beacon/latest
curl "https://fairdice.ir/api/verify?token=eyJ2IjoxLC..."

Protocol spec (v1)

Everything needed to write an independent verifier in any language. Implementations must match test-vectors.json.

Seeds and commitment

  • serverSeed: 32 random bytes encoded as 64 lowercase hex characters.
  • commitment = hex(SHA-256(UTF-8 bytes of the serverSeed hex text)). You can check it with any online SHA-256 tool.
  • clientSeed: any UTF-8 string, 1-256 characters.

Byte stream

block_i = HMAC-SHA256(key = UTF8(serverSeed), message = UTF8(clientSeed + ":" + nonce + ":" + i))   // i = 0, 1, 2, ...
stream(nonce) = block_0 || block_1 || block_2 || ...       // each draw reads its own stream from the start

Unbiased integers and floats

uint32()  = next 4 stream bytes, big-endian
int(n)    = n == 1 ? 0 (no bytes read)
          : loop { x = uint32(); if (x < 2^32 - (2^32 mod n)) return x mod n }    // 1 <= n <= 2^32
float()   = ((uint32() >>> 5) * 2^26 + (uint32() >>> 6)) / 2^53

Shuffles and picks

// forward Fisher-Yates, stopped after k steps (k = n for a full shuffle)
a = [0, 1, ..., n-1]
for i in 0 .. k-1:
    j = i + int(n - i)
    swap(a[i], a[j])
result = a[0 .. k-1]        // shuffle(deck) = deck[a[0]], deck[a[1]], ...

Proof token

token = base64url( UTF8( JSON.stringify({
  v: 1,                 // protocol version
  s: serverSeed,        // revealed
  c: clientSeed,
  n: firstNonce,
  o: [[code, params, times], ...],   // run-length encoded op log, in order
  g: "Backgammon",      // optional label
  m: { match: "m-1842" },  // optional metadata (not verified)
  t: 1764720000         // optional unix seconds
})))
draw k (0-based, in log order) uses nonce = n + k

Beacon

round r is due at unix time r * 60
chainValue[r] = H^(L - (r - startRound + 1))(secret),  H(x) = hex(SHA-256(UTF8(x)))
SHA-256(chainValue[r]) == chainValue[r - 1]   and   SHA-256(chainValue[startRound]) == anchor
drandRound    = floor((r*60 - 1595431050) / 30) + 1      // drand mainnet, 30 s period
output        = hex(SHA-256("fairdice-beacon-v1|" + r + "|" + chainValue + "|" + (drandRandomness || "none")))
signature     = Ed25519("fairdice-beacon-v1|" + r + "|" + output)     // key: /api/beacon/info
beacon client seed for games: "fdb:" + r + ":" + output

Embeds

Show a live "verified" card for a proof on your site, in a match history or in a launcher:

<iframe src="https://fairdice.ir/embed/v/<token>" width="380" height="150" style="border:0;border-radius:16px" loading="lazy"></iframe>

Or just link the proof. Every proof page has a QR code, a short link and a JSON download.