Skip to content

t1k:unity:dots-core:economy

FieldValue
Moduledots-core
Version3.56.1
Effortmedium
Tools—
/t1k:unity:dots-core:economy

DOTS Economy — Wallet, Energy, Production, Storage & Sale

Section titled “DOTS Economy — Wallet, Energy, Production, Storage & Sale”

Version caveat (at the time of the WarShip port, 2026-10-11): the library APIs this text names, WalletUtility.TryApplyAndQueue, WalletSettlementMode and ItemPurchaseSystem, are absent from the unity-dots-library baseline that port was built against (grep -rlE "TryApplyAndQueue|WalletSettlementMode|ItemPurchaseSystem" --include='*.cs' over the whole package: 0 files; WalletSystem and WalletTransaction exist). These sections describe a newer library: verify against your pinned library version before writing code against them; see references/single-owner-managed-ledger.md § “Version note”.

Package: com.the1studio.dots-economy — namespace DOTSEconomy (.Production, .Storage, .Sale sub-namespaces) Verified against dots-economy 0.9.0 (paired with dots-core 12.1.0, 2026-09-28). Re-check the version before trusting a signature after a library bump. Assembly: DOTSEconomy.Runtime (runtime), DOTSEconomy.Authoring (bakers) Group: EconomySystemGroup (SimulationSystemGroup, after InventorySystemGroup) API reference: references/economy-api.md

⚠️ This package ships Wallet + Energy + Production + Storage + Sale — and NO IAP. WalletTransactionSource.IAP is merely an enum value; it buys nothing. Real purchase flow, receipt validation, and restore live in Assets/TheOneFeature/ (IIapServices → UITemplateIapServices) plus com.gdk.3rd. Reading this package as “the monetisation layer” has already cost this project a mis-scoped wave — check the platform layer before planning IAP work.

  • Implementing multi-currency wallets (gold, gems, event tokens) on player/entity
  • Building spend/earn flows with audit trail or analytics bridge
  • Handling “not enough currency” rejection with UI feedback
  • Implementing energy/stamina/hearts with real wall-clock regen (accrues while app is closed)
  • Draining energy before a level/dungeon action and reacting to success or rejection
  • Building a producer/crafting building that consumes inputs on a timed cycle and emits goods
  • Batch counts on a +/− stepper, or a “copy this recipe to every building of this kind” affordance
  • Per-entity stock hoppers (StoredItem) and selling stock for currency
  • Buying an item from a shop — spend coins, deposit units into the buyer’s hopper

Code examples for: wallet + energy authoring, earning/spending currency via the WalletTransaction buffer, querying balance (Burst-safe), consuming energy, reacting to CurrencyEarnedEvent same-frame, setting up a production building (recipe/cycle/inputs — inputs consume from the entity’s OWN StoredItem hopper, output enters the world as a CarrySpawnRequest, never a currency delta directly), the batch stepper (wraps) vs programmatic clamp, copying a recipe to every building of the same kind, the storage hopper (StorageUtility.TryConsume/TryDeposit), selling stock (runs BEFORE WalletSystem, which owns the ledger), and BUYING an item from a shop (ItemPurchaseRequest — a present-but-disabled component, not a buffer; caller-resolved UnitPrice; deposit-then-spend so a full hopper is never charged). Full code for each: references/quick-setup-examples.md.

