Python theorytheory 0/50 · 0%
Capstone · hard

46. Simulating a token ledger (design)

Modeling balances, transfers, and invariants with plain Python.

A simple in-memory ledger models balances as a dict and transfers as validated state transitions, which mirrors (in miniature) how a blockchain's state transition function works.

python
class Ledger:
    def __init__(self):
        self.balances: dict[str, float] = {}

    def mint(self, to: str, amount: float) -> None:
        self.balances[to] = self.balances.get(to, 0) + amount

    def transfer(self, frm: str, to: str, amount: float) -> None:
        if self.balances.get(frm, 0) < amount:
            raise ValueError("insufficient balance")
        self.balances[frm] -= amount
        self.balances[to] = self.balances.get(to, 0) + amount

An important invariant: total supply (sum of all balances) should only change on `mint`/`burn`, never on `transfer`. Testing this invariant after each operation catches logic bugs early — the same principle underlies real smart contract auditing.

Check your understanding

  1. 1. What invariant should hold after any `transfer` call?

  2. 2. What does `self.balances.get(frm, 0)` protect against?

  3. 3. Why raise ValueError on insufficient balance rather than allowing negative balances?