Skip to main content

Admin domain semantics

This is the most important page in the backend docs. It describes the rules the backend guarantees — the ones client code must never second-guess or reimplement.

Read it before you touch anything financial. Not because the rules are hard, but because each one exists after somebody worked out the hard way what happens without it.

Every section links to the real source. When this page and the code disagree, the code wins — please fix the page.

Money and units​

Money is always integer cents. Store it, transmit it, and compute with it in cents. Formatting to dollars happens in the UI and nowhere else.

The reason is floating point. 0.1 + 0.2 isn't 0.3 in binary floating point, and a rounding error of a fraction of a cent, repeated across thousands of transactions, becomes a real discrepancy that someone has to reconcile by hand. Integers don't have that problem. So: cents, or explicit ledger numeric values mapped to cents.

Never write ledger balances directly. Cash movement posts balanced transactions through the ledger. A balance is the result of the entries, not a field you set. If you update a balance directly you've created money from nothing, and the books no longer add up.

Rewards are not cash. XP, diamonds, spin tokens, and freeplay are reward balances with their own events. Freeplay is still represented in cents where it carries value — but it's still a reward, not cash, and the two are not interchangeable.

Cash-out settlement has to balance: actual_fee + actual_net == gross withdrawal amount. If it doesn't, the handler rejects the request with a specific message rather than storing numbers that don't add up.

Source: api/ledger, api/payments, withdrawalMarkPaidErrorMessage.

Idempotency​

The problem it solves: an admin clicks "approve", the network hiccups, the response never arrives, and they click again. Without protection, that's two payouts. Idempotency makes the second request return the first request's result instead of doing the work twice.

How it works here: mutating admin operations that move money or change durable state require an Idempotency-Key header, unless their OpenAPI description says otherwise. The backend ties that key to the actor, the operation, a hash of the request, its processing status, and the stored result.

What happenedWhat you get back
Same actor, same operation, same key, same request — already finishedThe stored result, marked replayed where the schema exposes it
Same key, work still runningConflict / in-progress
Same key, but a different request bodyConflict — the key is already spoken for by different work
Missing or invalid key on an operation that needs oneBad request

That third row catches people. A key identifies one specific request, not a session or a user. Reusing a key with different content is a bug, and the backend tells you so rather than guessing which one you meant.

Source: api/idempotency, internal/idempotency/postgres/workflow.go, wallet adjustments Execute, off-app deposits CreateOffAppDeposit.

Audit records​

Every admin action leaves a record behind. These tables are append-only: you add rows, you don't overwrite them.

DomainWhat gets written
Admin password resetadmin_password_change_events, unique by actor plus idempotency key
Payment depositspayment_events, plus proof assets and reversal attempts
Payment cash-outspayment_withdrawal_events, with actor, source, and prior/new state where applicable
Wallet adjustmentsadmin_wallet_adjustments, plus ledger, reward, and payment-reversal references
Rewardsreward_events, with actor, reason, deltas, and resulting balance
Provider capabilities and healthcapability transition rows, probe runs and statuses, redacted evidence
Supportconversation, message, and read-state records

If you're adding an admin action, work out which of these it writes to before you write the service method. An action with no audit trail will pass code review, work fine, and then be impossible to investigate.

Key migrations: 000065_admin_password_changes.sql, 000071_admin_wallet_adjustments.sql, 000047_payment_withdrawal_admin_gate.sql.

State machines​

A state machine here means: a record can only be in one of a fixed set of states, and only certain moves between them are legal. The backend enforces the moves. Client code should never infer that a record "must be" in some state — ask, don't assume.

Off-app deposits​

A payment that arrived outside the app and was typed in by an admin.

requested --update--> requested
requested --settle--> succeeded
requested --void----> voided
succeeded --reverse-> reversed
(create with settle_now) -----------------> succeeded
stuck provider deposit --convert-to-off-app--> superseded (+ a succeeded off-app deposit)
  • Create and update need a valid player, a positive amount, a supported method, and an idempotency key.
  • Create with settle_now is any active admin's one step: the draft and its settlement happen in one transaction, and the acting admin is recorded as both created_by and settled_by. It needs a reason code (and an optional note), recorded on the settle event. No super-admin approval is needed; a non-admin gets 403. Settling an existing draft stays super admin only.
  • Convert to off-app is super admin only. It takes a provider deposit that was never credited and is still open (checkout created or stale, provider pending, player or KYC pending, or awaiting reconciliation) but was paid another way. One transaction records and settles an off-app deposit linked by supersedes_payment_id and moves the original to the terminal superseded state with a superseded_by_off_app event. It needs the payment's external reference and a reason code. A deposit with any wallet credit, even one only started, is refused.
  • Settle needs the expected state, and posts the wallet credit and reward effects atomically. This is the step where money becomes real.
  • Void ends a draft without any financial effect. Only from requested.
  • Reverse needs the deposit to be succeeded, a reason code, and a clean reversal preview. The service refuses if the money has already been spent, or if related reward, referral, or mission effects can't be safely unwound.

