SENIORCHAPTER 19

Disputes, chargebacks and refund abuse

A chargeback takes the money back before you have said a word, arrives weeks after the sale, and counts against you whether you win or lose. Measure the ratio, post every stage once, and answer only with evidence you can stand behind

60 MINPAYMENTSUPDATED 2026-11-14
PREDICT

Owoleaf's stolen-card ring worked in April. You compute the dispute ratio three ways: by the month of the sale, by the month the chargeback arrived over that month's sales, and by the month it arrived over the previous month's sales. Which months come out highest, in that order?

Module 2 taught the payment’s life up to settlement and refund. A dispute is what happens after all of that looks finished. The lesson on chargebacks draws the state machine and shows the refund-on-top-of-chargeback bug. This chapter does not repeat it. It takes the three things a company with real card volume has to do with money, not with a diagram: measure how disputed it is, post each stage to the ledger so the books agree with the processor, and decide which disputes to answer and what to say.

A dispute is a clock, a debit and a decision

The cardholder tells their bank, the issuer, that they do not accept a charge. The issuer raises a chargeback through the card scheme. The acquirer and processor (the card chapter names the four parties) take the amount back from the merchant, usually out of the next settlement, and charge a fee for the chargeback. The merchant then chooses. It accepts, and the money stays with the cardholder. Or it sends evidence, called representment, and waits for the issuer to decide. Everything about this is slow, one-sided and timed.

Stripe’s documentation, a vendor’s, says card networks generally let a cardholder dispute within 120 days of the original payment, though some situations allow more time, and that once a chargeback is created a merchant usually has about 7 to 21 days to respond, depending on the networkas of 2026-11. Both clocks matter to a ledger. The first means a sale is not final for months. The second means a late answer is a lost dispute, whatever the evidence says.

In Nigeria there is a second layer of rules on top of the schemes’. Search summaries of the CBN’s revised timelines for electronic channels, effective 8 June 2020, say that switches must shorten their chargeback cycle to 24 hours, from 72, and that refunds on disputed or failed POS and web transactions must be made within 48 hours. Those summaries are law-firm and press commentary, because the CBN’s documents could not be opened in this build. A processor’s support page, a vendor’s, reports a shorter response time for merchants than the 72-hour figure, which it says is directed at banks, so sources differ on who is bound by which clock. A 2025 CBN draft on ATM operations says it would replace the ATM provisions of the 2020 guidelines; whether it is in force was not confirmedas of 2026-11. Read the guidelines before you build a service level on any of those figures. The customer’s side has its own rule: the CBN’s Consumer Protection Regulations of 2019 require an institution to acknowledge a complaint within 24 hours with a unique tracking number, as search summaries quote them, and the CBN has also published an exposure draft of a revised version, 2.0, in early 2024. The clause text was not read here and whether the revision is in force was not confirmedas of 2026-11. The point for an engineer is that a cardholder has two doors, the bank’s complaint process and the scheme’s dispute process, and a merchant can be asked about either.

The lab’s disputes use four reasons. Real schemes use many more reason codes, and they differ by scheme, so treat these as the lab’s simplification. All of the numbers below are Owoleaf’s, measured in step 1, and the ₦1,000 fee, the 10-day evidence window and the reasons themselves are the generator’s, not any scheme’s.

Reason The cardholder says Disputes Amount Median days from sale to chargeback
fraud I did not make this payment 63 ₦516,727.00 44
not_recognised I do not recognise this charge 29 ₦273,744.00 27
not_credited I paid and was not credited 10 ₦54,683.00 26
duplicate I was charged twice 7 ₦72,135.00 34

Two lessons are already in the table. A chargeback moves money at the other side’s request, before you have said anything. And it arrives late: the shortest gap in the data is 3 days and the longest 74.

The ratio that programmes watch

Card schemes watch each merchant’s disputes, and acquirers pass the watching on. A merchant over a line goes into a monitoring programme, pays fines, and in the end can lose the ability to take cards. The line is a ratio: disputes divided by transactions. Three decisions inside it change the answer, and the lab shows each.

Which thing is counted. Visa’s Acquirer Monitoring Program (VAMP) fact sheet, as summarised in search results, defines the VAMP ratio as the count of fraud reports (record type TC40) plus disputes (TC15), divided by the count of settled card-not-present transactions (TC05). It says, in a footnote, that the merchant Excessive level falls to 150 basis points (1.5%) on 1 April 2026 in Asia-Pacific, Canada, the EU and the US, shows 220 basis points (2.2%) for CEMEA, the Central and Eastern Europe, Middle East and Africa region, and sets a floor of 1,500 fraud-plus-dispute items in a month in most regions, against 150 items and US$75,000 in CEMEA. The PDF could not be opened in this build, and the copy found is the 2025 edition. Vendor pages disagree with each other, for example by listing Latin America and the Caribbean at 150 basis points, so check the current fact sheet. This chapter does not say which region applies to a Nigerian merchant; ask your acquireras of 2026-11. A basis point is a hundredth of a percent. The formula adds two counts: disputes, and fraud reports that the issuer sent whether or not a chargeback followed. Owoleaf has both, in disputes and in the issuer_report rows of fraud_reports.

Which month. A payment provider’s support page on chargeback and fraud monitoring, so a vendor’s claim, is summarised in search results as naming Mastercard’s excessive-chargeback and excessive-fraud programmes and a minimum of 100 disputes before a merchant is enrolled. Other vendor pages give 1.5% for the chargeback programme, and 0.5% for fraud together with a US$50,000 fraud-chargeback amount, and one vendor blog gives different tiers altogether. Mastercard’s own chargeback guide was not found in search results, so these figures rest on vendor pages and search summaries and disagree about when a merchant enters and leaves a programmeas of 2026-11. So one rule counts by the month of the sale, another by the month of arrival over the same month’s sales, another by arrival over the previous month’s. Owoleaf’s April shows how far apart they land:

Rule Highest month Ratio
By the month of the sale April 1.78% (36 of 2,018)
By the month it arrived, over that month’s sales June 0.94% (30 of 3,197)
By the month it arrived, over the previous month’s sales March 1.53% (10 of 655)

The first is a cohort view: it asks how risky April’s sales turned out to be, and it can only be known weeks later. The other two are what a programme can compute at the time. The ring’s April sales show up in the arrival views in May and June, and the April by-arrival figure of 0.59% looks calm. Teams that watch their own ratio only by arrival month see a ring when it has already finished.

Count or value. Owoleaf’s value ratio in April is 0.83% against a count ratio of 1.78%, and March’s value ratio is 1.32% against a count of 1.17%. The ring’s top-ups were small. A programme that counts items, as VAMP does, sees them. A finance view that tracks naira does not.

Add the issuer’s fraud reports and the picture sharpens. Counted as the fact sheet’s formula adds them, April’s 36 disputes and 13 issuer reports make 49 items on 2,018 sales: 2.43%. But 10 of the 13 reports are on transactions that were also disputed. Counted once per transaction, April is 39 items and 1.93%. Vendor guides in the search results say a transaction that generates both a fraud report and a dispute counts twice, but I could not confirm that in Visa’s own text, so the lab prints both and your acquirer’s answer decides. Either way April is above the 150-basis-point line, but a programme also needs a minimum count. The 1,500-item floor is about thirty times April’s 49 at this scale, and the lab does not tag cards by scheme, so it cannot isolate Visa transactions. The numbers are for practice, not a forecast.

One more point is easy to miss. The formula, as summarised, counts disputes received. The summaries I found do not say that a won dispute is taken out; one vendor FAQ mentions an exclusion only for disputes resolved through Visa’s Compelling Evidence 3.0, described below. Check the fact sheet before relying on a win to protect the ratio. Winning recovers the money, and prevention is the part that lowers the count.

Posting a chargeback: a claim, then an outcome

The processor debits the chargeback from settlement, and the ledger must say what that is. It is not yet a loss. Owoleaf has a claim: it will get the money back if it wins. Booking the debit straight to an expense would overstate the loss for every dispute still open, and booking nothing would leave card_clearing too high against what the processor will pay. The lab uses three new accounts.

Account Type Holds
dispute_receivable asset Card money the processor has withheld for a chargeback, claimed back until it is decided
chargeback_fees expense The processor’s fee per chargeback, win or lose
dispute_losses expense Chargebacks that stood

Each stage that moves money has one posting.

