CPG-Core FSD Transaction
FSD — Core
A. Document controlA. Kiểm soát tài liệu
| Doc ID | CPG-FSD-CPG-Core_FSD_Transaction |
|---|---|
| VersionPhiên bản | 1.1 |
| StatusTrạng thái | Draft |
| Owner | CPG BA / Architecture |
| AudienceĐối tượng | Backend, QA, Product, Security, Load-test engineering |
| ClassificationPhân loại | Internal |
| Effective dateNgày hiệu lực | 01/12/2026 |
| Related docs | Core Index · BR/NFR Catalog |
B. Version historyB. Lịch sử phiên bản
| Version | Date | Author | ChangesThay đổi |
|---|---|---|---|
| 1.0 | 21/08/2026 | Khoa Trinh | Version 1.0, Initial FSD-Transaction (Doc02) from Ledger, Sync, Smart Contract, MP Transaction, MP Setting Service |
| 1.1 | 01/12/2026 | Khoa Trinh | Version 1.1: Data Requirement + Endpoints synced from transaction code + webhook-dispatcher migrations |
C. Table of contentsC. Mục lục
- 1. Scope
- 1.1 In scope
- 1.2 Out of scope
- 1.3 Actors (S2S)
- 1.4 Delivery phases
- 2. Business Requirement
- 2.1 FR / BR → FSD coverage matrix
- 2.2 NEED CONFIRM — proposed designs (locked for implementation planning)
- 2.3 Status mapping (Portal ↔ Core) — mandatory
- 3. Flow
- 3.0 System context
- 3.1 Create payment session
- 3.2 Deposit match
- 3.3 Allocate → KYT → confirm funds
- 3.4 Merchant list / detail
- 3.5 Refund (BR-09)
- 3.6 Settlement batch (FR8)
- 3.7 Crash recovery and outbound exactly-once (L04 / L15)
- 3.8 Webhook delivery
- 3.9 Incident: freeze, pause, backpressure
- 4. Features
- 4.1 Session and match
- 4.2 Ledger merchant flows
- 4.3 Outbound exactly-once and refund / settlement
- 4.4 Query, webhook, freeze, observability
- 5. Usecases
- 6. Data Requirement (Data Model)
- 7. Endpoints and Payloads
- 8. Security
- 8.1 Application security (Doc03)
- 8.2 Specific security (Transaction module)
- 9. NFR (non-functional)
- 9.1 Acceptance test profiles (for QA / load-test)
D. ContentD. Nội dung
1. Scope
The Transaction module is the sole owner of the merchant payment lifecycle after a deposit is observed, and of all outbound money movement that is not Sync credit or un-credit. It answers: which payment session a chain occurrence belongs to, when merchant funds become available, how refunds and settlements are signed and broadcast exactly once, and how merchants are notified — without owning the ledger journal, address registry, or chain scanner.
Sibling documents remain authoritative for their modules. This FSD owns the orchestrator (transaction-service) that sits between them.
1.1 In scope
- Payment session / intent execution for QR Payment, Checkout Link, and API Payment (instruments created by Setting Service)
- Matching Sync observations / ledger virtual-account credits to a session (amount, asset, chain, VA, invoice rules)
- Ledger merchant flows:
payment_allocate,confirm_funds, invoice holds,refund_lock/refund_execute,settlement_lock/settlement_batch_init/settlement_batch_complete - KYT gate before
confirm_funds(FSD-Ledger §3.10 / FEAT-KYT-01); REVIEW/FAIL never reaches merchantavailable - Honor ledger write-layer freezes and Smart Contract pause before any outbound template or chain broadcast
- Outbound exactly-once (FSD-Ledger BR-L04 outbound portion and BR-L15):
intent_id, nonce family, replacement transactions, crash replay - Phase 2 EVM operator / settlementManager orchestration of VirtualAccount + Forwarder (FSD-SmartContract)
- Phase 1 TRON off-chain equivalent (no clones): custody-adapter sign/broadcast; fee split booked in ledger only
- BR-09 refund policy: KYC/whitelist destination, block exchange
toSource, dual approval before broadcast - Merchant transaction query, refund initiate, and webhook delivery/resend APIs consumed by FSD-MP-Transaction
- Merchant webhook worker using Setting Service webhook config (HMAC, retries, event catalog)
1.2 Out of scope
- Address issuance and BR-02 registry (FSD-Account)
- Chain scanning, finality, reorg un-credit (FSD-Sync)
- Ledger journal, Numscript templates, over-book prevention, hash logs, period close (FSD-Ledger)
- Solidity bytecode, CREATE2 math, factory pause implementation (FSD-SmartContract); this FSD honors pause and orchestrates operator/settlement calls
- Portal UI, branding, API-key 2FA screens (FSD-MP-Transaction, FSD-MP-Setting)
- QR / Checkout catalog CRUD, webhook URL config, API keys / IP whitelist persistence — merchant-settings owns these; this FSD only reads them
- Sweep VA → hot (
sweep_initiate/sweep_complete) — ops/treasury (FSD-Ledger UC-SWP-01); Transaction consumes hot/invoice funded state and does not own sweep jobs - Fiat, on/off-ramp, admin force status override (Portal out of scope; keep)
- MPC/HSM key ceremonies and private-key material (A4)
1.3 Actors (S2S)
| Actor | Role |
|---|---|
| transaction-service | Owns sessions, match, allocate/confirm, outbound intents, webhooks |
| sync-service | Finalized credit + ingested_confirming UX feed; never allocates or broadcasts outbound |
| ledger-service | Authoritative journal; templates only; Idempotency-Key = intent or occurrence identity |
| account-service | VA / HW / beneficiary lookup; never moves merchant funds |
| merchant-settings | Fees, webhook endpoint/secret, instrument bind (QR / checkout / API) |
| Custody adapter (MPC / HSM) | Sign and broadcast outbound txs; never returns seed, xprv, xpub, or private keys |
| risk / KYT | Immutable decision referenced by confirm_funds |
| Portal JWT / merchant API key | List, detail, refund, webhook resend |
| Platform ops | Freeze, maker-checker refund/settlement, pause orchestration |
flowchart LR
subgraph ingress [Ingress]
Payer[Payer]
Sync[sync-service]
Ledger[ledger-service]
end
subgraph txn [transaction-service]
Session[PaymentSession]
Match[DepositMatch]
Alloc[AllocateConfirmKYT]
Outbound[OutboundExactOnce]
Hook[WebhookDelivery]
end
subgraph deps [Dependencies]
Acct[account-service]
SC[VA_Forwarder]
Settings[merchant-settings]
Custody[MPC_HSM]
end
Portal[MerchantPortal]
Payer -->|pay to VA| Sync
Sync -->|deposit_detected| Ledger
Sync -->|observation status| Match
Session --> Match
Match --> Alloc
Alloc -->|payment_allocate confirm_funds| Ledger
Alloc --> Outbound
Outbound -->|flush refund settle| SC
Outbound -->|sign nonce broadcast| Custody
Outbound -->|refund_execute settlement| Ledger
Settings -->|fees webhook QR checkout| Session
Acct -->|VA HW beneficiary| Session
Hook --> Portal
Portal -->|list refund resend| txn
Fig 1: Actor S2S and money-path orchestrator
1.4 Delivery phases
| Phase | Chains | Outbound / custody model |
|---|---|---|
| Phase 1 | tron (USDT/6, USDC/6) | Dedicated VA/HW addresses (FSD-Account). No VA/Forwarder clones. Match → allocate → KYT confirm. Refund/settlement via custody adapter. Fee split booked in ledger only. |
| Phase 2 | bsc, eth, polygon | transaction-service is OPERATOR + settlementManager: VA registerDeposit → flush to Forwarder; FW registerTransaction → settleBatch. Same ledger templates; gas_record on chain txs. |
Phase 1 acceptance does not depend on Phase 2 code. Shared contracts (session schema, match rules, intent_id, Idempotency-Key, error envelope, webhook event catalog) are designed once so Phase 2 plugs in without redesigning TRON.
Sweep vs flush: EVM flush is the on-chain analogue of ledger sweep_*. Sync never flushes. Transaction (or ops, for treasury sweep jobs) orchestrates flush after KYT policy for that deposit. Ledger sweep templates remain the book of record for in-transit. Do not double-credit.
2. Business Requirement
Governing requirements are defined in BR-09/BR-10, FP-CPG-BR-LED (L04, L15, FR5, FR8), and the cited sibling FSDs. This FSD does not rewrite those BRs; it maps each requirement to design artifacts below.
| Source | Need (summary) | Solution location in this FSD |
|---|---|---|
| FSD-Ledger L04 outbound | Crash recovery for signing/broadcast is Transaction-owned | §3.7; FEAT-IDM-01; UC-IDM-01 |
| FSD-Ledger L15 | End-to-end outbound exactly-once | §3.7; FEAT-IDM-01; §6.5 |
| FSD-Ledger FR5 | Template-only money writes | FEAT-PAY-01; FEAT-REF-04; FEAT-STL-01 |
| FSD-Ledger FR8 | SoD operator vs settlement | §2.2; §8.2; UC-STL-01 |
| FSD-Ledger §3.3 / §3.10 | Allocate, confirm, KYT PASS before available | §3.3; FEAT-PAY-01; FEAT-KYT-01 |
| FSD-SmartContract BR-09 | Refund to verified owner; block exchange toSource; dual approval | §3.5; FEAT-REF-01/02/03 |
| FSD-SmartContract BR-10 | Honor pause; stop outbound fund movement | §3.9; FEAT-FRZ-01; UC-FRZ-01 |
| FSD-Sync §3.5 | Consume observation statuses; never invent occurrence_id | §3.2; FEAT-MCH-01 |
| FSD-MP-Transaction F6–F11 | Refund eligibility, lifecycle, webhook resend | §3.5; §3.8; FEAT-REF-; FEAT-WHK- |
| FSD-MP-Setting F2, F4 | Service enablement; webhook HMAC/retry/events | §3.1; §3.8; FEAT-SES-01; FEAT-WHK-01 |
Hard blockers (must be proven in architecture + tests): L04 outbound, L15, BR-09 AC1–AC3, KYT-before-available, freeze/pause fail-closed, no duplicate outbound value for one intent_id.
2.1 FR / BR → FSD coverage matrix
| ID | Level | Coverage in this FSD |
|---|---|---|
| TXN-01 Payment session execution | HARD | FEAT-SES-01; UC-SES-01; §3.1 |
| TXN-02 Deposit match to session | HARD | FEAT-MCH-01; UC-MCH-01/02/03; §3.2 |
| TXN-03 Allocate + confirm (Ledger FEAT-PAY-01) | HARD | FEAT-PAY-01; UC-PAY-01; §3.3 |
| TXN-04 KYT PASS before available | HARD | FEAT-KYT-01; UC-KYT-01; §3.3 |
| TXN-05 Outbound exactly-once (L04/L15) | HARD | FEAT-IDM-01; UC-IDM-01; §3.7; §6.5 |
| TXN-06 BR-09 AC1 KYC/whitelist refund destination | HARD | FEAT-REF-01; UC-REF-01 |
| TXN-07 BR-09 AC2 Block exchange refund-to-source | HARD | FEAT-REF-02; UC-REF-02 |
| TXN-08 BR-09 AC3 Manual refund dual approval | HARD | FEAT-REF-03; UC-REF-03 |
| TXN-09 Honor freeze / SC pause (BR-10) | HARD | FEAT-FRZ-01; UC-FRZ-01; §3.9 |
| TXN-10 Merchant webhook delivery + resend | HARD | FEAT-WHK-01/02; UC-WHK-01/02; §3.8 |
| TXN-11 Merchant list/detail (Portal F2–F5) | HARD | FEAT-QRY-01; UC-QRY-01; §7 |
| TXN-12 Settlement batch + FR8 SoD | IMPORTANT | FEAT-STL-01; UC-STL-01; §3.6 |
| TXN-13 Invoice under/over/expired holds | IMPORTANT | FEAT-INV-01; UC-MCH-02/03 |
| TXN-14 Gas accounting on outbound | IMPORTANT | FEAT-GAS-01 |
| TXN-15 Observability handoff | IMPORTANT | FEAT-OBS-01; §9 |
| FR5 Template-only writes | HARD | All money writes via ledger templates; no raw postings |
| FR8 Ops vs settlement clients | NEED CONFIRM | §2.2 proposed lock |
| Sync occurrence identity | HARD | Match consumes Sync occurrence_id; never mints a new one for the same inclusion |
2.2 NEED CONFIRM — proposed designs (locked for implementation planning)
| Topic | Proposed design (normative until Product rejects) |
|---|---|
| Instrument catalog | merchant-settings owns QR / Checkout / API-key CRUD. Transaction owns payment sessions only. Creating a QR or Checkout Link MUST result in a session this service persists (settings calls POST /internal/v1/payment-sessions or equivalent). |
| Settlement service boundary | Settlement lives in this FSD and in transaction-service, isolated by a separate OAuth/API client (ledger:write:settlement). Not a separate settlement-service for G1. |
| G1 refund signing | CPG custody / MPC operator only. Merchant Web3 wallet and Web3Auth signing from FSD-MP-Transaction F8 are out of G1. |
| Sweep jobs | Remain ops/treasury. Transaction does not call sweep_initiate / sweep_complete. Phase 2 EVM flush after KYT is Transaction-owned (distinct from treasury sweep). |
| Invoice CRUD | Remains settings / invoice helper. Transaction owns matching and invoice_*_hold templates only. |
| Outbound confirmation | Transaction-owned (outbound_intent state + receipt). Not a Sync credit path. Sync may still observe the outbound hash for recon evidence; it must not deposit_detected that hash as a customer credit. |
| Sync → Transaction handoff | Durable queue consumer. Sync posts deposit_detected to ledger and emits a durable observation event. Transaction must not require a second uncoordinated Sync HTTP call to stay consistent. Replay uses the same occurrence_id. |
| FR8 SoD | Ops/transaction client may call allocate, confirm, risk, refund, invoice-hold, flush templates. Settlement client may call settlement_* only. Enforce at gateway or ledger client ACLs. |
| Portal path alias | Core public API is /api/v1/payments/... (Account-style). Portal routes under /merchant/transactions/... are a BFF/gateway alias onto the same resources; this FSD is the contract. |
2.3 Status mapping (Portal ↔ Core) — mandatory
Portal txn_status must not be invented by UI. Map from session + ledger + KYT:
Portal txn_status |
Core session_status (typical) | Withdrawable merchant available |
|---|---|---|
| PENDING | awaiting_deposit, confirming, matched, allocated |
No |
| SUCCESS | available |
Yes (via ledger volumes after confirm_funds) |
| FAILED | expired, kyt_hold with FAIL terminal refund, match rejected |
No |
| Portal field | Core source |
|---|---|
| Compliance APPROVED / IN_REVIEW / REJECTED | KYT PASS / REVIEW / FAIL |
| Risk LOW / MEDIUM / HIGH | Latest risk decision (informational; risk_hold is a separate ledger bucket after available) |
| Webhook SENT / PENDING / FAILED | Latest webhook_delivery.delivery_status for the primary event |
| Refundable amount | session.amount_minor - sum(successful refund amount_minor) after refunds confirm on-chain |
Sync ingested_confirming is UX-only (FSD-Sync §3.5). Merchant available only after confirm_funds + KYT PASS.
3. Flow
All money movements that change balances go through ledger-service v2 templates. Amounts use integer minor units and Formance notation {asset} {integer_minor_units} (e.g. USDT/6 1000000 = 1.0 USDT). Canonical chain slugs: tron | bsc | eth | polygon. Network types: mainnet | testnet. Assets: USDT/6, USDC/6.
transaction-service never writes ledger volumes except via documented templates. It never issues deposit addresses. It never scans blocks.
3.0 System context
sequenceDiagram
participant Payer
participant Chain
participant Sync as sync-service
participant Ledger as ledger-service
participant Txn as transaction-service
participant Settings as merchant-settings
participant Custody as custodyAdapter
Payer->>Settings: Open QR or Checkout or API payment
Settings->>Txn: Create payment_session
Payer->>Chain: Transfer to VA address
Sync->>Sync: Observe and wait for finality
Sync->>Ledger: deposit_detected occurrence_id
Sync->>Txn: Durable observation event
Txn->>Txn: Match amount asset VA
Txn->>Ledger: payment_allocate
Note over Txn: KYT PASS required
Txn->>Ledger: confirm_funds
Txn->>Settings: Webhook payment.success HMAC
Fig 2: Happy-path payment session (Phase 1; Phase 2 adds registerDeposit/flush around match)
3.1 Create payment session
| Item | Detail |
|---|---|
| Actor | merchant-settings (QR / Checkout create); merchant API key (API Payment); Portal JWT |
| Precondition | Merchant exists; payment service enabled (FSD-MP-Setting F2); VA active and bound to an active same-chain Hot Wallet (FSD-Account §3.1); asset/network allowed |
| Idempotency | Header Idempotency-Key is authoritative. Replay returns the same payment_id. |
| Reject | Service disabled → SERVICE_DISABLED; missing/inactive VA or HW → VALIDATION_ERROR; amount/asset mismatch with invoice when fixed → VALIDATION_ERROR |
Steps
- Validate merchant, service (
QR_PAYMENT|PAYMENT_LINK|API_PAYMENT), chain, network, asset, VA, HW, amount mode (fixed vs flexible), optional invoice/order, expiry, one-time-use. - If Idempotency-Key hit → return prior session; do not create a second session.
- Persist
payment_sessionwith statuscreatedthenawaiting_deposit. Storeamount_minor(null if flexible). Bindinstrument_id(qr_id / checkout_link_id / api_request_id) as opaque foreign key; do not copy catalog rows. - Return
payment_id, VA address (from account-service), expiry, expected amount.
| Success | Session persisted; merchant can display pay-to address; Sync already watches the VA independently |
|---|---|
| Failure | Disabled service; validation; idempotency conflict on different payload (CONFLICT) |
One-time-use and expiry are enforced at match time, not only at catalog status. An expired catalog row must not accept a new match even if a late Sync credit arrives; apply invoice_expired_hold / session expired and webhook qr.expired or checkout.expired as applicable.
3.2 Deposit match
| Item | Detail |
|---|---|
| Actor | transaction-service (durable observation consumer) |
| Trigger | Sync observation reached credited (ledger deposit_detected succeeded) for a watched VA |
| Identity | occurrence_id from Sync is mandatory. Transaction MUST NOT mint a new occurrence identity for the same inclusion. |
| Confirming UX | Observation ingested_confirming may move session to confirming and emit payment.pending. No allocate. |
Match rules (amount vs session expected, same asset + chain + VA)
| Case | Session / ledger action | Portal txn_status |
|---|---|---|
| Exact (or flexible session with any positive credited amount per product min) | Status matched; proceed to allocate |
PENDING until confirm |
| Underpaid (fixed amount) | invoice_underpaid_hold; session underpaid_hold; do not allocate to available |
PENDING or FAILED per product; default PENDING until expiry/refund |
| Overpaid (fixed amount) | Allocate expected net; excess via invoice_overpaid_hold; session overpaid_hold + allocated expected |
PENDING then SUCCESS for expected portion |
| Asset/chain/VA mismatch | Ignore for this session; do not steal another merchant's credit | N/A |
| Expired or one-time already filled | Do not allocate; hold / refund workflow; webhook expired if not already sent | FAILED |
Idempotency: one payment_match row per (payment_id, occurrence_id). Replay of the same observation is a no-op.
Under/over hold templates: FSD-Ledger §3.7 / §6.2.
3.3 Allocate → KYT → confirm funds
| Item | Detail |
|---|---|
| Actor | transaction-service |
| Precondition | Session matched; source funded (hot and/or invoice clearing per product); ledger freeze not blocking this merchant/asset/chain |
| Templates | payment_allocate then confirm_funds (FSD-Ledger §3.3) |
| Ledger reference | intent_id for allocate = pay_alloc_{payment_id}; confirm = pay_confirm_{payment_id} |
| Fees | From merchant-settings fee schedule at match time; persist fee_amount_minor + fee_schedule_version on the session. Never recompute from a later schedule for this payment. |
KYT gate (FSD-Ledger §3.10)
| Decision | Action |
|---|---|
| PASS | confirm_funds with kyt_decision_id, policy version, actor/service, decision time. Session → available. Webhook payment.success. |
| REVIEW | Keep pending or kyt_hold template. Session kyt_hold. Webhook remains payment.pending (or a future dedicated event; do not emit payment.success). |
| FAIL | Move to kyt_hold / refund workflow. Do not pass through available. Webhook payment.failed. |
| Missing / expired | Reject confirm. Same as non-PASS. |
risk_hold after availability is not a substitute for this gate.
Phase 2 EVM additional steps (same intent_id family):
- After credited match, OPERATOR
registerDeposit(depositId=payment_id_hash, token, source, amount)on VA clone. - After KYT PASS (or product-defined flush policy),
flush/flushBatchto Forwarder beneficiary. - Ledger sweep/flush booking must use the same identity; do not create a second credit.
3.4 Merchant list / detail
| Item | Detail |
|---|---|
| Actor | Portal JWT or merchant API key |
| Scope | Rows for merchant_id on the token only. Re-check ownership in service layer. |
| Filters | FSD-MP-Transaction F2–F4 (wallet, hash, invoice, customer, address, network, asset, amount range, dates, compliance, risk, webhook, txn status, payment service) |
| Detail | Portal F5 fields: ids, hash, order, amounts, from/to, chain, timestamps, risk, compliance, webhook, refund eligibility |
Statuses are derived (§2.3). Transaction hash for inbound payments is Sync provenance (tx_hash), not a Transaction-invented value.
3.5 Refund (BR-09)
Align eligibility with FSD-MP-Transaction F6–F9 and on-chain policy with FSD-SmartContract §3.2.
Eligibility (all must pass)
| Rule | Reject code / reason |
|---|---|
Session available (or product-defined pre-settlement refund from held amount — G1: available only unless underpaid_hold/kyt_hold FAIL path) |
NOT_REFUNDABLE |
| Compliance not REJECTED | NOT_REFUNDABLE |
| Not fully refunded; amount ≤ remaining refundable | NOT_REFUNDABLE / VALIDATION_ERROR |
| Asset supports refund | NOT_REFUNDABLE |
| Caller has refund permission | FORBIDDEN |
No other refund intent in created/signed/broadcast for overlapping amount |
INTENT_IN_FLIGHT |
| Ledger freeze / SC pause not blocking outbound | OUTBOUND_FROZEN |
| Destination is KYC-verified / whitelisted refund wallet | VALIDATION_ERROR |
If deposit source is exchange, to_source must be false |
EXCHANGE_REFUND_BLOCKED |
| Dual approval recorded (maker ≠ checker) | FORBIDDEN until approved |
Steps
- Validate eligibility and persist refund resource
pending. - Dual-control approval (ops ticket or in-product maker-checker). Do not broadcast without it (BR-09 AC3).
- Ledger
refund_lockwith reference =intent_id. - Build outbound intent; persist before sign (see §3.7).
- Phase 1 TRON: custody adapter sign/broadcast to
refund_wallet(never exchange hot wallet when source tagged exchange). - Phase 2 EVM: OPERATOR
refund(depositId, toSource=false)when still on VA; or Forwarder/hot path per settlement state. Off-chain policy must forcetoSource=falsefor exchange sources even if the contract still allowstruetoday (FSD-SmartContract UC-REF-02). - Wait receipt (Transaction-owned confirmation). On success:
refund_execute; incrementrefunded_amount_minor; webhookrefund.processed. - On broadcast/receipt failure: intent
failed; compensating unlock / do notrefund_execute; webhookrefund.failed. Remaining refundable unchanged until success. - Failed refund is not retried by mutating the same intent. A new refund with a new
intent_idis required if refundable remains (FSD-MP-Transaction F4).
G1 signing: CPG custody/MPC only. Portal “Merchant Web3 / Web3Auth” models are out of G1.
Refund records are immutable after creation except status, chain hash, fees, and webhook metadata.
3.6 Settlement batch (FR8)
| Item | Detail |
|---|---|
| Actor | Settlement OAuth client (not the ops/allocate client) |
| Templates | settlement_lock → settlement_batch_init → settlement_batch_complete (FSD-Ledger §3.5) |
| Phase 1 TRON | Custody adapter payout from hot wallet to merchant beneficiary; fee split in ledger only |
| Phase 2 EVM | registerTransaction / markReady then settleBatch as settlementManager (FSD-SmartContract FEAT-FW-02). Fee + VAT from on-chain FeeMath MUST equal ledger fee postings for that batch (recon exception if not). |
Fail-closed on ledger freeze, SC pause, float-cap outbound block, or missing maker-checker where policy requires it.
intent_id per batch + phase (lock / init / complete / chain broadcast).
3.7 Crash recovery and outbound exactly-once (L04 / L15)
Ledger owns booking idempotency. Transaction owns signing/broadcast/nonce/replacement-family exactly-once.
- Allocate a stable
intent_id(ULID/UUID). Persistoutbound_intentrow increatedwith payload hash, chain, from-account, to-address,amount_minor, asset,nonce_family_id, before any sign or broadcast. - Ledger mutating calls use
Idempotency-Keyandreferencederived fromintent_id(and phase suffix). Replay returns the prior booking. - Sign via custody adapter. Store signature/tx bytes. Status
signed. - Broadcast. Store
tx_hash. Statusbroadcast. - Crash after broadcast, before ledger
refund_execute/settlement_batch_complete: on restart, look up chain receipt by tx_hash / nonce family, then replay the same ledger reference. Never sign a second value-bearing transaction for the sameintent_id. - Replacement (stuck nonce / underpriced): same
nonce_family_idand nonce; newreplacement_idlinked tointent_id; still one economic outcome. Conflicting confirmed replacements → incident + freeze outbound for that family. - Terminal
faileddoes not auto-open a new family. Operator/merchant creates a new intent.
stateDiagram-v2
[*] --> created
created --> signed: custody sign
signed --> broadcast: submit
broadcast --> confirmed: receipt success
broadcast --> replaced: same nonce replacement
replaced --> confirmed: replacement receipt
broadcast --> failed: receipt revert or drop policy
signed --> failed: sign/submit error after persist
created --> failed: freeze or validation
confirmed --> [*]
failed --> [*]
Fig 3: outbound_intent states
3.8 Webhook delivery
Config is read from merchant-settings (FSD-MP-Setting F4). Transaction owns retries, attempt history, and resend.
Events
| Event | When |
|---|---|
payment.pending |
Session enters confirming or matched/allocated before available |
payment.success |
Session available after confirm_funds |
payment.failed |
Terminal fail (KYT FAIL, expired unmatched, rejected) |
refund.processed |
Refund intent confirmed + ledger execute |
refund.failed |
Refund intent terminal failed / rejected |
checkout.expired |
Checkout-linked session expires |
qr.expired |
QR-linked session expires |
Rules
- Production URL must be HTTPS. Unsigned or secret-less delivery is forbidden in production.
- HMAC over body with current webhook secret; header scheme documented in §7.8.
- At-least-once delivery.
event_idis stable for the logical event; retries reuseevent_id. Resend creates a new attempt row and a newevent_idsuffix (…:resend:{n}) so merchants can distinguish; original history is preserved (FSD-MP-Transaction F11). - Webhook status MUST NOT change payment/refund money status.
- Browser callback (FSD-MP-Setting F5) is not a substitute for webhook. If POST callback is enabled, log attempts separately; money truth remains ledger + session.
- Disabled webhook config: persist
delivery_status=skipped(ops-visible); do not block money movement.
3.9 Incident: freeze, pause, backpressure
| Signal | Source | Transaction action |
|---|---|---|
| Ledger control_state BLOCK_OUTBOUND / BLOCK_ALL | FSD-Ledger FEAT-FRZ-01 | Reject new allocate-to-outbound, refund broadcast, settlement broadcast. OUTBOUND_FROZEN. Queue intents durable. |
| VA / Forwarder paused | FSD-SmartContract §3.3 | Do not call flush/refund/settle. Poll/wait; do not busy-spin RPC. |
| BR-10 emergency stop | Factory/orchestrator pause | Stop new broadcasts within ≤5 minutes of observing pause/freeze (Transaction SLO). Clone fan-out remains Smart Contract / ops. |
| Ledger backpressure | FSD-Ledger FEAT-BKP-01 | Retry template posts; do not drop monetary events. |
Direct Formance access that bypasses ledger-service is prohibited.
4. Features
4.1 Session and match
FEAT-SES-01 Payment session
- Create/read payment sessions for QR, Checkout, API Payment. Bind VA, HW, asset, chain, amount_minor (or flexible), instrument_id, expiry, one-time-use.
- Reject if merchant service is disabled.
- Related: TXN-01; FSD-MP-Setting F2/F7/F9.
- Acceptance: UC-SES-01; duplicate Idempotency-Key returns one session; disabled service →
SERVICE_DISABLED.
FEAT-MCH-01 Deposit match
- Consume Sync credited observations; unique
(payment_id, occurrence_id); exact / under / over / expired rules. - Related: TXN-02; FSD-Sync §3.5; FSD-Ledger invoice holds.
- Acceptance: UC-MCH-01/02/03; replay same occurrence does not double-match; never mint a new occurrence_id.
FEAT-INV-01 Invoice hold posting
- Underpaid / overpaid / expired / refund holds via ledger templates.
- Related: TXN-13; FSD-Ledger §3.7.
- Acceptance: Overpay books expected to pending/allocate path and excess to overpaid hold; totals reconcilable.
4.2 Ledger merchant flows
FEAT-PAY-01 Allocate and confirm
payment_allocatethenconfirm_fundswith frozen fee schedule version. Production: templates only.- Related: TXN-03; FSD-Ledger §3.3.
- Acceptance: UC-PAY-01; over-allocate rejected by ledger FR2; volumes match net + fee.
FEAT-KYT-01 Pre-availability KYT gate
confirm_fundsrequires PASS decision reference. REVIEW/FAIL stay pre-availability.- Related: TXN-04; FSD-Ledger FEAT-KYT-01.
- Acceptance: UC-KYT-01; missing/non-PASS cannot produce merchant
available.
FEAT-GAS-01 Gas record
- After outbound confirmation,
gas_recordagainst treasury:gas / platform network fee accounts when gas was spent. - Related: TXN-14; FSD-Ledger FEAT-GAS-01.
- Acceptance: Sampled outbound intents have a gas booking or an explicit zero-gas reason (e.g. sponsored).
4.3 Outbound exactly-once and refund / settlement
FEAT-IDM-01 Outbound exactly-once (L04 / L15)
- Persist intent before broadcast; nonce family uniqueness; crash replay; replacement linked; no second economic tx per intent.
- Related: TXN-05.
- Acceptance: UC-IDM-01 — kill after broadcast, restart, exactly one confirmed value-bearing tx and one ledger execute.
FEAT-REF-01 KYC-verified refund destination
- Destination = customer KYC-verified / whitelisted
refund_wallet. - Related: BR-09 AC1; FSD-SmartContract FEAT-REF-01.
- Acceptance: UC-REF-01.
FEAT-REF-02 Block exchange refund-to-source
- Exchange-tagged source → refuse
to_source=true. - Related: BR-09 AC2.
- Acceptance: UC-REF-02;
EXCHANGE_REFUND_BLOCKED.
FEAT-REF-03 Manual refund dual approval
- Maker ≠ checker strong identities before broadcast. API key alone is not sufficient identity for the checker.
- Related: BR-09 AC3.
- Acceptance: UC-REF-03; single operator cannot complete refund.
FEAT-REF-04 Refund ledger lock/execute
refund_lockthenrefund_executeafter chain confirm. Partial and full refunds. Remaining refundable decreases only on success.- Related: FSD-Ledger §3.6; Portal F6–F9.
- Acceptance: UC-REF-01; insufficient available → ledger FR2 reject; no partial journal commit.
FEAT-STL-01 Settlement batch
- Settlement client only; lock → init → on-chain settle → complete.
- Related: TXN-12; FR8; FSD-SmartContract FEAT-FW-02.
- Acceptance: UC-STL-01; ops client calling
settlement_*→ authz deny.
4.4 Query, webhook, freeze, observability
FEAT-QRY-01 Merchant transaction query
- List/detail/filter for hot-wallet and VA payments and refunds; merchant scoped.
- Related: TXN-11; Portal F2–F5.
- Acceptance: UC-QRY-01; merchant B cannot read merchant A; filters match Portal query params.
FEAT-WHK-01 Signed webhook delivery
- HMAC, retries from settings, event catalog, attempt log, at-least-once,
event_id. - Related: TXN-10; Setting F4.
- Acceptance: UC-WHK-01; invalid secret verification fails on a test harness; HTTPS enforced in prod.
FEAT-WHK-02 Webhook resend
- New attempt; history preserved; permissioned.
- Related: Portal F11.
- Acceptance: UC-WHK-02.
FEAT-FRZ-01 Honor freeze and pause
- Fail-closed outbound and affected allocate/confirm per control_state and SC pause.
- Related: TXN-09; BR-10 honor path.
- Acceptance: UC-FRZ-01; paused VA flush/refund not submitted; SLO stop new broadcasts ≤5 min after freeze/pause observed.
FEAT-OBS-01 Transaction observability
- Metrics: session create RPS, match lag vs Sync credit, allocate/confirm latency, outbound sign/broadcast p50/p99, intent in-flight age, idempotency hit/conflict, webhook success/fail/retry, freeze rejects, KYT non-pass rate.
- Related: TXN-15; FSD-Ledger FEAT-OBS-01 (federated dashboard).
- Acceptance: Dashboards and alert rules listed in §9 are delivery 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)
dead_letter
| Field | Type | Required | Description |
|---|---|---|---|
| id | Integer | No | Primary key |
| consumer | String | Yes | Consumer |
| event_id | String | Yes | Event id |
| event_type | String | Yes | Event type |
| version | Integer | Yes | Version |
| reason | String | Yes | Decision / rejection reason |
| body | JSON | Yes | Body |
| created_at | DateTime | Yes | Created timestamp (UTC) |
inbox
| Field | Type | Required | Description |
|---|---|---|---|
| consumer | String | Yes | Consumer |
| event_id | String | Yes | Event id |
| processed_at | DateTime | Yes | Processed at |
inbox_retry
| Field | Type | Required | Description |
|---|---|---|---|
| consumer | String | Yes | Consumer |
| event_id | String | Yes | Event id |
| attempt | Integer | Yes | Attempt |
| retry_at | DateTime | Yes | Retry at |
| reason | String | Yes | Decision / rejection reason |
| body | JSON | Yes | Body |
webhook_delivery_attempt
| Field | Type | Required | Description |
|---|---|---|---|
| id | Integer | No | Primary key |
| job_id | Integer | Yes | Job id |
| attempt_number | Integer | Yes | Attempt number |
| status | String | Yes | Lifecycle status (active / inactive / domain-specific values) |
| http_status | Integer | No | Http status |
| error | String | No | Error |
| created_at | DateTime | Yes | Created timestamp (UTC) |
webhook_delivery_audit
| Field | Type | Required | Description |
|---|---|---|---|
| id | Integer | No | Primary key |
| actor | String | Yes | Actor |
| source_event_id | String | Yes | Source event id |
| created_at | DateTime | Yes | Created timestamp (UTC) |
webhook_delivery_job
| Field | Type | Required | Description |
|---|---|---|---|
| id | Integer | No | Primary key |
| merchant_id | UUID | Yes | Owning merchant identifier |
| payment_id | String | Yes | Payment id |
| source_event_id | String | Yes | Source event id |
| delivery_class | String | Yes | Delivery class |
| event_type | String | Yes | Event type |
| status | String | Yes | Lifecycle status (active / inactive / domain-specific values) |
| attempt_count | Integer | Yes | Attempt count |
| next_retry_at | DateTime | No | Next retry at |
| body | JSON | Yes | Body |
| created_at | DateTime | Yes | Created timestamp (UTC) |
| updated_at | DateTime | Yes | Last updated timestamp (UTC) |
7. Endpoints and Payloads
| Method | Route | Description | Request | Response |
|---|---|---|---|---|
| GET | /api/v1/transaction/health |
Liveness | {} |
{status, service} |
| GET | /api/v1/transaction/transactions |
List transactions | {merchant_id?, status?, type?, from?, to?, page?, page_size?} (query) |
{items[{id, merchant_id, type, status, amount, asset, tx_hash?, created_at, …}], page, page_size, total} |
| POST | /api/v1/transaction/transactions |
Create transaction | {merchant_id, type, amount, asset, …CreateTransactionRequest fields} |
transaction item payload |
| PUT | /api/v1/transaction/transactions |
Update transaction | {id, status?, …updatable fields} |
transaction item payload |
| GET | /api/v1/transaction/transactions/{id} |
Transaction detail | {id} |
detail payload |
8. Security
8.1 Application security (Doc03)
Fleet-wide application security is defined in Doc03 — Application Security. This FSD does not restate Doc03. Apply as baseline for transaction-service:
| Doc03 area | Relevance |
|---|---|
| Part A trust zones / money-movement | Transaction is a high-privilege money path (allocate, refund, settlement) |
| APPSEC-ID-01 | Authenticate public payment APIs (JWT / API key) |
| APPSEC-ID-08 | Internal observation and settlement authentication |
| APPSEC-ID-09 | Ledger client Bearer keys (ops vs settlement) |
| APPSEC-ID-13 / 14 | Secrets via Vault; webhook secrets, API keys never in git |
| APPSEC-ID-15 / 18 | Stable error envelope + request_id |
| APPSEC-ID-16 | Validate addresses, amounts, enums |
| APPSEC-ID-19 | Audit who approved refunds and settlement batches |
| APPSEC-ID-20 | No secrets, tokens, or raw PII in logs |
| G1–G9 | Timeouts on outbound RPC/HTTP; S2S discipline |
Out of Doc03 depth: custody cryptography and DR → A4.
8.2 Specific security (Transaction module)
| Control | Requirement | Notes |
|---|---|---|
| AuthN public | Merchant JWT or API key | Portal list/refund/resend; API Payment create |
| AuthN internal | Internal secret / mTLS for observations and settlement | Do not expose /internal/* publicly |
| AuthZ | Merchant scoped to own merchant_id; re-check in service | Cross-tenant 404 |
| SoD FR8 | Separate ledger clients: ops vs settlement templates | UC-STL-01 |
| Idempotency | Mandatory on money and session/refund creates | L15; FEAT-IDM-01 |
| Outbound exactly-once | Intent persist-before-broadcast; nonce uniqueness | L04/L15 |
| KYT | No available balance without PASS | FEAT-KYT-01 |
| Refund destination | Whitelist only; no exchange toSource | BR-09 AC1/AC2 |
| Refund SoD | Dual approval before broadcast | BR-09 AC3 |
| Freeze/pause | Fail-closed broadcast | BR-10 honor; FEAT-FRZ-01 |
| Webhook | HMAC; HTTPS prod; secret not logged | Setting F4 |
| Keys | Never persist or log seed/xprv/xpub/operator keys | Custody adapter |
| Template-only | No raw ledger postings in production | FR5 |
| Audit | Refund create, approval, broadcast, resend, settlement | Portal §8 analogue |
9. NFR (non-functional)
Planning values pending business forecast (same discipline as FSD-Ledger §7.12). Load-test engineering must record measured evidence; do not treat the table as an untested SLA.
| Parameter | Planning value | Transaction implication |
|---|---|---|
| Session create | 50–200 RPS | POST /api/v1/payments soak; unique keys per worker |
| Observation ingest | At least Sync credit peak | Match lag p99 proposed ≤5 s after credited event, excluding KYT vendor time |
| Allocate+confirm | Included in match SLO when KYT pre-fetched | Ledger write p99 federated with Ledger T08 |
| Outbound sign+broadcast p99 | TBD per rail; instrument in tests | Exclude mempool congestion from app SLO; bound queue age |
| Webhook retry | Settings retry_attempts × retry_delay; default propose 5 × 30s | Exhaustion → FAILED; resend still allowed |
| Soak | ≥72 h | Zero duplicate outbound confirms; zero double-match per occurrence; zero lost durable events |
| BR-10 honor | Stop new broadcasts ≤5 min after freeze/pause observed | Distinct from 100k clone pause fan-out |
| Idempotency | Parallel duplicate POST session/refund | One row / one intent |
| Error envelope | Canonical JSON | Every non-2xx has error.code and request_id |
| Projected peak | Include inbound matches and outbound refunds/settlements per asset | Input to pool/nonce sizing |
9.1 Acceptance test profiles (for QA / load-test)
| Test | Required evidence |
|---|---|
| TC-TXN-IDM | Crash after broadcast; restart; one chain tx; one ledger execute |
| TC-TXN-KYT | Non-PASS cannot reach available |
| TC-TXN-REF-EXCH | Exchange source + to_source=true rejected |
| TC-TXN-REF-SOD | Single approver cannot broadcast |
| TC-TXN-FRZ | Freeze injected; refund/settlement HTTP OUTBOUND_FROZEN; no RPC send |
| TC-TXN-WHK | HMAC verify; resend new attempt |
| TC-TXN-MCH | Exact/under/over/replay occurrence |
| TC-TXN-SOAK | 72 h; invariants above |
| TC-TXN-STL-SOD | Ops token cannot settlement_* |
Backpressure: when ledger or RPC throttles, intents and observations remain durable; no monetary event dropped.
Document refs: FSD-Ledger, FSD-Account, FSD-Sync, FSD-SmartContract, FSD-MP-Transaction, FSD-MP-Setting, Doc03 Application Security, A4 Key Management.