1. Scope
The Ledger module is the sole trusted source of balance truth for CPG customers and merchants. It answers, at any moment: whose money, where it sits, and in what status - recorded accurately, uniquely, without retroactive edits, and reconcilable with on-chain activity after BL-01 removes reliance on on-chain logs as the book of record.
1.1 In scope
- Double-entry journaling in integer minor units; balanced postings (Σ source amounts \= Σ destination amounts per asset)
- Synchronous over-book prevention at the write layer
- Synchronous idempotency for money writes (Idempotency-Key and/or stable reference / tx_hash)
- Append-only hashed audit log; corrections via reversing entries (transaction revert) only
- Account chart and schema enforcement for crypto rails (USDT/6, USDC/6 on bsc, eth, polygon, tron)
- Numscript fund-flow templates (deposit, sweep, allocate, confirm, risk, settlement, refund, invoice holds, gas)
- Volumes and balances query APIs for consumers and ops
- Write-layer account/rail freeze controls, pre-availability KYT gating, maker-checker execution controls, and period-close enforcement
- Configurable log-integrity mode, externally signed checkpoints, privileged-DB tamper-detection handoff, DR/PITR requirements, and daily balance attestation
- Canonical asset identity, authoritative business sequence, hot-account pooling, ledger segmentation criteria, backpressure, and benchmark evidence
- Deposit address uniqueness data model and enforcement contract (BR-02) - registry may be owned by account/custody services; uniqueness constraints and binding to ledger virtual accounts are specified here
1.2 Out of scope
- Chain scanning, solidified/finality gates, and reorg un-credit engines (BR-03 → Synchronizer FSD)
- Custody, HSM/MPC, xpub private-key material (Doc03 / A4 key management)
- Merchant Portal / CRM UI screens
- Full Daily Reconciliation product FSD (FR6 hooks are defined here; cycle ownership may live in Reconciliation FSD)
- Outbound signing/broadcast/nonce/replacement-family exactly-once controls (Transaction/Custody FSD owns BR-L04 outbound portions and BR-L15)
- KYT vendor selection and legal/accounting retention policy; this FSD specifies only the enforceable integration contract and ledger controls
1.3 Actors (S2S)
| Actor |
Role |
| sync-service |
Posts deposit_detected after chain finality |
| account-service |
Registers hot-wallet (and related) account metadata |
| transaction-service |
Posts payment allocate and related merchant flows |
| Platform ops |
Schema provision, ledger admin, bulk ops, restore |
| ledger-service |
Authoritative write/read of journal, volumes, logs |