That refusal is a feature. If reversal is blocked, the correct response is to escalate, not to find another route to the same outcome.

Source: off_app_deposit_commands.go, PreviewOffAppDepositReversal, ReverseOffAppDeposit.

Deposits closed without a credit​

A provider deposit can end without ever crediting the wallet: superseded means an off-app deposit replaced it. A provider can still report it paid later. That late success never credits. Every success path (webhook, reconciler, player refresh, direct charge) checks the intent under its row lock before the wallet credit, records a signed webhook_mismatch event and leaves the state alone. A trigger stamps that event, under the same lock, with the state it met (observed_state). A closed state there opens the deposit's financial case, and the case only offers notes and escalation: the extra provider payment is settled outside the wallet.

Source: closed_intent_guard.go, 000128_superseded_deposits.sql.

Cash-outs​

awaiting_approval -> dispatch_queued -> provider_created -> succeeded
awaiting_approval -> rejected
dispatch_queued / provider_created / action_required / unknown_requires_reconcile -> failed_internal
provider or webhook mismatch -> unknown_requires_reconcile

Two different things are going on here, and confusing them causes bugs. There's the financial state above, and separately there's how the operator inbox groups rows:

  • open — every unknown or non-final state
  • paid — succeeded, and only succeeded
  • closed — rejected, canceled, expired, and failed final outcomes

Operator status labels are workflow guidance derived by the backend. Don't recompute them in the client from the lifecycle state. They exist precisely because the mapping is not obvious, and two implementations of "not obvious" will diverge.

Opening a row records the first reviewer idempotently and changes no financial state — that's why it's safe for the UI to do it automatically.

The rules:

  • Player-created cash-outs reserve the value first. Approval is a separate, super-admin command.
  • Rejecting records a player-visible category and a private reason code, and releases the reserved value.
  • Approve of a hand-paid cash-out (the mark-paid endpoint) is final: the admin answers Yes to "Did you pay the player already?" and approving records the payout paid; there is no separate Mark paid step (ADR 0019, 2026-11-16). It is an admin's record that they sent a manual payout (Cash App, Chime, PayPal, or a crypto payout the provider left to an admin) by hand. It needs the payment reference, which becomes the provider transaction id so one confirmation cannot settle two payouts. The fee defaults to the quoted fee and Postgres computes the net; a finalized proof is required only when the payout settings say so. Unknown or failed automatic payouts are not marked paid here: they resolve through their evidence-backed financial case.
  • Confirm-failed is for an unresolved or failed state after manual review.
  • Webhooks settle states they're compatible with. When a webhook and our state disagree, the record goes to unknown_requires_reconcile rather than being forced to look successful.

That last point is the philosophy of this whole system in one line: when we don't know, we record that we don't know. Never paper over an unknown outcome with a plausible-looking success.

Source: internal/payments/withdrawal_lifecycle.go, and the commands ApproveWithdrawal, RejectWithdrawal, MarkWithdrawalPaid, ConfirmWithdrawalFailed.

Wallet adjustments​

Super-admin corrections to a player's balances. Deliberately two steps:

  1. POST /api/v1/admin/wallet-adjustments/preview works out current balances, blockers, what's available, and whether a source payment is an exact deposit reversal.
  2. POST /api/v1/admin/wallet-adjustments executes, passing the expected balances so the backend can compare-and-set.

The split is what makes the operation safe. The preview is where the human sees consequences; the expected balances are what guarantee nothing changed in between.

  • Cash and cash-out balance are ledger-backed.
  • XP, diamonds, spin tokens, and freeplay are reward-event backed.
  • A deposit reversal must match the source payment's cash and reward effects exactly, or it's rejected. Approximate reversals are not allowed, because an approximate reversal is just a second discrepancy.
  • Records are immutable and reference the idempotency key plus any ledger transaction, reward event, and source payment reversal.

Source: Preview, Execute, 000071_admin_wallet_adjustments.sql.

Reconciliation​

Reconciliation views show problems. They do not fix them. There is no "resolve" command, and that's intentional — the resolution is real investigation against provider evidence, not a status change.

  • GET /api/v1/admin/reconciliation/queue lists provider transfers needing review.
  • Cash-out detail includes events and proof assets, so an operator can see the whole history before acting.
  • Provenance endpoints explain where a player's funds came from, so a reviewer can tell real external money from rewards, tester and system sources, and provider-transfer history.
  • Provider health includes recent runs, freshness, classifications, redacted evidence and durable unresolved legacy probe verification items independent of recent history. These items carry identities and neutral verification steps; health reads do not call providers or select a settlement outcome. Acknowledgements are annotations, not health overrides — acknowledging doesn't make a provider healthy, it records that a human has seen the alert.