Stage Debit Credit Why
Chargeback received dispute_receivable for the amount; chargeback_fees for the fee card_clearing for both The processor will pay less next time. The fee is gone now
Accepted, or lost dispute_losses dispute_receivable The claim failed
Won card_clearing dispute_receivable The processor owes the amount again; the fee is not returned
Evidence submitted nothing nothing A state, not money
Chargebackclock startsAcceptedEvidence sentWonLostreceivable up, card_clearing downreceivable to dispute_lossesreceivable back to card_clearingreceivable to dispute_losses

The diagram is the shape, and the key is the check. After every stage, dispute_receivable must equal the sum of the amounts of disputes that have a chargeback and no outcome. If it does not, a posting was missed, doubled or posted in the wrong order, and the receivable tells you the day.

Two rules of module 2 apply again. First, nothing is edited: a lost dispute adds a transaction that moves the claim to an expense, and the original chargeback entry stays. Second, the provider delivers the same event more than once, so exactly once is a property of your key, not of the network. The key is the dispute and the phase, open or close, not the event id. A provider may send several events for one dispute, such as updated and closed, and a retry can repeat any of them. With a unique key on the dispute and the phase, a repeat is harmless, and a second outcome, such as lost after won, is refused with a reason a person can read. That is the same idea as an idempotency key, applied to a state machine with two money phases.

The ledger is one of three records, as in reconciliation. The processor’s settlement report carries the chargeback debits and the won reversals as lines of their own, and the lab’s mock puts them under chargebacks_kobo and dispute_reversals_kobo. A chargeback you have not posted is a break of the kind reconciliation finds: a settlement shorter than card_clearing expects.

Fight or accept

Every dispute costs the fee. The lab’s is ₦1,000, paid win or lose, as it is in the data. So the choice between accepting and answering is only about the amount you might recover and what answering costs: a person’s time to collect the facts, write them and watch a deadline. Accept when the chance of winning, times the amount, is less than that cost.

The chance is something Owoleaf can measure from its own history. In the 109 disputes, 20 were accepted and 89 had evidence submitted. Of those 89, 61 were won. Split by reason and by what 3-D Secure did on the sale, they look very different:

Reason 3-D Secure Accepted Fought Won Win rate
fraud challenged 0 37 34 92%
fraud not challenged 20 6 1 17%
not_recognised challenged 0 4 1 25%
not_recognised not challenged 0 25 15 60%
not_credited not challenged 0 10 7 70%
duplicate not challenged 0 7 3 43%

(3-D Secure is the card scheme’s way of asking the cardholder to prove it is them, with a one-time code or an app approval. The chapter on authenticating the payer, later in this module, covers how it works; here it is a field on the card attempt.) The 92% is the lab’s own rate, and the generator built it to be high. The lesson is the shape: a fraud dispute where the payer passed a challenge is a different kind of dispute from one where nobody was asked. Several groups are small. Six fought disputes is not a win rate to rely on, and not_recognised with a challenge has only four. A rule built on them should say so.

What goes in the evidence is a different question, and it is where the temptation lies. Evidence is facts, each from a record someone else could check: the provider’s own record of the charge, the issuer’s approval code, what the ledger credited, what the customer did with the money afterwards, the 3-D Secure result. It must never include a fact the records do not hold. A pack that says the customer authenticated, when the field says frictionless, is a false statement to the card network, and the provider’s mock cannot tell. A real issuer can.

Visa’s Compelling Evidence 3.0, as described in search results, lets a merchant answer certain card-not-present fraud disputes with at least two earlier undisputed transactions on the same payment method, settled between 120 and 365 days before the dispute, where at least two data elements match and one of them is the IP address or the device identifier. Sources differ on the exact matching rule and on which date the window is measured from, and the page was not opened in this build, so read Visa’s rules or your acquirer’s guide before relying on the shapeas of 2026-11. History as evidence needs history. Owoleaf’s data is 180 days long and its disputed customers are mostly new, so the lab’s evidence pack counts the earlier undisputed fundings on the card and says how many are old enough. Step 3 asks the same question of all 109 disputes, and the answer is that none has two on the same card and device at least 120 days earlier. A ring of new accounts is exactly the case where history is empty.

Evidence also has a clock. The pack has to arrive before evidence_due_at, and the receiver must answer the webhook that carries the dispute, not wait for someone to open a dashboard. The chapter on integrating a provider built the receiver; here it does more: verify the signature, keep each event once, build the pack, decide, and answer.

Refund abuse and the wallet

Two words need defining. Friendly fraud is a dispute by a cardholder who made the purchase or received its benefit and disputes it anyway. Refund abuse is getting money back twice, or on a claim that is not true. The commonest form is a refund followed by a chargeback.

The refund-then-chargeback case is arithmetic, and the lab runs it. A ₦20,000 card payment is captured. Support refunds all of it. Weeks later the cardholder disputes the same payment, and the provider debits the chargeback and the fee: ₦20,000 and ₦1,000. In settlement terms Owoleaf has taken ₦20,000, paid the provider a ₦200 processing fee, returned ₦20,000 as a refund and ₦21,000 as a chargeback and fee: 2,000,000 − 20,000 − 2,000,000 − 2,100,000 = −2,120,000 kobo, a loss of ₦21,200.00 on a ₦20,000 sale. The other order, chargeback first, is cheaper only because support can be stopped: with the dispute open, a refund guard refuses, and the money goes back through the dispute once, which costs −₦1,200.00.

The guard has a limit that is worth saying out loud. It can only refuse a refund for a dispute it knows about. If the refund comes first, the chargeback comes second, and nothing at refund time could have known. The defence in that order is evidence: proof of the refund, with its date and id. The lab’s mock, like most providers, takes that evidence on trust, and the processor’s rules on refunded charges are in its contract.

For a wallet company, a disputed top-up has a second exposure that a shop does not have. The customer’s money is in a wallet, and it may leave before the chargeback arrives. Across the 109 disputes, 13 arrived within 14 days of the funding and 46 within 30. A hold on withdrawals of card-funded money that is shorter than the dispute window protects against the early ones only. In the lab’s data the exposure was small: on the day each chargeback arrived, the wallets still held 94.5% of the disputed amount, and only 3 of 109 held none of it. That is the lab, not the world. The ring in the data does not cash out fast, and a real ring does. A balance is also fungible: the money in a wallet may be another top-up. Taking it back from the customer needs a clause in the terms and a check against consumer-protection rules, and it is a policy a person signs. Machine-learning fraud scoring is a later chapter of this module, and fraud systems in depth belong to the Compliance course; neither is repeated here.

Where it goes wrong

Name the failures first. Each looks like a working process.

Counting disputes by arrival only. The ring is invisible while it runs, and the ratio looks calm for the month after. Watch a cohort view as well, even though it is late.

Watching naira, not counts. A value ratio of 0.83% in April hid a count ratio of 1.78%. A programme counts items.

Booking the debit as a loss. Every open dispute is then a loss that may be won. Use the receivable, and check it against the stages.

Posting by event. Two deliveries make two postings. The lab’s second replay posts nothing, because the key is the dispute and the phase.

A refund button that does not know about disputes. It pays twice. Make the guard ask the provider as well as your own table, because your table may not have received the webhook yet.

An evidence pack that says more than the records do. A sentence that the cardholder confirmed by phone, from no record, is a false statement. Every sentence cites a fact id, as in the dispute evidence step of the LLM chapter.

Answering everything, or nothing. Fighting a dispute you win one time in six, for ₦3,964, loses time. Accepting every dispute gives up the 92% ones.

Fighting disputes but not preventing them. A win does not leave the ratio. Fewer disputes does, which is a matter of authentication, descriptors, delivery proof and refunds that are fast enough that a customer does not need a chargeback.

What Ojaline builds

Ehi and Imaobong build in this order. First the refund guard, because it stops a loss that is certain. Second the posting function, with the receivable checked against the stages every day, because the books must agree with the processor before anything else can be trusted. Third the receiver, with the pack and the expected-value rule and a person who signs the answers. Last the ratio, in two views, cohort and arrival, with the processor’s own count beside it. The arrival view is the one a programme can compute at the time, and the cohort view is the one that warns.

LAB Measure the ratio three ways, post chargebacks exactly once, answer webhooks with evidence, and see a refund paid twice ~60 MIN
YOU NEEDPython 3.9 or later (standard library only)labs/finance with the data generated (python3 generate.py, then python3 cards.py)Three terminals for steps 4 and 5No Docker, no packages, no sqlite3 program

You work in labs/finance. The scripts go in a work folder so the lab’s own files stay clean. The data is generated at seed 42 and scale 0.1, so your numbers match the ones below. Every query goes through Python’s sqlite3 module. The generator’s fee, window, reasons and win rates are invented and labelled so. Do not open data/answers/card_fraud_truth.csv: later chapters use it.

