This page mirrors the real ARCHITECTURE.md from the repository root — kept in sync
automatically by .github/workflows/docs-sync.yml
on every push that changes it, not a hand-maintained copy (see that workflow and
scripts/sync_docs.py for exactly why a GitHub Action does this instead of a plain
Jekyll tag — Jekyll's own include/include_relative tags refuse any path
containing .., so neither can reach a file one directory above docs/
directly). Prefer reading the real file itself?
It's directly on GitHub.
GARBATI Core Banking: Platform Architecture
Status: Draft v0. Proposed boundaries, not final. Each “Proposed” item needs your confirmation or change before it goes in the decisions log (Section 8).
This document is the map. It says which service owns which kind of truth and who may call whom. Each service keeps its own docs/DESIGN.md for the detail; this file never repeats it.
1. Purpose and principles
GARBATI is an open-source core banking platform for Sharia-compliant microfinance institutions, built in tranches (one service at a time, each designed before it is coded).
- One kind of truth, one owner. Every fact has exactly one service that is allowed to say what is true. Other services ask; they never keep their own copy.
- Money truth lives only in LedgerApi. No other service stores balances or posts entries.
- Fail closed. If a service cannot establish a positive answer, the operation stops.
- Decisions and effects are separate. A service that decides (is this allowed? what fee applies?) does not do (move money). Money moves only through LedgerApi, called by the orchestrator.
- Design before code. Every service starts as a questions-only skeleton, then adversarial review, then a decisions log.
2. Service map (Proposed)
| Service | Owns (source of truth) | Does NOT own | Status |
|---|---|---|---|
| LedgerApi | Accounts, entries, balances, idempotency, ledger audit | Customers, products, fees, limits | Built, deployed |
| IdentityApi (Garbati.IdentityApi) | Customer identity, KYC status and tier, mandates (who may operate which account, including joint accounts with configurable multi-holder approval), suspension, reversal authorization | Product rules, fees, tax, standing orders, transaction flow | v1 fully built across 4 PRs: Customer, KYC, Mandates, single-holder and joint-account (M-of-N) grant issuance, and reversal authorization all merged. Reversal is callable only by a trusted “ops channel” that doesn’t exist yet (same “no consumer yet” pattern as the account-freeze outbox). Key rotation/compromise tooling beyond the basic Production guard not yet built. docs/DESIGN.md |
| ProductApi (Product & Pricing) | Product catalog, account-to-product binding, product rules (minimum balance, allowed operations), fee and tax rules, limit definitions. Sharia product rules live here | Executing anything; storing money; customer identity | v1 (minimal) foundation built and merged (T-045, 24 Oct 2026): Product/ProductLimitPolicy/AccountProductBinding real and working (limits still placeholder values pending compliance confirmation, same as KycTierPolicy); FeeRule/ProfitSharingTerms exist as real tables but are deliberately unseeded, pending a qualified scholar’s sign-off (research/sharia-product-rules.md) — a fee quote always returns an explicit NoFeeConfigured today. QA-approved, no blockers. Now wired to OrchestratorApi for account opening (T-046, 25 Oct 2026) — step 5 of Section 10’s sequence. Deployed to Azure (T-048, 27 Oct 2026), live and smoke-tested; the transfer-time fee-quote call remains deliberately unwired (no real FeeRule content to ask for yet). docs/DESIGN.md |
| OrchestratorApi (Transaction Orchestrator) | The ordered steps of each customer operation; decision binding (decisionId); in-flight operation state; account-opening flow |
Any truth of its own about customers, products or balances | v1 (minimal) built and merged: account opening (4-step sequence, resumable) and a plain transfer (authorization-then-post), calling the real IdentityApi/LedgerApi contracts. No fee, no reversal, no real Channel auth (known gap, Section 1.6) — matches the deliberately minimal design. docs/DESIGN.md |
| ScheduleApi (Standing Orders) | Recurring instructions and their run history | Moving money (it submits requests to the orchestrator like any channel) | Built, tested, merged (T-071, 10 Nov 2026); not yet deployed to Azure. docs/DESIGN.md |
| Financing services (Murabaha, etc.) | Financing contracts and schedules | Ledger postings | Later tranche |
| Channel/Gateway | Customer login, sessions, API for apps | Everything above | Later tranche |
| StaffIdentityApi | Staff accounts, roles (Teller/CustomerServiceOfficer/Supervisor/ComplianceOfficer/RiskOfficer/Auditor/Administrator), who is logging in as a bank employee and what they’re permitted to do | Customer identity/KYC/mandates (that’s IdentityApi’s job — staff and customers are deliberately separate identity domains, D-13); any money/customer truth |
v1 foundation built and merged (T-032): entities, all 8 endpoints, the one-time Administrator seed. Deployed to Azure (T-048, 27 Oct 2026) — garbati-staffidentityapi, live and smoke-tested. docs/DESIGN.md |
| OpsApi (ops console backend-for-frontend) | The staff-facing login session (cookie-based); holds the real service API keys for IdentityApi/OrchestratorApi/LedgerApi/StaffIdentityApi server-side, never exposed to the browser; proxies/aggregates calls for the ops console UI |
Any truth of its own — same “orchestrates, doesn’t own” role OrchestratorApi plays for customer-facing flows, but for staff-facing ones |
v1 fully built (T-033 foundation + T-034 workflows): sessions, cascade revocation, all 4 downstream clients, every endpoint group including both maker-checker workflows — both OpsReversalRequest and (since T-047, 26 Oct 2026) OpsCustomerEditRequest are now fully executable end to end, mirroring the same try/catch → outcome pattern. Deployed to Azure (T-048, 27 Oct 2026) — garbati-opsapi, live and smoke-tested, with real production API keys issued by StaffIdentityApi/IdentityApi/LedgerApi/OrchestratorApi (not dev placeholders). docs/DESIGN.md |
| Ops console (React + TypeScript frontend) | Nothing — a pure client of OpsApi | Everything; never talks to IdentityApi/OrchestratorApi/LedgerApi/StaffIdentityApi directly, never holds a real service credential |
Design v1 ratified (T-029); not yet built, depends on OpsApi being built first. docs/DESIGN.md |
3. Dependency rules
Channels / ScheduleApi
|
v
OrchestratorApi ----> IdentityApi (who may do this?)
| ----> ProductApi (what rules, fees, tax, limits apply?)
v
LedgerApi (only the orchestrator posts money)
- Channels and ScheduleApi call only the orchestrator for anything that moves money. One narrow, read-only exception (D-33, 10 Nov 2026):
ScheduleApiqueriesLedgerApi’s existing balance-enquiry endpoint directly for itsAllowPartialTransferfeature — a read with no authorization question, mirroringOpsApi’s own existing precedent of callingLedgerApi’s funding endpoint directly. No write path, no new endpoint on either side. - The orchestrator calls IdentityApi, ProductApi and LedgerApi.
- IdentityApi and ProductApi never call each other. Anything needing both goes through the orchestrator.
- LedgerApi calls nobody (LedgerApi decision #34 stays true). It checks a decision token locally, using IdentityApi’s public key (P-12).
- No service reads another service’s database. No foreign keys across services.
3.1 Ops console (staff-facing, separate from the customer path above, D-13):
Ops console (browser)
|
v
OpsApi ----> StaffIdentityApi (who is this staff member, what role?)
| ----> IdentityApi (customer/KYC/mandate lookups and actions)
| ----> OrchestratorApi (account opening, transfers, reversals)
| ----> LedgerApi (balance/transaction lookups)
- The browser only ever talks to
OpsApi. It never holds a realIdentityApi/OrchestratorApi/LedgerApi/StaffIdentityApicredential — only anHttpOnly/Secure/SameSitesession cookieOpsApiissues after checking the staff member’s credentials againstStaffIdentityApi. OpsApiis the only thing that holds real service API keys for the other four services, and the only thing that knows a staff member’s role — every privileged action (approving a reversal, editing an account) is authorized here, per request, not just at login.StaffIdentityApiandIdentityApinever call each other — they are deliberately separate identity domains (workforce vs. customer, D-13). Anything needing both goes throughOpsApi, the same “orchestrates, owns no truth” roleOrchestratorApiplays on the customer path.
4. End-to-end flows
4.1 Customer transfer. Channel authenticates the customer, then calls the orchestrator. The orchestrator asks IdentityApi for an authorization decision, asks ProductApi for rules, fees, tax and limits, and builds the full set of postings (the transfer, the fee, the tax). It posts them to LedgerApi with the decisionId bound to the exact request. The fee and tax are ordinary legs of the same chain (P-14), paid to system income and tax accounts. A transaction with no fee or tax is a chain of one leg.
4.2 Account opening. Orchestrator runs: create customer (Identity), wait for KYC, choose product (Product), create ledger account (Ledger), attach mandate (Identity), bind product (Product). If a later step fails, earlier steps are retried or reversed explicitly; no half-opened account stays silently valid.
4.3 Standing order. ScheduleApi fires on schedule and submits an ordinary request to the orchestrator, with idempotency key derived from the standing order id and the run date. A repeated trigger therefore cannot pay twice.
4.4 Fee. ProductApi computes the amount. The orchestrator posts it. ProductApi never touches the ledger.
5. Shared conventions (every service follows these)
- Service authentication: API key plus scopes, hash-only configuration, one client per calling service (LedgerApi decision #35).
- Idempotency: client-supplied key, unique per calling client, stored with a hash of the request; same key with a different body returns 409.
- Audit: written in the same database transaction as the change it describes, append-only.
- Correlation id:
X-Correlation-IDon every call, passed on to every downstream call. - Errors: 400 validation, 401 no/unknown key, 403 missing scope, 404 not found, 409 conflict, 422 business-rule failure, 500 unexpected; a timeout is never treated as approval.
- Logs: never contain identity numbers (BVN/NIN), documents, keys or full request bodies.
- Versioning:
/v1/in the path; a breaking change creates/v2/. - Health checks:
/health/liveand/health/ready. - Observability posture: structured logs + correlation id + audit trail only, no metrics/tracing/alerting stack today — a deliberate “bring your own observability” choice, not an oversight. See
OBSERVABILITY.md. - Secrets-management posture: hand-run
azCLI, scattered across each service’s own App Service settings, no centralized vault today — a deliberate, stage-appropriate deferral (D-25), not an oversight. SeeSECRETS-MANAGEMENT.md. - Infrastructure-provisioning posture: hand-run
azCLI, no Infrastructure-as-Code tool today — a deliberate deferral (D-27), not an oversight. SeeDEPLOYMENT-RUNBOOK.mdfor the exact, repeatable sequence and the real gotchas it already caught.
6. Repository layout
One repository per service, each with README.md and docs/DESIGN.md. This repo (or a garbati-platform repo) holds only this file, the service map, and cross-service contracts.
garbati-platform/ ARCHITECTURE.md, contracts/, ADRs
LedgerApi/ docs/DESIGN.md (exists)
Garbati.IdentityApi/ docs/DESIGN.md (exists)
Garbati.OrchestratorApi/ docs/DESIGN.md (exists)
Garbati.StaffIdentityApi/docs/DESIGN.md (exists)
Garbati.OpsApi/ docs/DESIGN.md (exists)
Garbati.ProductApi/ docs/DESIGN.md (exists — design only, not yet built)
garbati-ops-console/ docs/DESIGN.md (exists — design only, not yet built)
7. Build order — updated to reflect what’s actually happened, 24 Oct 2026 (originally “Proposed”)
- LedgerApi — built, deployed, live on Azure.
- IdentityApi — built across 4 PRs (customer/KYC, mandates, joint-approval, reversal authorization), deployed, live on Azure. BVN/NIN storage and real KYC-tier evidence enforcement added since (T-044, D-26).
- OrchestratorApi — v1 (minimal) built: account opening, plain transfer, reversal. Deployed, live on Azure. Fee integration still waiting on ProductApi, per its own original minimal scope.
- StaffIdentityApi and OpsApi (the ops-console initiative, D-13, independent of 1-3) — both fully built, tested, and deployed, live on Azure (T-048, 27 Oct 2026). The ops console frontend itself (garbati-ops-console, T-062, 2 Nov 2026) is now built and merged too — login, role-gated nav, all 8 v1 screens, verified by real HTTP calls against a live backend. Not yet deployed to Azure (that wiring, into
OpsApi’s existing Web App per the frontend’s own design doc Section 7, is a separate step) — the whole D-13 initiative’s code is otherwise complete. - ProductApi — v1 (minimal) foundation built and merged (T-009 design, T-045 build, 24 Oct 2026): the real, mechanical parts (catalog, account-binding, limits) are built and QA-approved. Fee/profit-sharing content remains deliberately unseeded, pending a qualified scholar’s sign-off (
research/sharia-product-rules.md) — not blocked entirely on that sign-off, but not inventing rules in its absence either. Deployed to Azure (T-048, 27 Oct 2026) —garbati-productapi, live and smoke-tested;OrchestratorApi’sBindProductstep (T-046) now calls it with a real production key, not a dev placeholder. - ScheduleApi — built and merged (T-071, 10 Nov 2026), targeting full Fineract-equivalent standing-instruction functionality (
StandingInstruction/StandingInstructionRun, all 7 endpoints, a plain-BackgroundServicescheduler, both downstream clients). Not yet deployed to Azure — real infrastructure provisioning is a separate task, same precedent as T-048 for every other service. Financing services, Channel/Gateway remain “later tranche,” none designed yet, in that order of likely priority (matching D-1’s original “channel doesn’t exist yet” framing).
Deployment guidance: design these as separate services, but you do not need separate deployments on day one. Each deployed service costs money and needs its own database, pipeline and monitoring. Start with Ledger and Identity deployed separately (their data sensitivity justifies it). Start Product and Orchestrator as separate projects inside one deployable, with the same boundaries enforced in code, and split them later if there is a reason.
8. Platform decisions log
| # | Decision | Options considered | Proposed choice | Why | Status |
|---|---|---|---|---|---|
| P-1 | Transaction flow owner | Channels call each service / Ledger calls Identity / separate orchestrator | Separate OrchestratorApi | One place enforces step order; the ledger stays independent; fixes the “nothing forces the gate” gap in Identity review | Decided (owner, D-2, 16 Oct 2026; matches the orchestration-based Saga pattern — research/architecture-patterns-p1-p6.md) |
| P-2 | Where product rules, fees, tax live | Inside IdentityApi / inside Orchestrator / separate ProductApi | Separate ProductApi | Identity answers “who”, product answers “what rules”; they change for different reasons and on different schedules | Decided (owner, D-2, 16 Oct 2026; matches decide/execute separation seen in core-banking product-engine-vs-ledger splits — research/architecture-patterns-p1-p6.md) |
| P-3 | Standing orders | Inside Identity / inside Orchestrator / separate ScheduleApi | Separate ScheduleApi that calls the orchestrator | Scheduling needs its own run history and retry logic; money still moves only through the orchestrator | Decided (owner, D-2, 16 Oct 2026; matches the Scheduler/Agent/Supervisor pattern — research/architecture-patterns-p1-p6.md). Retry-on-failure resolved, D-33, 10 Nov 2026: no auto-retry — see Section 9. Design v1 ratified, Garbati.ScheduleApi/docs/DESIGN.md |
| P-4 | Who computes vs who posts | Product posts fees / orchestrator posts | Product computes, orchestrator posts | Keeps “money moves only via the ledger” absolute | Decided (owner, D-2, 16 Oct 2026; same decide/execute split as P-2, applied per step — research/architecture-patterns-p1-p6.md) |
| P-5 | Cross-service data | Shared DB / copies / API calls only | API calls only, no shared DB, no cross-service FK | Services stay independently changeable | Decided (owner, D-2, 16 Oct 2026; matches the standard database-per-service pattern — research/architecture-patterns-p1-p6.md) |
| P-6 | Deployment shape | One service per deployment / modular monolith for new services | Separate design, minimal deployables initially | Solo developer and budget | Decided (owner, D-2, 16 Oct 2026; matches Fowler’s “Monolith First” / modular-monolith guidance — research/architecture-patterns-p1-p6.md; later split not guaranteed easy, depends on keeping P-5’s no-shared-database discipline intact in practice) |
| P-7 | Where account numbers are created | Move creation into IdentityApi / keep in LedgerApi | Keep in LedgerApi; the orchestrator runs the account-opening sequence (Section 10) | Only the ledger can guarantee its own account-number uniqueness; Identity would need ledger write access, so a breach of Identity could open accounts | Decided |
| P-8 | Aggregate limits | In orchestrator / in ledger / separate limits service | Orchestrator, using reserve, then confirm or release, with one atomic counter update | Orchestrator is the single gate every operation passes; Product owns the limit definitions | Decided (owner), mechanism proposed |
| P-9 | Fee and tax timing | Separate linked transactions / same ledger transaction | Same all-or-nothing unit as the transfer, built as a chain of legs committed in one database transaction (P-14); if the fee leg fails, the whole chain fails and is retried | No state where the transfer succeeded but the fee did not | Decided (owner); shape Decided (owner), option B |
| P-10 | Reversal of fees and tax | Reverse principal only / reverse everything | Reversing a chain reverses every leg, last leg first, in one database transaction. A single leg of a chain cannot be reversed on its own | Nobody can refund the principal and keep the fee | Decided (owner) |
| P-11 | Product changes | Edit in place / versioned | Immutable published versions; each account binds to a version; every fee records the version used; moving accounts to a new version is an explicit audited step | A past fee can always be explained | Decided (owner) |
| P-12 | Decision binding | Shared signing key / Identity signs, ledger verifies a public key / ledger confirms online with Identity | IdentityApi signs a decision token with a private key. The orchestrator verifies it, then the ledger verifies it again locally with the public key. Expiry 30 seconds, single use | No call from the ledger to Identity, so no added latency and no new dependency. The orchestrator cannot forge a decision. IdentityApi stays the source of truth for authorization, LedgerApi for financial transactions | Decided (owner); stale-window cost in Section 9 |
| P-13 | Create-account idempotency | None / client key with request hash | Idempotency key plus request hash on POST /api/accounts |
A retried account-opening step must not create a second account | Decided (owner, D-2, 16 Oct 2026) — built, LedgerApi decision #43 (merged PR #24, 14 Oct 2026) |
| P-14 | Shape of multi-part transactions | One transaction with many entries (A) / chain of ordinary two-entry legs committed together (B) | B: a chain of legs. Each leg is a normal two-entry transaction (principal, fee, tax). All legs commit in one database transaction or none do. A transaction with no fee or tax is a chain of one leg | Keeps the tested guarantee of one debit and one credit per transaction, keeps POST /api/transfers unchanged, and lets reversal reuse the existing single-leg logic. Statements show one line per leg |
Decided (owner); details in Section 12 |
| P-15 | Staff/ops identity vs. customer identity | Bounded context inside IdentityApi / new dedicated StaffIdentityApi | New dedicated service (StaffIdentityApi), built the low-cost way (P-6) — separate project/database, not necessarily a separate deployment day one | Workforce identity (staff, provisioned by an admin, least-privilege/audit) and customer identity (CIAM, self-registered, KYC-gated) are treated as distinct domains almost everywhere real core-banking platforms were checked; merging staff credentials into IdentityApi’s database would share blast radius with regulated customer PII | Decided (owner, D-13, 19 Oct 2026, after T-026 research — research/staff-ops-identity-patterns.md) |
9. Open questions
- Token rules (P-12). IdentityApi signs with ES256; only IdentityApi holds the private key. Claims:
iss,aud(the ledger),jti(thedecisionId),iat,exp(30 seconds), operation, debit account, principal amount, currency, and a hash of the exact request including the client’s idempotency key. The orchestrator verifies signature, expiry and that the token matches the request it is about to send. The ledger verifies the same things again with the public key from configuration, pins the algorithm and issuer, allows about 5 seconds of clock difference, and reads a key id so keys can be rotated with two active at once. - Single use. The ledger stores the
decisionIdwith the posting under a unique constraint, in the same transaction. A second posting with the same token fails. - Retries. The ledger looks up the idempotency key first. A retry of a request that already succeeded returns the stored result even if the token has since expired. Only a new key needs a valid token.
- Failure behaviour. A missing, malformed, expired or mismatched token fails closed: no posting. If IdentityApi is down, tokens already issued can still be verified, but no new customer operations can start.
- Stale window. A suspension or revocation within the 30 seconds does not cancel a token already issued, and the ledger cannot see it. This is the accepted in-flight window (Identity design 3.4), bounded by the expiry. IdentityApi marks expired grants as expired for audit; nothing needs revoking.
- What the token cannot cover. Fee and tax entries are added by the orchestrator from ProductApi’s rules; the token covers only the customer’s own request. A reconciliation job should compare posted fees with ProductApi’s rules. T-054 (29 Oct 2026,
research/reconciliation-nibss-integration-patterns.md) researched this directly: this is not nostro/vostro-style reconciliation — both sides (the posted leg, the rule version that produced it) are already GARBATI’s own data, exactly keyed by P-11’s versioned product rules, so this can be a deterministic recomputation-and-compare job, not a fuzzy-matching reconciliation desk. The research also found this is the same underlying check as the token’s own fee/tax-leg gap below, not a separate one — and that decision #34 (“LedgerApi calls nobody”) plus P-5 (no shared DB) structurally rule out putting this check inside LedgerApi itself; it fits more naturally as a scheduled job inside OrchestratorApi. Not yet designed or built. T-055 (29 Oct 2026,research/modern-treasury-gap-analysis.md) adds a concrete fact T-054 didn’t have: Modern Treasury’s own “Expected Payment” object (a declared, tolerance-windowed, fuzzy-matched awaited external payment with its own partial/tentative/overdue lifecycle) is the named, already-productized shape of mechanism a future NIBSS-settlement reconciliation would eventually need — GARBATI has no equivalent today, correctly, since there’s no external counterparty concept at all yet (same T-054 precondition: no live external-rail leg). Not proposed for building; named as a future reference point only. - Orchestrator crash mid-operation. A limit reservation was made but the ledger post never happened. Define reservation expiry and a reconciliation job that checks the ledger by idempotency key. Same research: this is closer to a scheduled sweep (find expired reservations with no matching idempotency key in LedgerApi, retry-forward or release) than to real reconciliation, since the matching key is exact and unique by construction — real banks need fuzzy matching specifically because two separate organizations don’t share a perfect identifier, which doesn’t apply here since both sides are GARBATI’s own data. Not yet designed or built.
- Does a reversal restore the limit allowance? Decided (owner, D-7, 16 Oct 2026): yes. This still needs to be wired up when the limit-reservation mechanism (P-8) is actually built — nothing to restore yet, since limits aren’t implemented.
- Leg purpose codes. Decided (owner, D-7, 16 Oct 2026):
Principal,Fee,Taxonly, as built in decision #45. A later code (e.g.Charityfor Sharia late fees, pending T-007’s research) is a new decision and a ledger code change, not an automatic extension. - Reversing when the recipient already spent the money. Decided (owner, D-7, 16 Oct 2026): the whole chain reversal fails; no manual remediation path defined yet. Built and tested in decision #45 (
ChainReversal_WhenOneLegCannotBeReversed_RollsBackTheWholeReversal). - Maximum legs per chain. Decided (owner, D-7, 16 Oct 2026): 10, as built in decision #45.
- Sharia rules. Which product rules (profit-sharing instead of interest, late-fee-to-charity, no prohibited charges) are enforced by ProductApi and which by the later financing services? T-050 (28 Oct 2026) adds two closely related, still-open questions to fold into the same eventual decision, surfaced by real-world evidence (
research/sharia-rule-configuration-patterns.md), not resolved by it: (1) is GARBATI meant to be deployed once per adopting institution, or as a shared multi-tenant platform serving several institutions at once — the latter needs an explicit institution/tenant key onProduct/FeeRule/ProfitSharingTermsthat doesn’t exist today; (2) should a Sharia-board approval reference (which board, which meeting/fatwa, which date) be a modeled, queryable part of these tables rather than an external, undocumented fact — every real governance source checked (Saudi Arabia’s SAMA rulebook, Nigeria’s ACE→FRACE ratification chain) treats that provenance record as essential, andKycTierPolicydoesn’t model it either. Also: even the set of permissible contract types (not just ratios/fees within a type) varies by jurisdiction/school — e.g. bay’ al-‘inah/organized tawarruq, accepted in Malaysia, rejected by Saudi Arabia’s Council of Senior Scholars — so the eventual financing-contract extension likely needs its own institution-configurable “which contract types do we offer” layer, not a single fixed enum every adopter inherits unmodified. Partially resolved, 28 Oct 2026 (D-28): GARBATI’s own initial financing-module scope is limited to the contract types with no scholarly disagreement surfaced in either brief — Murabaha, Musharaka, Mudarabah, Qard Hasan, Wadiah, Ijarah, Istisna, late-fee-to-charity. Bay’ al-‘inah and organized tawarruq are explicitly out of scope for now, deferred pending a qualified scholar’s specific input, not rejected as impermissible by this project. The multi-tenancy and approval-provenance questions above remain open. T-059 (1 Nov 2026) adds a concrete, real-world data point to the multi-tenancy question specifically (research/fineract-core-functionality-gap-analysis.md): this question’s own framing implicitly assumed the likely fix would be “an institution/tenant key on shared tables” — Apache Fineract’s actual, shipped answer is materially different: a separate database per tenant, with one small, separate tenant-registry database holding only connection metadata, routed per request via aFineract-Platform-TenantIdheader. Worth noting: this separate-database shape is arguably more consistent with GARBATI’s own existing “no shared database” discipline (P-5/P-6, already applied between services) than the shared-table-tenant-key approach this entry originally assumed — an observation, not a decision; the choice remains the owner’s. - Product version migration. Moving accounts to a new version may need customer notice, especially for fee increases. Compliance must confirm the notice period.
- Standing order retry-on-failure (P-3). A real standing order (customer-initiated push payment) is traditionally not auto-retried on failure — unlike a direct debit, which can be re-presented by the payee’s bank (
research/architecture-patterns-p1-p6.md, Q3). ScheduleApi’s design (T-010+ tranche) must decide: does a failed run (e.g. insufficient funds) get retried automatically, or just recorded and left for the customer to notice? Owner decision needed when ScheduleApi is designed, not now. T-059 (1 Nov 2026) independently confirms this entry’s own one-line scope statement is the real shape real systems use (research/fineract-core-functionality-gap-analysis.md): Apache Fineract’s real, shipped standing-instruction model is exactly the same two-part split — astandinginstructionsdefinition resource plus a separatestandinginstructionrunhistoryexecution-tracking resource — useful external confirmation, not new information. Separately, T-059 also found that no GARBATI service anywhere has any scheduled-job/background-worker mechanism today —LedgerApicalls nobody (decision #34);OrchestratorApi’s own retry path is caller-initiated, not a background sweep; no cron/timer-triggered pattern exists in any of the six services. This is the actual infrastructureScheduleApiwill need to build from scratch, not an incremental extension of something that already exists — and the same missing capability a future interest/profit-posting mechanism (see “Sharia rules” above) would also need, making this one shared piece of future infrastructure, not two separate gaps. Resolved, D-33, 10 Nov 2026: no auto-retry. Before designingScheduleApi’s v1, a deeper research pass (T-069,research/fineract-standing-instructions-detail.md) confirmed Fineract’s own real, shipped, bug-fixed behavior directly: a real, merged fix (PR #6806) moved away from one failure rolling back an entire batch, to today’s per-instruction transaction isolation with no automatic retry of a failed instruction before its own next naturally-scheduled occurrence. GARBATI’s own choice matches this exactly, not merely the generic real-world convention T-011 first found. The plainBackgroundServicescheduling mechanism (no new dependency) is specified inGarbati.ScheduleApi/docs/DESIGN.mdSection 3. - CBN data-localisation deadline (new, T-037, 22 Oct 2026; corrected and researched further, 22 Oct 2026, T-041). CBN Circular PSS/DIR/PUB/CIR/001/004 (15 June 2026) requires Nigeria-originated payment/financial data to be stored and processed inside Nigeria by 1 January 2027 (≈71 days from 22 Oct 2026 — T-037’s original “over a year out” framing was a dating error, corrected).
LedgerApicurrently runs on Azure App Service in “South Africa North.” Confirmed directly: none of the three major Western hyperscalers (Azure, AWS, GCP) has a true Nigeria region — AWS has a Lagos Local Zone (EC2 only, managed RDS not confirmed there); Azure and GCP have none at all. T-041 found six independent secondary legal sources now consistently naming “microfinance banks” in the circular’s addressee list (medium-high confidence, still not primary-text-verified — the primary PDF 403s on every attempt, URL now on record for a future retry). T-041 also surfaced a real, unresolved legal question: secondary sources suggest remote access to a Nigeria-hosted database may itself count as cross-border “processing,” which — if accurate — could mean migrating onlyLedgerApi’s database (keeping its application tier and the other 4 services on Azure) does not actually satisfy the circular; this needs direct compliance-officer confirmation before anyone relies on a database-only migration. Across every Nigerian hosting option surveyed (Huawei Cloud, AWS Lagos Local Zone, Rack Centre, MainOne/Equinix, Open Access Data Centres, Africa Data Centres, Galaxy Backbone), no managed-PostgreSQL-equivalent to Azure Flexible Server was confirmed to exist — any realistic path means GARBATI takes on self-managed Postgres (backup, patching, HA) for the first time. Decided (owner, D-24, 22 Oct 2026): stay on Azure (South Africa North) for now — not a permanent close, a deliberate “stay for now.” Revisit once the owner has personally pursued the Huawei personal-connection credit lead and/or other alternatives further, and/or a compliance officer confirms the cross-border-access question. Seeresearch/oss-core-banking-readiness-gaps.mdG4 andresearch/nigeria-hosting-options.md(T-041) for full detail. -
BVN/NIN field-level encryption pattern (re-flagged, T-037, 22 Oct 2026; legal basis corrected, T-043, 23 Oct 2026). Still unresolved since T-016 (
Garbati.IdentityApi/docs/DESIGN.mdAppendix B,#TBD-4) — the column doesn’t exist yet, deliberately left out pending a cryptography decision. Correction: T-037 said NDPA 2023 “explicitly includes encryption at rest” as a requirement — this overstated the primary text. T-043 read the Act directly: Section 39(1) is a general, risk-based “appropriate measures” duty; encryption is one of seven optional illustrative measures (Section 39(2), “may include”), not a named mandate, and BVN/NIN are not in the Act’s own closed “sensitive personal data” list. No specific CBN encryption rule was found either (the BVN framework PDF remains unreadable — image-scan, two independent extraction attempts failed) and the one real, specific encryption mandate found anywhere (NIMC Act 2007 s.21(2)(b)) binds NIMC’s own ID card, not a third party storing a customer’s NIN. This does not mean plaintext is “fine,” though — Section 39(1)’s own risk factors (sensitivity, likely harm, breach-notification consequences under s.40(7)(a)) point toward encryption as the defensible choice regardless, and NDPC states it is moving into “full enforcement mode” from 2026. Decided (owner, D-26, 23 Oct 2026): store BVN/NIN unencrypted for now, with the explicit intention to revisit encryption later — not a permanent close, the same “decide later” framing as D-24. This unblocks building the actualCustomerIdentityDataBVN/NIN column and real Tier 2/3 KYC verification, currently blocked entirely by#TBD-4. Retention period is still open (5 years, primary-source-confirmed CBN AML/CFT floor, vs. a secondary-source-only 6-year MFB-specific figure —research/nigerian-regulatory-requirements.mdQ2/Q3) — to be resolved when the actual build task is scoped, not decided here. Seeresearch/ndpa-encryption-requirement.mdfor the full primary-source finding behind this decision. - Teller till/vault cash operations — not researched before T-056, 31 Oct 2026.
StaffIdentityApialready defines aTellerrole, but GARBATI has no concept anywhere of a vault, a till, cash movement between them, or end-of-day cash balancing — confirmed by a repo-wide search before T-056 was even written (zero matches).research/teller-till-vault-cash-operations.mdfound real banks keep a branch’s bulk cash in a dual-custody vault and issue each teller a personally-accountable till/cash drawer for their shift; “balancing” means comparing the ledger’s own calculated expected figure against a physical cash count, with any difference (short/over) posted as a real correcting entry to a dedicated system account — confirmed directly in both Oracle FLEXCUBE’s own documentation and Apache Fineract’s real, shippedTeller/Cashierendpoints andCASH_AT_MAINVAULT/CASH_AT_TELLERGL constants (Fineract is directly relevant as the project GARBATI’s own Apache 2.0 license choice, D-21, was modeled on). Honest structural finding: vault↔till movement and shortage/overage correction fit as bounded extensions of GARBATI’s existing chain/LegPurpose/System-account mechanism (decisions #45/#46) — a new leg purpose and a shortage/overage system account, not a new mechanism. But a till’s shift-scoped, staff-owned, opens-and-closes lifecycle, and the fact that its balance is never fully authoritative until a human physically confirms it against a count, have no analogue anywhere in GARBATI’s current model — every balance today is “the sum of this account’s own entries, full stop,” with nothing external it’s ever checked against. No CBN-specific primary source on branch cash custody was found or could be read (samecbn.gov.ngPDF-access limitation documented since T-037); a compliance officer must confirm whether a specific rule exists. Not designed, not scheduled — input for a future task only. - Multi-charge, compounding, currency-dependent transaction charges — not researched before T-057, 1 Nov 2026. A single real Nigerian transfer can carry a bank fee, VAT calculated on that fee (never on the principal — confirmed directly in two real Nigerian institutions’ own published material, Kuda and Access Bank), and stamp duty (a flat ₦50 government levy on electronic transfers ≥₦10,000, Finance Act 2020 s.48 → Stamp Duties Act s.89A, the Electronic Money Transfer Levy) — all compounding on one transaction, with FCY typically carrying a different schedule entirely.
research/multi-charge-transaction-modeling.mdfoundLegPurposeis hard-closed toPrincipal/Fee/Tax(decision #45/D-7) andFeeRule/FeeQuoteServicecompute exactly one flat-or-percentage charge per(ProductCode, OperationType)call, against the transaction’s own principal only — never against another charge’s result. Two genuine regulatory tensions surfaced and left honestly unresolved, not picked either way: who actually pays the levy (KPMG’s 2022 reading says the receiver; several 2026 news sources report a shift to the sender from 1 Jan 2026, not independently confirmed from the Tax Act’s own text) and whether the levy is LCY-only at all (the same KPMG source states it also applies to FX transactions, converted at a CBN rate) — directly complicating this entry’s own “FCY is different” framing. Honest structural finding: the chain/leg-posting mechanism itself (post several tagged charges atomically) already matches real practice closely — ISO 20022’s ownpacs.008ChargesInformationarray is the same shape.FeeRule’s computation side has four concrete gaps with no existing field to stretch: no currency field, no threshold-gate logic (stamp duty only applies above ₦10,000), no way to compute a charge from another charge’s result (closest real precedent found, Apache Fineract’sTaxGroup-on-Charge, bundles tax into the charge’s own definition rather than one rule referencing another), andFeeQuoteService’s own “one call, one answer” contract has no concept of a list of applicable charges at all. Separately, cheque usage was checked (not assumed) and found real but small and declining nationally, with Nigerian MFBs specifically reported (lower confidence, primary source unreadable) as barred from direct cheque-clearing participation — weighted accordingly as lower priority than the electronic-transfer charge questions.FeeRuleremains unseeded regardless, pending Sharia scholar sign-off; nothing here changes that gate. Not designed, not scheduled — input for a future task only. - Six real gaps found comparing GARBATI against an actual production core-banking transfer payload — T-058, 1 Nov 2026. The owner shared a real sample transfer-posting payload from their own professional work (Sterling Bank’s MIZAN/SEABASS, integrated via the KUSALA BPM system). Direct comparison against GARBATI’s real code found six gaps, then triangulated against Apache Fineract and Oracle FLEXCUBE (
research/real-corebanking-payload-gap-analysis.md) to check which are common, load-bearing core-banking patterns versus narrower to one institution’s integration. Three confirmed cleanly in both platforms: (1) value-date / multi-stage transaction timestamps — FLEXCUBE explicitly supports back- and forward-dated value dates, even per-leg; Fineract’s ownacc_gl_journal_entrytable (read directly, independently re-verified by the coordinator) has distinctentry_date/transaction_datecolumns —Transactionhas onlyCreatedAt/CompletedAttoday, the same underlying gapresearch/modern-treasury-gap-analysis.md(T-055) already found from a different angle, now confirmed a third way; (2) branch attribution per lifecycle stage — confirmed real at GARBATI’s own scale too (Fineract’s minimal one-office_id-per-posting model), not just FLEXCUBE’s richer inter-branch subsystem, same finding as T-056; (3) named-actor persistence separate from a cryptographic authorization record — the most consequential finding of the six: both FLEXCUBE (“Input By”/”Authorized By” fields, shown on every record) and Fineract (maker/checkerfields, pluscreatedby_id/lastmodifiedby_idon the ledger table itself) persist a plain, queryable human name as their entire authorization record — neither was found to also keep a separate signed/cryptographic grant alongside it, meaning GARBATI’s own decision #13 (never persist the grant or the approver’s name, only aDecisionId) is the less common design relative to real practice, not the reverse. A real, deliberate trade-off (the grant is a secret, decision #13’s own reasoning), but now confirmed to have a real, concrete cost: GARBATI genuinely cannot answer “who approved this, by name” from the ledger alone, the way both comparison platforms’ own ordinary audit trails can. Two gaps turned out narrower than they first appeared: multi-entry (N:M) posting is real and named in both platforms (Fineract’s “compound journal entry,” FLEXCUBE’s “Single Debit Multiple Credit”/”Batch Booking”) but every real-world justification found is payroll disbursement or bulk collection, not an ordinary retail transfer — squarely outside GARBATI’s current scope; and a dedicated “reconciliation remarks” field, distinct from narration, was not confirmed as standard in either platform — what both have instead is a structured correlation identifier (Fineract’sexternalId, built specifically to survive renumbering after a reversal), the same shape T-057 already found at the ISO 20022 wire-message level (AccountServicerReference/EndToEndIdvs.RemittanceInformation). One gap (transaction category/source/channel attribution) confirmed as a real need with no single universal shape — the same repeated pattern T-054/T-056/T-057 already found; real systems answer it with several differently-purposed fields, not one flat numeric triple the way the sample payload does. Not designed, not scheduled — input for a future task only. - Group/joint-liability lending (Groups and Centers) — the one genuinely microfinance-specific gap found anywhere in this project’s research, T-059, 1 Nov 2026. A full comparison against Apache Fineract’s core functionality (
research/fineract-core-functionality-gap-analysis.md) found GARBATI has zero equivalent, anywhere, to Fineract’sGroup/Centerentities — the real, named, documented model (confirmed directly from Fineract’s own documentation) for organizing clients into joint-liability groups, where the group itself (not an individual) can hold a savings or loan account its members are jointly responsible for, with groups organized into centers carrying their own meeting schedules and collection-sheet/attendance workflows. Unlike every other gap this project’s research has found so far, this one isn’t a generic commercial-banking pattern — it’s historically foundational to microfinance as a field (Grameen Bank’s own model). Honestly scoped, not overstated: this is real, but currently a non-issue — GARBATI’s scope today is individually-held deposit accounts only, with financing deliberately deferred (D-28), and nothing in GARBATI’s existingMandatemechanism (joint authorization on one account) is a structural analogue for joint liability across several accounts — a genuinely different concept. This becomes load-bearing specifically once GARBATI’s financing module is actually scoped, as a real methodology a Nigerian MFI adopting GARBATI could reasonably want — worth an explicit flag for that future task so the financing data model isn’t accidentally designed without room for it, not something to build now. T-066, 9 Nov 2026 (research/group-lending-joint-liability-patterns.md), adds three concrete findings a future financing-module design should have in hand: (1) “joint liability” is not one universal mechanism even in conventional group lending — Grameen Bank’s own founder states, directly quoted, that Grameen itself uses no formal/legal joint liability, only “moral responsibility,” while many other real MFIs implement the same “solidarity group” label as true, formal joint liability — a future design must not assume Grameen’s name implies Grameen’s mechanics. (2) Islamic group lending reaches for a named, real concept, kafala (mutual guarantee, sometimes linked to takaful), confirmed at real named institutions (Islami Bank Bangladesh’s RDS, PNM Mekaar Syariah’s “tanggung renteng”) — but kafala itself carries a live, unresolved scholarly tension (classical jurisprudence treats it as a gratuitous tabarru’ contract; a fee on top can look like riba) directly relevant to any future “group fund”/guarantee-fee mechanism, needing a qualified scholar’s input specifically, separate from and in addition to D-28’s existing contract-type sign-off gate. (3) Fineract’s own real schema, read directly (m_loan.group_id/glim_id/loan_type_enum), confirms group-ness is structurally separable from the loan-product definition in at least one real system — but GARBATI’s ownMandatemechanism is confirmed directly against its real OpenAPI contract to be structurally incapable of expressing group liability (it’s per-(customerId, ledgerAccountId)authorization, not cross-account liability), andLedgerApi’s chain/leg model operates at the single-transaction level, not the multi-installment loan-account lifecycle a group loan needs — any future design starts from “needs a new entity and a new relationship type,” not “can extendMandate.” None of this changes D-28’s own gate: a qualified Sharia scholar’s sign-off remains the precondition for building any part of the financing module, group-lending-related or otherwise.
10. Account opening sequence (orchestrator-run)
All 5 steps now built and merged (T-046, 25 Oct 2026) — step 5 (“bind product version”) was the one
gap in this sequence from the day this table was first written, waiting on ProductApi to exist. The
ProductCode it binds to is a hardcoded {JurisdictionCode}-{SAV|CUR}-STD placeholder mapping (same
“demo stub” honesty as the account-opening flow’s existing DemoKycTier stub, not a real product-
selection design) — an AccountType/JurisdictionCode with no matching seeded product fails this step
cleanly (Status = Failed, a plain reason), which is the correct failure mode today, not a bug.
| Step | Service | If it fails |
|---|---|---|
| 1. Create customer (pending) | IdentityApi | Nothing else exists; retry |
| 2. KYC verified | IdentityApi | Stop; customer stays pending |
| 3. Create ledger account (idempotency key) | LedgerApi | Retry with the same key; never creates a second account |
| 4. Attach mandate | IdentityApi | Account exists but cannot be used (no mandate); retry |
| 5. Bind product version | ProductApi | Same; retry |
| 6. Mark opening complete | Orchestrator | The operation record shows the current step |
11. Required LedgerApi amendments
- Request hash and per-client idempotency (from the external review): Done, LedgerApi decisions #42 and #44 (merged 6 and 15 October 2026).
- Idempotency on
POST /api/accounts(P-13): Done, LedgerApi decision #43 (merged 14 October 2026). Keys are 1-128 characters of letters, digits,-,_,.,:(decision #44). - Chains of legs (P-9, P-10, P-14): a new chain endpoint posts an ordered list of legs in one database transaction. Every leg is still an ordinary two-entry transaction, so the “exactly one debit and one credit” rule is not amended.
TransferServiceis split into a core that posts one leg inside a database transaction owned by the caller, and the existing wrapper.ReversalServicekeeps its single-leg logic and gains a chain reversal that loops over the legs. Done, LedgerApi decision #45 (built onfeat/ledger-chains, merged as LedgerApi PR #26 on 15 Oct 2026 and PR #27 on 15 Oct 2026, ahead of this task board’s QA step; independently QA-reviewed and approved 16 Oct 2026,qa/reports/T-001.md; owner-ratified 16 Oct 2026). Detail in Section 12. - Fee-income and tax-payable system accounts per currency, seeded like the funding accounts (decision #25). Done, LedgerApi decision #46 (merged as LedgerApi PR #28, 16 Oct 2026; QA-approved,
qa/reports/PR-28.md). The accounts exist and are configured (FeeIncome:Accounts,TaxPayable:Accounts), but nothing routes a Fee/Tax leg to them yet — decision #45’s chain validation still only checksAccountClass == System. Wiring a specific fee-income/tax-payable account into a transaction is future ProductApi/OrchestratorApi work. - Token verification (P-12): the ledger verifies an IdentityApi-signed decision token locally before posting a customer-originated transaction, and stores the
decisionIdunder a unique constraint. This amends decision #34 narrowly: the ledger still calls nobody and stores nothing about identity. Proposed as decision #47.
12. Chain model for LedgerApi (draft of decision #45)
12.1 What it is, in plain words
A chain is a list of legs that the ledger posts together. Each leg is a normal LedgerApi transaction: one debit entry, one credit entry. The chain is the envelope that says “these legs belong together, and they either all happen or none do.”
| Transaction | Legs |
|---|---|
| Transfer, no fee | 1: Principal |
| Transfer with a fee | 2: Principal, Fee |
| Transfer with a fee and tax on the fee | 3: Principal, Fee, Tax |
The ledger does not work out fees or tax and does not know which products have them. ProductApi computes, the orchestrator builds the list of legs, and the ledger posts exactly the list it is given (P-4).
12.2 Why all-or-nothing still holds
Each leg is posted inside one database transaction that the chain owns. If any leg fails, the database throws away every leg, exactly as it throws away the two entries of today’s single transfer. Atomicity comes from the one database transaction, not from there being one transaction row. Legs are never committed one at a time.
12.3 Data shape
- New table
transaction_chains: id, public reference,initiated_by,idempotency_key,request_hash,status(Pending, Success, Failed),failure_reason,failed_sequence,reverses_chain_id(unique, null unless this chain is a reversal),created_at,completed_at.decision_id(unique, from the token, P-12) is deferred to decision #47 (token verification), not part of #45 — #45 shipped without it (D-6, token timing, is still open on the board; #45 simply does not need it yet). - Unique index on (
initiated_by,idempotency_key) withNULLS NOT DISTINCT, the same rule as transactions (decision #42). transactionsgets three nullable columns:chain_id,sequence,purpose. Unique on (chain_id,sequence). Rows from before this change stay null and behave as today.purposeis a fixed list:Principal,Fee,Tax(confirmed by the owner, D-7, 16 Oct 2026).- A leg’s own idempotency key is generated by the ledger as
chain:{chainId}:{sequence}, so it can never collide with a client’s key. The single-transfer, deposit and withdrawal endpoints reject client keys that start withchain:.
12.4 Rules the ledger enforces on every chain
- At least one leg, at most 10.
- Sequences are
1..Nwith no gaps. Leg 1 is the onlyPrincipalleg. - Every leg amount is greater than zero. A zero fee means no fee leg, and no fee means no tax leg. The caller never sends a zero leg.
- Every leg uses the same currency, and each amount respects that currency’s decimal places (the existing rule).
- Fee and Tax legs must credit a System account (fee-income or tax-payable). The ledger checks the account class, not the amount.
- One balance check per paying account, up front. For each customer account that pays any leg, the total of everything it pays across the chain (principal plus fee plus tax) must not exceed its balance. This gives one clear error (“Insufficient balance”) instead of a principal that passes and a fee that fails. System accounts keep the existing overdraft floor.
- The existing status rules apply per leg (source must be Active, destination must not be Blocked).
12.5 Locking
Before posting anything, the ledger locks every account that is debited by any leg with SELECT ... FOR UPDATE, in one fixed order (ascending account number), once for the whole chain. The fixed order stops two chains that touch the same accounts from waiting on each other forever (deadlock). Credited accounts are not locked, as today.
12.6 Failure and retry
- Business failure (insufficient funds, closed account, rule 1 to 7): the database transaction rolls back every leg. A second, small database transaction stores the chain as
Failedwithfailure_reasonandfailed_sequenceand writes the audit row. A retry with the same key and the same body returns that stored failure. To try again for real, use a new key. This matches today’s decision #6 for single transfers. - Technical failure (database down, crash): everything rolls back and nothing is stored. A retry with the same key runs again from the start.
- Same key, different list of legs (even a different fee): 409, as in decision #42.
12.7 Request hash
SHA-256 of the JSON of the ordered legs: for each leg, debit account, credit account, amount (normalised with G29) and purpose. Narration is excluded, as in decision #44.
12.8 Reversal
POSTa reversal against a chain reference. The ledger posts one reversing leg for each original leg, last leg first (Tax, then Fee, then Principal), all inside one database transaction. Each reversing leg uses the existing single-leg reversal logic, which keeps working because every leg still has exactly one debit and one credit. TheSingle/Firstassumptions inReversalServicestay valid.- The reversal is stored as its own chain with
reverses_chain_idset. A unique index on that column means a chain can be reversed only once (the same jobix_reversals_original_transaction_iddoes for a single transaction). - A leg that belongs to a chain cannot be reversed alone. The old single-transaction reversal endpoint returns 422 “this transaction is part of chain X; reverse the chain”. Without this rule someone could refund the principal and keep the fee.
- Locking: lock every account that the reversing legs debit (the original credit accounts), in the same ascending order as 12.5.
- Frozen accounts may be debited by a reversal (decision #38), applied per leg.
- If any reversing leg fails, the whole reversal rolls back.
12.9 Audit
In the same database transaction as the postings: one audit row per leg (so existing audit queries keep working) and one audit row for the chain as a whole.
12.10 Token (P-12)
The token binds the principal leg and the idempotency key (debit account, principal amount, currency, hash of the exact customer request). The ledger stores decision_id on the chain under a unique constraint. Fee and tax legs are added by the orchestrator from ProductApi’s rules and are not covered by the token; the reconciliation job in Section 9 checks them.
12.11 Code changes (outline)
- Split
TransferService:PostLegAsyncruns the checks and writes one leg inside a database transaction supplied by the caller. A rejected leg throws a business exception; it does not commit. The existingTransferAsyncbecomes a thin wrapper that opens the database transaction, callsPostLegAsynconce and keeps today’s behaviour and responses. - New
ChainServicethat validates rules 1 to 6, locks accounts (12.5), callsPostLegAsyncfor each leg in order, and handles 12.6. ReversalService: extract the single-leg reversal into a method that runs inside the caller’s database transaction; addReverseChainAsync; make the old endpoint refuse chain legs.- One EF migration for the new table and three columns, with a migration test like the earlier ones.
- Responses for existing transaction reads gain optional
chainReference,sequenceandpurpose.
12.12 Tests to write first
- One-leg chain gives the same balances and entries as a plain transfer.
- Three-leg chain where the fee leg is rejected leaves no entry from any leg, and the stored Failed chain returns on retry.
- Payer can afford the principal but not principal plus fee: fails with a clear message, nothing posted.
- Two chains touching the same accounts in opposite directions, run in parallel: no deadlock.
- Same key with a changed fee: 409.
- Chain reversal restores every balance; a second reversal returns the already-reversed error.
- Reversing a single leg of a chain: 422.
- A client key starting with
chain:is rejected on the single-transfer endpoint.