Skip to content

Economy and inventory

The Economy service owns everything a player can own and everything that can be paid to them: currencies, items, the shop, gacha pools, rewards for matches, and progress tracks. It is built around a double-entry ledger so that money never appears or disappears without a record.

For the SDK side (showing items and rolling a pool from a client) read Show a player's items and craft with them. This page is about how the service guarantees correct balances.

The one idea: mechanism in code, nouns in data

Economy knows currencies, items, reward classes, ceilings, offers, pools, counters, tracks and keys. It does not know what an item is for, what a currency is called or that a game has ranks. A game states all of that in four server-audience documents published through Config, and Economy validates and enforces them:

Namespace Holds
economy.rules Currencies, the item catalogue, reward classes (named payouts), faucet ceilings, entitlement kinds
economy.shop Offers: cost, what they grant, per-player limit, time window
economy.gacha Pools: cost, weighted entries, pity, maximum draw count, duplicate policy, window
economy.tasks Facts (typed event schemas) and tracks: what to measure, the rungs, the reward for each

Staff edit these in the admin website's table editor and publish a release like any other config; Economy picks it up within its refresh interval (60 s by default) with no restart. A release is applied whole or not at all: a shop that names a class the rules no longer have is a broken release, so the previous rules stay in force and economy_config_loads_total{result="failed"} counts the failure. Every roll stores the release it was made under, so "what were the odds then" stays answerable. See Config, Patch and content delivery.

The key consequence is that callers never name an amount. A game server says "pay class match.casual to this player for match m1"; the amount comes from economy.rules. A grant body with an amount field is rejected as an unknown field.

The ledger

Money lives in five tables:

ledger_account  one per owner and currency   (player | system:faucet | system:sink | system:escrow)
ledger_entry    append-only journal           (txn_id, account, delta, reason, ref)
ledger_balance  cached balance per account    (written in the same transaction as the entries)
idempotency     (player, key) -> stored result
ledger_budget   what each player has received per faucet in the rolling window

Double entry. Every grant credits the player's account and debits the currency's system:faucet account in the same transaction; every spend does the reverse with system:sink. Amounts are bigint in minor units; there is no float anywhere.

Four invariants are enforced by the database, not by application code:

  1. Both journals are append-only. A trigger rejects UPDATE and DELETE on ledger_entry and on the item journal inventory_event.
  2. A player account is never negative. A trigger on ledger_balance refuses it. System accounts may go negative: a faucet's balance is minus everything it has paid out.
  3. A possession is one row. A unique key makes a second grant of the same unique item an observable duplicate rather than a second copy.
  4. A claim is one row. A task rung cannot be paid twice, even with a fresh idempotency key.

The fifth property, the cache equals the sum of the entries, cannot be a constraint. It is kept by writing both in one transaction and checked by reconciliation (below).

One payout, five doors