DirectionPackageDetail
Depends onDOTSCoreEconomySystemGroup parent; WallClock singleton for regen timestamps
Depends onDOTSInventory (ordering only)EconomySystemGroup runs after InventorySystemGroup
Used byDOTSCombatLoot drops write WalletTransaction.Delta > 0 (Source=Loot)
Used byDOTSProgressionQuest rewards, idle income, battle-pass grants
Used byDOTSBridgesAnalytics bridge drains CurrencyEarnedEvent/CurrencySpentEvent
Produces intoDOTSCore.LogisticsProductionTickSystem appends CarrySpawnRequest on cycle completion — see the dots-core:logistics skill
NOT hereAssets/TheOneFeature/ + com.gdk.3rdIAP purchase flow, receipt validation, restore. This package has none of it.
OrderSystemNote
before ProductionTickSystemProductionCopyToAllSystemTwo-pass: collect every request payload, then apply
—ProductionTickSystemConsumes inputs, advances Elapsed, emits output
before WalletSystemSaleSystemSell side: consumes stock, appends WalletTransaction (credit)
before WalletSystemItemPurchaseSystemBuy side: deposits into the hopper, appends WalletTransaction (debit)
—WalletSystemSole owner of balance, ledger and earned/spent events
—EnergyRegenSystem → EnergyConsumeSystemRegen always settles before consume

