Picture an online role-playing game (RPG) with a player marketplace, where players buy and sell swords and armor from each other for Gold. Gold can be earned, bought with real money, traded and spent, but it never cashes out. Most backends for a game like this start with a gold column on the players table. The quest service adds to it, the shop subtracts from it, and the trade service does both inside a database transaction. The careful version of the shop's update is UPDATE players SET gold = gold - 100 WHERE id = $1 AND gold >= 100, so nobody goes below zero.
That column holds a total, and each update changes one number without recording its counterpart. You can sum it across players, but you can't ask the economy where any of that Gold came from.
Say you ship a patch on Tuesday. By Thursday a mid-tier sword costs three times what it did, and your economy designer wants to know how much Gold entered the game since the patch, and through which door. Quest rewards, a new login bonus, a refund script somebody ran by hand? SUM(gold) says supply is up. Nothing in the schema says why.
Mental model: faucets, wallets, and sinks
Game economy designers describe a closed-loop economy with two words: faucets, where currency enters, and sinks, where it leaves. A ledger adds two more: wallets, where players hold currency, and holds, where currency is reserved but not yet settled.
- Faucets are where Gold enters: a real-money top-up, a quest reward, a login bonus. Give each door its own faucet and you can measure each one.
- Wallets belong to players and are the only place a player spends from. They never go below zero.
- Sinks are where Gold leaves circulation: store purchases, repair costs, the marketplace fee. A sink only receives.
- Holds are Gold reserved for a pending trade. It's out of what the buyer can spend, but nobody has received it yet.
Every movement has a source, a destination, an amount, and a reference your game controls: one quest completion, one store receipt, or one trade gets one reference. The ledger refuses a second movement with the same reference, which turns a retry or a replayed webhook into a no-op instead of free Gold.
Because each movement takes from one place what it gives another, all balances sum to zero. Faucets go negative by exactly what they've issued, so circulating supply is issued - absorbed, and it must equal the sum of the player wallets. If those disagree, Gold moved outside the model.
Setting up the ledger
We'll use Blnk Core, our open-source ledger, but the same structure works on Postgres. Wallets live in a ledger of their own, tagged with the player id from your game:
const ledger = await blnk.Ledgers.create({ name: "Player Wallets" });
async function createWallet(playerId: string) {
return blnk.LedgerBalances.create({
ledger_id: ledger.data.ledger_id,
currency: "GOLD",
meta_data: { player_id: playerId },
});
} {
"balance_id": "bln_0a7e3c91-5d2b-4f68-b1e4-7c9a2d6f3e15",
"ledger_id": "ldg_4f1c2a9e-8b3d-4e07-a2c6-9d5e1f7b3a80",
"currency": "GOLD",
"balance": 0,
"inflight_balance": 0,
"meta_data": {
"player_id": "plr_ada"
}
} Gold is whole-number, so every transaction below uses precision: 1, and precise_amount: 100 means 100 Gold. Faucets and sinks don't belong to a player, so they're internal balances with an @ prefix, which Blnk creates the first time a transaction names them. We'll use @GameTreasury and @QuestPool as faucets, and @ItemSink and @MarketplaceFees as sinks.
Top-ups: the same receipt can't pay twice
A top-up handler runs UPDATE players SET gold = gold + 500 when the app store confirms a purchase. Stores retry notifications your server doesn't acknowledge, so if your handler is slow and doesn't answer in time, the retry arrives and the player gets 1,000 Gold for one purchase.
On the player row, the fix is an idempotency table keyed on the store's transaction id. That's a second write you have to commit in the same database transaction as the credit, in every place Gold enters. On the ledger, the movement is the dedupe:
async function creditTopUp(walletId: string, storeTxnId: string, gold: number) {
return blnk.Transactions.create({
precise_amount: gold,
precision: 1,
currency: "GOLD",
reference: `topup_${storeTxnId}`,
source: "@GameTreasury",
destination: walletId,
allow_overdraft: true,
});
} Blnk requires a unique reference on every transaction and discards a request whose reference is already in the ledger, so the retried notification records nothing. allow_overdraft is on faucets only, because they start at zero and have to go negative to issue Gold. Wallets never get it. A quest reward is the same call from @QuestPool, with a reference like quest_${playerId}_${questId}.
Spending Gold and granting the item
A purchase is the same movement in reverse: wallet to @ItemSink, with your order id as the reference. Blnk checks the wallet's available balance before it records anything, and locks the balance first, so two concurrent purchases can't both spend the same 100 Gold.
await blnk.Transactions.create({
precise_amount: price,
precision: 1,
currency: "GOLD",
reference: `order_${orderId}`,
source: walletId,
destination: "@ItemSink",
meta_data: { kind: "store_purchase", sku, order_id: orderId },
}); By default Blnk answers QUEUED and a worker applies the transaction, or rejects it if the wallet can't cover the price. So you grant the sword when the outcome arrives, not when you post. A POST_TRANSACTION hook calls your endpoint once a transaction is applied or rejected. Filter on the meta_data you set, and make the grant idempotent on the transaction id, because Blnk retries a failed delivery:
app.post("/blnk/hooks/post", async (req, res) => {
const { transaction_id, data } = req.body;
if (data.meta_data?.kind === "store_purchase") {
if (data.status === "APPLIED") {
// Unique on transaction_id, so a retried delivery grants nothing twice.
await inventory.grantOnce(transaction_id, data.meta_data.sku);
} else if (data.status === "REJECTED") {
await orders.markFailed(data.meta_data.order_id, data.meta_data.blnk_rejection_reason);
}
}
res.sendStatus(200);
}); A PRE_TRANSACTION hook looks like the place to enforce rules such as "banned players can't buy", but in Core's source the call is queued and the transaction doesn't wait for your answer. Keep game rules in your own server, before you post.
Player trades: hold, move, settle
In our RPG, a seller lists a sword for 400 Gold and a buyer accepts. The Gold lives in your ledger, but the sword lives in an inventory service, so one database transaction can't cover both. Move the Gold first and a failed item transfer leaves the buyer paying for nothing. Move the item first and a failed Gold update leaves the seller giving it away.
And if the buyer can spend the same 400 Gold in the store while the trade is pending, you've created Gold. Duplication exploits around trading are a real problem in live games: in 2021 Amazon switched off player-to-player gold transfers in New World while it investigated one.
What you want is an escrow, which Blnk models as an inflight transaction: the amount is recorded on inflight fields, and the main balances don't move until you commit or void. A trade has three steps:
Hold the Gold
When the buyer accepts, open an inflight transaction from the buyer's wallet to the seller and
@MarketplaceFees. The 400 Gold leaves what the buyer can spend, and the seller can't spend it yet either.Move the sword
Your inventory service transfers the item. This part is your code, outside the ledger.
Settle the hold
If the sword moved, commit: the seller receives 380 Gold and
@MarketplaceFeesreceives the 20 Gold fee, which is a sink. If the transfer failed, void: the buyer keeps all 400. If your service crashes between steps, the hold'sinflight_expiry_datevoids it for you.
The fee is a second destination on the same transaction, so the seller's share and the fee are held and released together:
async function openTrade(trade: Trade) {
const fee = Math.max(1, Math.floor(trade.price * 0.05));
const hold = await blnk.Transactions.create({
precise_amount: trade.price,
precision: 1,
currency: "GOLD",
reference: `trade_${trade.id}`,
source: trade.buyerWalletId,
destinations: [
{ identifier: "@MarketplaceFees", precise_distribution: String(fee) },
{ identifier: trade.sellerWalletId, distribution: "left" },
],
inflight: true,
inflight_expiry_date: "2026-12-10T09:40:00+00:00",
atomic: true,
});
// Save the root id. It commits or voids every leg of the split.
await trades.saveHoldId(trade.id, hold.data.transaction_id);
} While the trade is held, the main balances haven't moved:
| Balance | balance | inflight_debit_balance | inflight_credit_balance |
|---|---|---|---|
| Buyer | 1,000 | 400 | 0 |
| Seller | 250 | 0 | 380 |
| @MarketplaceFees | 0 | 0 | 20 |
The buyer can still spend 600 Gold in the store, but not the 400 that's promised. Once the inventory service answers, commit or void the hold:
async function settleTrade(tradeId: string, itemMoved: boolean) {
const holdId = await trades.getHoldId(tradeId);
return blnk.Transactions.updateStatus(holdId, {
status: itemMoved ? "commit" : "void",
});
} On the default queue this returns INFLIGHT with queued: true until a worker finishes, so wait for the transaction.applied or transaction.void webhook before you tell both players the trade is done.
One note on the fee. A 5% distribution rounds down at precision 1: we ran Core's split code, and a 37 Gold trade splits 36 and 1, while a 19 Gold trade pays no fee at all. If every trade should pay at least 1 Gold, compute the fee yourself and send it as a precise_distribution, as above.
Reading the supply
Back to Thursday. Each faucet's debit_balance is everything it has issued, and each sink's credit_balance is everything it has absorbed, so your designer's question is a read:
const quest = await blnk.LedgerBalances.getByIndicator("@QuestPool", "GOLD");
console.log(quest.data.debit_balance); // total Gold issued by quests Read the same balance at the patch time with historical balances and subtract to get "since Tuesday". To hear about it before the market does, a balance monitor on a faucet's debit_balance sends a webhook when issuance crosses a threshold you choose. If every faucet looks normal but the wallets grew anyway, Gold moved outside the ledger, and that's a bug to find.
The gold column can stay on the player row as a cached display value for the HUD (the heads-up display players see in-game). The ledger stays the source of truth for every faucet, wallet, sink, and hold, and it is where you go when Thursday comes. To try the model on a running ledger, start with Blnk Cloud or run Blnk Core locally.