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:
- Both journals are append-only. A trigger rejects
UPDATEandDELETEonledger_entryand on the item journalinventory_event. - A player account is never negative. A trigger on
ledger_balancerefuses it. System accounts may go negative: a faucet's balance is minus everything it has paid out. - 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.
- 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:
- claims the idempotency key;
- for loot, checks the match was observed;
- locks the balance rows in a fixed order, so two calls can never deadlock;
- checks every ceiling that applies (the class's own and the platform-wide wildcard; the stricter wins);
- appends the entries, moves the cached balance and the items, records the budget row;
- 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/walletis the cached balances. - Inventory.
inventory_itemrows carry a quantity (for stackable items, up tomax_stack) or aunique_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/attrsand.../items/advance(a bounded increment). - Instanced items. An item listed under
instances.itemsineconomy.rulesis held one row per copy: every grant of it makes a new row with its ownunique_refand with attrs the economy rolled (a level, one primary stat, a few secondary stats), up toinstances.max_per_itemcopies. A player upgrades a copy withPOST /api/player/economy/instances/upgradeby 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/rulesdiscloses every weight, so a client shows the real chances beforehand, and the answer lists the weights each level used.POST .../instances/dismantleturns 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 withGET /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/purchasetakes 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/rollrolls a poolcounttimes. 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: afterafterconsecutive 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_matchif 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:
- 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. - 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). - 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.
Related pages¶
- How otomo works: the big picture
- Matchmaking and game servers: where match rosters come from.
- Config, Patch and content delivery: how the four documents are published.
- Show a player's items and craft with them
- Edit tables of game data
- Repository:
design/24-economy-and-session-behaviours.md,design/27-item-levels-and-external-periods.md,design/30-mission-facts.md,services/economy/README.md.