Для разработчиков / API приложений

Сервер Arcade

Сервер WebSocket для пяти игр, с горсткой маршрутов HTTP рядом. Для четырёх из пяти клиент не отправляет никакого игрового ввода - ввод есть транзакция, а сокет есть то, как вы смотрите, как она приземляется.

Сокет, а не API

Один процесс держит пять игровых комнат плюс холл на одном цикле событий, читает цепочку через собственный сокет к узлу и раздаёт результат каждому подключённому клиенту. Интерфейс - это WebSocket; маршруты HTTP существуют для проверок здоровья и для двух чисел, которые обрамление сайта рисует на каждой странице.

Игровой ввод - это транзакция, а не кадр

Руление на арене, ставка на кривую, спин, ставка на поле - всё это транзакции, которые игрок отправляет контракту. Этот сокет несёт то, за кем вы смотрите, пинг живости и взгляд сервера на то, что сделала цепочка. Ничто из отправляемого клиентом по нему ничего не авторизует и не меняет исход.

Комната с клешнёй - намеренное исключение: управлять клешнёй значило бы транзакцию на кадр, поэтому намерения едут по сокету. Даже там шов узкий - три глагола, ни один из которых не несёт ни позиции, ни времени, ни вердикта, и водитель авторизован прообразом, который браузер уже опубликовал в цепочке в собственном захвате.

Подключение

Точка доступаValue
Сокетwss://minigame.picklechain.xyz/ws/<room>собственный nginx сайта передаёт апгрейд
HTTPhttps://minigame.picklechain.xyz/api/тот же процесс, с отрезанным префиксом
Ваш собственный стекhttp://127.0.0.1:3008сайт аркады; сам сервер живёт в сети контейнеров
Originпроверяется на апгрейдеOrigin вне настроенного списка получает отказ 403 до рукопожатия, так что сокет не открывается вовсе

Неизвестный путь под /ws/ получает отказ 404 на апгрейде, а соединение сверх лимитов ниже получает отказ 429 - оба как простой ответ HTTP на сыром сокете, до всякого рукопожатия WebSocket. Клиент, который обрабатывает только событие error своего сокета, увидит общий сбой; прочитайте статус, если хотите знать, какой именно.

Шесть комнат

/ws/arena

комната
При входе
`hello`, then a full snapshot of the arena.

The snake arena. Steering is a transaction, so the socket carries no input for it.

/ws/crash

комната
При входе
`hello`, then the whole round: phase, time left, the commitment, every bet placed and every cash-out judged so far.

The curve. Bets are transactions.

/ws/claw

комната
При входе
`hello`, then the cabinet: what is left, where each capsule stands, the machine's constants and every attempt being driven.

The claw cabinet, and the ONLY room whose gameplay input rides this socket rather than the chain - a transaction per frame is not a game.

/ws/patch

комната
При входе
`hello`, then the machine: the bet ladder, the paytable, the meter and the spins still open.

The reels. A spin is a transaction; the socket watches it.

/ws/trellis

комната
При входе
`hello`, then the table: every cell's multiplier, the current snapshot, the line so far and the bets still standing.

The board. Bets are transactions; the socket has one verb, and it buys nothing.

/ws/stack

комната
При входе
`hello`, then `stack`: every run being climbed with its rules state, the day's board and the rules' constants.

The tower. A start and every tap are transactions; the socket only listens, and says what the rules made of each tap.

/ws/derby

комната
При входе
`hello`, then `derby`: the current and next race, recent history, the rules and the paddock.

The race. A bet is a transaction; the socket only listens, and every runner is one of the chain's own oracle feeds.

/ws/glide

комната
При входе
`hello`, then `glide`: the day's board, every run in the air, the canyon cards and the rules.

The canyon. A start and every flap are transactions; the socket only listens, and the canyon it draws comes from a live price feed.

/ws/hall

комната
При входе
`hello` alone.

The lobby. Somebody who has not chosen a game sits here, and it is counted in the socket total.

Каждая комната отвечает одной и той же открывающей последовательностью: кадр hello, несущий имя комнаты, число играющих, число смотрящих и адрес оператора расчётов, затем полный снимок состояния этой комнаты. Оба счётчика ОТНОСЯТСЯ К КОМНАТЕ - раньше они приходили с арены, какую бы комнату вы ни запросили, что объявляло игроков, которых там не было.

Что может отправить клиент

watch

every room
Форма
{"t":"watch","account":"0x…"}

Says which account this socket is following, so the server can address one player directly - a refused join has to reach the person it was refused for. In the reels room it also arms that account.

Полезно знать. It AUTHORISES NOTHING. The account is not verified, the contract decides who may play, and the address must match a 40-hex pattern or the message is ignored in silence.

ping