Source: GetAdminReconciliationQueue, http_provenance.go, http_provider_health.go.

Domain map​

A quick orientation to what each domain exposes.

DomainMutating operationsRead operationsWorth knowing
Admin accountsCreate/update admin, reset passwordNone in this namespaceSuper-admin only; password reset is idempotent
TestersAdd/remove testerList testersTesters are excluded from business reporting by default
Users / Player 360NoneUsers, detail, Player 360 snapshot, deposits and ledger, walletAny admin reads Player 360 (ADR 0019); reporting is a super-admin read
DepositsCreate, update, settle, void, reverse, proof upload-finalizeList, detail, reversal preview, proof previewOff-app commands split across admin and super-admin
Cash-outsApprove, reject, mark-paid, confirm-failed, proof upload-finalizeList, detail, proof preview, provenanceApproval permission currently maps to super-admin
Wallet adjustmentsPreview, executeNoneExecute requires expected balances plus idempotency
ProvidersCapability patch, fake outcome, fallback putProviders, games, fallbacks, healthFake controls are local-only
Provider healthRun probes, canary quarantine/bootstrap, acknowledgeList, detailFull-system probe needs confirm plus an idempotency key in the body
RewardsAdmin grant, sandbox session/step/deleteReward history, sandbox presets/sessionSandbox is local/dev only and flag gated
SupportSend message, mark read, resolve/reopen/claim; any admin searches chatsConversations, messagesAdmin support rate limits differ from player limits
Visitor insightsNone in admin namespaceObserved browser aggregates and ordered signup/deposit/load cohortsAny active admin; individual identifiers never returned; see ADR 0049
Analytics and reportingNoneBusiness, player, growth, product events/overview, ops eventsThe backend owns filters, caveats, and timezone

Support contact destinations​

Support contacts are versioned and audited. Superadmins can configure official HTTPS Facebook/Messenger destinations and an optional https://t.me/<username> Telegram destination. Contacts require exact official hosts without userinfo or ports. Telegram accepts only a username path, with no query or fragment. Rejected saves return a field-specific message. Omitted optional destinations are preserved; an empty destination hides it. Player shortcuts and Open in browser use Messenger, Telegram, WhatsApp, SMS, then email.

Game-load funding policy​

The payout-policy revision includes block_withdrawable_loads, seeded true. Superadmins must send an explicit boolean with every full policy replacement, expected revision, reason and confirmation. ON keeps Cash out Amount unavailable for game loads. OFF funds loads from Playable Cash, then Cash out Amount, then eligible Freeplay. The Freeplay threshold combines Playable Cash and eligible Cash out Amount. Policy changes expire unexecuted preflights; completed/recovered transfers retain their original source allocations and provenance. Refunds restore those sources once. See ADR 0018.

Deposit bonus​

Migration 223 introduces the deposit-bonus ledger bucket after 6.9.2 migration 222. Backend schema expectation is 223; historical free play is preserved.

New deposit bonuses have a separate wallet bucket; older free play is preserved. The wallet's server-owned total includes Cash, Withdrawable Cash, Deposit bonus and Free play, excluding reserved Pending cash-out. Disabled bonus recovery actions retain their precise server-provided blocker in the staff case view. Loads draw paid cash and deposit bonus proportionally in whole game credits. Eligible withdrawable cash counts as paid cash. Redemption minimums and limits use the paid portion only. A bonus-only load waits for funds; free-play cycles never consume deposit bonus. The final paid load consumes and separately audits un-loadable bonus dust.

A reversed deposit revokes its bonus, claws back the unused portion and opens a deposit_bonus_recovery financial case for any spent portion. Loads and redemption remain blocked while it is open. The existing financial-case preview/resolve flow records an explicit recovery from Playable Cash. Confirmed failed-load refunds recover revoked bonus; a refund after staff recovery returns replacement paid cash, so the player is not charged twice. Grants, allocations and recovery journals retain immutable audit facts.

Referral formulas​

Settings → Bonuses & referrals edits versioned, reasoned base rules. The inviter and friend each have an on/off switch plus flat_cents, percent_bps and cap_cents. Flat may be zero. PostgreSQL pays min(flat+floor(basis*bps/10000),cap) as claimable free play; referral grants never become deposit bonus or cash. Percentages use integer basis points (20.25%=2025bps). Existing validated amount bounds apply ($0–$1,000 flat; positive cap up to$1,000; percentage0–100%).