A reward grant, a match reward (loot), a task claim, a shop purchase and a gacha roll all go through the same function. In one transaction it:

  1. claims the idempotency key;
  2. for loot, checks the match was observed;
  3. locks the balance rows in a fixed order, so two calls can never deadlock;
  4. checks every ceiling that applies (the class's own and the platform-wide wildcard; the stricter wins);
  5. appends the entries, moves the cached balance and the items, records the budget row;
  6. stores the result and commits. A refusal anywhere rolls all of it back.

Spending uses a guarded statement, UPDATE ... WHERE balance - $amount >= 0, so "insufficient funds" is a zero-row update, not a read followed by a write, and a multi-currency spend moves all of it or none of it.

Idempotency

Every money-moving route takes an idempotency_key. The first call stores its answer; a retry with the same key returns that stored answer (with "replayed": true) and moves nothing. The same key for a different operation is 409 idempotency_key_reused. A player-route call with no key is given a fresh one, which makes a transport retry safe but a second button press a second purchase. A match reward's key is the match_id.

Wallets and items

  • Wallet. GET /api/player/economy/wallet is the cached balances.
  • Inventory. inventory_item rows carry a quantity (for stackable items, up to max_stack) or a unique_ref (one row per distinct possession) and free-form attrs the instance declares, such as a level and a counter. Attribute changes are journalled (inventory_attr_event). Game servers change them with /internal/economy/consume, .../items/attrs and .../items/advance (a bounded increment).
  • Instanced items. An item listed under instances.items in economy.rules is held one row per copy: every grant of it makes a new row with its own unique_ref and with attrs the economy rolled (a level, one primary stat, a few secondary stats), up to instances.max_per_item copies. A player upgrades a copy with POST /api/player/economy/instances/upgrade by spending declared materials: the pot buys a whole number of levels, each level raises the primary by a fixed step and rolls one secondary, and what the pot holds weights that roll. GET /api/player/economy/instances/rules discloses every weight, so a client shows the real chances beforehand, and the answer lists the weights each level used. POST .../instances/dismantle turns a copy back into the item's declared grants. Game-server routes cannot write a copy's attrs. A dedicated server reads a player's copies with GET /internal/economy/players/{id}/instances; a peer-hosted match gets them as descriptor strings in its signed roster. Publish the block only after the economy that reads it is deployed: a release with a member the running service does not know is refused.
  • Display slots. Session lets a player pin an owned item to a named slot; it asks Economy for the catalogue entry and ownership. Chat asks Economy whether a player holds an item before it accepts it as an attachment.

Shop and gacha

  • Shop. POST /api/player/economy/shop/purchase takes an offer, a quantity and a key. Offers have costs, grants, per-player limits and windows (offer_closed, offer_limit_reached).
  • Gacha. POST /api/player/economy/gacha/roll rolls a pool count times. The pool lists weighted entries and discloses them to clients. A pool's cost can be currencies, stackable items or both. Pity is a counter per player and pool: after after consecutive rolls without the target rarity the next roll is forced to it, and the counter resets. A duplicate policy can convert a repeated unique item into another currency. A pool can be rolled by payment instead of an id: the pool whose cost exactly matches what the player offers is rolled (422 no_match if none).
  • Loop protection. Documents are refused at load if an offer grants a currency it also costs, if a pool's duplicate payout is the currency it charges, or if two documents form a cycle of currency payouts (a shop mint with a click in the middle).

Loot per match

A match reward is paid by POST /internal/economy/loot, keyed by match_id, using a game server's key. Economy pays only against a match the platform observed:

  1. When the Allocator places a match it registers the match and its roster with the Matchmaker (POST /internal/matchmaker/matches, Allocator key only). A game server cannot register or change a roster.
  2. When the game server reports the match ended, the Matchmaker records ended_at, then sends Economy one claim carrying that stored roster (POST /internal/economy/matches, Matchmaker key only). This is retried with backoff until it lands and is idempotent on (match_id, player_id).
  3. Only then will loot for that player and match succeed; otherwise 409 match_not_observed.

So the process that asks for a payout cannot author the fact that authorises it. The seam is one method, MatchOracle.Observed, so another source of truth could replace it.

Ceilings: the faucet limits

A ceiling caps how much of a currency one player may receive from a faucet in a rolling window. It is enforced inside the payout transaction, so there is no moment when a caller's number could win. If a gacha duplicate would breach a ceiling, the roll is not rolled back: the draw is recorded as an unpaid duplicate and still commits, because rolling back would refund the pull, hand over a free reroll and leave the pity counter unmoved. Raising the platform-wide wildcard is an operator's decision, not a game's.

Entitlements and tracks

An entitlement is a reward owed: claimable once, not before available_at, paid through a reward class when claimed. One row serves a timed box, compensation, an event mail or a daily reward by changing kind, rule and available_at. Each kind is declared in economy.rules (an undeclared kind is 422 kind_unknown) and can carry guards: max_open (how many may be owed at once), mint_limit (how many may be given in a rolling window, claimed or not), the classes it may pay, a delay range, and an optional early_claim price.

A track is a ladder of rungs advanced by counters or reported facts. Game servers report progress with POST /internal/economy/progress, .../progress/gauge or .../facts, each keyed so a retry counts once. A player claims a rung with POST /api/player/economy/tasks/claim, or the track pays it automatically (auto_claim). A fact can also mint an entitlement through entitlement_triggers.

Reconciliation

A background pass runs at start-up and then every ECONOMY_RECONCILE_INTERVAL. It compares each account's cached balance with the sum of its entries and exports the number of disagreements as economy_ledger_imbalance (a real 0, not a missing series). It repairs nothing: when the journal and the cache disagree, which one is right is an operator's decision. Staff read the report on the admin website's Economy > Reconciliation page or at GET /api/admin/economy/reconciliation. Rows name accounts, not players.

Who calls what

Caller Door Examples
Player (token) /api/player/economy/* through gateway wallet, inventory, shop, gacha, tasks, entitlements
Staff (token) /api/admin/economy/* through gateway_dev player wallet, ledger, entitlements (viewer); reconciliation (viewer); grant a reward class by hand (live_ops, with a required reason)
Game server (key) /internal/economy/* grants, loot, progress, facts, consume, attrs, entitlements
Matchmaker (key) /internal/economy/matches record an observed match
Session, Chat (key) /internal/economy/items/..., .../players/... catalogue, ownership

The identity domains never mix: a player token on a staff route is 401, a staff token below the route's role is 403 insufficient_role, and a service key on a public route is 401. Today there is no revoke: staff can grant but not take away, and that would need a new Economy route.