2. Business Requirement
Governing requirements are defined in BR-01-02 LEDGER. This FSD does not rewrite the BR; it maps each requirement to design artifacts below.
| BR section |
Need (summary) |
Solution location in this FSD |
| BR-01 (§5.1) |
Ledger as sole trusted source for balance changes (FR1–FR12) |
Features, Flow, Data Model, Security |
| BR-02 (§5.2) |
Absolute uniqueness of deposit addresses |
§6.3 Address registry; Specific security |
Hard blockers (must be proven at write layer, not T+1 only): FR2, FR3, FR4, FR9, FR10.
FR10 credit-finality is owned by Synchronizer; ledger only accepts credit posts that consumers assert as finalized.
2.1 FR → FSD coverage matrix
| FR |
Level |
Coverage in this FSD |
| FR1 Double-entry balanced journal |
HARD |
§4 Features; §6 templates-by-event |
| FR2 Synchronous over-book prevention |
HARD |
FEAT-BAL-01; UC-OVR-01; write rejects insufficient balance |
| FR3 Synchronous idempotency |
HARD |
FEAT-IDM-01; UC-IDM-01; §7 Idempotency-Key / reference |
| FR4 Crash recovery governed by tx_hash |
HARD |
§3.9 Recovery contract; consumers use stable reference |
| FR5 State machine authority |
IMPORTANT |
Template-only writes in prod; authorized callers only |
| FR6 Continuous reconciliation |
IMPORTANT |
FEAT-REC-01 hooks; detail may defer to Reconciliation FSD |
| FR7 Immutable audit trail |
IMPORTANT |
§6.2 logs; FEAT-AUD-01; revert-only corrections |
| FR8 SoD operator vs settlement |
NEED CONFIRM |
§8.2 proposed scopes ledger:write:ops / ledger:write:settlement |
| FR9 Unique address registry |
HARD |
§6.3; UC-ADR-01; BR-02 |
| FR10 Credit-finality / un-credit |
HARD |
Out of scope → Synchronizer; ledger accepts finalized credits only |
| FR11 Float cap |
NEED CONFIRM |
FEAT-FLT-01 - platform:float:{rail} tracking + alert contract |
| FR12 Controlled rounding dust |
NEED CONFIRM |
FEAT-DST-01 - platform:dust:{asset} + dedicated entries |
2.2 NEED CONFIRM - proposed designs (locked for implementation planning)
| FR |
Proposed design |
| FR8 |
Separate OAuth/API clients: ops client may call deposit/sweep/risk/refund templates; settlement client may call settlement_* only. Enforce at gateway or ledger auth client ACLs until Formance custom scopes land. |
| FR11 |
Maintain aggregate credited-but-unconsolidated balance on platform:float:{chain} (or query aggregate over treasury:virtual:*). Thresholds in config; exceed → high-priority alert + optional outbound freeze flag in metadata. |
| FR12 |
Record dust via template posting to platform:dust:{asset}; after N settlements, sum of dust entries must equal dust account balance (audit query). |
2.3 FP-CPG-BR-LED v1.1 coverage and disposition
This section is normative for v1.1. It records the design disposition of BR-L01–BR-L23. Cross-module rows define Ledger’s interface responsibility without claiming ownership of the other module’s implementation.
| BR-L |
Ledger disposition |
Updated feature / section |
| L01 |
Balanced, integer-unit, log-derived bookings remain mandatory; Numscript source and version must be reviewable. |
FR1; FEAT-TXN-01; FEAT-GOV-01 |
| L02 |
Over-book rejection remains synchronous. A separate suspect-account control can reject new credits and/or outbound writes until maker-checker clearance. |
FEAT-BAL-01; FEAT-FRZ-01 |
| L03 |
Ledger enforces booking idempotency and stores occurrence/provenance fields supplied by Sync. Sync owns construction of deep chain identity. |
FEAT-IDM-01; §6.5/§6.7; Sync FSD v1.1 |
| L04 |
Ledger crash recovery remains reference/idempotency based. Outbound signing/broadcast state is Transaction-owned. |
§3.9; Transaction FSD |
| L05 |
Ledger accepts only a finalized assertion from Sync and performs append-only revert when authorized. |
FEAT-REV-01; Sync FSD v1.1 |
| L06 |
Ledger exposes lifecycle slices and enforces write-layer freezes; full equations and cycle operation remain Reconciliation-owned. |
FEAT-REC-01/REC-02; FEAT-FRZ-01 |
| L07 |
Hash mode, integrity recomputation, signed checkpoints, and tamper-detection requirements are explicit. |
FEAT-HSH-01; FEAT-CHK-01; FEAT-DBT-01 |
| L08 |
Sequential derivation plus database uniqueness remains mandatory. |
FR9; §6.3 |
| L09 |
Formance version/deployment is pinned; production is template-only; migrations require immutable template versions, snapshot rehearsal, rollback, and invariant comparison. |
FEAT-SCH-01; FEAT-MIG-01 |
| L10 |
Per-service credentials/template ACLs plus maker-checker for adjustment, revert, and clear-freeze. |
FEAT-SOD-01 |
| L11 |
Float/dust cap breach requires alert plus freeze or throttle; values are configuration. |
FEAT-FLT-01; FEAT-DST-01; FEAT-CAP-01 |
| L12 |
KYT PASS is required before funds become available; REVIEW/FAIL is held before availability. |
§3.10; FEAT-KYT-01 |
| L13 |
WAL/PITR, replicas, declared replication mode, numeric RPO/RTO, degraded operation, and recovery drill are required. |
§3.12; FEAT-DR-01; §8.3 |
| L14 |
Daily internal asset-by-asset attestation is required; external proof-of-reserves remains negotiated. |
FEAT-ATT-01; §6.8 |
| L15 |
Ledger provides booking idempotency only; end-to-end outbound exactly-once is Transaction/Custody-owned. |
FEAT-IDM-01; Transaction FSD |
| L16 |
Every Formance asset code maps one-to-one to a canonical network/contract/native/token identity and immutable scale policy. |
FEAT-AST-01; §6.6 |
| L17 |
Ledger commit/business-effective times are distinct and state changes use an authoritative business sequence, not wall-clock ordering. |
FEAT-ORD-01; §6.7 |
| L18 |
Ledger stores provenance supplied by Sync; provider acquisition and disagreement handling remain Sync-owned. |
§6.5; Sync FSD v1.1 |
| L19 |
Closed periods reject ordinary backdated entries; retrospective adjustment is append-only, approved, and auditable. |
§3.11; FEAT-CLS-01 |
| L20 |
Chart/template versions require immutable IDs, approval, deployment pinning, migration rehearsal, and rollback evidence. |
FEAT-GOV-01; FEAT-MIG-01 |
| L21 |
Independent privileged-DB tamper detection and retention/legal-hold handoffs are required; key controls cross-reference Doc03/A4. |
FEAT-DBT-01; §8.3 |
| L22 |
Replication, reconciliation, invariant, idempotency, queue, and latency metrics plus alerts/dashboard/runbook are deliverables. |
FEAT-OBS-01; §7.11 |
| L23 |
Deterministic account pools, measured segmentation triggers, dual-mode benchmark, and durable no-drop backpressure are mandatory. |
FEAT-POOL-01; FEAT-SEG-01; FEAT-PRF-01; FEAT-BKP-01 |
3. Flow
All money movements that change balances must go through ledger-service v2 transactions. Amounts use Formance notation {asset} {integer_minor_units} (e.g. USDT/6 1000000 \= 1.0 USDT).
3.0 System context
3.1 Deposit credit - deposit_detected
| Item |
Detail |
| Actor |
sync-service (after Synchronizer/finality - BR-03) |
| Template |
deposit_detected |
| Movement |
world:{senderAddress} → treasury:virtual:{chain}:{va_id} |
| Idempotency |
Production reference \= versioned occurrence_id supplied by Sync; tx_hash remains provenance. Idempotency-Key equals or deterministically derives from the same occurrence identity. |
| Success |
Virtual account volumes increase; usable withdrawable balance only after later confirm flows as product rules dictate |
| Failure |
Duplicate reference → idempotent hit / conflict; invalid chart address → reject |
3.2 Sweep - sweep_initiate / sweep_complete
| Step |
Template |
Movement |
| Initiate |
sweep_initiate |
treasury:virtual:{chain}:{va} → treasury:sweep_in_transit:{chain}:{batch} |
| Complete |
sweep_complete |
treasury:sweep_in_transit:{chain}:{batch} → treasury:hot:{chain}:{hot_id} |
Idempotency keys must include batch id + phase. Failure mid-flight leaves funds in transit for ops recovery (replay complete or reverse initiate).
3.3 Payment allocate → confirm funds
| Step |
Template |
Movement |
| Allocate |
payment_allocate |
Source (hot/invoice) → merchants:{id}:pending + platform:fees:accrued:... |
| Confirm |
confirm_funds |
merchants:{id}:pending → merchants:{id}:available |
Actor: transaction-service (allocate); confirm may be transaction or risk/ops per product rules.
3.4 Risk hold / release
| Template |
Movement |
| risk_hold |
merchants:{id}:available → merchants:{id}:risk_hold |
| risk_release |
merchants:{id}:risk_hold → merchants:{id}:available |
3.5 Settlement batch
| Step |
Template |
Movement |
| Lock |
settlement_lock |
merchants:{id}:available → merchants:{id}:settlement_locked |
| Batch init |
settlement_batch_init |
merchants:{id}:settlement_locked → treasury:settlement_in_transit:{chain}:{batch} |
| Complete |
settlement_batch_complete |
transit → merchants:{id}:settled + platform fee settled/network accounts |
3.6 Refund
| Step |
Template |
Movement |
| Lock |
refund_lock |
merchants:{id}:available → merchants:{id}:refund_locked |
| Execute |
refund_execute |
refund_locked → beneficiary (world or designated) + optional platform refund fee |
3.7 Invoice holds and gas
| Template |
Purpose |
| invoice_underpaid_hold / invoice_overpaid_hold / invoice_expired_hold / invoice_refund_hold |
Move invoice clearing into hold buckets |
| gas_record |
Record gas cost against treasury:gas:{chain}:{wallet} / platform network fee accounts |
| merchant_adjustment |
Controlled adjustment bucket movements |
3.8 Correction path - transaction revert
Corrections never UPDATE or DELETE journal rows. Call POST /v2/{ledger}/transactions/{id}/revert to create a reversing transaction. Original row remains with reverted_at set; logs append REVERTED_TRANSACTION.
3.9 Crash recovery contract (FR4)
- Consumer broadcasts or observes on-chain tx and obtains stable tx_hash.
- Before or after chain success, the consumer posts the ledger booking with reference \= canonical occurrence_id for inbound chain events (or intent_id/canonical outbound reference for outbound booking) and an Idempotency-Key derived from the same identity. tx_hash is retained as provenance.
- If the process crashes after chain success but before/during ledger write: on restart, replay the same canonical reference. Ledger returns the prior transaction (idempotency hit) or creates exactly one booking — never a second credit.
- Scanner/credit path must not invent a new reference for the same chain occurrence. Reorg/re-inclusion or approved early-credit recovery uses an explicitly linked new booking_attempt_id, not an overwrite.
3.10 KYT-gated credit and write-layer freeze
payment_allocate places funds in merchants:{id}:pending. confirm_funds MUST require a valid, immutable KYT decision reference with decision PASS. A missing, expired, REVIEW, or FAIL decision is rejected and MUST NOT move funds to available.
| Decision |
Ledger action |
| PASS |
confirm_funds moves pending → available and records kyt_decision_id, policy version, actor/service, and decision time. |
| REVIEW |
Keep in pending or move through the planned kyt_hold template to merchants:{id}:kyt_hold. |
| FAIL |
Move to kyt_hold/refund workflow; do not first pass through available. |
Reconciliation, provider disagreement, privileged-DB tamper detection, float-cap breach, or nonce/custody incident may create a control-state record for a chain, asset, account, merchant, or template. Ledger-service MUST enforce this state before posting. Direct Formance access that bypasses the wrapper is prohibited in production. Clearing a freeze requires an approved maker-checker request and creates an audit event.
3.11 Period close and retrospective adjustment
Ledger-service maintains an accounting-period registry. Once a period is CLOSED, ordinary bookings with a business-effective time inside that period are rejected. No existing journal entry is updated or deleted. A retrospective correction uses a dedicated retrospective_adjustment template in the current open period, references the affected closed period and original booking, and requires maker-checker approval plus a reason/evidence link.
3.12 Recovery, integrity checkpoint, and balance attestation
- WAL archiving and PITR are enabled for the ledger database; replica topology, replication mode, and fault independence are recorded in the deployment manifest.
- Proposed G1 target: zero loss of acknowledged committed postings within the primary region and RTO ≤1 hour. Cross-region asynchronous lag and degraded-operation policy MUST be stated numerically.
- Recovery drills restore a selected point, replay required queues, and compare transaction count, log integrity, account volumes, checkpoints, and attestation totals before service is reopened.
- A daily attestation aggregates ledger liabilities by canonical asset and compares them with reconciled controlled-wallet balances. The artifact contains the ledger set/PIT, formula version, exceptions, approvals, and optional KMS/HSM signature. Retention target is ≥7 years subject to Legal approval.
4. Features
4.1 Core ledger engine
FEAT-LED-01 Ledger and bucket provisioning
- Create/list/read ledgers under /v2; ledger cpg hosted in a Postgres bucket schema (default _default).
- Acceptance: POST /v2/cpg (or provision script) yields readable ledger; storage in _system.ledgers.
FEAT-SCH-01 Schema and chart enforcement
- Insert versioned schema cpg-crypto v1.0.0 (chart + transaction templates + assets).
- Production: schema enforcement mode rejects writes that violate chart/templates.
- Related FR: FR1, FR5.
- Acceptance: Unprovisioned template name fails; invalid account path fails chart validation.
FEAT-TXN-01 Create transaction (postings or template)
- POST /v2/{ledger}/transactions with postings or script.template + vars.
- CPG production path: templates only (see §4.2).
- Related FR: FR1.
- Acceptance: Balanced entry persisted; volumes updated atomically.
FEAT-BAL-01 Synchronous over-book prevention
- Debit against insufficient account balance fails at write layer (unless explicit force - forbidden in CPG prod).
- Related FR: FR2.
- Acceptance: UC-OVR-01 fails immediately; no partial commit.
FEAT-IDM-01 Synchronous idempotency
- Header Idempotency-Key on mutating ops; unique reference on transactions.
- For chain-derived bookings, occurrence_id is mandatory and unique within the ledger. reference MUST equal occurrence_id or map one-to-one through a uniqueness registry enforced before posting.
- Replay returns prior result (Idempotency-Hit) without second booking.
- Related FR: FR3, FR4.
- Acceptance: UC-IDM-01 - identical tx_hash reference yields one credit only.
FEAT-AUD-01 Append-only audit log
- Every commit appends hashed logs row (NEW_TRANSACTION, REVERTED_TRANSACTION, metadata ops).
- Journal rows are not mutated for amount correction.
- Related FR: FR7.
- Acceptance: No UPDATE of posting amounts; revert creates new opposite transaction.
FEAT-REV-01 Transaction revert
- POST .../transactions/{id}/revert creates reversing entry.
- Related FR: FR7.
- Acceptance: Balances restored; original retained for audit.
FEAT-QRY-01 Accounts, volumes, aggregate balances
- Read account with volumes; list transactions; aggregate balances for prefixes.
- Acceptance: Balance equals input − output per asset.
FEAT-BLK-01 Bulk operations
- POST /v2/{ledger}/_bulk for batched creates (atomic/parallel flags).
- Acceptance: Atomic bulk all-or-nothing when atomic=true.
- Add/delete metadata with revision history tables.
- Used for hot-wallet registration and flow tags (flow, chain, tx_hash, network).
4.2 CPG fund-flow templates (features)
| Feature ID |
Template |
Related FR |
| FEAT-DEP-01 |
deposit_detected |
FR1, FR3, FR10 (consumer gate) |
| FEAT-SWP-01 |
sweep_initiate, sweep_complete |
FR1, FR2 |
| FEAT-PAY-01 |
payment_allocate, confirm_funds |
FR1, FR5 |
| FEAT-RSK-01 |
risk_hold, risk_release |
FR5 |
| FEAT-STL-01 |
settlement_lock, settlement_batch_init, settlement_batch_complete |
FR1, FR8 |
| FEAT-REF-01 |
refund_lock, refund_execute |
FR1, FR2 |
| FEAT-INV-01 |
Invoice hold templates |
FR1 |
| FEAT-GAS-01 |
gas_record |
FR1 |
| FEAT-ADJ-01 |
merchant_adjustment |
FR7 (controlled) |
4.3 Operational / control features
FEAT-REC-01 Reconciliation hooks (FR6)
- Expose volumes/logs for continuous compare vs expected chain/custody totals.
- On mismatch: emit alert; set ledger or consumer freeze metadata to block outbound settlement templates until cleared.
- Cycle target: real-time or ≤5 minutes (product/ops).
FEAT-FLT-01 Float cap tracking (FR11 - proposed)
- Track credited-but-unconsolidated float per rail; threshold breach → high-priority alert.
FEAT-DST-01 Dust accounting (FR12 - proposed)
- Dedicated dust account + entries so aggregate dust matches dust balance after N settlements.
FEAT-ADR-01 Address uniqueness contract (FR9 / BR-02)
- See §6.3; issue addresses only after registry uniqueness check; bind to virtual account path.
FEAT-FRZ-01 Write-layer control state
- Fail-closed checks apply to configured credit and outbound templates by chain, asset, account, merchant, or global scope.
- Freeze reasons are versioned (RECON_MISMATCH, PROVIDER_DISAGREEMENT, DEEP_REORG, FLOAT_CAP, DB_TAMPER, OPS_INCIDENT).
- Clear-freeze requires maker-checker approval and an immutable audit reference.
- Acceptance: TC-06 injects a discrepancy; affected writes are rejected within the agreed SLO.
FEAT-KYT-01 Pre-availability KYT gate
- confirm_funds requires a PASS decision reference and policy version.
- REVIEW/FAIL remains pre-availability using pending/kyt_hold; risk_hold after availability is not a substitute.
- Acceptance: a missing or non-PASS decision cannot produce merchant available balance.
FEAT-REC-02 Versioned lifecycle reconciliation contract
- Expose and version the seven required reconciliation slices: deposit↔credit, sweep state, controlled-wallet balances↔liabilities, in-transit assets, merchant liabilities, fees/dust, and exception inventory.
- Equations are versioned per rail and canonical asset and explicitly address gas, issuer freeze/blacklist, fee-on-transfer/rebasing behavior, and mistakenly sent tokens.
- Ledger provides PIT/aggregate data and control-state enforcement; the Reconciliation FSD owns scheduling, operator workflow, and external evidence acquisition.
FEAT-AUD-02 Booking traceability
- Every booking records booking_id, occurrence_id or outbound intent_id, actor/service identity, authentication context, business-effective time, commit time, schema/template version, and applicable approval/control-request ID.
- Acceptance: sampled entries can be traced from client/chain occurrence through approval and ledger commit without relying only on free-form metadata.
FEAT-HSH-01 Ledger log-integrity mode
- Deployment parameter HASH_LOGS_MODE is frozen at G1 (ENABLED, ASYNC, or DISABLED). Baseline is ENABLED pending T08 benchmarks.
- Periodic integrity job recomputes balances from journal/logs and compares with stored volumes.
- For ASYNC, the blind window and maximum unhashed backlog are measured and alerted.
FEAT-CHK-01 Externally signed checkpoints
- Mandatory when HASH_LOGS_MODE != ENABLED; generated at least as often as the reconciliation cycle.
- Checkpoint includes ledger/PIT, last log ID/hash, transaction count, asset/account aggregate digest, timestamp, and signature/key version.
- Verification must be reproducible independently from the ledger database.
FEAT-DBT-01 Privileged-database tamper detection
- Mandatory when HASH_LOGS_MODE != ENABLED and required as defense in depth in all modes.
- Direct UPDATE/DELETE or privileged DDL affecting ledger tables is exported to an independently controlled audit destination and detected within the agreed SLO.
- The monitored privileged database role cannot disable or erase the detector/evidence store.
FEAT-MIG-01 Schema/template migration governance
- Pin Formance version, deployment edition/license, chart version, template version, hash mode, and deployment configuration.
- Every booking records immutable schema/template version.
- Production migration requires approval, production-scale snapshot rehearsal, invariant comparison, rollback procedure, and TC-12 evidence.
FEAT-SOD-01 Maker-checker execution
- merchant_adjustment, transaction revert, clear-freeze, period close/reopen, and retrospective adjustment require a durable approved control request.
- Maker and checker must be different strong identities; an API credential alone is not sufficient identity.
- Ledger execution records the approval request ID and refuses expired/reused approvals.
FEAT-CAP-01 Mandatory float/dust cap action
- Per-rail/canonical-asset thresholds and cadence are configuration.
- Cap breach emits a high-priority alert and automatically freezes or throttles the affected outbound/credit scope according to policy; alert-only behavior is insufficient.
FEAT-DR-01 Ledger DR/PITR
- WAL archiving, PITR, replica topology/fault independence, replication mode, numeric RPO/RTO, degraded-operation policy, credential recovery, and TC-10 restore drill are required deliverables.
FEAT-ATT-01 Daily balance attestation
- Produce an asset-by-asset artifact comparing total ledger liabilities with reconciled controlled-wallet balances and documenting exceptions.
- Internal attestation is required; public proof-of-reserves remains negotiated.
FEAT-AST-01 Canonical asset registry
- Every ledger asset code maps one-to-one to a versioned canonical asset identity: network namespace/version + native or contract identity + token ID where applicable + immutable decimal policy.
- Symbol/scale aliases alone are prohibited for new production assets.
FEAT-ORD-01 Authoritative business ordering
- Bookings store distinct chain/observed/finality/business-effective/commit times as applicable.
- An authoritative business sequence or predecessor reference orders fund-state transitions. Wall-clock timestamps do not decide state order.
- Out-of-order, late, or backdated events are rejected, quarantined, or applied by an explicitly versioned rule.
FEAT-CLS-01 Period close
- Closed periods reject ordinary backdated booking. Reopen is exceptional and dual-controlled; preferred correction is current-period retrospective adjustment with full linkage.
FEAT-GOV-01 Chart/template approval and source availability
- Numscript source, chart, migration, reviewer approvals, and content hashes are stored with immutable version IDs.
FEAT-POOL-01 Hot-account pooling
- Aggregate accounts such as world ingress, hot wallets, sweep transit, and fee collectors use deterministic pools per canonical asset. Pool count/routing are configuration and every pool reconciles independently.
- Acceptance: TC-03 at ≥20× projected peak meets the agreed p99 lock-wait SLO.
FEAT-SEG-01 Ledger topology and segmentation
- Baseline remains the cpg ledger while measured write utilization, p99 commit latency, and lock contention remain below G1 thresholds.
- Segmentation is activated by network/cohort/period only after benchmark evidence. Cross-ledger money movement is prohibited in v1. If introduced, use a tested reserve-then-confirm saga with compensating release and reconciliation; no false atomicity claim.
- Cross-ledger reads used for attestation/reconciliation require a manifest of per-ledger point-in-time positions or another consistent-cut mechanism so aggregate reports cannot silently use a torn read.
FEAT-PRF-01 Measured capacity
- T08 publishes sustainable writes/s plus commit latency p50/p99 for the selected Formance version and production-equivalent storage in both HASH_LOGS=ENABLED and the proposed scale mode. Scope includes inbound and outbound ledger postings.
FEAT-BKP-01 Durable backpressure
- When approaching the measured ceiling, upstream events remain in a durable queue. Ledger-service throttles/retries without dropping or skipping monetary events.
- Acceptance: overload injection yields zero lost events and meets the agreed credit-latency SLO.
FEAT-OBS-01 Ledger observability handoff
- Required metrics: write/commit latency, lock wait/contention, queue depth/age, idempotency hit/conflict rate, reconciliation lag, credit latency, Sync cursor/finality lag (federated dashboard), invariant/checkpoint status, replication lag, freeze state, cap utilization, attestation status, and migration version.
- Alert rules, dashboards, operational runbook, and DR credential-recovery procedure are acceptance artifacts.
5. Usecases
Detailed use-case catalog for this module is maintained under 08_UC:Catalog use case chi tiết của module này được quản lý tại 08_UC:
6. Data Requirement (Data Model)
CPG control SQL (Flyway)
7. Endpoints and Payloads
| Method |
Route |
Description |
Request |
Response |
| GET |
/v2/{ledger}/accounts |
List accounts |
{query params} |
{accounts[]} |
| GET |
/v2/{ledger}/accounts/{address} |
Get account |
{path params} |
{account} |
| POST |
/v2/{ledger}/transactions |
Create transaction |
TransactionRequest / numscript body |
{transaction} |
| GET |
/v2/{ledger}/transactions |
List transactions |
{query params} |
{transactions[]} |
| GET |
/v2/{ledger}/transactions/{id} |
Get transaction |
{path params} |
{transaction} |
| POST |
/_/control/freezes |
CPG freeze control |
{control fields…} |
{control state} |
| GET |
/_/control/... |
CPG control queries/approvals |
{…} |
{control fields…} |
8. Security
8.1 Application security (Doc03)
Fleet-wide application security is defined in Doc03 - Application Security.
Apply as baseline for ledger-service:
| Doc03 area |
Relevance |
| Part A trust zones / identity planes |
Ledger API key plane (S2S Bearer) |
| G1–G9 General controls |
Auth patterns, secrets (Vault), logging, SDLC, S2S discipline |
8.2 Specific security (Ledger module)
Aligned with Doc03 S9. ledger / ledger-service and BR hard requirements.
| Control |
Requirement |
Status / notes |
| AuthN |
OAuth2 / API key; scopes ledger:read, ledger:write. No public browser access to money APIs. |
|
| Callers |
Only account-service, sync-service, transaction-service via pkg/ledgerclient + LEDGER_API_KEY |
|
| Idempotency |
Mandatory on money writes (header and/or reference) |
FR3; e2e idempotency tests |
| Immutability |
Append-only journal; corrections via revert only |
FR7 |
| Schema enforcement |
Prod rejects arbitrary postings outside allowed templates/chart |
FR5 |
| Over-book prevention |
Reject insufficient balance at write; forbid force in prod |
FR2 |
| HTTP audit |
Audit middleware / audit-events on API |
Doc03 S9 |
| Address uniqueness |
Sequential registry + UNIQUE constraints; no UUID hash/mod |
FR9 / BR-02 |
| SoD (FR8 proposed) |
Separate clients/scopes: ops vs settlement templates |
NEED CONFIRM - implement via API key ACLs / gateway |
| Secrets |
DB creds via Vault CSI; never log API keys, tokens, or xpub |
Doc03 G4 / G5 |
| Float / freeze |
On recon mismatch or float breach, block outbound settlement writes |
FR6 / FR11 |