1. Measure the ratio three ways. Make sure the card tables exist, then save work/ratio.py and work/vamp.py.

cd labs/finance
ls data/disputes.csv >/dev/null 2>&1 || (python3 generate.py && python3 cards.py)
python3 check.py
mkdir -p work

The last two lines of check.py read card book: 10,680 card attempts, 109 disputes for 91,728,900 kobo; checks 12-15 run and OK: all invariants hold. If you ran loans.py earlier, a line about the loan book appears too.

"""Owoleaf's dispute ratio by month, two ways. Money is integer kobo."""
import datetime as dt
import sqlite3
import statistics
from collections import defaultdict

db = sqlite3.connect("data/finance.sqlite")

sales = defaultdict(lambda: [0, 0])          # month of the funding -> [count, kobo]
for month, n, kobo in db.execute("""
        SELECT substr(created_at, 1, 7), COUNT(*), SUM(amount_kobo) FROM transactions
        WHERE kind = 'funding_card' AND status = 'succeeded' GROUP BY 1"""):
    sales[month] = [n, kobo]

by_funding = defaultdict(lambda: [0, 0])     # the month the disputed funding was made
by_opened = defaultdict(lambda: [0, 0])      # the month the chargeback arrived
for fmonth, omonth, kobo in db.execute("""
        SELECT substr(t.created_at, 1, 7), substr(d.opened_at, 1, 7), d.amount_kobo
        FROM disputes d JOIN transactions t ON t.id = d.transaction_id"""):
    by_funding[fmonth][0] += 1
    by_funding[fmonth][1] += kobo
    by_opened[omonth][0] += 1
    by_opened[omonth][1] += kobo

print("A. by month of the funding (a cohort: every dispute of that month's sales)")
print(f"{'month':8}{'sales':>7}{'disputes':>10}{'count %':>9}{'value %':>9}")
for m in sorted(sales):
    n, kobo = sales[m]
    d, dk = by_funding[m]
    print(f"{m:8}{n:>7,}{d:>10}{100 * d / n:>9.2f}{100 * dk / kobo:>9.2f}")

print("\nB. by month the chargeback arrived, over that month's sales")
print(f"{'month':8}{'sales':>7}{'disputes':>10}{'count %':>9}{'prior-month %':>15}")
months = sorted(set(sales) | set(by_opened))
for i, m in enumerate(months):
    d = by_opened[m][0]
    n = sales[m][0]
    prev = sales[months[i - 1]][0] if i else 0
    print(f"{m:8}{n:>7,}{d:>10}{(100 * d / n if n else 0):>9.2f}{(100 * d / prev if prev else 0):>15.2f}")

total_d, total_n = sum(v[0] for v in by_funding.values()), sum(v[0] for v in sales.values())
print(f"\nall months: {total_d} disputes on {total_n:,} succeeded card fundings = {100 * total_d / total_n:.2f}%")

lags = defaultdict(list)                     # days from the funding to the chargeback, by reason
for reason, funded, opened in db.execute("""SELECT d.reason, t.created_at, d.opened_at FROM disputes d
                                            JOIN transactions t ON t.id = d.transaction_id"""):
    lags[reason].append((dt.datetime.fromisoformat(opened) - dt.datetime.fromisoformat(funded)).days)
print("\ndays from funding to chargeback")
for reason, v in sorted(lags.items()):
    print(f"  {reason:16} {len(v):>3} disputes: shortest {min(v)}, median {statistics.median(v):.0f}, longest {max(v)}")
every = [x for v in lags.values() for x in v]
for days in (14, 30):
    print(f"  arriving within {days} days of the funding: {sum(1 for x in every if x <= days)} of {len(every)}")

Run it with python3 work/ratio.py.