every room
Форма
{"t":"ping","id":<any>}

Answered with `{t:"pong", id}`. The server also sends protocol-level pings and terminates a socket that stops answering them.

Полезно знать. This is not the liveness mechanism the server relies on; it is the one a client can observe.

Форма
{"t":"claim","tx":"0x…","secret":"0x…"} and three verbs after it

Takes the wheel of an attempt and drives it. The proof is a preimage: the hash of the secret must equal the seed the pull published on chain, so the only client that can drive an attempt is the one that made it - no signature, no challenge, no round trip.

Полезно знать. None of the verbs carries a position, a time or a verdict. A wrong secret is refused and counted and never logged. A reconnect takes the wheel from the previous socket, which is told so.

quote

the trellis room only
Форма
{"t":"quote", …}

Asks the operator to sign the price already printed in a square.

Полезно знать. It carries no stake and no account, and the contract checks the clock, the lock and the float itself. A flood of them costs this process signatures and nothing else.

javascript
const socket = new WebSocket("wss://minigame.picklechain.xyz/ws/crash");

socket.addEventListener("open", () => {
  // Tell the server which account to address directly. It verifies nothing:
  // this only decides who a per-player frame is sent to.
  socket.send(JSON.stringify({ t: "watch", account: myAddress }));
});

socket.addEventListener("message", (event) => {
  const frame = JSON.parse(event.data);
  switch (frame.t) {
    case "hello": /* room, playing, watching, operator */ break;
    case "full":  /* the whole room, sent once after hello */ break;
    case "chain": /* resyncing, and the range of mini-blocks lost, if any */ break;
    default:      /* IGNORE. The frame list is not versioned and rooms gain frames. */
  }
});

Что отправляет сервер

Every frame is a JSON object with a `t` discriminator. `hello` arrives first and carries the room, the number playing, the number watching and the operator's address; a full snapshot follows. After that the room pushes what changed.

Across the eight rooms: chain, tick, state, full, bet, settled, settle-failed, refused, refunded, refund-due, fulfil-failed, pull, claimed, released, blocked, armed, quote, feed, unsealed, void, race, started, finished, paddock, board, run, points, flight, over, cancelled, canyons, eat, death, pong.

Разрыв в цепочке объявляется, и в каждой комнате он значит своё

Кадр chain несёт resyncing и диапазон мини-блоков, которые читатель не смог забрать. Он рассылается во все комнаты, и каждая обходится с ним по-своему: раунд, пересёкшийся с потерянным диапазоном, говорит, что его список победителей может быть неполным, вместо того чтобы объявить победителями всех, а комната с клешнёй отправляет потерянный диапазон в свой журнал, чтобы ставки внутри него можно было найти и вернуть. Клиент, который игнорирует этот кадр, нарисует уверенную картину неполной.

Маршруты HTTP

Params
none
Возвращает
{ok, loop:{p50Ms, p99Ms, maxMs, windowMs}}

Liveness, plus the event loop's recent delay. Eight rooms, a physics step and every socket's fan-out share one loop, so a loop that stalls stalls every quote, every echo and every frame at once.

Полезно знать. This is the figure that answers `the arcade is slow sometimes`. It is measured over ten-second windows and reset each time.

Params
none
Возвращает
{ok, reasons, miniBlock, appliedMiniBlock, appliedLagMs, resyncing, lost}

503 when the socket to the node is down, or when the last APPLIED mini-block is more than five seconds old.

Полезно знать. It measures what was applied, not what arrived. Measuring arrival meant a wedged dispatch chain answered 200 while no input had been applied for minutes, which is the exact failure this probe exists to catch.

Params
none
Возвращает
{total:{playing, sockets, spectators}, arena, crash, claw, patch, trellis, stack, derby, glide, …}

The whole arcade in one object: a summary per game and three numbers for the chrome every page draws. `playing` means somebody with something at stake right now, and each game measures that its own way.

Полезно знать. PUBLIC AND UNAUTHENTICATED, which decides what may appear on it. The crash summary withholds its point until the curve has stopped, and the claw summary carries the published commitment and never a link beneath it - one link is the outcome of the next pull nobody has made.

Params
none
Возвращает
{supply, remaining, claimed, cells, price, pullsPerAccount, commit, chainLeft, blocked, machine}

The cabinet on its own, so a page can state what is left without opening a socket.

Полезно знать. 503 when the claw room is not running.

Params
the pull id in the path
Возвращает
one finished pull, whole

The seed the player published, every intent the server recorded, the tick the drop landed on and the verdict that came out of them - the arithmetic a reader can rerun.

Полезно знать. A pull still being driven is a 404, deliberately: its trace is not finished and its link is not revealed. A revealed link is served only because the fulfilment that finished the pull already put it on chain.

