Economy, player stats, timers and claims

Use core player state for pools, balances, progression and custom numeric game values. Use EconomyService for money movement. The service couples balance changes to ledger records inside database transactions; assigning $stat->money directly bypasses those records.

Component Responsibility Resolve/access
App\Core\Models\PlayerStat One state row per account PlayerStat::getOrCreateForUser($userId)
App\Core\Services\EconomyService Transfers, cash/bank conversion, credit/debit, balances, audit app(EconomyService::class)
App\Core\Services\CurrencyRegistry Built-in and registered currencies app(CurrencyRegistry::class)
App\Core\Models\EconomyTransaction Ledger row and hash helpers Query the model; write through the economy service
App\Core\Services\TimerService Durable, atomic cooldowns (player_cooldowns) app(TimerService::class)
App\Core\Services\ClaimService Exactly-once reward claims (player_claims) app(ClaimService::class)
idempotent route middleware Idempotency-Key replay protection for money requests (idempotency_keys) ->middleware('idempotent')

Code below belongs in a booted backend service/controller/plugin handler. Values such as $user and $receiver refer to already authorized existing accounts. A service resolving successfully does not authorize the current player.

EconomyService

Transfer money

use App\Core\Services\EconomyService;

$tx = app(EconomyService::class)->transfer(
    $user,
    $receiver,
    'cash',
    250,
    'my-plugin.gift',
    ['note' => 'Welcome gift']
);

This example debits the sender's cash by 250, credits the receiver by 250 and returns one EconomyTransaction. It assumes adequate funds and distinct saved accounts. Currency is an integer unit; the service does not convert decimals, exchange rates or currencies.

Signature:

public function transfer(
    int|User $sender,
    int|User $receiver,
    string $currency,
    int $amount,
    string $actionType = 'transfer',
    array $metadata = []
): EconomyTransaction
Argument Meaning
sender, receiver Core User objects or account IDs. The service resolves stats from their IDs.
currency A key known to the currency registry: cash/money, bank, or a registered currency. Unknown keys throw UnknownCurrencyException (an InvalidArgumentException) before any balance or ledger row changes. Transfers also require the currency to be transferable.
amount Positive integer amount; zero and negatives are rejected.
actionType Ledger action label. It is descriptive metadata, not an authorization rule.
metadata JSON-compatible contextual values. There is no built-in idempotency check on these values.

The service rejects self-transfer and non-positive amounts with InvalidArgumentException. Insufficient funds raise RuntimeException. Database constraint failures may also throw. The HTTP controller translates caught operation failures into 422; calling PHP directly does not automatically turn exceptions into responses.

Player transfer limits

Since 1.0.4 every transfer between two players checks the player transfer rules (App\Core\Services\TransferLimitService::check()), inside the transfer transaction after both players' users and player_stats rows are locked. They govern the built-in cash/money and bank currencies only. Every rule is off in the engine; a game turns them on in its environment, and an admin can change each one later under Settings › Player Transfers (a saved value wins):

Setting key Environment value (config/economy.php, transfer_rules) Effect Off
transfer_min_level ECONOMY_TRANSFER_MIN_LEVEL The sender's level must be at least this 0
transfer_daily_send_cap ECONOMY_TRANSFER_DAILY_SEND_CAP Most one player sends to other players in any rolling 24 hours 0
transfer_daily_receive_cap ECONOMY_TRANSFER_DAILY_RECEIVE_CAP Most one player receives from other players in any rolling 24 hours 0
transfer_new_recipient_cooldown_minutes ECONOMY_TRANSFER_NEW_RECIPIENT_COOLDOWN_MINUTES The first payment to someone the sender never paid is refused and starts this clock 0

A refusal throws App\Core\Exceptions\TransferLimitException, which renders 422 with the rule. A payout path that does not call transfer() (a gang vault paying a member) must call check() itself; its docblock says how. Mafia: Underworld runs 5, 250000, 250000 and 10.

A player transfer that MariaDB picks as a deadlock victim (1213) is rerun from the start, up to three attempts (App\Core\Support\DeadlockRetry), when the transfer opened the transaction itself; inside a caller's transaction it runs once and the caller retries. Once the body has finished, a failure is never rerun: POST /api/v1/economy/transfer answers 409 outcome_unknown, so a resend with the same Idempotency-Key pays nothing twice, and 503 when every attempt deadlocked.

