caelum0x f3917aad16 fix(game-economy): an abandoned cosmetic/pass reservation no longer blocks the player forever
A single-owner reservation outlived its purchase when the purchase failed and
the release did not land (a storage error) or the process died: nothing ever
expired it, so the player could never buy that cosmetic or pass again.

A reservation held longer than the TTL (GAME_RESERVATION_TTL_SECS, default 15
minutes) by a purchase that never completed is now taken over by a new
purchase, but only after Mint proves the old purchase can never charge: its
hold is opened (if it never was) and released under the old purchase's own
keys. If that hold was already captured, the old purchase paid and stays
reserved for its same-key retry. Takeover is a compare-and-swap on the holder
(Postgres UPDATE ... WHERE idem_key = old).

Tests: core abandoned_reservation (takeover charges once and the old key can
no longer capture; a recent reservation still blocks and touches nothing; a
paid old purchase keeps it and completes on retry), and the first live
Postgres tests of the adapter (exclusive reservations, holder-only moves,
8 concurrent takeovers -> one winner). 104 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:44:41 +03:00
..

game-economy

A standalone Railyard storefront for card packs, cosmetics, and battle passes. Prices are integer microdollars and every purchase uses Mint's hold → capture or release lifecycle.

The entitlement path is restart-safe:

  1. persist a principal/SKU/idempotency-key purchase intent;
  2. create the deterministic Mint hold;
  3. capture only after fulfillment succeeds, otherwise release;
  4. require Mint's signed AITP-Receipt on the terminal response;
  5. atomically commit the completed purchase and player inventory.

If the process stops after Mint captures but before the local commit, retrying the same purchase replays the same Mint keys and recovers ownership without a second charge. Two state backends implement GameStateRepository:

  • game-economy-store-postgres::PostgresGameState (set GAME_DATABASE_URL or DATABASE_URL) — multi-instance safe. Inventories are row-locked for every read-modify-write, single-owner reservations are rows keyed by (player, ownership_key), and purchase commits and refunds are single transactions. Migrations run at boot.
  • game-economy-store::JsonFileGameState (GAME_STATE_PATH) — atomic local durability for ONE process (desktop / single instance).

Refunds

POST /v1/refunds (game-server key) and the operator console's Refund button move the captured amount from the revenue account back to the player with a Mint transfer keyed <receipt_id>:refund, then atomically mark the purchase refunded and remove what it granted. Retrying never pays out twice. POST /v1/entitlements/revoke is the chargeback path: it removes the grant without moving money and marks the purchase revoked (it can no longer be refunded). Purchase history shows status (completed / refunded / revoked) plus the reversal record.

HTTP surface (game-economy-server)

Route Auth Purpose
GET /healthz, GET /v1/catalog public Liveness; SKUs with prices, odds tables and item pools
GET /store page Player storefront: shop, inventory, pack opening, receipt history
POST /v1/purchase player token Mint hold -> fulfillment -> capture -> signed receipt
POST /v1/packs/open player token Open an owned pack; the roll seed is server-committed (keyed by the server secret) and revealed in the response for audit — players cannot choose it
GET /v1/wallet/:player player token Mint balance + inventory in one read
GET /v1/inventory/:player player token Granted entitlements
GET /v1/purchases/:player[/:receipt_id] player token Receipt history / one receipt
POST /v1/tokens game-server key Issue an expiring player token
POST /v1/players game-server key Open a Mint account for a new player (store the returned id)
POST /v1/pass/advance game-server key Report the battle-pass tier a player earned
POST /v1/entitlements/revoke game-server key Chargeback: remove a purchase's grant, no money moved
POST /v1/refunds game-server key Refund through Mint, then remove the grant
GET /admin page Operator console: revenue/refund totals, purchases, player lookup, refund/revoke, pass tiers
GET /v1/admin/summary, GET /v1/admin/purchases, GET /v1/admin/players/:player admin token Console data
POST /v1/admin/refunds, POST /v1/admin/revoke, POST /v1/admin/pass/advance admin token Console actions
GET /v1/admin/catalog admin token Full catalog incl. archived SKUs + revision (console Catalog tab)
PUT /v1/admin/catalog/products/:sku admin token Create or update a product ({"product":{"CardPack":{...}},"expected_revision":N})
POST /v1/admin/catalog/products/:sku/archive admin token Archive / restore a SKU ({"archived":true}); archived SKUs leave the storefront but owned copies keep working
PUT /v1/admin/catalog/pools/:rarity admin token Replace a rarity's item pool ({"items":[...]})
POST /v1/iap/credit, POST /v1/iap/reverse game-server key Credit (or reverse) premium currency for a store-verified App Store / Play purchase; idempotent per transaction
POST /v1/iap/revenuecat RevenueCat webhook auth RevenueCat purchase/refund events -> credit/reverse

Full request/response contract, IAP setup and an Expo example: docs/HTTP-API.md. Drop-in TypeScript client (no deps): clients/ts/game-economy.ts.

The catalog is editable live. GAME_CATALOG_PATH only seeds the persisted catalog on first boot (Postgres tables game_catalog_*, or GAME_CATALOG_STATE_PATH JSON for a single instance); afterwards the console is the source of truth (GAME_CATALOG_RESEED=true overwrites it from the file). Every edit is re-validated as a whole catalog and saved with an optimistic revision check; other instances pick edits up within GAME_CATALOG_REFRESH_SECS. Products are archived, never deleted. Each purchased pack snapshots the odds it was sold under, a cosmetic's name and rarity (its item identity) are locked, and a battle pass can gain but never lose tiers. A catalog where a pack can roll a rarity with an empty item pool is rejected.

Server-to-server routes require X-Game-Server-Key: <GAME_SERVER_SECRET>; a player token is never accepted there, so players cannot advance their own pass.

Configuration: GAME_CATALOG_PATH (JSON: {"products":[{"CardPack":{...}}, ...], "pools":{"Common":[...]}}, validated at boot; GAME_CATALOG=demo serves the sample catalog), GAME_FULFILLMENT_URL + GAME_FULFILLMENT_SECRET (signed delivery webhook — capture happens only after it returns 2xx), GAME_SERVER_SECRET, GAME_TOKEN_TTL_SECS, GAME_ALLOW_LEGACY_TOKENS, GAME_ADMIN_TOKEN (operator console bearer token, at least 24 characters), GAME_DATABASE_URL, plus the Mint settings listed in crates/game-economy-server/src/main.rs.

cd apps/game-economy
cargo test --workspace --offline

The real HTTP adapter is game-economy-mint-client; tests exercise it against a local HTTP Mint contract and verify that locally synthesized receipts are never accepted as entitlement proof.