A. by month of the funding (a cohort: every dispute of that month's sales)
month     sales  disputes  count %  value %
2026-01     224         1     0.45     0.41
2026-02     655         7     1.07     0.49
2026-03   1,284        15     1.17     1.32
2026-04   2,018        36     1.78     0.83
2026-05   2,902        24     0.83     0.54
2026-06   3,197        26     0.81     0.98

B. by month the chargeback arrived, over that month's sales
month     sales  disputes  count %  prior-month %
2026-01     224         0     0.00           0.00
2026-02     655         1     0.15           0.45
2026-03   1,284        10     0.78           1.53
2026-04   2,018        12     0.59           0.93
2026-05   2,902        24     0.83           1.19
2026-06   3,197        30     0.94           1.03
2026-07       0        24     0.00           0.75
2026-08       0         8     0.00           0.00

all months: 109 disputes on 10,280 succeeded card fundings = 1.06%

days from funding to chargeback
  duplicate          7 disputes: shortest 4, median 34, longest 60
  fraud             63 disputes: shortest 13, median 44, longest 74
  not_credited      10 disputes: shortest 4, median 26, longest 57
  not_recognised    29 disputes: shortest 3, median 27, longest 60
  arriving within 14 days of the funding: 13 of 109
  arriving within 30 days of the funding: 46 of 109

Table A is the cohort view and its April is 1.78%. Table B’s second column divides by the same month’s sales and peaks in June at 0.94%; its last column divides by the previous month’s sales and peaks in March at 1.53%, because 10 chargebacks met 655 sales. July and August have disputes and no sales: the generated data stops on 29 June, so those rows show how late the chargebacks arrive. The ratio over all months is 109 of 10,280, 1.06%. The last block shows the delay: the median fraud dispute arrives 44 days after the sale.

"""A VAMP-style count: fraud reports plus disputes, over settled card fundings, by funding month."""
import sqlite3
from collections import defaultdict

db = sqlite3.connect("data/finance.sqlite")
sales = dict(db.execute("""SELECT substr(created_at, 1, 7), COUNT(*) FROM transactions
                           WHERE kind = 'funding_card' AND status = 'succeeded' GROUP BY 1"""))
disp = defaultdict(set)
issuer = defaultdict(set)
for tid, month in db.execute("SELECT d.transaction_id, substr(t.created_at, 1, 7) FROM disputes d JOIN transactions t ON t.id = d.transaction_id"):
    disp[month].add(tid)
for tid, month in db.execute("""SELECT f.transaction_id, substr(t.created_at, 1, 7) FROM fraud_reports f
                                JOIN transactions t ON t.id = f.transaction_id WHERE f.source = 'issuer_report'"""):
    issuer[month].add(tid)

print(f"{'month':8}{'sales':>7}{'disputes':>10}{'issuer':>8}{'both':>6}{'added %':>9}{'once %':>8}")
for m in sorted(sales):
    d, i = disp[m], issuer[m]
    print(f"{m:8}{sales[m]:>7,}{len(d):>10}{len(i):>8}{len(d & i):>6}"
          f"{100 * (len(d) + len(i)) / sales[m]:>9.2f}{100 * len(d | i) / sales[m]:>8.2f}")

Run it with python3 work/vamp.py.

month     sales  disputes  issuer  both  added %  once %
2026-01     224         1       0     0     0.45    0.45
2026-02     655         7       2     1     1.37    1.22
2026-03   1,284        15       4     3     1.48    1.25
2026-04   2,018        36      13    10     2.43    1.93
2026-05   2,902        24       7     6     1.07    0.86
2026-06   3,197        26      10     8     1.13    0.88

added counts disputes plus issuer fraud reports as the VAMP formula adds them; once counts a transaction once. April’s 36 disputes and 13 reports overlap on 10 transactions: (36 + 13) / 2,018 = 2.43%, and (36 + 13 − 10) / 2,018 = 1.93%.

2. Post the chargebacks to a copy of the ledger. Save work/dledger.py. It copies data/finance.sqlite to work/ledger.sqlite, adds the three accounts and a dispute_postings table whose primary key is (dispute, phase), and posts each stage inside one database transaction. It tries the guards first, then replays the disputes to 30 April, then to the cut-off, then replays everything again.

"""Post chargebacks to a COPY of Owoleaf's ledger, one stage at a time, exactly once, and prove the books balance.

Stages that move money: chargeback (opens), then exactly one of accepted, lost or won (closes).
Evidence submitted moves nothing. Money is integer kobo.
"""
import shutil
import sqlite3
import sys

SRC, COPY = "data/finance.sqlite", "work/ledger.sqlite"
PHASE = {"chargeback": "open", "accepted": "close", "lost": "close", "won": "close"}


class Refused(Exception):
    pass


def setup():
    shutil.copy(SRC, COPY)
    db = sqlite3.connect(COPY, isolation_level=None)
    for code, name, typ in [
        ("dispute_receivable", "Card money withheld for a chargeback, claimed back until it is decided", "asset"),
        ("chargeback_fees", "The processor's fee per chargeback, win or lose", "expense"),
        ("dispute_losses", "Chargebacks that stood", "expense"),
    ]:
        db.execute("INSERT INTO accounts (code, name, type, customer_id, currency, opened_at) VALUES (?,?,?,NULL,'NGN','2026-01-01T00:00:00+01:00')",
                   (code, name, typ))
    db.execute("""CREATE TABLE dispute_postings (
        dispute_id INTEGER NOT NULL, phase TEXT NOT NULL, stage TEXT NOT NULL, transaction_id INTEGER NOT NULL,
        PRIMARY KEY (dispute_id, phase))""")        # the key is what makes a repeat harmless
    return db


def post_stage(db, dispute_id, stage, at):
    """Post one stage. Returns 'posted' or 'already posted'; raises Refused for an out-of-order or conflicting stage."""
    if stage not in PHASE:
        raise Refused(f"stage {stage} moves no money")
    phase = PHASE[stage]
    acct = {c: i for i, c in db.execute("SELECT id, code FROM accounts WHERE code IN ('card_clearing', 'dispute_receivable', 'chargeback_fees', 'dispute_losses')")}
    db.execute("BEGIN IMMEDIATE")
    try:
        row = db.execute("SELECT transaction_id, amount_kobo, fee_kobo FROM disputes WHERE id = ?", (dispute_id,)).fetchone()
        if not row:
            raise Refused(f"no dispute {dispute_id}")
        funding, amount, fee = row
        have = dict(db.execute("SELECT phase, stage FROM dispute_postings WHERE dispute_id = ?", (dispute_id,)))
        if phase == "close" and "open" not in have:
            raise Refused(f"dispute {dispute_id}: {stage} before the chargeback was posted")
        if phase in have:
            if have[phase] == stage:
                db.execute("ROLLBACK")
                return "already posted"
            raise Refused(f"dispute {dispute_id}: already {have[phase]}, cannot post {stage}")
        legs = {
            "chargeback": [("dispute_receivable", "debit", amount), ("chargeback_fees", "debit", fee),
                           ("card_clearing", "credit", amount + fee)],
            "accepted": [("dispute_losses", "debit", amount), ("dispute_receivable", "credit", amount)],
            "lost": [("dispute_losses", "debit", amount), ("dispute_receivable", "credit", amount)],
            "won": [("card_clearing", "debit", amount), ("dispute_receivable", "credit", amount)],
        }[stage]
        assert sum(k for _, d, k in legs if d == "debit") == sum(k for _, d, k in legs if d == "credit")
        cur = db.execute("""INSERT INTO transactions (kind, status, customer_id, amount_kobo, fee_kobo, rail, external_ref,
                            related_transaction_id, created_at) VALUES (?, 'succeeded', NULL, ?, ?, 'card', ?, ?, ?)""",
                         (f"dispute_{stage}", amount, fee if stage == "chargeback" else 0, f"DISPUTE{dispute_id:06d}-{stage}", funding, at))
        tid = cur.lastrowid
        for code, direction, kobo in legs:
            db.execute("INSERT INTO entries (transaction_id, account_id, direction, amount_kobo, posted_at) VALUES (?,?,?,?,?)",
                       (tid, acct[code], direction, kobo, at))
        db.execute("INSERT INTO dispute_postings VALUES (?,?,?,?)", (dispute_id, phase, stage, tid))
        db.execute("COMMIT")
        return "posted"
    except BaseException:
        if db.in_transaction:
            db.execute("ROLLBACK")
        raise


def balance(db, code):
    return db.execute("""SELECT COALESCE(SUM(CASE e.direction WHEN 'debit' THEN e.amount_kobo ELSE -e.amount_kobo END), 0)
                         FROM entries e JOIN accounts a ON a.id = e.account_id WHERE a.code = ?""", (code,)).fetchone()[0]


def unbalanced(db):
    return db.execute("""SELECT COUNT(*) FROM (SELECT transaction_id FROM entries GROUP BY transaction_id
                         HAVING SUM(CASE direction WHEN 'debit' THEN amount_kobo ELSE -amount_kobo END) <> 0)""").fetchone()[0]


def open_by_the_events(db, until):
    """Independent of the ledger: what the dispute stages say is open at `until`."""
    return db.execute("""SELECT COUNT(*), COALESCE(SUM(d.amount_kobo), 0) FROM disputes d
        WHERE EXISTS (SELECT 1 FROM dispute_events e WHERE e.dispute_id = d.id AND e.stage = 'chargeback' AND e.at <= :u)
          AND NOT EXISTS (SELECT 1 FROM dispute_events e WHERE e.dispute_id = d.id AND e.stage IN ('accepted', 'lost', 'won') AND e.at <= :u)""",
                      {"u": until}).fetchone()


def replay(db, until):
    n = {"posted": 0, "already posted": 0}
    for did, stage, at in db.execute("""SELECT dispute_id, stage, at FROM dispute_events
                                        WHERE stage IN ('chargeback', 'accepted', 'lost', 'won') AND at <= ? ORDER BY at, id""", (until,)).fetchall():
        n[post_stage(db, did, stage, at)] += 1
    return n


def report(db, label, until):
    cnt, kobo = open_by_the_events(db, until)
    rec = balance(db, "dispute_receivable")
    ok = "matches" if rec == kobo else "DIFFERS"
    print(f"{label}: {unbalanced(db)} unbalanced transactions; dispute_receivable {rec:,} kobo; "
          f"the stages say {cnt} open for {kobo:,} kobo ({ok})")


if __name__ == "__main__":
    db = setup()
    print("guards")
    for args in [(1, "won", "2026-03-01T10:00:00+01:00")]:
        try:
            post_stage(db, *args)
        except Refused as e:
            print("  refused:", e)
    first = db.execute("SELECT dispute_id, at FROM dispute_events WHERE stage = 'chargeback' ORDER BY at, id LIMIT 1").fetchone()
    print("  first chargeback:", post_stage(db, first[0], "chargeback", first[1]))
    print("  the same delivery again:", post_stage(db, first[0], "chargeback", first[1]))
    try:
        post_stage(db, first[0], "won", "2026-12-31T10:00:00+01:00")
        post_stage(db, first[0], "lost", "2026-12-31T11:00:00+01:00")
    except Refused as e:
        print("  refused:", e)
    db.close()
    db = setup()                                   # start again from the untouched copy
    report(db, "before any dispute", "2026-01-01T00:00:00+01:00")
    print("replayed to 30 April:", replay(db, "2026-04-30T23:59:59+01:00"))
    report(db, "as of 30 April", "2026-04-30T23:59:59+01:00")
    print("replayed to the cut-off:", replay(db, "2026-10-28T23:59:59+01:00"))
    print("replayed again:", replay(db, "2026-10-28T23:59:59+01:00"))
    report(db, "at the cut-off", "2026-10-28T23:59:59+01:00")
    for stage in ("chargeback", "accepted", "lost", "won"):
        n, k = db.execute("SELECT COUNT(*), COALESCE(SUM(amount_kobo), 0) FROM transactions WHERE kind = ?", (f"dispute_{stage}",)).fetchone()
        print(f"  {stage:11}{n:>4} postings{k:>14,} kobo")
    print(f"  chargeback_fees {balance(db, 'chargeback_fees'):,} kobo; dispute_losses {balance(db, 'dispute_losses'):,} kobo")
    fees = db.execute("SELECT SUM(fee_kobo) FROM transactions WHERE kind = 'funding_card' AND status = 'succeeded'").fetchone()[0]
    cost = balance(db, "chargeback_fees") + balance(db, "dispute_losses")
    print(f"disputes cost {cost:,} kobo, {100 * cost / fees:.1f}% of the {fees:,} kobo that customers paid in fees on card top-ups")

Run it, then run the lab’s own checker over the copy.

python3 work/dledger.py
python3 check.py --db work/ledger.sqlite
guards
  refused: dispute 1: won before the chargeback was posted
  first chargeback: posted
  the same delivery again: already posted
  refused: dispute 1: already won, cannot post lost
before any dispute: 0 unbalanced transactions; dispute_receivable 0 kobo; the stages say 0 open for 0 kobo (matches)
replayed to 30 April: {'posted': 32, 'already posted': 0}
as of 30 April: 0 unbalanced transactions; dispute_receivable 12,162,400 kobo; the stages say 14 open for 12,162,400 kobo (matches)
replayed to the cut-off: {'posted': 186, 'already posted': 32}
replayed again: {'posted': 0, 'already posted': 218}
at the cut-off: 0 unbalanced transactions; dispute_receivable 0 kobo; the stages say 0 open for 0 kobo (matches)
  chargeback  109 postings    91,728,900 kobo
  accepted     20 postings    20,609,700 kobo
  lost         28 postings    19,786,200 kobo
  won          61 postings    51,333,000 kobo
  chargeback_fees 10,900,000 kobo; dispute_losses 40,395,900 kobo
disputes cost 51,295,900 kobo, 31.0% of the 165,247,321 kobo that customers paid in fees on card top-ups

A chargeback before it is received, a repeat and a second outcome are refused or ignored. On 30 April 14 disputes are open for ₦121,624.00 (12,162,400 kobo), and the receivable says the same. At the cut-off none is open, 109 chargebacks of ₦917,289.00 are posted, and of them 61 are won (₦513,330.00), 20 accepted and 28 lost. The expense is ₦109,000.00 of fees (109 × ₦1,000) and ₦403,959.00 of losses (20,609,700 + 19,786,200 = 40,395,900 kobo): ₦512,959.00, 31.0% of the card fees customers paid. The replay at the end posts nothing: 218 repeats were ignored.

card book: 10,680 card attempts, 109 disputes for 91,728,900 kobo; checks 12-15 run
accounts by type (debit-positive kobo): {'asset': 17303758989, 'equity': -5000000000, 'expense': 161886167, 'income': -221782321, 'liability': -12243862835}
settlement_bank in ledger 17,189,646,589 kobo; on the statement 17,192,741,324 kobo
6 skipped: no answers/breaks.csv beside the database (looked for …/labs/finance/work/answers/breaks.csv)
OK: all invariants hold

Every transaction still balances and invariants 12 to 15, which concern the card tables, still hold. Check 6 is skipped because the copy has no answers/breaks.csv beside it; the path in your output is your own.

3. See what Owoleaf fought and what the wallets held. Save work/fight.py and work/exposure.py.

"""Which disputes did Owoleaf fight, and how did they end? By reason and by what 3-D Secure did on the funding."""
import datetime as dt
import sqlite3
from collections import defaultdict

db = sqlite3.connect("data/finance.sqlite")
rows = db.execute("""
    SELECT d.reason, a.three_ds, d.status, d.amount_kobo,
           EXISTS (SELECT 1 FROM dispute_events e WHERE e.dispute_id = d.id AND e.stage = 'evidence_submitted')
    FROM disputes d JOIN card_attempts a ON a.transaction_id = d.transaction_id""").fetchall()

groups = defaultdict(lambda: {"accepted": 0, "won": 0, "lost": 0, "won_kobo": 0, "lost_kobo": 0})
for reason, three_ds, status, kobo, fought in rows:
    g = groups[(reason, "challenge" if three_ds == "challenge" else "no challenge")]
    g[status] += 1
    if status == "won":
        g["won_kobo"] += kobo
    elif status == "lost":
        g["lost_kobo"] += kobo

print(f"{'reason':16}{'3-D Secure':14}{'accepted':>9}{'fought':>8}{'won':>5}{'lost':>6}{'win rate':>10}")
for (reason, ds), g in sorted(groups.items()):
    fought = g["won"] + g["lost"]
    rate = f"{100 * g['won'] / fought:.0f}%" if fought else "-"
    print(f"{reason:16}{ds:14}{g['accepted']:>9}{fought:>8}{g['won']:>5}{g['lost']:>6}{rate:>10}")
print("evidence was submitted on", sum(1 for r in rows if r[4]), "of", len(rows), "disputes; every accepted one had none")

# History as evidence: earlier undisputed fundings on the same card, and on the same card and device, 120 or more days before.
any_prior = old_same_device = 0
for did, funded, card, device in db.execute("""SELECT d.id, t.created_at, a.card_id, a.device_id FROM disputes d
        JOIN transactions t ON t.id = d.transaction_id JOIN card_attempts a ON a.transaction_id = t.id"""):
    prior = db.execute("""SELECT t.created_at, a.device_id FROM card_attempts a JOIN transactions t ON t.id = a.transaction_id
                          WHERE a.card_id = ? AND t.status = 'succeeded' AND t.created_at < ?
                            AND NOT EXISTS (SELECT 1 FROM disputes x WHERE x.transaction_id = t.id)""", (card, funded)).fetchall()
    old = [p for p in prior if (dt.datetime.fromisoformat(funded) - dt.datetime.fromisoformat(p[0])).days >= 120 and p[1] == device]
    any_prior += bool(prior)
    old_same_device += len(old) >= 2
print(f"{any_prior} of {len(rows)} disputed fundings have an earlier undisputed funding on the card; "
      f"{old_same_device} have two on the same card and device at least 120 days earlier")
"""Where was the money when the chargeback arrived? The wallet's balance on the day, against what the top-up credited."""
import sqlite3
from collections import defaultdict

db = sqlite3.connect("data/finance.sqlite")
rows = db.execute("""
    SELECT d.id, d.reason, d.amount_kobo, d.opened_at, t.created_at, t.amount_kobo - t.fee_kobo, a.id
    FROM disputes d
    JOIN transactions t ON t.id = d.transaction_id
    JOIN accounts a ON a.customer_id = t.customer_id AND a.code LIKE 'wallet:%'
    ORDER BY d.id""").fetchall()

def wallet_at(account_id, when):
    """Credit balance of a wallet at a moment, in kobo. Both timestamps are ISO with +01:00, so they sort as text."""
    return db.execute("""SELECT COALESCE(SUM(CASE direction WHEN 'credit' THEN amount_kobo ELSE -amount_kobo END), 0)
                         FROM entries WHERE account_id = ? AND posted_at <= ?""", (account_id, when)).fetchone()[0]

tally = defaultdict(lambda: [0, 0, 0])       # reason -> [disputes, kobo disputed, kobo still held]
gone = 0
for did, reason, amount, opened, created, credited, acct in rows:
    held = min(amount, max(0, wallet_at(acct, opened)))
    t = tally[reason]
    t[0] += 1; t[1] += amount; t[2] += held
    gone += held == 0
print(f"{'reason':16}{'disputes':>9}{'disputed ₦':>15}{'still held ₦':>15}{'held %':>8}")
tot = [0, 0, 0]
for reason, (n, k, h) in sorted(tally.items()):
    print(f"{reason:16}{n:>9}{k / 100:>15,.2f}{h / 100:>15,.2f}{100 * h / k:>8.1f}")
    tot = [a + b for a, b in zip(tot, (n, k, h))]
print(f"{'all':16}{tot[0]:>9}{tot[1] / 100:>15,.2f}{tot[2] / 100:>15,.2f}{100 * tot[2] / tot[1]:>8.1f}")
print(f"disputes where the wallet held nothing of it: {gone} of {tot[0]}")

Run both.

python3 work/fight.py
python3 work/exposure.py
reason          3-D Secure     accepted  fought  won  lost  win rate
duplicate       no challenge          0       7    3     4       43%
fraud           challenge             0      37   34     3       92%
fraud           no challenge         20       6    1     5       17%
not_credited    no challenge          0      10    7     3       70%
not_recognised  challenge             0       4    1     3       25%
not_recognised  no challenge          0      25   15    10       60%
evidence was submitted on 89 of 109 disputes; every accepted one had none
49 of 109 disputed fundings have an earlier undisputed funding on the card; 0 have two on the same card and device at least 120 days earlier
reason           disputes     disputed ₦   still held ₦  held %
duplicate               7      72,135.00      72,135.00   100.0
fraud                  63     516,727.00     490,455.42    94.9
not_credited           10      54,683.00      48,751.70    89.2
not_recognised         29     273,744.00     255,548.66    93.4
all                   109     917,289.00     866,890.78    94.5
disputes where the wallet held nothing of it: 3 of 109

Fraud disputes with a 3-D Secure challenge were won 34 times in 37. Without a challenge, 20 were accepted and 1 of the 6 fought was won. No dispute has two earlier undisputed fundings on the same card and device at least 120 days old, although 49 have an earlier undisputed funding on the card at all. Most of the money was still in the wallet when the chargeback arrived: 866,890.78 of 917,289.00 naira. A balance is fungible, and the lab’s wallets are not a ring that cashes out, so read the figure as a floor on what a hold could protect, not a forecast.

4. Answer the webhooks with evidence. Start the provider with its webhooks pointed at your receiver. The flags make a decision take 3 seconds, make a well-evidenced dispute win so that the run repeats, and repeat half of all deliveries. A real processor decides on its own rules and its own time.

Terminal 1, from labs/finance:

python3 mock_provider.py --fresh --quiet --webhook-url http://127.0.0.1:9000/hook --dispute-review-seconds 3 --dispute-win-rate 1 --webhook-dup-rate 0.5

Save work/evidence.py. It verifies the signature (the method from integrating a provider), keeps each event id once, builds the pack from the provider, the ledger and the card attempt, decides by expected value, and submits evidence or accepts.

"""Dispute webhooks: verify, de-duplicate, build an evidence pack from facts, decide, answer.

  python3 work/evidence.py serve      the receiver on port 9000
  python3 work/evidence.py raise      raise three chargebacks at the provider and print what the receiver did
Money is integer kobo. REVIEW_COST_KOBO is ILLUSTRATIVE: what an hour of an analyst's time costs.
"""
import datetime as dt
import hashlib
import hmac
import json
import sqlite3
import sys
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

KEY = b"sk_test_owoleaf_mock"
PROVIDER, PORT = "http://127.0.0.1:8101", 9000
LEDGER = "data/finance.sqlite"
REVIEW_COST_KOBO = 250_000                       # ILLUSTRATIVE: ₦2,500 to prepare and answer one dispute
INBOX = sqlite3.connect("work/inbox.sqlite", check_same_thread=False, isolation_level=None, timeout=10)
INBOX.executescript("""
CREATE TABLE IF NOT EXISTS events (event_id TEXT PRIMARY KEY, type TEXT, seen INTEGER DEFAULT 1);
CREATE TABLE IF NOT EXISTS answers (dispute_id TEXT PRIMARY KEY, reference TEXT, reason TEXT, amount_kobo INTEGER,
    action TEXT, p_win REAL, pack TEXT, result TEXT);""")


def api(method, path, body=None):
    req = urllib.request.Request(PROVIDER + path, method=method, data=json.dumps(body).encode() if body is not None else None,
                                 headers={"Authorization": "Bearer " + KEY.decode(), "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.load(r)


def win_rates():
    """What Owoleaf's own fought disputes did, by reason and by whether 3-D Secure challenged the payer."""
    db = sqlite3.connect(LEDGER)
    g = {}
    for reason, ds, status in db.execute("""SELECT d.reason, a.three_ds = 'challenge', d.status FROM disputes d
                                            JOIN card_attempts a ON a.transaction_id = d.transaction_id WHERE d.status IN ('won', 'lost')"""):
        w, n = g.get((reason, bool(ds)), (0, 0))
        g[(reason, bool(ds))] = (w + (status == "won"), n + 1)
    return {k: (w / n, n) for k, (w, n) in g.items()}


def naira(kobo):
    return f"₦{kobo // 100:,}.{kobo % 100:02d}"


def build_pack(reference, reason):
    """Facts from three independent places, each labelled. Nothing is claimed that a fact does not show."""
    db = sqlite3.connect(LEDGER)
    t = db.execute("""SELECT t.id, t.customer_id, t.amount_kobo, t.fee_kobo, t.created_at, a.card_id, a.device_id,
                             a.device_age_days, a.ip_state, a.three_ds, a.approval_code
                      FROM transactions t JOIN card_attempts a ON a.transaction_id = t.id
                      WHERE t.external_ref = ? AND t.kind = 'funding_card'""", (reference,)).fetchone()
    if t is None:
        return None, 0, False                      # not one of the ledger's card fundings
    tid, cust, amount, fee, created, card, device, age, ip, three_ds, approval = t
    charge = api("GET", f"/charges/{reference}")["charge"]
    wallet = db.execute("SELECT id FROM accounts WHERE customer_id = ? AND code LIKE 'wallet:%'", (cust,)).fetchone()[0]
    credited = db.execute("SELECT amount_kobo FROM entries WHERE transaction_id = ? AND account_id = ?", (tid, wallet)).fetchone()[0]
    used = db.execute("""SELECT COUNT(*), COALESCE(SUM(amount_kobo), 0) FROM entries
                         WHERE account_id = ? AND direction = 'debit' AND posted_at > ?""", (wallet, created)).fetchone()
    prior = db.execute("""SELECT t.created_at FROM card_attempts a JOIN transactions t ON t.id = a.transaction_id
                          WHERE a.card_id = ? AND t.status = 'succeeded' AND t.created_at < ?
                            AND NOT EXISTS (SELECT 1 FROM disputes d WHERE d.transaction_id = t.id)""", (card, created)).fetchall()
    day = dt.datetime.fromisoformat(created)
    old = [p for p in prior if (day - dt.datetime.fromisoformat(p[0])).days >= 120]
    facts = {
        "F1": f"The provider reports charge {reference} as {charge['status']} ({charge['gateway_response']}) for {naira(charge['amount_kobo'])}, paid {charge['paid_at']}.",
        "F2": f"The issuer's approval code for the attempt was {approval}.",
        "F3": f"The ledger credited the customer's wallet {naira(credited)} after a customer fee of {naira(fee)}.",
        "F4": f"The wallet was debited {used[0]} times for {naira(used[1])} in all after the top-up.",
        "F5": f"The attempt came from a device first seen {age} days earlier, from an IP address in {ip}.",
        "F6": f"3-D Secure on the attempt: {three_ds}.",
        "F7": f"Earlier undisputed fundings on this card: {len(prior)}; of those, {len(old)} at least 120 days before this one.",
        "F8": f"The provider reports {charge['refunded_kobo']} kobo refunded.",
    }
    pack = {"summary": f"Top-up {reference}: " + " ".join(f"[{k}] {v}" for k, v in facts.items() if k in ("F1", "F2", "F3", "F8")),
            "customer_history": f"[F7] {facts['F7']} [F4] {facts['F4']}"}
    if three_ds == "challenge":                    # only a challenge is an authentication result
        pack["authentication"] = f"[F6] {facts['F6']}"
    return pack, amount, three_ds == "challenge"


def decide(reason, amount, challenged, rates):
    p, n = rates.get((reason, challenged)) or rates.get((reason, False)) or (0.0, 0)
    return ("fight" if p * amount > REVIEW_COST_KOBO else "accept"), p, n


class Hook(BaseHTTPRequestHandler):
    rates = win_rates()

    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        if not hmac.compare_digest(hmac.new(KEY, raw, hashlib.sha512).hexdigest(), self.headers.get("X-Mock-Signature", "")):
            self.send_response(401); self.send_header("Content-Length", "0"); self.end_headers()
            return
        ev = json.loads(raw)
        first = INBOX.execute("INSERT OR IGNORE INTO events (event_id, type) VALUES (?, ?)", (ev["id"], ev["type"])).rowcount
        if not first:
            INBOX.execute("UPDATE events SET seen = seen + 1 WHERE event_id = ?", (ev["id"],))
        elif ev["type"] == "charge.dispute.created":
            d = ev["data"]
            pack, amount, challenged = build_pack(d["charge_reference"], d["reason"])
            if pack is None:
                print(f"{d['id']}: {d['charge_reference']} is not in the ledger; nothing to answer here", flush=True)
                return self._ok()
            action, p, n = decide(d["reason"], d["amount_kobo"], challenged, self.rates)
            INBOX.execute("INSERT OR REPLACE INTO answers VALUES (?,?,?,?,?,?,?,NULL)",
                          (d["id"], d["charge_reference"], d["reason"], d["amount_kobo"], action, p, json.dumps(pack)))
            if action == "fight":
                api("POST", f"/disputes/{d['id']}/evidence", pack)
            else:
                api("POST", f"/disputes/{d['id']}/accept")
            print(f"{d['id']} {d['reason']} {naira(d['amount_kobo'])}: {action} (history says {p:.0%} of {n})", flush=True)
        elif ev["type"] == "charge.dispute.closed":
            d = ev["data"]
            INBOX.execute("UPDATE answers SET result = ? WHERE dispute_id = ?", (d["status"], d["id"]))
            print(f"{d['id']} closed: {d['status']}", flush=True)
        self._ok()

    def _ok(self):
        self.send_response(200); self.send_header("Content-Length", "0"); self.end_headers()

    def log_message(self, *a):
        pass


def pick():
    """One fraud funding that passed a challenge, one that did not (small), one 'not recognised' top-up that was spent."""
    db = sqlite3.connect(LEDGER)
    base = """SELECT t.external_ref, t.amount_kobo FROM transactions t JOIN card_attempts a ON a.transaction_id = t.id
              WHERE t.kind = 'funding_card' AND t.status = 'succeeded'
                AND NOT EXISTS (SELECT 1 FROM disputes d WHERE d.transaction_id = t.id) AND """
    a = db.execute(base + "a.three_ds = 'challenge' AND t.amount_kobo BETWEEN 2000000 AND 5000000 ORDER BY t.id LIMIT 1").fetchone()
    b = db.execute(base + "a.three_ds = 'frictionless' AND t.amount_kobo BETWEEN 300000 AND 800000 ORDER BY t.id LIMIT 1").fetchone()
    c = db.execute(base + "a.three_ds = 'frictionless' AND t.amount_kobo BETWEEN 1500000 AND 3000000 ORDER BY t.id LIMIT 1").fetchone()
    return [("fraud", *a), ("fraud", *b), ("not_recognised", *c)]


if __name__ == "__main__":
    if sys.argv[1:] == ["serve"]:
        print(f"receiver on :{PORT}; win rates from Owoleaf's own disputes: " +
              ", ".join(f"{r}{'+3DS' if c else ''} {p:.0%}/{n}" for (r, c), (p, n) in sorted(Hook.rates.items())), flush=True)
        ThreadingHTTPServer(("127.0.0.1", PORT), Hook).serve_forever()
    elif sys.argv[1:] == ["raise"]:
        for reason, ref, amount in pick():
            d = api("POST", "/admin/disputes", {"reference": ref, "reason": reason})["dispute"]
            print(f"raised {d['id']}: {reason} on {ref[-8:]} for {naira(amount)}, evidence due {d['evidence_due_at'][:10]}")
        time.sleep(12)
        print(f"\n{'dispute':22}{'reason':16}{'amount':>12}  action  result")
        for did, reason, amount, action, result in INBOX.execute("SELECT dispute_id, reason, amount_kobo, action, result FROM answers ORDER BY rowid"):
            print(f"{did:22}{reason:16}{naira(amount):>12}  {action:7} {result}")
        print("\nevents received:", [tuple(r) for r in INBOX.execute("SELECT type, COUNT(*), SUM(seen) FROM events GROUP BY type")])
        created = [e for e in api("GET", "/events")["events"] if e["type"] == "charge.dispute.created"][0]["id"]
        api("POST", f"/webhooks/replay/{created}")      # the provider sends the first 'created' event again
        time.sleep(2)
        print("\nafter a replay of", created, "->", tuple(INBOX.execute("SELECT type, seen FROM events WHERE event_id = ?", (created,)).fetchone()),
              "; answers:", INBOX.execute("SELECT COUNT(*) FROM answers").fetchone()[0])
        first = INBOX.execute("SELECT pack FROM answers ORDER BY rowid LIMIT 1").fetchone()[0]
        print("\nthe first pack:\n" + json.dumps(json.loads(first), indent=2, ensure_ascii=False))

Terminal 2, from labs/finance: rm -f work/inbox.sqlite; python3 work/evidence.py serve. Terminal 3: python3 work/evidence.py raise.

Terminal 1 prints mock_provider on http://127.0.0.1:8101 secret sk_test_owoleaf_mock webhooks -> http://127.0.0.1:9000/hook. Terminal 2 prints the win rates it learnt from Owoleaf’s own disputes, then one line per decision. Terminal 3 prints the following. The mock gives seven days to answer by default, which is why the date is a week ahead; the generated data uses ten.

raised dp_a1d78995fa61438d: fraud on 93382244 for ₦31,280.00, evidence due 2026-11-21
raised dp_23d7aadc6ccf4d85: fraud on 65641299 for ₦3,964.00, evidence due 2026-11-21
raised dp_d14654e0c90240be: not_recognised on 63835897 for ₦22,154.00, evidence due 2026-11-21

dispute               reason                amount  action  result
dp_a1d78995fa61438d   fraud             ₦31,280.00  fight   won
dp_23d7aadc6ccf4d85   fraud              ₦3,964.00  accept  lost
dp_d14654e0c90240be   not_recognised    ₦22,154.00  fight   won

events received: [('charge.dispute.closed', 3, 5), ('charge.dispute.created', 3, 3), ('charge.dispute.updated', 2, 4)]

after a replay of evt_65062b44407f4243 -> ('charge.dispute.created', 2) ; answers: 3

the first pack:
{
  "summary": "Top-up 364423343755727080331393382244: [F1] The provider reports charge 364423343755727080331393382244 as success (Approved) for ₦31,280.00, paid 2026-01-05T15:11:28+01:00. [F2] The issuer's approval code for the attempt was F4CFFZ. [F3] The ledger credited the customer's wallet ₦30,810.80 after a customer fee of ₦469.20. [F8] The provider reports 0 kobo refunded.",
  "customer_history": "[F7] Earlier undisputed fundings on this card: 1; of those, 0 at least 120 days before this one. [F4] The wallet was debited 46 times for ₦380,767.46 in all after the top-up.",
  "authentication": "[F6] 3-D Secure on the attempt: challenge."
}

Your dispute ids and the evidence date differ, and the duplicate counts vary from run to run. The first pack is for a ₦31,280.00 fraud dispute on a challenged payment, so it carries an authentication section and the receiver fights it. The second is a fraud dispute for ₦3,964.00 with no challenge: one in six of ₦3,964 is about ₦660.67, less than the ₦2,500 the rule says answering costs, so it is accepted. The third, a not_recognised dispute for ₦22,154.00, is fought on 60%. After the replay the event was seen twice and there are still three answers: the second delivery did nothing. The authentication section is absent from any pack where the field says anything but challenge.

5. Pay a sale back twice, then guard it. With the provider still running, save work/abuse.py. It charges test card 0001 twice. Charge A is refunded in full and then disputed. Charge B is disputed first, and then support tries to refund it.

"""Refund, then chargeback: the same sale paid back twice. Then the guard that stops the refund after a chargeback."""
import datetime as dt
import json
import time
import urllib.request

PROVIDER, KEY = "http://127.0.0.1:8101", "sk_test_owoleaf_mock"
RUN = int(time.time())


def api(method, path, body=None):
    req = urllib.request.Request(PROVIDER + path, method=method, data=json.dumps(body).encode() if body is not None else None,
                                 headers={"Authorization": "Bearer " + KEY, "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.load(r)


def charge(label):
    ref = f"SALE-{label}-{RUN}"
    api("POST", "/charges", {"reference": ref, "amount_kobo": 2_000_000, "customer_ref": "C0000042",
                             "card_number": "4000000000000001"})          # test card 0001 succeeds
    return ref


def open_dispute(ref):
    return [d for d in api("GET", "/disputes")["disputes"]
            if d["charge_reference"] == ref and d["status"] in ("needs_response", "under_review")]


def refund(ref):
    """The guard: no refund while a chargeback is open. Money goes back through the dispute, once."""
    if open_dispute(ref):
        return "REFUSED: a chargeback is open on this charge; accept the dispute instead of refunding"
    r = api("POST", "/refunds", {"reference": ref})["refund"]
    return f"refund {r['status']} for {r['amount_kobo']:,} kobo"


# A: the refund goes first, the chargeback arrives later (no guard could have known)
a = charge("A")
print("A refund:", refund(a))
time.sleep(6)                                                  # the mock processes a refund after 5 seconds
dp = api("POST", "/admin/disputes", {"reference": a, "reason": "not_recognised"})["dispute"]
print("A chargeback:", dp["status"], f"{dp['amount_kobo']:,} kobo, fee {dp['fee_kobo']:,}")
api("POST", f"/disputes/{dp['id']}/accept")

# B: the chargeback arrives first, then support tries to refund
b = charge("B")
dpb = api("POST", "/admin/disputes", {"reference": b, "reason": "not_recognised"})["dispute"]
print("B refund:", refund(b))
api("POST", f"/disputes/{dpb['id']}/accept")

tomorrow = (dt.date.today() + dt.timedelta(days=1)).isoformat()
s = api("GET", f"/settlements?date={tomorrow}")
print(f"\nsettlement for {tomorrow}")
for name, ref in (("A", a), ("B", b)):
    gross = sum(x["amount_kobo"] for x in s["lines"] if x["reference"] == ref)
    fee = round(gross * 0.01)
    refunded = sum(x["amount_kobo"] for x in s["refunds"] if x["reference"] == ref)
    cb = sum(x["amount_kobo"] + x["fee_kobo"] for x in s["chargebacks"] if x["charge_reference"] == ref)
    print(f"{name}: captured {gross:,} - processing fee {fee:,} - refunded {refunded:,} - chargeback and fee {cb:,}"
          f" = {gross - fee - refunded - cb:,} kobo")

Run python3 work/abuse.py.

A refund: refund pending for 2,000,000 kobo
A chargeback: needs_response 2,000,000 kobo, fee 100,000
B refund: REFUSED: a chargeback is open on this charge; accept the dispute instead of refunding

settlement for 2026-11-15
A: captured 2,000,000 - processing fee 20,000 - refunded 2,000,000 - chargeback and fee 2,100,000 = -2,120,000 kobo
B: captured 2,000,000 - processing fee 20,000 - refunded 0 - chargeback and fee 2,100,000 = -120,000 kobo

The settlement date is the day after you run it. A is the double payment: 2,000,000 − 20,000 − 2,000,000 − 2,100,000 = −2,120,000 kobo, ₦21,200.00 lost on a ₦20,000 sale. B is the best a lost dispute can be: −120,000 kobo, the ₦1,000 fee and the ₦200 processing fee. The guard stopped the refund because the provider said a dispute was open.

Remove the receiver’s memory of events, and replay one. Stop the receiver in terminal 2, make a copy with the check taken out, and start it. Then run work/failing.py, which replays the first charge.dispute.created event and lists the deliveries of it that failed.

sed '/INSERT OR IGNORE INTO events/s/.*/        first = 1/' work/evidence.py > work/evidence_break.py
python3 work/evidence_break.py serve

Save work/failing.py and run it from terminal 3.

"""Replay the first dispute.created event and list the deliveries of it that did not succeed."""
import json
import time
import urllib.request

PROVIDER, KEY = "http://127.0.0.1:8101", "sk_test_owoleaf_mock"


def call(path, method="GET"):
    req = urllib.request.Request(PROVIDER + path, method=method, data=b"" if method == "POST" else None,
                                 headers={"Authorization": "Bearer " + KEY})
    return json.load(urllib.request.urlopen(req, timeout=10))


created = [e["id"] for e in call("/events")["events"] if e["type"] == "charge.dispute.created"][0]
call("/webhooks/replay/" + created, "POST")
time.sleep(10)                                   # the provider retries after 2 s, then 4 s, then 8 s
failed = sorted({(d["attempt"], d["outcome"]) for d in call("/webhooks/deliveries")["deliveries"]
                 if d["event_id"] == created and d["outcome"] != "delivered"})
for attempt, outcome in failed:
    print(created, "attempt", attempt, outcome)

The receiver now treats the second delivery as a new dispute and sends evidence again. The provider answers 400 because the dispute is already under review, the handler raises, the connection drops and the provider retries.

evt_65062b44407f4243 attempt 1 error: RemoteDisconnected
evt_65062b44407f4243 attempt 2 error: RemoteDisconnected
evt_65062b44407f4243 attempt 3 error: RemoteDisconnected

Each retry fails the same way, after 2, 4 and then 8 seconds, up to six attempts. The cause is not the signature or the pack: the receiver did the same work twice. The key that makes a repeat harmless belongs in the first line of the handler, before anything that moves state or calls the provider. Put the line back.

ARTEFACT Write the fight-or-accept procedure ~50 MIN
YOU PRODUCEDispute fight-or-accept procedure with evidence pack checklist

Template

# Dispute procedure: fight or accept
Written by <disputes operations lead> · Approved by <head of payments> · Version <n>, <date>

## Triage
Sort each dispute by reason, then by 3-D Secure result, then by amount.
Cost of answering: <₦ per dispute, and where the figure comes from>
Rule: fight when win rate × amount is more than the cost of answering. The fee is lost either way.

| Reason | 3-D Secure | Fought | Won | Win rate | Fight above (₦) | Sample too small? |
|---|---|---|---|---|---|---|

## Evidence pack by reason
| Reason | Fact | Record it comes from | Never claim unless |
|---|---|---|---|

## Deadlines
Due date: <field that holds it>. Decide by <day>. Submit by <day>. Late means lost.

## The ratio we watch
Counted: <disputes, issuer fraud reports, once or added>
Month: <sale month and arrival month, both shown>
Over: <denominator>
Review level: <figure, who is told, who acts>

## Close calls
Goes to <role> when <conditions>. Everything else is decided by <role>.

## Out of scope
<what this procedure does not cover>

## How this could be wrong
<one way, and what would show it>
WORKED EXAMPLE

Ehi, who runs payments operations at Ojaline, writes this procedure. Ojaline’s head of payments approves it, and Ehi signs every response. Imaobong owns the pack builder that fills the checklist.

Triage is by reason, 3-D Secure result and amount. Assumption: answering costs ₦2,500 of an analyst’s time, the lab’s illustrative figure. The ₦1,000 fee is lost either way, so the rule is to fight when win rate times amount beats ₦2,500. Until Ojaline has its own history, the rates are Owoleaf’s: fraud with a challenge 34 of 37 won, fraud without one 1 of 6 fought (20 more accepted), not_recognised without one 15 of 25, not_credited 7 of 10, duplicate 3 of 7. A ₦3,964 fraud dispute with no challenge is worth about ₦660.67 of winning, so it is accepted. A challenged ₦31,280 fraud dispute is fought, and so is a ₦22,154 not_recognised on 60%. duplicate and challenged not_recognised rest on seven and four disputes, so they are marked small.

Evidence: fraud takes the 3-D Secure field (F6), the approval code (F2) and the provider’s charge record (F1). not_credited takes the ledger’s wallet credit (F3). Refunded charges add F8. Authentication is claimed only when the field says challenge.

Deadlines: decide three days before evidence_due_at and submit a day before it, whichever the dispute’s own date is. Late means lost.

Ratio: disputes plus issuer reports over settled card sales, by sale month with arrival month beside it. The lab’s April shows 2.43% added and 1.93% counted once. Review level, an assumption: 1.0% counted once. Ehi is told and the head of payments acts.

Close calls: amounts over ₦50,000, an assumption, go to the head of payments. Ehi decides the rest.

Out of scope: the refund guard, ledger posting and prevention.

How this could be wrong: Owoleaf’s rates may not fit Ojaline’s buyers, and several groups are small. If Ojaline’s first twenty fought disputes win well below these rates, the rule is wrong and Ehi reopens it.

Now you

You are the disputes operations lead at Owoleaf, a month after the lab’s data ends. April’s ring is in the books and the head of payments wants one procedure before the next one arrives. Use the lab’s outputs: the reason table (fraud 63 of 109 disputes), the win rates from work/fight.py, the three counting views from work/ratio.py and work/vamp.py, and the pack from work/evidence.py. The generated data gives ten days to answer, the mock gives seven. The wallets still held 94.5% of the disputed money, so say whether that changes any rule. Choose the cost of answering and say where it comes from. Write the procedure for your team, and name who decides a ₦40,000 not_recognised dispute with a challenge, where only four were fought. The head of payments will read it and decide whether to approve it as the team’s standing rule.

Self-check

DECIDE

Ojaline's chargebacks have doubled in two months and some are on orders support refunded. Ehi has three people in payments operations, who answer disputes by hand in a weekly session, and the acquirer has said the marketplace is near its monitoring line. Imaobong can build one thing by the end of the month, so each option below is a single piece of work. What goes in first?

READING
  1. DOC
    Visa Acquirer Monitoring Program fact sheet (2025) Visa, 2025

    Visa's own statement of how the program counts fraud reports and disputes, and its thresholds by region. Read the ratio definition and the footnotes on regions and effective dates. It was not opened in this build, so check the figures the chapter takes from search summaries.

  2. DOC
    How disputes work (Stripe documentation) Stripe

    A payment company's account of the dispute life cycle: windows, responses, outcomes. A vendor's documentation, useful for the vocabulary and timelines. Skip the product-specific dashboard steps; processors differ in what they support.

  3. DOC
    Chargeback and fraud monitoring programs (Paystack support) Paystack

    A provider's own page on the monitoring programmes and how it passes them to merchants. A vendor's claim, summarised in search results and not opened here. Read it for how a provider describes thresholds, fines and exit, and compare with the scheme's own document.

  4. DOC
    Visa Compelling Evidence 3.0 Visa

    A Visa-run page on how prior undisputed transactions can be used as evidence in a fraud dispute. Read it for what has to match and for how old the history must be. It was not opened here, so check the rule against Visa's rules or your acquirer's guide.

  5. DOC
    Guidelines on Operations of Electronic Payment Channels in Nigeria (CBN, 2020) Central Bank of Nigeria, 2020

    The CBN's own text on card and POS acceptance, whose dispute and refund timelines this chapter takes from search summaries. Read the sections on dispute resolution and merchant duties, and check the wording against what the chapter says.

  6. DOC
    Consumer Protection Regulations (CBN, 2019) Central Bank of Nigeria, 2019

    The CBN's rules on complaints and redress for customers of the institutions it regulates. Read the complaint-handling provisions. The chapter did not read the clause text, and a revised draft exists, so check what is in force.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Interchange, MDR, scheme fees and pricing →