Sub topic 14
Exploits, Ledgers, and Safeguards
This chapter assumes you know sources, sinks, and the stock-and-flow balance from earlier chapters. It also assumes you can read short Python. It covers how players break an economy, how to record every currency change so you can detect and undo the damage, and which limits keep one bug from becoming permanent inflation.
What an exploit is
An exploit is any path that puts currency into the game faster than you designed, or lets players skip a sink. Your inflow model assumed a rate per hour of play. An exploit breaks that assumption for one player, or for everyone once the method spreads.
Exploits matter more than ordinary tuning errors because they scale with player cleverness, not play time. A loop that pays 30 coins per click can be repeated by a script all night. The extra currency also lowers the real cost of every item for everyone who holds it.
| Exploit class | Example | Main safeguard |
|---|---|---|
| Arbitrage loop | Craft a sword for 110, sell it for 140 | Check every buy, craft, and sell cycle before release |
| Replay or duplication | Send one "claim reward" request twice | Idempotency keys on every grant |
| Race condition | Two simultaneous spends from the same balance | Atomic balance changes on the server |
| Client trust | Modified client reports "quest complete" | Server decides what was earned |
| Botting | Automated farming of one source | Per-source caps, anomaly alerts |
| Multi-account | Alts feed currency to a main account | Transfer limits, linked-account checks |
| Refund abuse | Buy hard currency, spend it, charge back | Reversal entries, negative balances allowed |
Finding loops before players do
Most arbitrage comes from three places: a shop that buys items for more than it sells the ingredients for, a conversion rate that is not symmetric, and a reward that pays more than the activity's entry cost. Check every cycle on paper or in a script. The script below checks crafting recipes against shop prices.
buy = {"ore": 10, "ingot": 35, "sword": 120} # price the shop charges the player
sell = {"ore": 3, "ingot": 12, "sword": 140} # price the shop pays the player
recipes = [
{"output": "ingot", "inputs": {"ore": 3}, "fee": 0},
{"output": "sword", "inputs": {"ingot": 3}, "fee": 5},
]
for recipe in recipes:
cost = sum(buy[item] * n for item, n in recipe["inputs"].items()) + recipe["fee"]
profit = sell[recipe["output"]] - cost
status = "EXPLOIT" if profit > 0 else "ok"
print(recipe["output"], profit, status)The sword recipe prints a profit of 30, so a player can buy ingots, craft, and sell for free money. The fix is not always a price change. You can also add a crafting fee, a durability loss, or a sell price that is always below the buy price.
Run a check like this whenever prices, recipes, or conversion rates change. It is cheap, and a single typo in a price table can open a loop.
Why a ledger is the core safeguard
The Ledger class from earlier in this tutorial changes a balance and counts totals by reason. A production ledger has to do more:
- Keep an append-only list of entries. Never edit or delete one.
- Store the balance after each entry, so any entry can be checked.
- Accept a request ID with each change, so a repeated request does nothing.
- Enforce caps on sources, so a broken source has a bounded cost.
- Support an audit that replays the entries and compares the result with the stored balance.
from collections import defaultdict
from dataclasses import dataclass
class CapReached(Exception):
pass
@dataclass(frozen=True)
class Entry:
seq: int
kind: str
reason: str
amount: int
request_id: str
balance_after: int
class Ledger:
def __init__(self, daily_caps=None):
self.entries = []
self.balance = 0
self.daily_caps = daily_caps or {}
self.earned_today = defaultdict(int)
self._by_request = {}
def _apply(self, kind, reason, amount, request_id):
if request_id in self._by_request:
return self._by_request[request_id] # replay: return the original entry
if amount <= 0:
raise ValueError("amount must be positive")
if kind == "earn":
cap = self.daily_caps.get(reason)
if cap is not None and self.earned_today[reason] + amount > cap:
raise CapReached(reason)
self.balance += amount
self.earned_today[reason] += amount
else:
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
entry = Entry(len(self.entries) + 1, kind, reason, amount, request_id, self.balance)
self.entries.append(entry)
self._by_request[request_id] = entry
return entry
def earn(self, reason, amount, request_id):
return self._apply("earn", reason, amount, request_id)
def spend(self, reason, amount, request_id):
return self._apply("spend", reason, amount, request_id)
def new_day(self):
self.earned_today.clear()
def audit(self):
running = 0
for e in self.entries:
running += e.amount if e.kind == "earn" else -e.amount
if running != e.balance_after:
return False
return running == self.balance
wallet = Ledger(daily_caps={"daily_dungeon": 1000})
wallet.earn("daily_dungeon", 600, "req-1")
wallet.earn("daily_dungeon", 600, "req-1") # same request sent twice: ignored
print(wallet.balance) # 600
try:
wallet.earn("daily_dungeon", 600, "req-2")
except CapReached:
print("cap reached")
wallet.spend("repair", 100, "req-3")
print(wallet.balance, wallet.audit()) # 500 TrueThe second earn with req-1 returns the first entry and changes nothing. Network retries, double taps, and replayed packets all become harmless.
The ledger still cannot tell a legitimate request from a forged one. It only guarantees that whatever reaches it is applied once, is bounded, and is recorded.
Where the checks sit
Safeguards work in layers. Each layer catches what the one before it missed.
The client never says how much a player earned. It reports an action, and the server computes the reward from its own rules. Anything the client can set, a modified client can set to a large number.
Limits that bound the damage
Caps are the safeguard that works even when you do not know the exploit yet. If a source is capped per day, a bug in that source can add only the cap per account per day. Common limits:
- Per-source daily caps on repeatable rewards, such as a dungeon that pays currency.
- Diminishing returns where each repeat pays less, which is kinder than a hard stop.
- Transfer limits on gifts, trades, and mail between accounts, scaled to account age.
- Rate limits on how many claims one account can send per minute.
- Cooldowns on high-value actions.
Caps have a cost. A cap that is too low punishes your most engaged players, who are also the ones most likely to hit it. Set caps above what your fastest legitimate players earn. You can measure that rate in telemetry, as the chapter on live tuning describes.
A hard cap can also feel arbitrary. Show players the remaining amount so a cap reads as a rule, not a bug.
Detecting what the caps miss
Watch the ledger the way you watch server health:
- Total currency minted per source per hour, compared with the same hour last week.
- Per-account earn rate. Flag accounts far above the typical high-percentile rate, for example more than ten times the 99th percentile.
- Share of total currency held by the top accounts. A sudden jump means someone found a loop or a duplication bug.
- Rejected requests by reason. A spike in
CapReachedor duplicate request IDs often marks a bot or a client bug. - Audit failures. Any mismatch between replayed entries and stored balances is a defect in your own code.
Alerts need a human response plan, and the plan should be written before the first alert.
Responding to an exploit
- Stop the source. Disable the reward, shop item, or recipe with a server-side switch. The switch should not need a client update.
- Measure the damage from the ledger. Filter entries by reason and time window to find affected accounts and the amount minted.
- Correct with new entries. Add compensating
spendentries or reduce balances with a labeled reason. Never edit old entries, because that destroys the audit trail. - Handle spent currency. If players already turned the money into items, decide whether to remove the items, drain a sink, or accept the inflation. Document the choice.
- Tell players what happened and what you did. Silence reads as favoritism.
Common mistakes
- Validating prices on the client and trusting the result.
- Checking the balance and then writing it in two separate steps, which allows a race between simultaneous requests. Use one atomic operation, such as a database transaction.
- Capping sources but not conversions, so players use an uncapped path to bypass the cap.
- Adding a new currency or recipe without rerunning the loop check.
- Logging only totals. Without a reason and a request ID per change, you cannot reconstruct what happened.
Exercise
A dungeon pays 400 coins per run, capped at 1000 coins per day. A player's client sends the same "claim run 7" request three times because of a network retry. The request ID is the same each time. What is the ledger balance change after the three requests, and which safeguard produced that result?
Show answer
The balance rises by 400 once. The idempotency check returns the original entry for the second and third requests, so nothing is applied again. The daily cap was not involved, because only one grant reached it.
Exercise
A shop sells potions for 50 coins and buys them back for 40. A crafting recipe turns 2 herbs (buy price 15 each, sell price 5) plus a 10 coin fee into 1 potion. Is there a profitable loop that starts by buying herbs, crafting, and selling the potion? Show the numbers.
Show answer
Cost is 2 * 15 + 10 = 40 coins. The potion sells for 40 coins, so profit is 0. This is not profitable, but it has no margin. A small price change to herbs, the fee, or the potion buyback would turn it into a loop, so keep a gap between cost and sell price.