Project: a PSB's day, closed against its settlement account
Replay a payment service bank's week one day at a time, tie its wallets to its settlement account through the switch, and find the two postings a balanced day hides
You close one generated week for S01, the payment service bank (PSB) of Lumora Mobile in the lab’s payment network. S01 holds 602 customer wallets and 60 agent float wallets. It also holds a settlement account, where the net positions of NIP, the NIBSS Instant Payment service, are paid. This project is the finance-operations end of module 7: what a PSB is, and what it may not do, is the chapter Payment service banks, and Mobile money operators covers the other kind of wallet provider. Here you do its arithmetic. The week is the same generated week as module 6, Monday 15 to Sunday 21 June 2026, and its data is in labs/finance/data/rails.sqlite.
The lab is a model. The switch’s sessions and cut-offs, the fees, the cash-out tariff, the response codes and the balances are the generator’s, written to teach. None of them is NIBSS’s, the CBN’s or any bank’s, and nothing here says what a real PSB charges or when a real settlement happens.
Acceptance
The project is done when all of this holds on your run of the whole week:
- Every day closes. For each of the seven days the equation below balances to the kobo, with no difference left unexplained.
- Everything outside the wallets matches. All 512 NIP postings (256 credits, 254 payouts and 2 reversals) match the switch’s transfers, all 21 statement rows match both the switch’s positions and the ledger’s own totals, and, once the double charge is corrected, no wallet goes below zero.
- Both planted breaks are found and none invented. The answer key lists two for S01 at seed 42: the cash-out posted twice and the cash-out fee not posted. A third kind of break, an inflow credited with no settlement, is planted elsewhere in the network. At this seed the generator plants four of them, at B19, B07 and B23, none at S01, so it is not an S01 break here. Where a planted break lands depends on the seed, so a different seed can move it onto S01 or off it, and the acceptance test is the count in your own key, not the number two, and
accept.pyreads that count from the key. After you correct them in memory, every day still closes and a second search finds nothing.
What you build
Six small files in labs/finance, next to rails.py. They read data/rails.sqlite read-only and write nothing.
| File | Job |
|---|---|
psbkit.py |
Reads S01’s tables, prints kobo as naira, replays the ledger, holds the lab’s cash-out tariff |
replay.py |
Day-by-day wallet totals, and a search for postings that repeat |
match.py |
S01’s NIP postings against the switch’s transfers; the statement against the switch’s positions |
close.py |
The day-close equation |
breaks.py |
The two finders, the fee proof, the proposed corrections, and the answer key |
accept.py |
The three acceptance checks |
A seventh, status.py, is a short test of a rule the key does not list: which wallet statuses may move cash.
What “closed” means
A PSB’s wallets are what it owes: each balance is money a customer or an agent can claim. Against that it holds a settlement account, and a cash float held by agents that is not on its books at all. The rails move money through the settlement account only for NIP. A cash-in at an agent moves value from the agent’s float wallet to the customer’s wallet, and a cash-out moves it back. Neither touches the bank. So the wallets and the settlement account do not move together day by day, and a close has to say how they relate. The lab’s settlement account opens at ₦900,000,000.00 while the wallets total ₦31,344,534.00, so their levels do not tie and are not meant to: the account is a model input, and a real PSB’s holdings against customer money are set by its licence and its regulator’s rules, which this project does not test. What the close tests is that every change in the wallets is explained.
It says so with one equation, from double entry: assets move by what liabilities and income move.
change in wallets = change in settlement account + NIP money in transit - fees S01 kept
Each term has its own source. The wallets come from replaying psb_ledger onto the opening balances in psb_wallets, so they are S01’s own record. The settlement account comes from psb_settlement_statement, the bank’s record. The money in transit comes from the switch: for each NIP posting, transfers says which settlement session carries it, and settlement_sessions says when that session settles. A posting made by the close of day and settled after it is in transit. The fees come from the ledger’s fee column. If S01 lost a NIP posting, the wallets would be short by an amount the other terms still hold, and the equation would not balance. That is what the equation is for.
Money in transit
A NIP transfer credits the beneficiary at once. The banks settle afterwards, in sessions, so for a while the wallet has moved and the settlement account has not.
A NIBSS helpdesk article, as search results show it, describes NIP as a deferred net settlement system in which the beneficiary’s account is credited in real time, before settlement is doneas of 2026-11. Sources disagree on the schedule: that article, as summarised, gives two cut-overs a day, another NIBSS page refers to 12 settlement sessions, and a 2025 case study describes four a day. This chapter therefore gives none as real, and the lab’s four sessions are illustrative. The chapter How banks settle with each other works through sessions and netting on the same week.
In the lab a session settles an hour after its cut-off (04:00, 10:00, 14:00 and 18:00 on business days), and a transfer settles in the first session whose cut-off follows the moment it became final. Anything after 18:00 on a Friday, and everything on Saturday and Sunday, settles on Monday. At the close of each day S01 has some NIP money in transit: a net figure, positive when more money is waiting to arrive than to leave. By Sunday night the settlement account has not moved since Friday evening, and the in-transit line carries the weekend. The first thing you will see in the close is that the in-transit figure is never zero, and that it is not an error.
A balanced day can hide errors
The equation balances for a ledger with errors in it. A cash-out is posted to a customer’s wallet and to an agent’s float. If it is posted twice, the customer is charged twice and the agent’s float is credited twice. The wallets total changes by the fee only, since the amount leaves one wallet and enters another, and the fee is counted as income on the right of the equation. A fee left off a cash-out changes the wallets total and the fee total by the same amount. So both errors are invisible to the equation. This is the central lesson of the project: a total that balances is evidence about the totals, and an error that touches two sides equally does not show in it.
The errors need tests of their own, and each test starts from knowledge about the thing. A posting repeated in every field except its id is a duplicate whatever the amount. A fee is a function of the amount under the PSB’s tariff, so a fee that is not that function is a finding. In the lab, breaks.py finds both. The two are also the only two the answer key plants for S01.
Failed payouts and reversals
S01’s customers send NIP payouts too. A payout that fails at the switch has debited the customer, so the wallet must be repaid. The close checks that every failed payout has its nip_out_reversal, and counts a payout not yet repaid by the close as money in transit, a debit that is neither settled nor returned.
The CBN’s Regulation on Instant (Inter-Bank) Electronic Funds Transfer Services in Nigeria, effective 2 October 2018 according to search results (one entry gives 20 October), is a PDF on the CBN’s site. Search summaries and law-firm notes say the sending entity must refund the proceeds of a failed transaction returned by the receiving entity within 10 minutes (and one it was unable to process within one hour after the next settlement closure), that a wrongly credited transfer is reversed within one business day where funds are available, that funds delivered within 60 seconds mark a payment as instant, that settlement is as agreed among participants but no later than T+1, the next business day, and that a failed transfer not reversed within 24 hours of a complaint attracts a fine of ₦10,000 per item; the summaries do not reconcile the 10-minute and 24-hour clocks. This chapter did not open the regulation, so every figure rests on those summariesas of 2026-11. Read the text, and anything issued since, before using any such time as a rule. The lab does not test either clock: its two reversals both come 40 seconds after the payout. The chapter Debited but not credited covers the sender’s side of a timeout and states these figures with the same caveats. In the lab week S01 has two failed payouts, both refused by the receiving bank with 07 (no such account, here a closed one), and both are repaid within the day, so no payout is open at any close, but the check is there for the week where one is.
What the model leaves out
State the gaps before you trust the result.
- Switch fees.
transferscarries a switch fee for each S01 payout. It is a charge by the switch to the sending institution, and the lab’s settlement positions and statement do not include it, so this close does not test it. The chapter Clearing and settlement at the switch covers what the file between a switch and a bank holds. - The cash. The agents’ cash is theirs. S01 sees only their float wallets, which is why a double cash-out cannot be checked against any outside record here.
- Wallet status. The equation cannot see whether a wallet’s status allowed the posting. The generator keeps cash off wallets whose status forbids it (cash in only to active or post-no-debit wallets, cash out only from active ones), and
status.py(step 8) tests that rule on S01’s ledger, which the answer key does not list. Here it finds nothing, and the close should keep running it, because a posting on a frozen or closed wallet would balance every day. - Limits. No tier limits are tested. The KYC tiers belong to a layer in front of the ledger.
- The opening. The close assumes nothing was in transit when the week began.
Lab
You work in labs/finance. You create seven files there: psbkit.py, replay.py, match.py, close.py, breaks.py, accept.py and status.py. They open data/rails.sqlite read-only. No sqlite3 program is needed, because every query runs through Python’s sqlite3 module. Do not open data/answers/rails_truth.csv until step 6. The outputs below came from Python 3.13; the code uses nothing newer than 3.9.
1. Generate the week and check it. rails.py writes the payment-network week in about a second, a separate world from Owoleaf’s ledger. check.py --rails-only proves invariants 21 to 25, and 25 is the one this project leans on: S01’s ledger agrees with the switch except for the planted breaks.
cd labs/finance
python3 rails.py
python3 check.py --rails-only32 participants, 22,835 accounts, 17,998 transfers, 12,158 name enquiries, 136 status queries
21 settlement sessions, 125 batch files, 193 RTGS payments, 3,412 USSD sessions, 3,453 PSB postings
planted (answers/rails_truth.csv): credited_without_settlement 4, customer_fee_not_charged 6, customer_reversed_twice 3, levy_not_charged 5, mmo_trust_shortfall 1, participant_limit 4, participant_outage 1, psb_cash_out_fee_not_posted 1, psb_cash_out_posted_twice 1, reversed_after_late_success 4, same_number_two_banks 8, switch_incident 1, telco_record_missing 12
rails week: 17,998 transfers, 21 settlement sessions, 22,835 accounts; checks 21-25 run
OK: all invariants holdThe planted line counts the week’s breaks by kind. The two that begin psb_ are S01’s. The key stays closed until step 6.
2. Save the shared code and look at S01. psbkit.py prints naira from integer kobo with integer division, so no float touches an amount. replay posts the ledger onto the opening balances: a posting adds or subtracts its amount from wallet, takes the fee from the same wallet, and moves the opposite amount on counter (the agent’s float, for a cash-in or cash-out). cash_out_fee is the tariff you will test the ledger against. It reads the data’s pattern: cash-out fees are ₦100.00 up to ₦5,000.00 and ₦200.00 above, bar one posting that step 6 finds.
"""What every script in this project shares: S01's tables read into memory, money printed from integer
kobo, and the lab's illustrative cash-out tariff. Nothing here writes to the database."""
import sqlite3
from collections import Counter, defaultdict
DB = "data/rails.sqlite"
PSB = "S01"
DAYS = [f"2026-06-{d}" for d in range(15, 22)] # Monday 15 to Sunday 21 June 2026, WAT
SIGN = {"nip_in": 1, "nip_out": -1, "nip_out_reversal": 1, "cash_in": 1, "cash_out": -1}
def naira(kobo):
"""Integer kobo to a printed amount. Never a float."""
sign = "-" if kobo < 0 else ""
kobo = abs(kobo)
return f"{sign}{kobo // 100:,}.{kobo % 100:02d}"
def cash_out_fee(amount_kobo):
"""The tariff S01's ledger follows in the lab (illustrative): 10,000 kobo up to 500,000 kobo, else 20,000."""
return 10_000 if amount_kobo <= 500_000 else 20_000
def load(path=DB):
db = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
q = lambda sql: db.execute(sql).fetchall()
d = {}
d["wallets"] = {w: (kind, tier, opening) for w, kind, tier, opening in q("SELECT * FROM psb_wallets")}
d["ledger"] = [dict(zip(("id", "at", "kind", "wallet", "counter", "amount", "fee", "ref"), r))
for r in q("SELECT * FROM psb_ledger ORDER BY at, id")]
d["statement"] = [dict(zip(("at", "desc", "debit", "credit", "balance"), r))
for r in q("SELECT * FROM psb_settlement_statement ORDER BY at")]
cols = ("sid", "at", "src", "dst", "debit_acc", "credit_acc", "amount", "fee", "sfee", "first", "final",
"session")
d["transfers"] = {r[0]: dict(zip(cols, r)) for r in q(
"""SELECT session_id, at, src, dest, debit_account, credit_account, amount_kobo, customer_fee_kobo,
switch_fee_kobo, first_response, final_status, settlement_session
FROM transfers WHERE src = 'S01' OR dest = 'S01'""")}
d["settled_at"] = dict(q("SELECT id, settled_at FROM settlement_sessions"))
d["positions"] = {s: (sent, recv) for s, sent, recv in q(
"SELECT session, sent_kobo, received_kobo FROM settlement_positions WHERE participant = 'S01'")}
return d
def replay(d, upto_day=None, ledger=None):
"""Post the ledger onto the opening balances, in time order. Returns balances and the postings
that took a wallet below zero. Stops after upto_day (a 'YYYY-MM-DD' string) when given."""
bal = {w: v[2] for w, v in d["wallets"].items()}
negative = []
for r in (ledger if ledger is not None else d["ledger"]):
if upto_day and r["at"][:10] > upto_day:
break
s = SIGN[r["kind"]]
bal[r["wallet"]] += s * r["amount"] - r["fee"]
if r["counter"]:
bal[r["counter"]] -= s * r["amount"]
for w in (r["wallet"], r["counter"]):
if w and bal[w] < 0:
negative.append((r["id"], w, bal[w]))
return bal, negative
if __name__ == "__main__":
d = load()
kinds = defaultdict(lambda: [0, 0, 0])
for r in d["ledger"]:
k = kinds[r["kind"]]
k[0] += 1; k[1] += r["amount"]; k[2] += r["fee"]
print(f"{len(d['wallets'])} wallets: " + ", ".join(
f"{n} {kind}" for kind, n in sorted(Counter(v[0] for v in d['wallets'].values()).items())))
print(f"opening wallets total {naira(sum(v[2] for v in d['wallets'].values()))}")
print(f"{'kind':18}{'postings':>9}{'amount':>20}{'fees':>14}")
for kind, (n, a, f) in sorted(kinds.items()):
print(f"{kind:18}{n:>9,}{naira(a):>20}{naira(f):>14}")
print(f"statement: {len(d['statement'])} rows, opening {naira(d['statement'][0]['balance'])}, "
f"last {naira(d['statement'][-1]['balance'])} on {d['statement'][-1]['at'][:10]}")
print(f"switch: {len(d['transfers'])} transfers touch S01, {len(d['positions'])} sessions hold an S01 position")python3 psbkit.py662 wallets: 60 agent, 602 customer
opening wallets total 31,344,534.00
kind postings amount fees
cash_in 1,446 14,962,400.00 0.00
cash_out 1,495 15,478,500.00 263,100.00
nip_in 256 4,429,098.87 0.00
nip_out 254 3,661,588.00 5,210.00
nip_out_reversal 2 19,023.00 0.00
statement: 22 rows, opening 900,000,000.00, last 900,786,533.87 on 2026-06-22
switch: 511 transfers touch S01, 21 sessions hold an S01 positionThe ledger holds 3,453 postings: cash in and out at agents are most of them, NIP the rest. The 256 NIP credits are 256 transfers the switch also carried to S01, and the statement’s last row, ₦900,786,533.87, is dated Monday 22 June because weekend traffic settles then.
3. Replay the ledger, one day at a time. replay.py posts each day’s rows onto the previous close and prints the customers’ and agents’ totals. It stops a wallet going below zero, and it searches the ledger for a posting that repeats another in every field except its id.
"""Step 3: replay S01's ledger onto Monday's opening balances, one day at a time."""
from collections import Counter
from psbkit import DAYS, load, naira, replay
def duplicates(ledger):
"""Postings that repeat another posting in every field but their id."""
seen = Counter((r["at"], r["kind"], r["wallet"], r["counter"], r["amount"], r["ref"]) for r in ledger)
return [k for k, n in seen.items() if n > 1]
if __name__ == "__main__":
d = load()
kind = {w: v[0] for w, v in d["wallets"].items()}
print(f"{'day':11}{'postings':>9}{'customers':>17}{'agents':>16}{'total':>17} negative")
for day in DAYS:
bal, neg = replay(d, day)
cust = sum(v for w, v in bal.items() if kind[w] == "customer")
agent = sum(v for w, v in bal.items() if kind[w] == "agent")
n = sum(1 for r in d["ledger"] if r["at"][:10] == day)
print(f"{day:11}{n:>9}{naira(cust):>17}{naira(agent):>16}{naira(cust + agent):>17} {len(neg)}")
dups = duplicates(d["ledger"])
print(f"postings repeated in every field but the id: {len(dups)}")
for k in dups:
print(" ", k)python3 replay.pyday postings customers agents total negative
2026-06-15 502 26,338,307.00 4,893,922.00 31,232,229.00 0
2026-06-16 494 26,258,144.00 5,043,422.00 31,301,566.00 0
2026-06-17 512 26,379,186.00 5,078,422.00 31,457,608.00 0
2026-06-18 489 25,773,640.00 5,374,922.00 31,148,562.00 0
2026-06-19 524 25,813,128.00 5,289,922.00 31,103,050.00 0
2026-06-20 465 25,919,749.00 5,231,122.00 31,150,871.00 1
2026-06-21 467 26,279,835.87 5,582,922.00 31,862,757.87 1
postings repeated in every field but the id: 1
('2026-06-19T15:01:27+01:00', 'cash_out', '6821010762', '6068917493', 1820000, '')From Saturday one posting takes a wallet below zero: the ₦27,847.00 payout at 07:17 on Saturday 20 June leaves wallet 6821010762 at -₦17,240.00. Hold that thought, because the search below finds why. Cash-in and cash-out move value between a customer and an agent, so the customers’ and agents’ columns move in opposite directions and their total moves only with NIP and fees. The search finds one posting that repeats exactly: a cash-out of ₦18,200.00 on Friday 19 June at 15:01:27, on the wallet that goes negative the next morning. Note it and go on: the next two steps will find nothing wrong, and that is the point.
4. Match the NIP postings and the statement to the switch. match_nip takes every nip_in, nip_out and nip_out_reversal posting and finds its transfer by ref, which is the session id. It checks the direction, the wallet, the amount and the fee (a fee is charged on a payout that succeeded and on nothing else). It also looks the other way: a settled credit with no posting, a payout with no posting, a failed payout never reversed. match_statement checks each statement row’s arithmetic, then compares its debit and credit with the switch’s position for S01 in that session, and with the ledger’s own total for the session.
"""Step 4: match S01's NIP postings to the switch's transfers, and its settlement statement to the
switch's positions. Every function returns findings: (day, kind, reference, what is wrong)."""
from psbkit import PSB, load, naira
def match_nip(d):
found, n_in, n_out, n_rev = [], 0, 0, 0
T, posted = d["transfers"], {"nip_in": set(), "nip_out": set(), "nip_out_reversal": set()}
for r in d["ledger"]:
if r["kind"] not in posted:
continue
day, t = r["at"][:10], T.get(r["ref"])
posted[r["kind"]].add(r["ref"])
if t is None:
found.append((day, "nip_unknown_to_switch", r["ref"], "no such transfer at the switch"))
continue
if r["kind"] == "nip_in":
n_in += 1
if t["dst"] != PSB or t["credit_acc"] != r["wallet"] or t["amount"] != r["amount"]:
found.append((day, "nip_in_mismatch", r["ref"], "wallet or amount differs from the switch"))
if t["final"] != "00":
found.append((day, "nip_in_never_settled", r["ref"], f"posted, but the switch ended it {t['final']}"))
elif r["kind"] == "nip_out":
n_out += 1
if t["src"] != PSB or t["debit_acc"] != r["wallet"] or t["amount"] != r["amount"]:
found.append((day, "nip_out_mismatch", r["ref"], "wallet or amount differs from the switch"))
fee = t["fee"] if t["final"] == "00" else 0
if r["fee"] != fee:
found.append((day, "nip_fee_mismatch", r["ref"], f"fee {r['fee']} kobo, switch says {fee}"))
else:
n_rev += 1
if t["final"] == "00":
found.append((day, "reversed_but_settled", r["ref"], "reversed to the customer, yet it settled"))
for sid, t in T.items():
day = t["at"][:10]
if t["dst"] == PSB and t["final"] == "00" and sid not in posted["nip_in"]:
found.append((day, "nip_in_not_posted", sid, f"settled credit of {t['amount']} kobo, no posting"))
if t["src"] == PSB and sid not in posted["nip_out"]:
found.append((day, "nip_out_not_posted", sid, "the switch carried it, no posting"))
if t["src"] == PSB and t["final"] != "00" and sid not in posted["nip_out_reversal"]:
found.append((day, "failed_out_not_reversed", sid, f"ended {t['final']}, customer not repaid"))
return found, (n_in, n_out, n_rev)
def match_statement(d):
found, bal, ok = [], d["statement"][0]["balance"], 0
by_session = {}
for r in d["ledger"]: # the ledger's own total for each session, by the switch's session id
t = d["transfers"].get(r["ref"])
if r["kind"] in ("nip_in", "nip_out") and t and t["final"] == "00":
s = by_session.setdefault(t["session"], [0, 0])
s[0 if r["kind"] == "nip_out" else 1] += r["amount"]
seen = set()
for row in d["statement"][1:]:
sid, day = row["desc"].split()[-1], row["at"][:10]
seen.add(sid)
bal = bal - row["debit"] + row["credit"]
if bal != row["balance"]:
found.append((day, "statement_arithmetic", sid, f"running balance {bal}, printed {row['balance']}"))
sw = d["positions"].get(sid)
if sw != (row["debit"], row["credit"]):
found.append((day, "statement_vs_switch", sid, f"statement {(row['debit'], row['credit'])}, switch {sw}"))
elif by_session.get(sid, [0, 0]) != [row["debit"], row["credit"]]:
found.append((day, "statement_vs_ledger", sid, "settled amounts differ from the ledger's postings"))
else:
ok += 1
for sid in d["positions"]:
if sid not in seen:
found.append((d["settled_at"][sid][:10], "session_not_on_statement", sid, "S01 has a position, no row"))
return found, ok
if __name__ == "__main__":
d = load()
f1, (n_in, n_out, n_rev) = match_nip(d)
print(f"NIP postings against the switch: {n_in} in, {n_out} out, {n_rev} reversals; {len(f1)} findings")
f2, ok = match_statement(d)
print(f"statement rows matched to the switch and the ledger: {ok} of {len(d['statement']) - 1}; {len(f2)} findings")
for f in f1 + f2:
print(" ", f)
last = d["statement"][-1]
print(f"settlement account: opened {naira(d['statement'][0]['balance'])}, "
f"closed {naira(last['balance'])} after {last['desc']}")python3 match.pyNIP postings against the switch: 256 in, 254 out, 2 reversals; 0 findings
statement rows matched to the switch and the ledger: 21 of 21; 0 findings
settlement account: opened 900,000,000.00, closed 900,786,533.87 after NIP settlement 20260622-1Everything matches, and the statement ties to the switch session by session. The 511 transfers that touch S01 are 256 credits, 254 payouts and one more; the 2 reversals are postings that repay 2 of the 254 payouts (the two the receiving bank refused with 07), not extra transfers. The one more is an inbound transfer S01 refused (response 57, a frozen account), which the switch ended unsettled, so it rightly has no posting. The ledger and the statement agree on NIP, and the two breaks are still in the ledger. Matching alone did not find them.
5. Close each day. close.py implements the equation. in_transit takes the NIP postings made by the close of the day whose session settles after it, from the switch’s side, and counts a failed payout not yet repaid as a debit. close_day replays to the close, reads the last statement balance on or before the day, adds the fees to date, and returns the difference between the two sides.
"""Step 5: close each day. The wallets S01 owes must equal what it holds for them.
change in wallets = change in the settlement account + NIP money in transit - fees S01 kept
Three independent sources: the wallets come from replaying the ledger, the settlement account from the
bank's statement, and the money in transit from the switch (which session settles each transfer, and
when that session is settled). Fees come from the ledger's fee column."""
from psbkit import DAYS, load, naira, replay
def in_transit(d, day, ledger=None):
"""NIP money posted to wallets by the end of `day` whose session is settled after it, from the switch's side.
A credit counts for S01, a debit against it. A failed payout not yet repaid by the close counts as a debit."""
total, repaid = 0, set()
rows = ledger if ledger is not None else d["ledger"]
for r in rows:
if r["at"][:10] <= day and r["kind"] == "nip_out_reversal":
repaid.add(r["ref"])
for r in rows:
if r["at"][:10] > day or r["kind"] not in ("nip_in", "nip_out"):
continue
t = d["transfers"][r["ref"]]
if t["final"] == "00":
if d["settled_at"][t["session"]][:10] > day:
total += r["amount"] if r["kind"] == "nip_in" else -r["amount"]
elif r["kind"] == "nip_out" and r["ref"] not in repaid:
total -= r["amount"]
return total
def close_day(d, day, ledger=None):
rows = ledger if ledger is not None else d["ledger"]
opening = sum(v[2] for v in d["wallets"].values())
bal, _ = replay(d, day, rows)
wallets = sum(bal.values())
bank = d["statement"][0]["balance"]
for row in d["statement"]:
if row["at"][:10] <= day:
bank = row["balance"]
fees = sum(r["fee"] for r in rows if r["at"][:10] <= day)
transit = in_transit(d, day, rows)
diff = (wallets - opening) - ((bank - d["statement"][0]["balance"]) + transit - fees)
return dict(day=day, wallets=wallets, bank=bank, transit=transit, fees=fees, diff=diff)
def table(d, ledger=None):
out = [close_day(d, day, ledger) for day in DAYS]
print(f"{'day':11}{'wallets':>15}{'settlement acct':>18}{'in transit':>13}{'fees to date':>14}{'difference':>12}")
for c in out:
print(f"{c['day']:11}{naira(c['wallets']):>15}{naira(c['bank']):>18}{naira(c['transit']):>13}"
f"{naira(c['fees']):>14}{naira(c['diff']):>12}")
return out
if __name__ == "__main__":
d = load()
out = table(d)
print(f"days that close: {sum(1 for c in out if c['diff'] == 0)} of {len(out)}")python3 close.pyday wallets settlement acct in transit fees to date difference
2026-06-15 31,232,229.00 900,013,776.00 -89,456.00 36,625.00 0.00
2026-06-16 31,301,566.00 899,939,021.00 94,356.00 76,345.00 0.00
2026-06-17 31,457,608.00 900,193,359.00 34,265.00 114,550.00 0.00
2026-06-18 31,148,562.00 900,070,769.00 -111,916.00 154,825.00 0.00
2026-06-19 31,103,050.00 899,918,159.00 32,237.00 191,880.00 0.00
2026-06-20 31,150,871.00 899,918,159.00 116,578.00 228,400.00 0.00
2026-06-21 31,862,757.87 899,918,159.00 868,374.87 268,310.00 0.00
days that close: 7 of 7All seven days close. Look at Saturday and Sunday: the settlement account is ₦899,918,159.00 on Friday, Saturday and Sunday, because nothing settles at the weekend, while the wallets move and the in-transit line carries the difference. Sunday’s ₦868,374.87 is the largest, and about ₦595,000 of it is two credits of ₦297,498.43 and ₦297,498.44 from B18 at 04:01 and 04:03. On Sunday the wallets have risen ₦518,223.87 since Monday morning (31,862,757.87 less 31,344,534.00), and the right side is -₦81,841.00 from the bank (899,918,159.00 less 900,000,000.00), plus ₦868,374.87 in transit, less ₦268,310.00 in fees. 868,374.87 - 81,841.00 = 786,533.87, and 786,533.87 - 268,310.00 = 518,223.87. Monday’s session then settles the weekend, and the account closes at ₦900,786,533.87. The ledger holds a double charge and a missing fee, and the day still closes.
6. Find what a balanced day hides, then open the key. find_breaks has two finders: the repeated posting from step 3, and every cash-out whose fee differs from the tariff. corrected builds the ledger as it would stand with both corrections, in memory. The script prints the fee proof, the proposed corrections and the close recomputed on the corrected ledger. With --key it reads rails_truth.csv and scores the findings. Run it without --key first, read the two findings, then add the flag.
"""Step 6: find what a balanced day can hide. Two finders, a fee proof, and the corrections S01 would
propose. Nothing is posted: a person approves a correction. `--key` scores the findings against the answer key."""
import csv
import sys
from replay import duplicates
from psbkit import cash_out_fee, load, naira
from close import table
def find_breaks(d):
found = []
for at, kind, wallet, counter, amount, ref in duplicates(d["ledger"]):
found.append(dict(day=at[:10], kind="posted_twice", at=at, wallet=wallet, counter=counter, amount=amount,
fee=cash_out_fee(amount)))
for r in d["ledger"]:
if r["kind"] == "cash_out" and r["fee"] != cash_out_fee(r["amount"]):
found.append(dict(day=r["at"][:10], kind="fee_not_posted", at=r["at"], wallet=r["wallet"],
counter=r["counter"], amount=r["amount"], fee=cash_out_fee(r["amount"]) - r["fee"]))
return found
def corrected(d, found):
"""The ledger as it would stand with both corrections applied (in memory only)."""
drop = {(b["at"], b["wallet"], b["amount"]) for b in found if b["kind"] == "posted_twice"}
fix = {(b["at"], b["wallet"], b["amount"]) for b in found if b["kind"] == "fee_not_posted"}
out, dropped = [], set()
for r in d["ledger"]:
k = (r["at"], r["wallet"], r["amount"])
if k in drop and r["kind"] == "cash_out" and k not in dropped:
dropped.add(k)
continue # keep the first posting, remove the repeat
out.append(dict(r, fee=cash_out_fee(r["amount"])) if k in fix and r["kind"] == "cash_out" else r)
return out
if __name__ == "__main__":
d = load()
found = find_breaks(d)
print(f"{len(found)} breaks in S01's ledger")
for b in found:
print(f" {b['day']} {b['kind']:15} cash_out at {b['at'][11:19]} wallet {b['wallet']} "
f"amount {naira(b['amount'])} fee {naira(b['fee'])}")
posted = sum(r["fee"] for r in d["ledger"] if r["kind"] == "cash_out")
owed = sum(cash_out_fee(r["amount"]) for r in d["ledger"] if r["kind"] == "cash_out")
print(f"cash-out fees posted {naira(posted)}; the tariff on the same {sum(1 for r in d['ledger'] if r['kind'] == 'cash_out'):,} "
f"postings gives {naira(owed)}; difference {naira(posted - owed)}")
uniq = sum(cash_out_fee(r["amount"]) for r in corrected(d, found) if r["kind"] == "cash_out")
fixed = sum(r["fee"] for r in corrected(d, found) if r["kind"] == "cash_out")
print(f"after both corrections: posted {naira(fixed)}, tariff {naira(uniq)}")
print("proposed corrections (for a person to approve):")
for b in found:
if b["kind"] == "posted_twice":
print(f" credit wallet {b['wallet']} {naira(b['amount'] + b['fee'])}; debit agent float {b['counter']} "
f"{naira(b['amount'])}; debit fee income {naira(b['fee'])}")
else:
print(f" charge wallet {b['wallet']} {naira(b['fee'])} to fee income, or waive it: a person decides")
print("close with both corrections applied:")
table(d, corrected(d, found))
if "--key" in sys.argv:
key = [r for r in csv.DictReader(open("data/answers/rails_truth.csv")) if r["who"] == "S01"]
planted = {(r["kind"].replace("psb_cash_out_", ""), r["ref"].split()[-1]) for r in key}
got = {(b["kind"], b["at"]) for b in found}
print(f"answer key for S01: {len(planted)} planted, {len(got & planted)} found, "
f"{len(planted - got)} missed, {len(got - planted)} invented")python3 breaks.py --key2 breaks in S01's ledger
2026-06-19 posted_twice cash_out at 15:01:27 wallet 6821010762 amount 18,200.00 fee 200.00
2026-06-15 fee_not_posted cash_out at 20:59:30 wallet 6867413277 amount 19,200.00 fee 200.00
cash-out fees posted 263,100.00; the tariff on the same 1,495 postings gives 263,300.00; difference -200.00
after both corrections: posted 263,100.00, tariff 263,100.00
proposed corrections (for a person to approve):
credit wallet 6821010762 18,400.00; debit agent float 6068917493 18,200.00; debit fee income 200.00
charge wallet 6867413277 200.00 to fee income, or waive it: a person decides
close with both corrections applied:
day wallets settlement acct in transit fees to date difference
2026-06-15 31,232,029.00 900,013,776.00 -89,456.00 36,825.00 0.00
2026-06-16 31,301,366.00 899,939,021.00 94,356.00 76,545.00 0.00
2026-06-17 31,457,408.00 900,193,359.00 34,265.00 114,750.00 0.00
2026-06-18 31,148,362.00 900,070,769.00 -111,916.00 155,025.00 0.00
2026-06-19 31,103,050.00 899,918,159.00 32,237.00 191,880.00 0.00
2026-06-20 31,150,871.00 899,918,159.00 116,578.00 228,400.00 0.00
2026-06-21 31,862,757.87 899,918,159.00 868,374.87 268,310.00 0.00
answer key for S01: 2 planted, 2 found, 0 missed, 0 inventedThe double charge is a customer debited ₦18,200.00 plus a ₦200.00 fee twice, and an agent’s float credited ₦18,200.00 twice: the correction repays the customer ₦18,400.00, takes ₦18,200.00 back from the agent’s float and reverses ₦200.00 of fee income. It is also what took wallet 6821010762 below zero in step 3: with ₦18,400.00 repaid the Saturday payout leaves ₦1,160.00, and the corrected ledger has no negative posting. The missing fee is a ₦200.00 cash-out fee never charged on a ₦19,200.00 cash-out on Monday 15 June. Whether to charge it now or waive it is not a posting the close makes: a person decides, which is why the script prints a choice and not an entry. The week’s fee check is -₦200.00 and not zero or +₦200.00, because the double charge’s fee is posted twice and counted twice in the tariff total, so only the missing fee shows. After both corrections the total is ₦263,100.00, the figure it had before, because one error added ₦200.00 and the other removed ₦200.00. A total can balance with two errors in it. The corrected close differs from the first from Monday 15 to Thursday 18 June (the fee, ₦200.00 lower in the wallets and higher in the fees) and returns to the old totals from Friday, when the double charge is repaid, and every day still closes. The key lists two for S01: two found, none missed, none invented.
7. Run the acceptance checks. accept.py runs the three checks and exits 1 on any problem. The below-zero test counts the corrected ledger, because the double charge is what overdraws the one wallet; the raw count is printed beside it.
"""Step 7: the three acceptance checks."""
import csv
import sys
from breaks import corrected, find_breaks
from close import close_day
from match import match_nip, match_statement
from psbkit import DAYS, load, replay
d = load()
problems = 0
# the breaks this project checks: S01's cash-out kinds in your own answer key, not a fixed number
planted = [r for r in csv.DictReader(open("data/answers/rails_truth.csv"))
if r["who"] == "S01" and r["kind"] in ("psb_cash_out_posted_twice", "psb_cash_out_fee_not_posted")]
closes = [close_day(d, day) for day in DAYS]
bad = [c["day"] for c in closes if c["diff"] != 0]
print(f"1. days that close: {len(DAYS) - len(bad)} of {len(DAYS)}" + (f"; open: {bad}" if bad else ""))
problems += len(bad)
f1, _ = match_nip(d)
f2, ok = match_statement(d)
found = find_breaks(d)
fixed = corrected(d, found)
_, neg = replay(d)
_, neg_fixed = replay(d, None, fixed)
print(f"2. NIP postings matched to the switch: {len(f1)} findings; statement rows matched: {ok} of 21, {len(f2)} findings; "
f"postings that take a wallet below zero: {len(neg)} as posted, {len(neg_fixed)} corrected")
problems += len(f1) + len(f2) + len(neg_fixed)
after = [c["day"] for c in (close_day(d, day, fixed) for day in DAYS) if c["diff"] != 0]
again = find_breaks(dict(d, ledger=fixed))
print(f"3. breaks found: {len(found)} ({', '.join(sorted(b['kind'] for b in found))}); "
f"key lists {len(planted)}; days that close with them corrected: {len(DAYS) - len(after)} of {len(DAYS)}; "
f"breaks left: {len(again)}")
problems += len(after) + len(again) + (0 if len(found) == len(planted) else 1)
print("PASS" if not problems else f"FAIL: {problems} problems")
sys.exit(1 if problems else 0)python3 accept.py1. days that close: 7 of 7
2. NIP postings matched to the switch: 0 findings; statement rows matched: 21 of 21, 0 findings; postings that take a wallet below zero: 1 as posted, 0 corrected
3. breaks found: 2 (fee_not_posted, posted_twice); key lists 2; days that close with them corrected: 7 of 7; breaks left: 0
PASS8. Test the status rule the key does not list. The generator keeps cash off wallets whose status forbids it: cash in only to active or pnd wallets, cash out and payouts only from active ones. Status pnd is read here as post no debit, the usual meaning of that abbreviation; the lab does not define it. status.py tests the rule on S01’s ledger. The equation cannot, and the key plants nothing here, so a finding would be a control failure outside the score.
"""The wallet-status rule, tested on S01's ledger. The key does not list it; the generator keeps it."""
import sqlite3
from collections import Counter
from psbkit import DB, load
RECEIVES_CASH = {"active", "pnd"} # cash in: a credit, so post-no-debit is allowed
PAYS = {"active"} # cash out and NIP payouts: debits need an active wallet
d = load()
db = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)
status = dict(db.execute("SELECT account_no, status FROM accounts WHERE institution = 'S01'"))
broken = [r for r in d["ledger"]
if (r["kind"] in ("cash_out", "nip_out") and status[r["wallet"]] not in PAYS)
or (r["kind"] == "cash_in" and status[r["wallet"]] not in RECEIVES_CASH)]
print(f"{len(broken)} cash or payout postings break the status rule")
n = Counter((status[r["wallet"]], r["kind"]) for r in d["ledger"] if status[r["wallet"]] != "active")
print(f"{sum(n.values())} postings touch a wallet that is not active")
for (s, kind), c in sorted(n.items()):
print(f" {s:8}{kind:10}{c:>4}")python3 status.py0 cash or payout postings break the status rule
26 postings touch a wallet that is not active
dormant nip_in 11
pnd cash_in 13
pnd nip_in 2The first line is the result: no posting breaks the rule. The 26 that remain are credits the rule allows, a cash-in to a post-no-debit wallet and NIP credits the switch delivered to dormant or pnd wallets, because a status that blocks debits still lets money in. A close that runs this every day would raise a posting that broke the rule to Tekena even though every equation balanced. Add the call to accept.py as a fourth line that reports apart from the planted breaks, so that the key score stays honest.
Take the in-transit term out of the equation. Copy close.py to close_break.py, change transit = in_transit(d, day, rows) to transit = 0, and run it:
python3 close_break.pyday wallets settlement acct in transit fees to date difference
2026-06-15 31,232,229.00 900,013,776.00 0.00 36,625.00 -89,456.00
2026-06-16 31,301,566.00 899,939,021.00 0.00 76,345.00 94,356.00
2026-06-17 31,457,608.00 900,193,359.00 0.00 114,550.00 34,265.00
2026-06-18 31,148,562.00 900,070,769.00 0.00 154,825.00 -111,916.00
2026-06-19 31,103,050.00 899,918,159.00 0.00 191,880.00 32,237.00
2026-06-20 31,150,871.00 899,918,159.00 0.00 228,400.00 116,578.00
2026-06-21 31,862,757.87 899,918,159.00 0.00 268,310.00 868,374.87
days that close: 0 of 7No day closes, and the difference is exactly the money in transit: -₦89,456.00 on Monday and ₦868,374.87 on Sunday. A close that ignores the time the banks take to settle shows a difference every day, and a team that signs it anyway learns to tolerate differences. Then a real one, such as the double charge, hides among them.
Template
# Day-close note: <PSB>, <day or period>
Prepared by <name, role> · Signed by <name, role> · Date <date>
Scope: <ledger, statement and switch records covered, and the days>
Decision needed: <what the signer must decide on this note>
## Result
<Closed or not closed, in one line. Difference: <₦ to the kobo>.>
## The close
| Day | Wallets | Settlement account | In transit | Fees to date | Difference |
|---|---|---|---|---|---|
Why the account and the wallets differ: <timing, in plain words>
## Breaks found
| What | When and where | Cause | Could the equation see it? | Proposed correction | Approver |
|---|---|---|---|---|---|
## Corrections
<Entries proposed, never posted by this note. The close recomputed as if posted.>
## Still open
- <item> · owner <name> · by <date>
## What this close cannot see
- <gap: cash, fees outside the test, limits, the opening>
## How this note could be wrong
<One way, and the figure that would show it.>
## Sign-off
<name, role> · <date> · <closed / closed with open items / not closed> WORKED EXAMPLE
At a real PSB a finance-operations analyst prepares this note and the head of finance operations signs it; here Udeme prepares it and Tekena signs.
Day-close note: S01, Monday 15 to Sunday 21 June 2026. Prepared by Udeme, finance operations tools · Signed by Tekena, finance operations · Date Monday 22 June 2026. Scope: S01’s ledger, statement and switch records for the generated week. Decision needed: whether the week is signed as closed with open items.
Result. Closed. All seven days close with a difference of ₦0.00.
| Day | Wallets | Settlement account | In transit | Fees to date | Difference |
|---|---|---|---|---|---|
| Mon 15 | ₦31,232,229.00 | ₦900,013,776.00 | -₦89,456.00 | ₦36,625.00 | ₦0.00 |
| Sun 21 | ₦31,862,757.87 | ₦899,918,159.00 | ₦868,374.87 | ₦268,310.00 | ₦0.00 |
The account and the wallets differ because of timing: NIP credits a wallet at once and the banks settle later, and nothing settles at the weekend. The account has not moved since Friday while the wallets rose ₦518,223.87 on the opening ₦31,344,534.00. All 512 NIP postings match the switch and all 21 statement rows tie to it.
Breaks. Two, neither visible to the equation.
- A cash-out of ₦18,200.00 on wallet 6821010762 posted twice at 15:01:27 on Friday 19 June. The posting repeats in every field but its id. Proposed: repay ₦18,400.00, take ₦18,200.00 back from agent float 6068917493, reverse ₦200.00 of fee income. Approver Tekena.
- A ₦200.00 fee not charged on a ₦19,200.00 cash-out on wallet 6867413277 at 20:59:30 on Monday 15 June. Why it was left off is not known. Proposed: charge or waive, Tekena’s decision. The week’s fee check shows -₦200.00.
Nothing is posted; with both applied every day still closes.
Still open. Tekena approves both corrections · by Tuesday 23 June.
Cannot see. Agents’ cash, switch fees, limits, anything in transit before Monday.
Could be wrong if the cash-out tariff (₦100.00 up to ₦5,000.00, ₦200.00 above) is only what the data follows and not S01’s real one: the fee break would then be wrong.
Signed Tekena, 22 June, closed with open items.
Now you
You work in finance operations at Lumora Mobile’s PSB. It is Monday 22 June 2026 and Saturday 20 June is the one day of the week not yet signed. Write the day-close note for Saturday alone, from your own run of the lab (close.py, replay.py and breaks.py). What you know: the settlement account has not moved since Friday, the weekend’s NIP money is in transit, and one posting took a wallet below zero. Find that wallet, the posting’s amount and the wallet’s balance afterwards, and trace it to the break behind it. Then decide what stays open. The ₦200.00 missing fee dates from Monday 15 June, so say whether it belongs in a note about Saturday.
Tekena reads it and signs. The note supports two decisions: whether Saturday counts as closed, and whether to approve the repayment to the overdrawn wallet.
Self-check
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.