Outside the group: TieredUpgradePurchaseSystem runs in SimulationSystemGroup ([UpdateBefore(EconomySystemGroup)]) with TieredUpgradePurchaseQueueSystem before it — so its zero-delta audit row reaches WalletSystem the same frame, and the two built-in effect systems run [UpdateAfter(TieredUpgradePurchaseSystem)].

  • WalletLedger is append-only; the library ships no trimmer. Ledger grows indefinitely. Add your own trim system after draining for analytics — keep only the last N entries or forward to a server and clear.
  • WalletTransaction with a CurrencyDefId not in the WalletEntry buffer: WalletSystem logs an Applied=false ledger row and continues silently. Always seed every currency you plan to spend in WalletAuthoring.InitialBalances.
  • WalletTransaction.Quantity is unit COUNT, and 0 means “not applicable” — never “zero units”. Delta folds UnitPrice × Count into one money value, and SaleSystem clears the SaleRequest buffer in the same frame, so the unit count is unrecoverable downstream unless it is recorded at the source — dividing it back out of Delta does not work, because the price varies and can be modified. SaleSystem sets it from SaleRequest.Count; WalletSystem mirrors it onto CurrencyEarnedEvent.Quantity / CurrencySpentEvent.Quantity. Most sources (Quest, IAP, Idle, Admin, …) grant a bare currency amount and leave it 0. An analytics / achievement / telemetry consumer counting “items sold” MUST treat 0 as no count available and skip the row — treating it as a real zero silently under-counts every sale that predates a producer setting the field. The producer owns this value. dots-economy never derives it; Delta and Quantity are two independent facts recorded once, at the source. Added 2026-08-11, additively — all existing producers use object-initializer syntax and keep compiling, defaulting to 0.
  • EnergyRegenSystem requires WallClock singleton. It declares state.RequireForUpdate<WallClock>() — the system is SKIPPED entirely until WallClock is published (W2.3 WallClockSystem). In tests, inject WallClock manually or the regen never runs.
  • EnergyRegenSystem stamps LastRegenUnixTimestamp = nowUtc when pool is at cap. This prevents a “free burst” on first consume — a player at cap who consumes 1 doesn’t immediately regen from epoch-0 backlog.
  • EnergyRegenSystem THROWS when the pool has no EnergyRegeneratedEvent buffer (since 0.9.0). It used to regenerate silently with no event, so a HUD listening for the event never learned the pool changed — the pool moved and nothing could observe it. Bake pools with EnergyAuthoring (which always adds the buffer) or add the buffer alongside Energy yourself. The throw is InvalidOperationException, raised before any branch, so a resource-regen entity assembled by hand is a hard failure on the first regen tick rather than a quiet one.
  • EnergyRegenSystem re-anchors the stamp when the clock moves BACKWARDS (since 0.9.0). A device clock change or an NTP correction used to leave LastRegenUnixTimestamp in the future, freezing regen until real time caught up — hours or days after a large correction. It now resets the stamp to the new “now” and resumes from there. Do not “fix” this by clearing the stamp to 0: that reintroduces the epoch-0 backlog burst the cap stamp exists to prevent.
  • EnergyConsumeSystem runs AFTER EnergyRegenSystem. A regen tick that brings the pool from 0 to 1 on the same frame as a consume request of 1 will SUCCEED (the intended happy path; tested).
  • Delta = 0 is legal: WalletSystem applies it (no-op balance), raises no event, but still writes a WalletLedger row with Applied=true. Useful for probe/audit entries.
  • Spend sign: Delta must be NEGATIVE for a debit. WalletTransaction.Delta > 0 earns; < 0 spends. Do not pass Math.Abs(cost) — pass -cost directly.
  • WalletEntry.Amount is long (64-bit). Idle/meta-progression games routinely exceed int.MaxValue in soft currency. Never cast to int for display; use long throughout until the final UI string format step.
  • A game whose balances live in a cloud-contract JSON save must NOT make the ECS Wallet the owner. Keep one managed ledger (synchronous, atomic, never negative), one document writer, and treat WalletEntry as a one-way projection of it; credits that exist only in ECS are lost at the next rebuild, and a debit that bypasses the ledger resurrects at the next Rebuild. Pattern, invariants, the compiled-code writer check and the pinned-library version note: references/single-owner-managed-ledger.md (WarShip phase 11).
  • This package ships NO IAP. WalletTransactionSource.IAP is an enum value and nothing more. Purchase flow, receipt validation and restore live in Assets/TheOneFeature/ + com.gdk.3rd. Do not scope monetisation work against this package.
  • A multi-input recipe must pre-check EVERY input before consuming ANY of them. StorageUtility.TryConsume is atomic only for the single item it targets. ProductionTickSystem pre-checks all inputs via GetCount first, then consumes — a short hopper leaves Elapsed at 0 and the slot stalls visibly rather than part-consuming. A stalled building is legible; silently eaten inputs are not.
  • ProductionSlot is IEnableableComponent — disabled means IDLE, not absent. Queries that need to find idle buildings (e.g. copy-to-all targets) must pass EntityQueryOptions.IgnoreComponentEnabledState, or they will only ever see already-running buildings.
  • ProductionTickSystem subtracts CycleSeconds from Elapsed; it never hard-resets to 0. A dt larger than the remainder must not be discarded or the timing harness drifts. A while loop handles several cycles completing inside one lagged frame — so a long frame can legitimately produce multiple items at once.
  • BatchUtility.Step WRAPS, BatchUtility.Clamp does not. Step is the +/− stepper (99+1 → 1, 1−1 → 99). For a programmatic absolute set, use Clamp — wrapping an absolute set would silently turn “set to 250” into an in-range number instead of rejecting it.
  • Copy-to-all STARTS its targets. It enables a previously-idle ProductionSlot on every matching-BuildingKind entity, not just those already running. That is the intended affordance, but it means one click can start every oven you own.
  • SaleRequest.UnitPrice is trusted as supplied — SaleSystem never recomputes it. Recomputing the price at the sale site would reopen a known design trap. Whoever builds the request owns the price.
  • SaleSystem never touches WalletEntry directly. It appends a WalletTransaction and runs UpdateBefore(WalletSystem), which owns balance, ledger and events. Selling stock the entity does not hold is rejected by TryConsume — no transaction, no stock change, silently, per request.
  • Use ProductionSlot.ResetCycle() on any recipe change — never Elapsed = 0f alone. CycleStarted is what distinguishes “no cycle attempted” from “in progress at Elapsed == 0”. A slot switched mid-cycle with a bare Elapsed = 0f keeps CycleStarted == true, so the new recipe’s first cycle runs on the old recipe’s already-consumed inputs and consumes nothing — a free output, once per switch. ResetCycle() zeroes Elapsed and clears CycleStarted. Inputs the discarded cycle already consumed are not refunded. (Added 0.9.0 after TinyTerraces hit this on its lever recipe swap.)
  • TieredUpgradeState.EffectValue is CUMULATIVE per tier, not an increment. Buying tier 2 means tier 2’s value alone applies, never tier1 + tier2. The built-in effect systems derive the effect from the current tier’s value alone (via TieredUpgradeEffectResolver), so a tier’s authored value must already include every earlier tier’s contribution: storage tiers that conceptually mean “+250, then +500 more, then +1000 more” are authored 250 / 750 / 1750. Both built-in effect systems reject a zero or negative value with an error. A tier table authored as increments yields the last increment as the whole bonus, silently.
  • A grant source that can fire twice in one frame must Enqueue — never write the request slot directly. TieredUpgradePurchaseRequest is a single present-but-disabled slot: a second write before the system runs overwrites the first and a paid grant is lost. Call TieredUpgradePurchaseQueue.AddRequesterComponents once when building the wallet entity (it adds the slot disabled + the queue buffer), then TieredUpgradePurchaseQueue.Enqueue(...) per grant. Enqueue makes no structural change — deliberately, because it runs inside a store SDK completion callback where moving the wallet entity to a new archetype is a sync point. It throws InvalidOperationException if the requester was never built with AddRequesterComponents; that is the intended failure, because the alternatives are a paid grant in a buffer nothing drains or a structural change inside a store callback. TieredUpgradePurchaseQueueSystem drains one entry per frame, lowest TierIndex first (ties keep arrival order).
  • WalletUtility.TryApplyAndQueue is the ONE settlement idiom this package’s buy/sell systems share — do not hand-roll apply-then-append. It applies the delta through TryApplyDelta (overflow guard included) and only on success appends the transaction stamped WalletSettlementMode.PreApplied, so WalletSystem ledgers it and raises the event without re-applying. Both buffers are untouched on failure. Use it when you must know the outcome on the same frame (a store callback, a synchronous UI read). It does not raise CurrencyInsufficientEvent — that is WalletSystem’s, on the Deferred path only.
  • Reaching the wallet from Mono/non-ECS code: use WalletRequesterLocator.ResolveRequester, and treat the three states separately. Its WalletResolveResult is NotFound = 0 (“no wallet yet” — normal before bootstrap), Resolved = 1, and MultipleHolders = 2 (a wiring defect). A bool was not enough because “none yet” and “more than one” must not look the same. On MultipleHolders it logs one error and returns — it never picks a winner and never throws, because every caller is a store callback or the grant-readiness gate in front of one (skills/t1k-library-decoupling/references/third-party-decoupling.md (theonekit-core)‘s warn + skip contract). TryGetRequester is the thin bool wrapper when you only care about the happy path.
  • EnergyAuthoring.SecondsPerUnit = 0 disables regen — deliberately, end to end. Authoring ([Min(0)]), Energy.CreateSeeded (passes it through) and EnergyRegenSystem all read <= 0 as “regen disabled”, so a purchase/reward-only pool is a supported design. Before 0.9.0 the field was [Min(1)] and the intent was silently repaired at bake time. Do not add a clamp.
  • Tiered upgrades carry NO currency movement — EffectValue is a magnitude, TieredUpgradePurchaseSystem appends a Delta = 0 audit row. The audit WalletTransaction (Source = IAP, Reference = the SKU) exists only so WalletSystem’s existing ledger picks the grant up. If you need the purchase to cost currency, settle the price yourself (via TryApplyAndQueue) — the tiered-upgrade system will not charge for you.