Execution and locking

The transfer starts a database transaction, locks both players' users rows and then both stats rows in ascending user-ID order, changes their balances, saves them and writes a ledger row. Missing stats rows are inserted with the model's starting values before they are locked.

The consistent lock order reduces deadlock risk. Initialization of previously missing rows still involves unique-row creation, so write tests for concurrent first-use and retry policy if your game depends on it. SQLite tests do not reproduce MariaDB row-lock semantics.

Every operation (transfer, deposit, withdraw, credit, debit) takes its locks in one order, whatever the currency: the users rows of the users involved, exclusively (FOR UPDATE), in ascending user-ID order; then their player_stats rows in ascending user-ID order; then any registered-currency balance rows (player_currency_balances) in ascending user-ID order; then the economy_ledger_heads row of each user the entry names, in ascending user-ID order, from which it takes prev_hash. The workspace lock order is therefore users → player_stats → balance rows → ledger heads, and users(user) is the per-user mutex: nothing in the service locks a user's player_stats row, balance row or head without holding it. Within one enclosing transaction you may mix currencies and call the service repeatedly for the same user in any order.

The rule for code that locks or writes a player's rows itself, in the same transaction as a payment:

  • Lock the player's users row with lockForUpdate() first, before you lock player_stats or any plugin state and before you insert or update any row that references the player (a claim, receipt, log or inventory row). Plugins already do this with User::whereKey($id)->lockForUpdate()->first(); PlayerActivityService and ClaimService do it in core.
  • Do not lock player_stats first and then pay. The service then asks for users while holding player_stats, the reverse of every users-first payer, and the two deadlock (1213).
  • Do not insert a row that references the player and only then pay. The insert's foreign key check takes a shared lock on users(player); when the service then asks for the exclusive lock while a concurrent payment for that player is already waiting for it, MariaDB reports a deadlock on the upgrade.
  • Touch the rows the service locks (balance rows and ledger heads) only through the service.