referral_qualification chooses first_wallet_deposit (default) or first_wallet_game_load and minimum_deposit_cents (default0). Below-minimum deposits do not close selection. A positive minimum in game-load mode requires an earlier successful deposit meeting it; the first eligible paid wallet load supplies the award basis. Free-play-only loads, canaries and game moves do not qualify. The separate mission minimum is unchanged.

Referral switches gate both base and scheme candidates. Each side selects the single best actual candidate. Zero/disabled sides expose no claim. Neither side paying creates a terminal no_reward outcome without milestone progress. Changed settings never erase or recalculate previously frozen awards. Audited system changes have a nullable actor and render as System; history keeps old JSON shapes.

Forward migration239 follows immutable235 and paylink237/shared238 in6.9.3.2: both enabled, inviter500+2000bps/ cap100000, friend0+3000bps/cap5000, first deposit/min0. Hman approved Fam; orchestrator rollout is dev→Penguin→Fam. No new admin operation was added.

Special scheme On/Off​

Every scheme has one On/Off switch. New application saves are Off; On activates in the same request. Live edits save directly and retain availability. There is no UI lifecycle or draft copy. Date windows still limit eligibility. Superadmins write using CAS, session/CSRF and original-key idempotency; history records the actor/reason and availability change. Settled awards never change.

Unshipped246 is a nullable column expansion only. Untouched legacy active rows remain On and draft/archive rows Off, with no data rewrite. Current writes store the flag explicitly and mirror its state into legacy status atomically, so the actual preceding binary's unchanged reader also honors the switch. Current explicit sqlc queries apply the availability/date/enrollment predicates.251 is withdrawn. Scheme owner tests cover availability changes and replay without changing live policy.

Configuration readiness​

Saved settings responses optionally include backend-owned readiness. The admin client displays these results and never infers availability from an enabled switch alone. Live describes configuration availability; it does not promise that an individual player qualifies or that an external provider call succeeds.

POST /api/v1/admin/settings/readiness/preview accepts exactly one proposed group and returns the same projection without saving a revision or audit event. Groups cover credit moves, withdrawal review, risk, payout policy, automatic crypto payout, campaigns, support contacts, provider API access, game/panel links, scheduled reads/refill warnings, alert recipients, Telegram and recent wins. Each existing command retains its authorization and audit rules. Alert and crypto previews require a super admin. Provider API previews read the shared saved mode and active-call count without changing admissions; Off and draining are Not live. Omitted legacy Messenger/Telegram fields preserve the current contacts, as on save.

Payout preview validates against playgo_payout_policy_valid, the revision table’s existing admission predicate. Campaign preview uses the create command’s preparation; new campaigns remain Off. Scheduled checks resolve local registry metadata and the stable check account. Telegram preview receives a token-change flag, never a token: replacement tokens stay unverified until the existing save verifies them, and recipients still need /start. No preview makes provider calls or sends notifications. Missing optional projections are displayed as unavailable; projection failure does not undo or obscure a confirmed settings save.

Visitor insights measurement​

Any active admin may read GET /api/v1/admin/insights/visitors?period=today|7d|30d. Counts describe observed random-cookie browsers, including anonymous landings, not a census of people. Collection begins at deployment; earlier history and blocked or undelivered JavaScript are unmeasured. Unknown/other buckets and known excluded-session counts are visible. No individual identifiers are returned.

Distinct visitors are computed over each entire exact window, never sums of daily distincts. New York midnight anchors the current window through now; the previous window is adjacent and equal in elapsed length. Returning means an earlier retained visit. Device buckets may overlap across sessions; conversion rates use funnel_visitors, the first-visit cohort attributed to that segment. Signup, first unreversed credited deposit, and the first completed game load at or after that deposit come from authoritative server facts, in order. Existing players who have deposited contribute to device mixes without fabricating new signup conversion. Staff/test/system/bot exclusions use current linked identity; anonymous excluded browsers cannot be recognized until server-bound.

POST /api/v1/visitors/sessions is an explicit telemetry-only CSRF/idempotency exception. Same-origin/Fetch-Metadata, bounded JSON/schema/rate admission and normal client-build checks apply. Optional existing identity is verified read-only; no guest auth bootstrap or presence write occurs. Signals are untrusted and cannot authorize any auth or financial action. Capture only queues bounded memory; a separate worker writes sessions and daily delivery counters. Derived rollups run independently every five minutes. Sessions retain 90 days, daily aggregates/counters 365 days. Delivery counters keep their observed New York date, but diagnostics cover complete dates touched by each elapsed window and do not support precise partial-date period comparisons.

Sources: ADR0049, visitor service.