Buy side — ItemPurchaseRequest / ItemPurchaseSystem

Section titled “Buy side — ItemPurchaseRequest / ItemPurchaseSystem”
  • ItemPurchaseRequest.UnitPrice is CALLER-RESOLVED — the library deliberately owns no price table. Exactly like SaleRequest.UnitPrice and Production.AutomationUnlockPurchaseRequest.Cost. A price table is game content; dots-economy holding one would be the same naming-charter failure as owning a recipe catalogue. The caller resolves the price from its own item catalogue — and validates purchasability there — before writing the request. This is the whole reason a complete, symmetric buy side fits in this package at all: no ItemDefinitionBlob dependency, no injected content blob, nothing to bake. Do not “improve” this by adding a lookup; that reopens the catalogue-seam trap.
  • Consequently there is NO NotPurchasable / InvalidItemRow outcome — only InvalidRequest. Those two would need catalogue knowledge the library structurally cannot have. InvalidRequest covers pure request-shape validation only: Count < ItemPurchaseConstants.MinCount (1) or UnitPrice < 0. An unknown or unpurchasable ItemDefId is the caller’s job to reject upstream — the system treats ItemDefId as opaque and will happily buy it. If you need “this row is not for sale”, enforce it at the call site.
  • The request is a present-but-disabled IComponentData, not a DynamicBuffer like SaleRequest. At most ONE in-flight purchase per entity per frame. Enable it to submit; the system disables it on drain regardless of outcome. Queuing N purchases in one frame is not expressible — submit them across frames, or over N entities. (This asymmetry with the sell side is deliberate: it is what makes the synchronous balance read race-free, see below.)
  • Deposit-then-spend, never spend-then-deposit. StorageUtility.TryDeposit runs BEFORE the WalletTransaction is enqueued, and only a successful deposit proceeds to the spend — so a full hopper is never charged for goods it could not receive (StorageFull, nothing debited). The wallet balance is still pre-checked read-only first, so when both a shortfall and a full hopper hold, the outcome is InsufficientFunds — the missing coin is the more actionable player-facing message.
  • The synchronous balance read is safe only because of [UpdateBefore(WalletSystem)] + the single-request shape. The system reads the CURRENT balance via WalletUtility.GetBalance to decide the outcome now rather than waiting a frame for WalletSystem to reject it. Nothing has drained the balance yet this frame, and one present-but-disabled component means no second read can race the first. Change either fact (move the system, or convert the request to a buffer) and you reintroduce a double-spend window.
  • Currency amounts are long throughout — CoinsCharged, UnitPrice, matching WalletTransaction.Delta. Any future currency-type unification must merge toward long. Reward buffers that use int truncate silently in the other direction — an idle/meta economy routinely exceeds int.MaxValue in soft currency.
  • Never multiply UnitPrice * Count inline — call ItemShopCostUtility.ComputeTotalCost(long, int). It clamps to long.MaxValue instead of wrapping. A wrapped-negative product reads as a free, or wallet-crediting, purchase. It assumes both inputs are already non-negative, which the system guarantees by settling InvalidRequest first.
  • ItemShopCostUtility.ClampCost(double) exists because a direct double → int cast is UNDEFINED in C# for out-of-range values and silently yields int.MinValue — again a free or crediting item. Narrow every authored double cost column (csv-baked catalogues) through it. Only the clamping math is generic here; the catalogue it clamps is not, which is why this utility ships and a price table does not.
  • ItemPurchaseResultEvent is present-but-disabled too, and holds only the MOST RECENT settlement. Read it in the same frame (or before the next request settles); it is not a queue.
  • Production emits goods into the WORLD, not into the wallet. Cycle completion appends DOTSCore.Logistics.CarrySpawnRequest; currency is credited only later at the sale step, downstream of delivery. See the dots-core:logistics skill for the haul loop in between.
  • StorageUtility is a linear scan with a -1 sentinel, mirroring WalletUtility. That is deliberate — a hopper holds a handful of distinct item types, and a hashmap would lose cache locality. Do not “optimise” it without a measurement.
  • StorageCapacity.MaxTotalItems is a total across ALL item types, not per-type — and it is enforced only by StorageUtility.TryDeposit. TryConsume and direct buffer writes ignore it entirely, so any code path that adds stock without going through TryDeposit can silently exceed the cap.