EconomyService::LOCK_ORDER names the order the running engine follows, so a package can check it instead of guessing from the version. 2 is the order above: users FOR UPDATE, then player_stats, then registered-currency balance rows, then ledger heads, each in ascending user ID. Engines without the constant follow the older order (player_stats, balance rows, heads, with users locked only by the ledger insert's foreign key check). GameKit 1.3.0 checks defined(EconomyService::class.'::LOCK_ORDER') && EconomyService::LOCK_ORDER >= 2 and reports itself degraded otherwise.

A payment to a user ID that has no users row fails, but at REPEATABLE READ (the server default, kept with DB_ISOLATION_LEVEL=server; the engine defaults to READ COMMITTED) its locking read of the missing row still takes a gap lock until the enclosing transaction ends. For an ID above the highest user ID that is the gap new users are inserted into, so registrations wait until then. Roll back promptly after such a failure rather than continuing the transaction.

Why users and why exclusive: every ledger insert already locks users for its foreign key check (and so does a fallback player_stats or head insert), so the service always locked users, only last, after player_stats. A plugin holding users and waiting for player_stats then deadlocked with a plain credit holding player_stats and waiting for users. Locking users first puts the existing lock where every plugin already takes it. A shared lock would have fixed that case but not code that pays and then locks users (activity listeners, achievements, quests): that upgrade from shared to exclusive deadlocks with a concurrent credit holding a shared lock. Across different users, keep a consistent user order in your enclosing transaction, as before; opposite orders can deadlock on MariaDB.

The head's locking read sees the latest committed entry even when the caller's transaction already fixed an older REPEATABLE READ snapshot. A plain SELECT for the previous entry did not, and concurrent entries forked the chain. User::created and the migration open one head per user; the service creates a missing head or balance row only as a fallback, inside the transaction and after player_stats is held, so for one user only one writer at a time creates them. A missing player_stats row cannot be covered by its own lock: the service inserts it with INSERT IGNORE before locking it, never locks the missing row first. First writers of different new users proceed without a deadlock, and now the first writers of one user already hold that user's users row, so they insert one at a time. Code that inserts player_stats rows around the service without that lock can still meet the shared-lock upgrade deadlock described in Common Errors, so a top-level retry is still worthwhile there.

Upgrading to the release that adds economy_ledger_heads: run its migration with the site down, or switch the code and migrate in one step with nothing writing in between. The migration backfills every head from the ledger once. An entry the old code writes after the backfill is missing from its user's head, and that user's next entry forks the chain permanently; the service trusts the head and does not repair it while running. The migration is safe to rerun after a partial failure: it skips an existing table and only inserts missing heads. The deploy sequence is:

php artisan down
php artisan migrate --force
php artisan pulse:ledger:audit --repair-heads --chains   # recompute heads, then report forks
php artisan up

--repair-heads recomputes every head from the ledger and refuses unless the application is in maintenance mode, because a head recomputed while writers run can be older than one the service just advanced. It rewrites heads only: it cannot undo a fork already written to the ledger. Those entries keep their prev_hash and --chains keeps reporting them, which is expected for forks created before this release.

WebSocket balance broadcasts are attempted inside the transaction. Exceptions from the broadcast helper are swallowed. A delivery is not an after-commit guarantee, and a missing WebSocket update does not establish that the transaction failed. Reload the persisted balance after an ambiguous response.

Deposit and withdraw

Method Arguments Result and effect
deposit(int|User $user, int $amount) Existing account, positive amount Moves money → bank, returns EconomyTransaction with action_type: deposit.
withdraw(int|User $user, int $amount) Existing account, positive amount Moves bank → money, returns EconomyTransaction with action_type: withdrawal.
use App\Core\Services\EconomyService;

$economy = app(EconomyService::class);
$deposit = $economy->deposit($user, 100);
$withdrawal = $economy->withdraw($user, 40);

Starting with cash 1,000 and bank 0, this sequence leaves cash 940 and bank 60. The two operations are individually transactional; they are not one combined transaction merely because they share a variable. Insufficient source balance throws.

Credit and debit

public function credit(int|User $receiver, string $currency, int $amount,
    string $actionType = 'mint', array $metadata = []): EconomyTransaction
public function debit(int|User $sender, string $currency, int $amount,
    string $actionType = 'sink', array $metadata = []): EconomyTransaction

credit() introduces currency: the ledger sender is null. debit() removes currency: the receiver is null. Each requires a positive integer and locks the affected stats row. Debit checks affordability; credit has no matching player debit.

Use credit for a validated reward or operator adjustment, and debit for a fee or sink. Neither method decides whether an item was earned or whether an actor is staff. Keep those decisions in your authorized handler.

Ledger-only balances (enforced)

money and bank are ledger balances. Change them only with credit, debit, transfer, deposit or withdraw; never assign $stats->money, call increment('money'), or pass 'money' => … to update(), fill(), create(), firstOrCreate() or similar. GameKit's consume()/award() route these two stats through EconomyService, so plugins may keep using them.

tests/Unit/LedgerOnlyMoneyWritesTest.php enforces the rule. It scans backend/app and every plugin search path present in the checkout (for example pulse-plugins mounted at app/Plugins/external), plus any roots in LEDGER_SCAN_PATHS. Tests, migrations, seeders, factories and frontend sources are skipped. The allowlist in the test holds only EconomyService, the PlayerStat models' new-row defaults and the bundled test harness. pulse-plugins runs the same scanner in CI (scripts/check-ledger-money-writes.php).

A balance write that passes the guard is not automatically safe. Read the state that decides a payout (holdings, claim flags, cooldowns) under the same lock as the payment, and check every consume()/award() result: they return success: false rather than throwing.

Plugin permissions

Every money-mutating service method calls PluginContext::assertPermission('ledger.write'). An active plugin needs that capability or an accepted alias such as economy.write or ledger.read_write. Operator-approved permissions in registry configuration can override manifest claims.

The guard is active only when execution has entered a plugin context. Plugin HTTP routes enter their plugin's context automatically, and hook listeners run in the context of the plugin that registered them. Jobs, commands and other code outside a request have no context unless they call PluginContext::run(). With no context, the assertion passes as core code. It is not a PHP sandbox or a substitute for checking the requesting user's role, ownership or permission. See plugin contexts and security.

Currencies

App\Core\Services\CurrencyRegistry (an application singleton) decides which currency strings the economy accepts. Before it existed, every string except bank silently moved cash.

Key Storage Notes
money (alias cash) player_stats.money Built in, transferable.
bank player_stats.bank Built in, transferable.
Registered key, e.g. gems One player_currency_balances row per user and currency (unique(user_id, currency), unsigned big-integer balance) Declared in config or registered at boot.

Register a currency from a plugin or game kit boot(). Your code calls core; core never imports your plugin:

use App\Core\Services\CurrencyRegistry;

app(CurrencyRegistry::class)->register('gems', [
    'label' => 'Gems',
    'transferable' => false,    // default true; false blocks player-to-player transfer()
    'max_balance' => 1_000_000, // optional cap on credit and incoming transfer
]);

Or declare it in config/economy.php:

'currencies' => [
    'tokens' => ['label' => 'Event Tokens', 'transferable' => true],
],

Keys are 1–32 characters: a lowercase letter, then a-z, 0-9, _, . or -. Matching is exact, so Gems is unknown. money, cash and bank cannot be redefined. A register() call replaces a config entry with the same key. The registry starts empty in every process, so register in boot(), which queue workers also run. If the plugin that registers a currency is disabled, calls using that currency throw; stored balances are kept.

Every currency uses the same calls:

$economy = app(EconomyService::class);
$economy->credit($user, 'gems', 50, 'my-plugin.daily_reward');
$economy->debit($user, 'gems', 20, 'my-plugin.shop');
$gems = $economy->balance($user, 'gems'); // 30

balance(int|User $user, string $currency): int reads without a lock. For a built-in currency it uses getOrCreateForUser(); for a registered one, a missing row reads as 0. Do not rely on it as the check before a debit: debit() checks again under the lock.

Ledger rows store the currency string exactly as passed, as before (cash and money stay as given), and that string is part of the row hash. A registered-currency change broadcasts economy.currency_balance_updated with currency and balance. Built-in changes still broadcast economy.balance_updated with money and bank.

Built-ins lock the users row and then the player_stats row. A registered currency also locks the users and then the player_stats rows first (ascending user ID), then creates any missing balance row with the driver-portable insertOrIgnore inside the transaction, where the player_stats lock already serialises the same user's first writers. It then locks the balance rows with lockForUpdate() in ascending user-ID order. A balance that would exceed max_balance or the PHP integer range throws RuntimeException.

The HTTP transfer and admin-adjust endpoints still accept only cash/bank. Expose a registered currency through your own authorized endpoint.

Model configuration

The default stats class is App\Core\Models\PlayerStat. getPlayerStatModel() checks the optional config key economy.player_stat_model before using that default. config/economy.php ships only the currencies list, so a custom provider still supplies the model key.

An invalid configured class raises RuntimeException. A replacement needs compatible columns and getOrCreateForUser() semantics; class existence alone does not validate that contract. Core must not import a concrete plugin stats model.

EconomyTransaction

Fields

Field Purpose
id, uuid Database identifier and transaction UUID.
sender_id, receiver_id Nullable account references; null represents the system side.
currency, amount, action_type Money unit label, integer amount and action label.
sender_balance_after, receiver_balance_after Recorded post-operation balances.
prev_hash, tx_hash Previous selected hash and current SHA-256 hash.
metadata Array-cast context.
created_at Datetime-cast creation timestamp. UPDATED_AT is disabled.

sender() and receiver() return BelongsTo relationships to core User. Either related account can be null after deletion; the foreign keys use set null.

Hash methods

Method Inputs Returns / behaviour
computeHash(): string Current instance attributes SHA-256 of UUID, sender, receiver, currency, amount, action type and prev_hash joined by |. Null sides use SYSTEM; null previous hash uses GENESIS.
isVerified(): bool Current instance Constant-time comparison of computed hash with tx_hash.
createWithHash(array $attributes): self Transaction attributes Adds/generates UUID and hash, then inserts. Lower-level helper; normal money movement uses the service.

The hash does not cover balance-after fields, metadata, creation time or every database attribute. UPDATED_AT = null expresses the intended append-only workflow but does not block Eloquent update() or delete(). Do not describe this as database-enforced immutability.

Audit limits

$report = $economy->verifyLedgerIntegrity($user);

Returns user_id, total_transactions, valid_count, tampered_count, tampered_ids, integrity_pass. It recomputes each selected row's own hash. It does not independently reconcile account balances, detect deleted rows, establish external authenticity, or verify that every prev_hash links to the actual expected preceding row. Hashes can be recomputed by someone with write access.

verifyLedgerChains($user) (read-only) checks the links: it walks the user's entries in id order with the three predecessor rules below, reports every entry whose prev_hash is not its predecessor's hash as a fork (forks), and compares the user's economy_ledger_heads row with the latest entry for each rule (stale_heads, head_missing). It returns chains_pass. pulse:ledger:audit --chains runs it for every audited user and fails on any fork or stale head.

The service selects a previous transaction differently across transfer/deposit/withdraw (the sender's latest entry in either role), credit (the receiver's latest entry as receiver) and debit (the sender's latest entry as sender); economy_ledger_heads stores the latest hash for each of those three chains per user. Treat this audit as row-tamper evidence for covered fields, not a complete global ledger reconciliation. The CLI pulse:ledger:audit wraps auditing; check its actual options in command reference.

PlayerStat

Stored state and defaults

player_stats.user_id is unique and references users.id with cascade deletion. The model's user() returns BelongsTo.

Fields Initial values / casts
energy, max_energy 100, 100; integers
nerve, max_nerve 15, 15; integers
health, max_health 100, 100; integers
money, bank 1,000, 0; integer casts, unsigned big-integer schema
level, exp 1, 0; integers
strength, defense, speed, dexterity 10 each; integers
custom_attributes Array cast; initialized to [] by the helper
last_tick_at Datetime; initialized to now by the helper
id, created_at, updated_at Standard Eloquent identifiers/timestamps

Get or initialize

use App\Core\Models\PlayerStat;

$stats = PlayerStat::getOrCreateForUser($user->id);
$energy = $stats->energy;

getOrCreateForUser(int $userId): self returns the existing row or persists a new one with defaults. It is a write-capable lookup and can fail for a nonexistent account ID. User creation does not itself guarantee this row exists.

Custom attributes

$stats->setCustomAttribute('my_plugin.reputation', 12)->save();
$reputation = $stats->getCustomAttribute('my_plugin.reputation', 0);

getCustomAttribute(string $key, mixed $default = null): mixed returns a value or default. setCustomAttribute(string $key, mixed $value): self changes the in-memory JSON map and returns the same stats model; it does not save until you call save().

Namespace keys for your plugin. Concurrent whole-map updates may overwrite each other, so use your own locked data model when several actions can update the same logical value. Money must use EconomyService, not custom JSON attributes.

Progression

Method Behaviour
getExpNeededForNextLevel(): int Uses a saved progression.exp_needed formula override when available; otherwise max(100, level * 100). Formula errors fall back.
checkAndApplyLevelUp(): bool Repeatedly spends required EXP, increases level and max pools, refills energy/health, saves if level changed; returns whether a level changed.
regenerate(int $energyGain = 5, int $nerveGain = 1, int $healthGain = 5): bool Adds gains up to current maxima, updates tick timestamp and saves every call. Returns whether any pool changed.

Each level adds max energy 5, max nerve 2 and max health 10. Nerve capacity increases but the method does not refill current nerve. EXP is remaining progress after spending each threshold, not an ever-increasing total.

regenerate() is a single opportunity to regenerate; it does not infer missed elapsed ticks or schedule itself. It does not reject negative gain arguments. Validate tuning values and avoid concurrent unlocked regeneration/consumption writes. See operations for scheduler and queue responsibilities.

Compatibility accessors

Property Getter / setter methods Stored field
experience getExperienceAttribute(), setExperienceAttribute(int $value) exp
nerve_max getNerveMaxAttribute(), setNerveMaxAttribute(int $value) max_nerve
energy_max getEnergyMaxAttribute(), setEnergyMaxAttribute(int $value) max_energy
health_max getHealthMaxAttribute(), setHealthMaxAttribute(int $value) max_health

Getters return integers; setters return void and update the in-memory raw stored attribute. Alias properties do not create extra database columns or automatically persist changes.

Timers and cooldowns

TimerService stores cooldowns in the player_cooldowns table: one row per user and key (unique(user_id, cooldown_key)), with available_at as a Unix timestamp. The database is the source of truth, so a cache or Redis flush does not reset cooldowns. The player argument can be an object with id or a positive user ID. Use a stable plugin-prefixed key such as my-plugin.scan (1 to 191 characters).

Gate an action with tryStart()

When a cooldown protects an action (attack, crime, training, travel), claim it with tryStart() before doing the work. Do not call isActive() and then setTimer(): two concurrent requests can both pass that check.

use App\Core\Services\TimerService;

$timers = app(TimerService::class);

if (! $timers->tryStart($user, 'my-plugin.scan', 60, ['target' => $targetId])) {
    return response()->json([
        'message' => 'Scan is cooling down.',
        'retry_after' => $timers->remaining($user, 'my-plugin.scan'),
    ], 429);
}

// Only one request reaches this point per 60 seconds.

tryStart() returns true for exactly one caller. It runs insertOrIgnore for the row, then one guarded UPDATE ... SET available_at = now + seconds WHERE user_id = ? AND cooldown_key = ? AND available_at <= now and checks that one row was affected. The database serialises concurrent updates to the same row, so the loser matches no row. The same SQL runs on SQLite and MariaDB. Expiry is inclusive: at available_at the cooldown is over.

If the action fails after a successful tryStart() and the player should not pay the cooldown, call clear(). If the action and the cooldown must commit together, call tryStart() inside the same DB::transaction() as the action, so a rollback releases the cooldown too.

Method Returns / effect
tryStart($player, string $key, int $seconds, ?array $metadata = null): bool Atomic claim. true when this call started the cooldown; false while one is active. Throws InvalidArgumentException for non-positive seconds.
setTimer($player, string $key, int $seconds, ?array $metadata = null): void Unconditional upsert that replaces any running cooldown. A non-positive duration clears it. Not a claim.
isActive() / hasActiveTimer($player, string $key): bool True while available_at is later than now.
remaining() / getRemainingSeconds($player, string $key): int Nonnegative remaining seconds; 0 when absent or expired.
clear() / clearTimer($player, string $key): void Deletes the row.
getActiveTimers($player): array Active cooldowns keyed by key, soonest first. Each entry has key, available_at, remaining_seconds and metadata.
pruneExpired(): int Optional housekeeping that deletes expired rows. Rows are reused per key, so the table grows with distinct keys, not with attempts.

The original method names are kept for compatibility. Rows are deleted with their user (cascadeOnDelete).

One-time reward claims

App\Core\Services\ClaimService::claimOnce() pays a reward at most once per player, scope and key: daily rewards, achievement rewards, quest turn-ins, referral milestones, event prizes. It inserts a player_claims row (unique(user_id, scope, claim_key)) and runs your grant in one database transaction:

  • A duplicate or concurrent claim cannot insert a second row. On MariaDB the second insert waits for the first transaction, then loses. It runs no grant and gets the stored result back.
  • If the grant throws, the claim row rolls back with it, so the player can retry.
use App\Core\Services\ClaimService;
use App\Core\Services\EconomyService;

$claim = app(ClaimService::class)->claimOnce(
    $user,
    'my-plugin.daily',        // scope: 1 to 64 characters
    now()->toDateString(),    // key: 1 to 191 characters (date, achievement ID, quest ID...)
    function () use ($user) {
        $tx = app(EconomyService::class)->credit($user, 'cash', 500, 'daily_reward');

        return ['amount' => 500, 'transaction_id' => $tx->id];
    },
);

if (! $claim->claimed) {
    return response()->json(['message' => 'Already claimed.', 'reward' => $claim->result], 409);
}
Member Meaning
ClaimResult::$claimed true only for the call that ran the grant. wasReplayed() is its negation.
ClaimResult::$result The grant's return value after a JSON round trip, the same shape on the first call and on replay. A result that cannot be encoded (NAN, a resource) throws InvalidArgumentException and rolls back.
ClaimResult::$claimedAt When the winning claim was made.
hasClaimed($player, $scope, $key): bool Read-only check for UI. Never gate a payout on it; use claimOnce().
claimedKeys($player, $scope): array Keys claimed in a scope, oldest first.

Rules for the grant:

  • Do all of the grant's work through the database: EconomyService, Eloquent or the query builder. Then it commits or rolls back with the claim. EconomyService transactions nest as savepoints.
  • Run external side effects (broadcasts, mail, webhooks, third-party APIs) after commit, for example with DB::afterCommit(). They cannot be rolled back.
  • Choose keys that name the reward, not the request. A daily reward keyed by date can be claimed once per day. An achievement keyed by its ID can be claimed once ever.

Idempotent money requests

POST /api/v1/economy/transfer, /deposit and /withdraw accept an optional Idempotency-Key header: 1 to 191 visible ASCII characters, for example a UUID the client creates for each user action. The generic idempotent route middleware (App\Core\Http\Middleware\EnforceIdempotency) handles it, backed by the idempotency_keys table.

Situation Response
First request with a key Runs normally. Status and body are stored for economy.idempotency_ttl_seconds (default 86400, env ECONOMY_IDEMPOTENCY_TTL).
Retry with the same key, method, path and input The stored status and body, with the Idempotent-Replayed: true header. The action does not run again. Stored 4xx outcomes, such as insufficient funds, are replayed too.
Same key with a different payload or endpoint 422 idempotency_key_reused. The client must use a new key.
Retry while the first request is still running, or after it crashed part-way 409 idempotency_in_progress, Retry-After: 2. The mutation never runs twice.
The key was released between this request's reservation and its lookup 409 idempotency_released, Retry-After: 1.
First request returned 5xx or threw The key is released, so a retry runs again.
Missing key on an idempotent:required route 400 idempotency_key_required.
Malformed key 400 idempotency_key_invalid.

Every refusal is JSON {"success": false, "message": "...", "error": "<code>"}. Match on error; the message text and the status codes are kept as they were for older clients.

error Status message Retry-After
idempotency_key_required 400 An Idempotency-Key header is required for this request. none
idempotency_key_invalid 400 Idempotency-Key must be 1 to 191 visible ASCII characters. none
idempotency_key_reused 422 This Idempotency-Key was already used for a different request. none
idempotency_in_progress 409 A request with this Idempotency-Key is still being processed. 2
idempotency_released 409 This Idempotency-Key was released; retry the request. 1

The two 409 codes are an unknown outcome: the first request may still commit, or may already have. Wait Retry-After seconds and resend the same key with the same body, so a finished request replays instead of running again. Never mint a new key for them. A key left by a crashed request stays in progress until it expires, so cap the resends, then reload the persisted state before offering the action again. The codes are constants on EnforceIdempotency (ERROR_*, RETRY_AFTER_*_SECONDS).

Keys are scoped per user. Input is compared after its keys are sorted recursively, so JSON key order and whitespace do not matter. Requests without the header behave as before.

Other mutation routes can opt in with ->middleware('idempotent') (optional header) or ->middleware('idempotent:required') (400 when the header is missing). Put it on authenticated routes: requests without a user pass straight through.

HTTP operations and debugging

Authenticated routes under /api/v1/economy: GET /ledger, POST /transfer, POST /deposit, POST /withdraw, GET /audit. The transfer endpoint validates currencies as cash/bank, positive amounts and an existing receiver. POST /api/v1/admin/economy/adjust uses the admin-group route gate; inspect actual middleware before assuming a narrower privilege.

Troubleshoot in order: validated account IDs → account authorization → plugin context capability → source balance → stats schema/class → transaction exception → persisted balances → transport update. A frontend timeout does not prove that nothing happened: retry a money mutation only with the same Idempotency-Key.

Sources and checks

  • EconomyService declarations
  • PlayerStat declarations and storage fields
  • EconomyTransaction
  • TimerService
  • App\Core\Services\ClaimService, App\Core\Support\ClaimResult, App\Core\Http\Middleware\EnforceIdempotency
  • Database definitions, API route definitions

Focused existing tests: EconomyServiceTest, EconomyCurrencyRegistryTest, PlayerStatTest, PluginContextTest, TimerServiceTest, ClaimServiceTest, EconomyIdempotencyTest. The concurrency tests simulate the losing side of a race by pre-inserting the winner's row. They establish tested cases, not a proof of concurrent production-driver behaviour. See testing.