Params
none
Возвращает
{playing, watching, day, pot, top, leaders}

Stack's day without a socket: the UTC day, its pot in wei, the chain's own top three and the tallest runs this server has finished today.

Полезно знать. 503 when the stack room is not running. The pot and the top three are read off the contract once a minute and after each finish, so they can trail a finish by a moment.

Params
the run id in the path
Возвращает
one run, whole: {id, a, t0Us, startMini, taps:[{us, mini, hash}], results, height, why, finished, rules}

Every tap of a run with the mini-block that carried it and what the rules made of it - the arithmetic a reader reruns with arcade-server/src/stack.js to check the height the operator reported.

Полезно знать. A 404 for a run this process never saw or has already let go of; it keeps the last five hundred. The chain still holds every tap, and the rules still apply to them.

Params
none
Возвращает
{playing, watching, k, phase, card, unsettled, current, next, history, rules}

Derby's board for a page that has no socket yet: the current race and the next one, recent history, and the rules (the feed allowlist, the wall and night cards, the stake bounds and the seed).

Полезно знать. 503 when the derby room is not running. `unsettled` counts bets still waiting on a settle, across every race this process still holds.

Params
the race number in the path
Возвращает
one race, whole: {k, state, card, gate, line, runners, handicaps, pools, startPrices, startRounds, lineRounds, roundsFrom, scores, winners, why, hashes, bets}

The lineup, the handicaps, the rounds both seals named, the scores, the winners and every bet - the arithmetic a reader reruns with arcade-server/src/derby.js against the same public rounds.

Полезно знать. A race this process never opened is a 404. `roundsFrom` says whether each end's rounds came from this room sealing them or were recomputed from the tape after a restart - the proof is the same either way.

Params
none
Возвращает
{playing, watching, day, pot, top, leaders, canyons}

Glide's board for a page that has no socket yet, with every canyon's card alongside the day's pot and its leaders.

Полезно знать. 503 when the glide room is not running.

Params
the run id in the path
Возвращает
one run, whole: {id, a, feed, symbol, r0, sigma, startUs, startMini, startHash, answers, flaps, result, rules}

r0, the rounds of the canyon this run flew, and every flap with the mini-block that carried it - the arithmetic a reader reruns with arcade-server/src/glide.js `replay` to get the same score.

Полезно знать. A run this process never saw or has already let go of is a 404.

Все четыре без аутентификации, и это решает, что на них может появиться. Ничего, что выдало бы незаконченный раунд, не публикуется: точка краха удерживается, пока кривая не остановится, а цепочка хешей клешни публикуется только как её обязательство, со звеном, раскрытым на /fair исключительно потому, что исполнение, завершившее тот захват, уже положило его в цепочку.

Лимиты, и что их ломает

ГраницаValue
Sockets256 total, 8 per addressthe upgrade is refused 429 before the handshake; the slot is released when the raw socket closes, not when the handshake succeeds
Originan allowlistthe upgrade is refused 403, so a page on another origin cannot drive this socket with a visitor's network
Frame size4 KiBtwo orders of magnitude above the largest real message; the library's default is 100 MiB
Inbound rate20 a second, burst 4045 and 90 in the claw room, because its driving is on this socket and a hand working a pad passes ten changes a second without trying
Overflowthe socket is closedclosing is kinder than ignoring - and in the claw room it ends a paid attempt, which is why that allowance is the wider one
Backpressure512 KiB buffereda socket further behind than that is cut and terminated rather than written to; a client that never reads would otherwise grow the process's heap without limit
Livenessa ping every half minuteanything that has not answered by the next one is terminated

Медленного читателя отключают, а не буферизуют

Библиотека буферизует всё, что не может записать, в куче этого процесса, без предела. Поэтому сокет, отставший больше чем на полмегабайта, обрезается и завершается, а не пишется снова - горстка клиентов, которые открывают сокет и никогда его не читают, иначе исчерпала бы контейнер, а на процессе, держащем ключ, это удалённое убийство. Полмегабайта - это примерно пятьдесят самых крупных кадров, которые шлёт этот сервер; ни один читающий клиент никогда так не отстаёт.

Бюджет сообщений шире в комнате с клешнёй, и это намеренно

В остальных местах клиент шлёт пинг раз в несколько секунд и больше ничего, так что двадцать сообщений в секунду могут быть только сломанным или враждебным клиентом. Управление клешнёй шлёт по сообщению на смену намерения - нажатие и отпускание это два - и игрок, работающий панелью в две руки, без труда переваливает за десять в секунду. Завершить этот сокет значит вырвать у него руль посреди попытки, и попытка, за которую он заплатил, истечёт об ограждение. Так что потолок там стоит выше того, что может выдать рука, а не вровень с ним.