t1k:unity:dots-core:economy
| Field | Value |
|---|---|
| Module | dots-core |
| Version | 3.56.1 |
| Effort | medium |
| Tools | — |
How to invoke
Section titled “How to invoke”/t1k:unity:dots-core:economyDOTS 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,WalletSettlementModeandItemPurchaseSystem, are absent from theunity-dots-librarybaseline that port was built against (grep -rlE "TryApplyAndQueue|WalletSettlementMode|ItemPurchaseSystem" --include='*.cs'over the whole package: 0 files;WalletSystemandWalletTransactionexist). These sections describe a newer library: verify against your pinned library version before writing code against them; seereferences/single-owner-managed-ledger.md§ “Version note”.
Package:
com.the1studio.dots-economy— namespaceDOTSEconomy(.Production,.Storage,.Salesub-namespaces) Verified againstdots-economy0.9.0 (paired withdots-core12.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.IAPis merely an enum value; it buys nothing. Real purchase flow, receipt validation, and restore live inAssets/TheOneFeature/(IIapServices→UITemplateIapServices) pluscom.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.
When This Skill Triggers
Section titled “When This Skill Triggers”- 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
Quick Setup
Section titled “Quick Setup”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.
Cross-Package Interactions
Section titled “Cross-Package Interactions”| Direction | Package | Detail |
|---|---|---|
| Depends on | DOTSCore | EconomySystemGroup parent; WallClock singleton for regen timestamps |
| Depends on | DOTSInventory (ordering only) | EconomySystemGroup runs after InventorySystemGroup |
| Used by | DOTSCombat | Loot drops write WalletTransaction.Delta > 0 (Source=Loot) |
| Used by | DOTSProgression | Quest rewards, idle income, battle-pass grants |
| Used by | DOTSBridges | Analytics bridge drains CurrencyEarnedEvent/CurrencySpentEvent |
| Produces into | DOTSCore.Logistics | ProductionTickSystem appends CarrySpawnRequest on cycle completion — see the dots-core:logistics skill |
| NOT here | Assets/TheOneFeature/ + com.gdk.3rd | IAP purchase flow, receipt validation, restore. This package has none of it. |
System Order Inside EconomySystemGroup
Section titled “System Order Inside EconomySystemGroup”| Order | System | Note |
|---|---|---|
before ProductionTickSystem | ProductionCopyToAllSystem | Two-pass: collect every request payload, then apply |
| — | ProductionTickSystem | Consumes inputs, advances Elapsed, emits output |
before WalletSystem | SaleSystem | Sell side: consumes stock, appends WalletTransaction (credit) |
before WalletSystem | ItemPurchaseSystem | Buy side: deposits into the hopper, appends WalletTransaction (debit) |
| — | WalletSystem | Sole owner of balance, ledger and earned/spent events |
| — | EnergyRegenSystem → EnergyConsumeSystem | Regen 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)].
Hard rules
Section titled “Hard rules”WalletLedgeris 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.WalletTransactionwith aCurrencyDefIdnot in theWalletEntrybuffer:WalletSystemlogs anApplied=falseledger row and continues silently. Always seed every currency you plan to spend inWalletAuthoring.InitialBalances.WalletTransaction.Quantityis unit COUNT, and0means “not applicable” — never “zero units”.DeltafoldsUnitPrice × Countinto one money value, andSaleSystemclears theSaleRequestbuffer in the same frame, so the unit count is unrecoverable downstream unless it is recorded at the source — dividing it back out ofDeltadoes not work, because the price varies and can be modified.SaleSystemsets it fromSaleRequest.Count;WalletSystemmirrors it ontoCurrencyEarnedEvent.Quantity/CurrencySpentEvent.Quantity. Most sources (Quest, IAP, Idle, Admin, …) grant a bare currency amount and leave it0. An analytics / achievement / telemetry consumer counting “items sold” MUST treat0as 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-economynever derives it;DeltaandQuantityare two independent facts recorded once, at the source. Added 2026-08-11, additively — all existing producers use object-initializer syntax and keep compiling, defaulting to0.EnergyRegenSystemrequiresWallClocksingleton. It declaresstate.RequireForUpdate<WallClock>()— the system is SKIPPED entirely untilWallClockis published (W2.3WallClockSystem). In tests, injectWallClockmanually or the regen never runs.EnergyRegenSystemstampsLastRegenUnixTimestamp = nowUtcwhen 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.EnergyRegenSystemTHROWS when the pool has noEnergyRegeneratedEventbuffer (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 withEnergyAuthoring(which always adds the buffer) or add the buffer alongsideEnergyyourself. The throw isInvalidOperationException, 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.EnergyRegenSystemre-anchors the stamp when the clock moves BACKWARDS (since 0.9.0). A device clock change or an NTP correction used to leaveLastRegenUnixTimestampin 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.EnergyConsumeSystemruns AFTEREnergyRegenSystem. 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 = 0is legal:WalletSystemapplies it (no-op balance), raises no event, but still writes aWalletLedgerrow withApplied=true. Useful for probe/audit entries.- Spend sign:
Deltamust be NEGATIVE for a debit.WalletTransaction.Delta > 0earns;< 0spends. Do not passMath.Abs(cost)— pass-costdirectly. WalletEntry.Amountislong(64-bit). Idle/meta-progression games routinely exceedint.MaxValuein soft currency. Never cast tointfor display; uselongthroughout until the final UI string format step.- A game whose balances live in a cloud-contract JSON save must NOT make the ECS
Walletthe owner. Keep one managed ledger (synchronous, atomic, never negative), one document writer, and treatWalletEntryas 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 nextRebuild. Pattern, invariants, the compiled-code writer check and the pinned-library version note:references/single-owner-managed-ledger.md(WarShip phase 11).
Production / Storage / Sale
Section titled “Production / Storage / Sale”- This package ships NO IAP.
WalletTransactionSource.IAPis an enum value and nothing more. Purchase flow, receipt validation and restore live inAssets/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.TryConsumeis atomic only for the single item it targets.ProductionTickSystempre-checks all inputs viaGetCountfirst, then consumes — a short hopper leavesElapsedat 0 and the slot stalls visibly rather than part-consuming. A stalled building is legible; silently eaten inputs are not. ProductionSlotisIEnableableComponent— disabled means IDLE, not absent. Queries that need to find idle buildings (e.g. copy-to-all targets) must passEntityQueryOptions.IgnoreComponentEnabledState, or they will only ever see already-running buildings.ProductionTickSystemsubtractsCycleSecondsfromElapsed; it never hard-resets to 0. Adtlarger than the remainder must not be discarded or the timing harness drifts. Awhileloop handles several cycles completing inside one lagged frame — so a long frame can legitimately produce multiple items at once.BatchUtility.StepWRAPS,BatchUtility.Clampdoes not.Stepis the+/−stepper (99+1 → 1, 1−1 → 99). For a programmatic absolute set, useClamp— 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
ProductionSloton every matching-BuildingKindentity, not just those already running. That is the intended affordance, but it means one click can start every oven you own. SaleRequest.UnitPriceis trusted as supplied —SaleSystemnever recomputes it. Recomputing the price at the sale site would reopen a known design trap. Whoever builds the request owns the price.SaleSystemnever touchesWalletEntrydirectly. It appends aWalletTransactionand runsUpdateBefore(WalletSystem), which owns balance, ledger and events. Selling stock the entity does not hold is rejected byTryConsume— no transaction, no stock change, silently, per request.- Use
ProductionSlot.ResetCycle()on any recipe change — neverElapsed = 0falone.CycleStartedis what distinguishes “no cycle attempted” from “in progress atElapsed == 0”. A slot switched mid-cycle with a bareElapsed = 0fkeepsCycleStarted == 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()zeroesElapsedand clearsCycleStarted. Inputs the discarded cycle already consumed are not refunded. (Added 0.9.0 afterTinyTerraceshit this on its lever recipe swap.) TieredUpgradeState.EffectValueis CUMULATIVE per tier, not an increment. Buying tier 2 means tier 2’s value alone applies, nevertier1 + tier2. The built-in effect systems derive the effect from the current tier’s value alone (viaTieredUpgradeEffectResolver), 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 authored250 / 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.TieredUpgradePurchaseRequestis a single present-but-disabled slot: a second write before the system runs overwrites the first and a paid grant is lost. CallTieredUpgradePurchaseQueue.AddRequesterComponentsonce when building the wallet entity (it adds the slot disabled + the queue buffer), thenTieredUpgradePurchaseQueue.Enqueue(...)per grant.Enqueuemakes 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 throwsInvalidOperationExceptionif the requester was never built withAddRequesterComponents; 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.TieredUpgradePurchaseQueueSystemdrains one entry per frame, lowestTierIndexfirst (ties keep arrival order). WalletUtility.TryApplyAndQueueis the ONE settlement idiom this package’s buy/sell systems share — do not hand-roll apply-then-append. It applies the delta throughTryApplyDelta(overflow guard included) and only on success appends the transaction stampedWalletSettlementMode.PreApplied, soWalletSystemledgers 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 raiseCurrencyInsufficientEvent— that isWalletSystem’s, on theDeferredpath only.- Reaching the wallet from Mono/non-ECS code: use
WalletRequesterLocator.ResolveRequester, and treat the three states separately. ItsWalletResolveResultisNotFound = 0(“no wallet yet” — normal before bootstrap),Resolved = 1, andMultipleHolders = 2(a wiring defect). Aboolwas not enough because “none yet” and “more than one” must not look the same. OnMultipleHoldersit 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).TryGetRequesteris the thin bool wrapper when you only care about the happy path. EnergyAuthoring.SecondsPerUnit = 0disables regen — deliberately, end to end. Authoring ([Min(0)]),Energy.CreateSeeded(passes it through) andEnergyRegenSystemall read<= 0as “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 —
EffectValueis a magnitude,TieredUpgradePurchaseSystemappends aDelta = 0audit row. The auditWalletTransaction(Source = IAP,Reference= the SKU) exists only soWalletSystem’s existing ledger picks the grant up. If you need the purchase to cost currency, settle the price yourself (viaTryApplyAndQueue) — the tiered-upgrade system will not charge for you.
Buy side — ItemPurchaseRequest / ItemPurchaseSystem
Section titled “Buy side — ItemPurchaseRequest / ItemPurchaseSystem”ItemPurchaseRequest.UnitPriceis CALLER-RESOLVED — the library deliberately owns no price table. Exactly likeSaleRequest.UnitPriceandProduction.AutomationUnlockPurchaseRequest.Cost. A price table is game content;dots-economyholding 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: noItemDefinitionBlobdependency, 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/InvalidItemRowoutcome — onlyInvalidRequest. Those two would need catalogue knowledge the library structurally cannot have.InvalidRequestcovers pure request-shape validation only:Count < ItemPurchaseConstants.MinCount(1) orUnitPrice < 0. An unknown or unpurchasableItemDefIdis the caller’s job to reject upstream — the system treatsItemDefIdas 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 aDynamicBufferlikeSaleRequest. 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.TryDepositruns BEFORE theWalletTransactionis 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 isInsufficientFunds— 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 viaWalletUtility.GetBalanceto decide the outcome now rather than waiting a frame forWalletSystemto 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
longthroughout —CoinsCharged,UnitPrice, matchingWalletTransaction.Delta. Any future currency-type unification must merge towardlong. Reward buffers that useinttruncate silently in the other direction — an idle/meta economy routinely exceedsint.MaxValuein soft currency. - Never multiply
UnitPrice * Countinline — callItemShopCostUtility.ComputeTotalCost(long, int). It clamps tolong.MaxValueinstead 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 settlingInvalidRequestfirst. ItemShopCostUtility.ClampCost(double)exists because a directdouble → intcast is UNDEFINED in C# for out-of-range values and silently yieldsint.MinValue— again a free or crediting item. Narrow every authoreddoublecost 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.ItemPurchaseResultEventis 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 thedots-core:logisticsskill for the haul loop in between. StorageUtilityis a linear scan with a-1sentinel, mirroringWalletUtility. 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.MaxTotalItemsis a total across ALL item types, not per-type — and it is enforced only byStorageUtility.TryDeposit.TryConsumeand direct buffer writes ignore it entirely, so any code path that adds stock without going throughTryDepositcan silently exceed the cap.