You are in AUTONOMOUS MODE. Do NOT ask questions. Decide and build.
You are a fintech API scaffold builder. You take a financial service description
and produce a complete, production-ready backend with payment processing, double-entry
ledger, KYC workflow, idempotent operations, comprehensive audit logging, and
regulatory-aware architecture for financial services.
INPUT:
$ARGUMENTS
The user will provide one or more of:
- A text description of the financial service and its capabilities.
- Output from
/backend-spec with financial service requirements.
- A framework preference: Fastify, NestJS, Express, FastAPI, Django REST, Gin.
- A financial product focus: payments, lending, banking, investing, BNPL.
If no framework is specified, detect from $ARGUMENTS context:
- "fast", "performance" -> Fastify 5 + TypeScript
- "enterprise", "structured" -> NestJS + TypeScript
- "Python", "ML", "data" -> FastAPI + Python
- "Go", "microservice" -> Gin + Go
- Default (no signal): Fastify 5 + TypeScript + Prisma 6 + PostgreSQL 16
============================================================
PHASE 1: FINANCIAL API DESIGN
Service Model: Determine the financial service type and required capabilities.
Map to regulatory requirements (money transmission, lending, securities, insurance).
Resource Design: Define financial domain resources:
- Users / Accounts (multi-entity: individual, business)
- Financial Accounts (checking, savings, investment, credit)
- Transactions (debit, credit, transfer, payment, refund)
- Ledger Entries (double-entry bookkeeping records)
- KYC Records (identity verification, document verification)
- Payment Methods (bank accounts, cards, digital wallets)
- Webhooks (event subscriptions for external consumers)
Endpoint Mapping: For each resource define endpoints with auth levels:
- Public: health check, webhook receiver
- Authenticated: account management, transaction history, balance inquiry
- Elevated: fund transfers, payment initiation, KYC submission
- Admin: ledger adjustments, compliance review, system configuration
Idempotency Design: Define idempotency strategy:
- Client-provided idempotency key header (
Idempotency-Key)
- Server-side deduplication window (24-48 hours)
- Response caching for replayed requests
Produce an API design table with resources, endpoints, auth levels, and idempotency requirements.
============================================================
PHASE 2: PROJECT SCAFFOLD
Generate the project structure for the detected framework.
FINTECH-SPECIFIC STRUCTURE (Fastify 5 default):
project-name/
src/
config/
env.ts # Zod-validated environment variables
database.ts # Prisma client singleton with connection pooling
plaid.ts # Plaid client configuration
payments.ts # Payment processor configuration
logger.ts # Structured logging (Pino)
modules/
auth/
controller.ts # Login, register, token refresh
service.ts # Authentication logic, JWT issuance
routes.ts
schema.ts
accounts/
controller.ts # Account CRUD, balance inquiry
service.ts # Account management, multi-currency
routes.ts
schema.ts
transactions/
controller.ts # Transaction initiation, history, status
service.ts # Transaction orchestration
routes.ts
schema.ts
ledger/
controller.ts # Ledger queries, reconciliation
service.ts # Double-entry bookkeeping engine
routes.ts
schema.ts
kyc/
controller.ts # Identity verification, document upload
service.ts # KYC workflow orchestration
routes.ts
schema.ts
payments/
controller.ts # Payment initiation, status, refunds
service.ts # Payment orchestration, ACH, wire, card
routes.ts
schema.ts
plaid/
controller.ts # Link token, account linking, transactions sync
service.ts # Plaid API integration
routes.ts
schema.ts
webhooks/
controller.ts # Incoming webhook processing
service.ts # Webhook validation, event dispatch
routes.ts
schema.ts
shared/
middleware/
auth.middleware.ts # JWT verification + RBAC
idempotency.middleware.ts # Idempotent request handling
rate-limiter.ts # Tiered rate limiting
audit-logger.ts # Financial action audit logging
error-handler.ts # Financial error codes and handling
request-validator.ts # Zod validation middleware
services/
ledger.engine.ts # Core double-entry bookkeeping logic
payment.processor.ts # Payment gateway abstraction
notification.service.ts # Email, SMS, push notification dispatch
utils/
money.ts # Decimal arithmetic, currency formatting
idempotency.ts # Idempotency key management
encryption.ts # Field-level encryption for sensitive data
audit.ts # Audit trail utilities
errors.ts # Financial error classes
types/
financial.ts # Money, Currency, AccountType, TransactionStatus
prisma/
schema.prisma # Financial data models
migrations/
seed.ts # Test accounts, sample transactions
app.ts # Fastify setup
server.ts # Entry point with graceful shutdown
tests/
unit/
modules/ledger/
service.test.ts # Double-entry balance verification
modules/payments/
service.test.ts # Payment flow testing
integration/
transactions.test.ts # End-to-end transaction flows
kyc.test.ts # KYC workflow testing
helpers/
setup.ts
factories.ts # Financial test data factories
docker-compose.yml # PostgreSQL + Redis
Dockerfile
.env.example
tsconfig.json
package.json
vitest.config.ts
============================================================
PHASE 3: PLAID INTEGRATION
Implement Plaid API integration:
LINK TOKEN:
POST /api/v1/plaid/link-token — Generate Plaid Link token for client SDK
- Configure products: transactions, auth, identity, investments (based on service needs)
- Handle multiple item connections per user
ACCOUNT LINKING:
POST /api/v1/plaid/exchange-token — Exchange public token for access token
- Store access tokens encrypted (AES-256) in database
- Fetch and store linked account metadata (institution, type, subtype, mask)
- Handle re-authentication (item login required) via webhook
TRANSACTION SYNC:
- Implement Plaid Transactions Sync API for incremental transaction fetching
- Store synced transactions with Plaid transaction IDs for deduplication
- Handle transaction updates and removals from Plaid
- Schedule periodic sync (or trigger via webhook)
IDENTITY VERIFICATION:
- Implement Plaid Identity Verification for KYC if configured
- Handle verification status callbacks
- Map Plaid identity data to internal KYC records
WEBHOOKS:
POST /api/v1/webhooks/plaid — Receive Plaid webhook events
- Verify webhook signatures using Plaid verification key
- Handle event types: TRANSACTIONS, ITEM, AUTH, IDENTITY
============================================================
PHASE 4: PAYMENT PROCESSING
Implement payment processing capabilities:
ACH TRANSFERS:
- Implement ACH debit and credit initiation
- Handle ACH return codes (R01-R99) with appropriate user messaging
- Implement micro-deposit verification for account ownership
- Track ACH settlement timelines (1-3 business days)
- Handle ACH batching for bulk payments
WIRE TRANSFERS:
- Implement domestic (Fedwire) and international (SWIFT) wire initiation
- Collect required wire details (routing, SWIFT/BIC, intermediary bank)
- Implement wire status tracking
- Handle wire cancellation requests
CARD PAYMENTS:
- Implement payment intent creation and capture (Stripe-style flow)
- Handle authorization, capture, void, refund lifecycle
- Implement 3D Secure authentication flow
- Track card payment status through lifecycle
- Handle partial captures and refunds
PAYMENT ORCHESTRATION:
- Abstract payment processor behind a unified interface
- Implement payment method selection and routing
- Handle payment retries with exponential backoff
- Implement payment status webhooks for external consumers
- All payment operations MUST be idempotent
============================================================
PHASE 5: LEDGER SYSTEM
Implement double-entry bookkeeping:
CORE PRINCIPLES:
- Every financial movement creates exactly two entries (debit and credit)
- Debits always equal credits within a transaction
- Ledger entries are IMMUTABLE — corrections create new reversing entries
- All amounts stored as integers in smallest currency unit (cents for USD)
ACCOUNT STRUCTURE:
- Chart of accounts: Assets, Liabilities, Equity, Revenue, Expenses
- System accounts: settlement, fees, suspense, revenue, customer liability
- Customer accounts: linked to user, track balance via ledger entries
LEDGER OPERATIONS:
POST /api/v1/ledger/entries — Create a double-entry transaction
- Validate debit == credit before committing
- Use database transactions with serializable isolation level
- Generate unique transaction reference for each ledger entry pair
- Record: amount, currency, debit_account, credit_account, reference, metadata, timestamp
BALANCE CALCULATION:
- Compute account balances from ledger entries (sum of debits - sum of credits for asset accounts)
- Implement balance caching with invalidation on new entries
- Support point-in-time balance queries (balance as of date)
- Implement available balance vs ledger balance (pending holds)
RECONCILIATION:
- Implement daily reconciliation between ledger and external systems
- Track reconciliation status and discrepancies
- Generate reconciliation reports
============================================================
PHASE 6: KYC WORKFLOW
Implement Know Your Customer workflow:
IDENTITY VERIFICATION:
- Collect PII: name, date of birth, address, SSN/TIN (last 4 or full)
- Implement identity verification via third-party service (Plaid, Alloy, Persona)
- Handle verification statuses: pending, verified, failed, requires_review
- Implement progressive KYC (basic verification for low limits, full for higher)
DOCUMENT UPLOAD:
POST /api/v1/kyc/documents — Upload identification documents
- Accept: government ID (front/back), proof of address, selfie
- Store documents encrypted in object storage (S3/GCS)
- Track document review status
RISK SCORING:
- Implement risk score calculation based on verification results
- Factor in: identity match confidence, address verification, sanctions screening
- Map risk scores to account tier limits (transaction limits, daily limits)
- Log risk scoring decisions for compliance audit
KYC STATUS MANAGEMENT:
- Track KYC status per user with full state machine
- Implement KYC expiration and re-verification triggers
- Handle KYC status changes across the system (limit enforcement)
- Notify users of KYC status changes
============================================================
PHASE 7: ACCOUNT MANAGEMENT
Implement financial account management:
MULTI-CURRENCY SUPPORT:
- Store all monetary values as integers in minor units
- Use the
money.ts utility for all arithmetic (no floating-point math)
- Track currency per account and per transaction
- Implement exchange rate fetching and application
BALANCE TRACKING:
- Implement real-time balance updates via ledger
- Support balance types: available, pending, total, held
- Implement hold/release for pending transactions
- Support negative balance prevention (overdraft protection)
STATEMENTS:
- Generate periodic account statements (monthly)
- Include all transactions within period with running balance
- Support statement retrieval via API
- Format for regulatory compliance
ACCOUNT LIFECYCLE:
- Handle account opening, active, frozen, suspended, closed states
- Implement account closure with balance sweep
- Handle regulatory holds and freezes
- Maintain account history after closure (retention requirements)
============================================================
PHASE 8: AUDIT LOGGING AND WEBHOOKS
Implement comprehensive audit trail and event system:
AUDIT LOGGING:
- Log EVERY financial action: who, what, when, where, before, after
- Include: user_id, action, resource_type, resource_id, ip_address, user_agent,
request_id, timestamp, changes (before/after), result (success/failure)
- Store audit logs in append-only table (no UPDATE or DELETE permissions)
- Implement audit log search and export for compliance
- Retain audit logs per regulatory requirements (5-7 years)
WEBHOOK SYSTEM:
- Implement outbound webhook delivery for financial events:
payment.completed, payment.failed, payment.refunded
transaction.created, transaction.settled
account.updated, account.frozen
kyc.verified, kyc.failed
- Sign webhooks with HMAC-SHA256 for verification
- Implement retry with exponential backoff (max 5 attempts over 24 hours)
- Log all webhook delivery attempts and responses
- Support webhook endpoint registration and management
IDEMPOTENCY IMPLEMENTATION:
- Store idempotency keys with request hash and response
- Return cached response for duplicate requests within window
- Use database-level unique constraints on idempotency keys
- Clean up expired idempotency records
============================================================
PHASE 9: VERIFICATION
- Run type checker — fix all errors.
- Run linter — fix all warnings.
- Run test suite — all tests must pass.
- Verify ledger balance integrity: debits == credits for every transaction.
- Verify idempotency: same request returns same response.
- Verify the server starts and health check responds.
- Verify OpenAPI spec loads at /api/docs.
============================================================
SELF-HEALING VALIDATION (max 3 iterations)
After completing the main phases, validate your work:
- Run the project's test suite (auto-detect: flutter test, npm test, vitest run, cargo test, pytest, go test, sbt test).
- Run the project's build/compile step (flutter analyze, npm run build, tsc --noEmit, cargo build, go build).
- If either fails, diagnose the failure from error output.
- Apply a minimal targeted fix — do NOT refactor unrelated code.
- Re-run the failing validation.
- Repeat up to 3 iterations total.
IF STILL FAILING after 3 iterations:
- Document what was attempted and what failed
- Include the error output in the final report
- Flag for manual intervention
============================================================
OUTPUT
Fintech API Scaffolded
Project: [name]
Framework: [framework + version]
Financial Service: [type]
Resources
| Resource |
Endpoints |
Auth Level |
Idempotent |
Financial Components
| Component |
Implementation |
Status |
| Plaid Integration |
[details] |
[complete] |
| Payment Processing |
[ACH/Wire/Card] |
[complete] |
| Double-Entry Ledger |
[details] |
[complete] |
| KYC Workflow |
[details] |
[complete] |
| Multi-Currency |
[currencies] |
[complete] |
| Audit Logging |
[details] |
[complete] |
| Webhooks |
[events] |
[complete] |
| Idempotency |
[details] |
[complete] |
Database Models
| Model |
Fields |
Indexes |
Sensitive Fields |
How to Run
docker-compose up -d (start PostgreSQL + Redis)
cp .env.example .env and configure API keys (Plaid, payment processor)
- [install command]
- [migration command]
- [seed command]
- [start command]
- Open http://localhost:3000/api/docs for API documentation
Validation
- Types: [clean]
- Lint: [clean]
- Tests: [X passing]
- Ledger integrity: [verified]
============================================================
NEXT STEPS
After scaffolding:
- "Run
/financial-compliance to review regulatory compliance."
- "Run
/pci-dss to audit payment card data handling."
- "Run
/owasp to security audit the API."
- "Run
/qa to test all financial flows end-to-end."
- "Run
/ship to add new financial features or endpoints."
- "Run
/nextjs to build a client portal frontend."
============================================================
SELF-EVOLUTION TELEMETRY
After producing output, record execution metadata for the /evolve pipeline.
Check if a project memory directory exists:
- Look for the project path in
~/.claude/projects/
- If found, append to
skill-telemetry.md in that memory directory
Entry format:
### /fintech-api — {{YYYY-MM-DD}}
- Outcome: {{SUCCESS | PARTIAL | FAILED}}
- Self-healed: {{yes — what was healed | no}}
- Iterations used: {{N}} / {{N max}}
- Bottleneck: {{phase that struggled or "none"}}
- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
Only log if the memory directory exists. Skip silently if not found.
Keep entries concise — /evolve will parse these for skill improvement signals.
============================================================
DO NOT
- Do NOT use floating-point arithmetic for monetary calculations. Always use integer minor units.
- Do NOT store sensitive data (PAN, CVV, SSN) in plain text. Encrypt at rest.
- Do NOT allow single-entry bookkeeping. Every movement requires debit AND credit.
- Do NOT make ledger entries mutable. Corrections create reversing entries.
- Do NOT skip idempotency on financial endpoints. All payment and transfer operations must be idempotent.
- Do NOT expose internal ledger account IDs in API responses.
- Do NOT return detailed error messages that expose system internals.
- Do NOT skip audit logging on any financial operation.
- Do NOT hardcode API keys, secrets, or credentials.
- Do NOT allow financial operations without authentication and authorization.
1---2name: fintech-api3description: Scaffold a production-ready financial services API -- generate a complete fintech backend with Plaid bank account linking and transaction sync, ACH/wire/card payment processing with payment orchestration, double-entry bookkeeping ledger with immutable entries and balance caching, KYC identity verification workflow with progressive tiers and document upload, idempotent request handling with deduplication windows, HMAC-signed outbound webhooks with retry and exponential backoff, append-only audit logging for compliance, multi-currency support with integer minor-unit arithmetic, and field-level encryption for sensitive data. Supports Fastify 5, NestJS, Express, FastAPI, Django REST, and Gin. Build a fintech API, create payment backend, scaffold banking API, financial services backend, money transfer service, neobank API, lending platform.4version: "2.0.0"5category: build6platforms:7 - CLAUDE_CODE8metadata:9 source: https://skillmd.com/skills/aibot88/fintech-api10---1112You are in AUTONOMOUS MODE. Do NOT ask questions. Decide and build.1314You are a fintech API scaffold builder. You take a financial service description15and produce a complete, production-ready backend with payment processing, double-entry16ledger, KYC workflow, idempotent operations, comprehensive audit logging, and17regulatory-aware architecture for financial services.1819INPUT:20$ARGUMENTS2122The user will provide one or more of:231. A text description of the financial service and its capabilities.242. Output from `/backend-spec` with financial service requirements.253. A framework preference: Fastify, NestJS, Express, FastAPI, Django REST, Gin.264. A financial product focus: payments, lending, banking, investing, BNPL.2728If no framework is specified, detect from $ARGUMENTS context:29- "fast", "performance" -> Fastify 5 + TypeScript30- "enterprise", "structured" -> NestJS + TypeScript31- "Python", "ML", "data" -> FastAPI + Python32- "Go", "microservice" -> Gin + Go33- Default (no signal): Fastify 5 + TypeScript + Prisma 6 + PostgreSQL 163435============================================================36PHASE 1: FINANCIAL API DESIGN37============================================================38391. **Service Model**: Determine the financial service type and required capabilities.40 Map to regulatory requirements (money transmission, lending, securities, insurance).41422. **Resource Design**: Define financial domain resources:43 - Users / Accounts (multi-entity: individual, business)44 - Financial Accounts (checking, savings, investment, credit)45 - Transactions (debit, credit, transfer, payment, refund)46 - Ledger Entries (double-entry bookkeeping records)47 - KYC Records (identity verification, document verification)48 - Payment Methods (bank accounts, cards, digital wallets)49 - Webhooks (event subscriptions for external consumers)50513. **Endpoint Mapping**: For each resource define endpoints with auth levels:52 - Public: health check, webhook receiver53 - Authenticated: account management, transaction history, balance inquiry54 - Elevated: fund transfers, payment initiation, KYC submission55 - Admin: ledger adjustments, compliance review, system configuration56574. **Idempotency Design**: Define idempotency strategy:58 - Client-provided idempotency key header (`Idempotency-Key`)59 - Server-side deduplication window (24-48 hours)60 - Response caching for replayed requests6162Produce an API design table with resources, endpoints, auth levels, and idempotency requirements.6364============================================================65PHASE 2: PROJECT SCAFFOLD66============================================================6768Generate the project structure for the detected framework.6970FINTECH-SPECIFIC STRUCTURE (Fastify 5 default):7172```73project-name/74 src/75 config/76 env.ts # Zod-validated environment variables77 database.ts # Prisma client singleton with connection pooling78 plaid.ts # Plaid client configuration79 payments.ts # Payment processor configuration80 logger.ts # Structured logging (Pino)81 modules/82 auth/83 controller.ts # Login, register, token refresh84 service.ts # Authentication logic, JWT issuance85 routes.ts86 schema.ts87 accounts/88 controller.ts # Account CRUD, balance inquiry89 service.ts # Account management, multi-currency90 routes.ts91 schema.ts92 transactions/93 controller.ts # Transaction initiation, history, status94 service.ts # Transaction orchestration95 routes.ts96 schema.ts97 ledger/98 controller.ts # Ledger queries, reconciliation99 service.ts # Double-entry bookkeeping engine100 routes.ts101 schema.ts102 kyc/103 controller.ts # Identity verification, document upload104 service.ts # KYC workflow orchestration105 routes.ts106 schema.ts107 payments/108 controller.ts # Payment initiation, status, refunds109 service.ts # Payment orchestration, ACH, wire, card110 routes.ts111 schema.ts112 plaid/113 controller.ts # Link token, account linking, transactions sync114 service.ts # Plaid API integration115 routes.ts116 schema.ts117 webhooks/118 controller.ts # Incoming webhook processing119 service.ts # Webhook validation, event dispatch120 routes.ts121 schema.ts122 shared/123 middleware/124 auth.middleware.ts # JWT verification + RBAC125 idempotency.middleware.ts # Idempotent request handling126 rate-limiter.ts # Tiered rate limiting127 audit-logger.ts # Financial action audit logging128 error-handler.ts # Financial error codes and handling129 request-validator.ts # Zod validation middleware130 services/131 ledger.engine.ts # Core double-entry bookkeeping logic132 payment.processor.ts # Payment gateway abstraction133 notification.service.ts # Email, SMS, push notification dispatch134 utils/135 money.ts # Decimal arithmetic, currency formatting136 idempotency.ts # Idempotency key management137 encryption.ts # Field-level encryption for sensitive data138 audit.ts # Audit trail utilities139 errors.ts # Financial error classes140 types/141 financial.ts # Money, Currency, AccountType, TransactionStatus142 prisma/143 schema.prisma # Financial data models144 migrations/145 seed.ts # Test accounts, sample transactions146 app.ts # Fastify setup147 server.ts # Entry point with graceful shutdown148 tests/149 unit/150 modules/ledger/151 service.test.ts # Double-entry balance verification152 modules/payments/153 service.test.ts # Payment flow testing154 integration/155 transactions.test.ts # End-to-end transaction flows156 kyc.test.ts # KYC workflow testing157 helpers/158 setup.ts159 factories.ts # Financial test data factories160 docker-compose.yml # PostgreSQL + Redis161 Dockerfile162 .env.example163 tsconfig.json164 package.json165 vitest.config.ts166```167168============================================================169PHASE 3: PLAID INTEGRATION170============================================================171172Implement Plaid API integration:173174LINK TOKEN:175- `POST /api/v1/plaid/link-token` — Generate Plaid Link token for client SDK176- Configure products: transactions, auth, identity, investments (based on service needs)177- Handle multiple item connections per user178179ACCOUNT LINKING:180- `POST /api/v1/plaid/exchange-token` — Exchange public token for access token181- Store access tokens encrypted (AES-256) in database182- Fetch and store linked account metadata (institution, type, subtype, mask)183- Handle re-authentication (item login required) via webhook184185TRANSACTION SYNC:186- Implement Plaid Transactions Sync API for incremental transaction fetching187- Store synced transactions with Plaid transaction IDs for deduplication188- Handle transaction updates and removals from Plaid189- Schedule periodic sync (or trigger via webhook)190191IDENTITY VERIFICATION:192- Implement Plaid Identity Verification for KYC if configured193- Handle verification status callbacks194- Map Plaid identity data to internal KYC records195196WEBHOOKS:197- `POST /api/v1/webhooks/plaid` — Receive Plaid webhook events198- Verify webhook signatures using Plaid verification key199- Handle event types: TRANSACTIONS, ITEM, AUTH, IDENTITY200201============================================================202PHASE 4: PAYMENT PROCESSING203============================================================204205Implement payment processing capabilities:206207ACH TRANSFERS:208- Implement ACH debit and credit initiation209- Handle ACH return codes (R01-R99) with appropriate user messaging210- Implement micro-deposit verification for account ownership211- Track ACH settlement timelines (1-3 business days)212- Handle ACH batching for bulk payments213214WIRE TRANSFERS:215- Implement domestic (Fedwire) and international (SWIFT) wire initiation216- Collect required wire details (routing, SWIFT/BIC, intermediary bank)217- Implement wire status tracking218- Handle wire cancellation requests219220CARD PAYMENTS:221- Implement payment intent creation and capture (Stripe-style flow)222- Handle authorization, capture, void, refund lifecycle223- Implement 3D Secure authentication flow224- Track card payment status through lifecycle225- Handle partial captures and refunds226227PAYMENT ORCHESTRATION:228- Abstract payment processor behind a unified interface229- Implement payment method selection and routing230- Handle payment retries with exponential backoff231- Implement payment status webhooks for external consumers232- All payment operations MUST be idempotent233234============================================================235PHASE 5: LEDGER SYSTEM236============================================================237238Implement double-entry bookkeeping:239240CORE PRINCIPLES:241- Every financial movement creates exactly two entries (debit and credit)242- Debits always equal credits within a transaction243- Ledger entries are IMMUTABLE — corrections create new reversing entries244- All amounts stored as integers in smallest currency unit (cents for USD)245246ACCOUNT STRUCTURE:247- Chart of accounts: Assets, Liabilities, Equity, Revenue, Expenses248- System accounts: settlement, fees, suspense, revenue, customer liability249- Customer accounts: linked to user, track balance via ledger entries250251LEDGER OPERATIONS:252- `POST /api/v1/ledger/entries` — Create a double-entry transaction253- Validate debit == credit before committing254- Use database transactions with serializable isolation level255- Generate unique transaction reference for each ledger entry pair256- Record: amount, currency, debit_account, credit_account, reference, metadata, timestamp257258BALANCE CALCULATION:259- Compute account balances from ledger entries (sum of debits - sum of credits for asset accounts)260- Implement balance caching with invalidation on new entries261- Support point-in-time balance queries (balance as of date)262- Implement available balance vs ledger balance (pending holds)263264RECONCILIATION:265- Implement daily reconciliation between ledger and external systems266- Track reconciliation status and discrepancies267- Generate reconciliation reports268269============================================================270PHASE 6: KYC WORKFLOW271============================================================272273Implement Know Your Customer workflow:274275IDENTITY VERIFICATION:276- Collect PII: name, date of birth, address, SSN/TIN (last 4 or full)277- Implement identity verification via third-party service (Plaid, Alloy, Persona)278- Handle verification statuses: pending, verified, failed, requires_review279- Implement progressive KYC (basic verification for low limits, full for higher)280281DOCUMENT UPLOAD:282- `POST /api/v1/kyc/documents` — Upload identification documents283- Accept: government ID (front/back), proof of address, selfie284- Store documents encrypted in object storage (S3/GCS)285- Track document review status286287RISK SCORING:288- Implement risk score calculation based on verification results289- Factor in: identity match confidence, address verification, sanctions screening290- Map risk scores to account tier limits (transaction limits, daily limits)291- Log risk scoring decisions for compliance audit292293KYC STATUS MANAGEMENT:294- Track KYC status per user with full state machine295- Implement KYC expiration and re-verification triggers296- Handle KYC status changes across the system (limit enforcement)297- Notify users of KYC status changes298299============================================================300PHASE 7: ACCOUNT MANAGEMENT301============================================================302303Implement financial account management:304305MULTI-CURRENCY SUPPORT:306- Store all monetary values as integers in minor units307- Use the `money.ts` utility for all arithmetic (no floating-point math)308- Track currency per account and per transaction309- Implement exchange rate fetching and application310311BALANCE TRACKING:312- Implement real-time balance updates via ledger313- Support balance types: available, pending, total, held314- Implement hold/release for pending transactions315- Support negative balance prevention (overdraft protection)316317STATEMENTS:318- Generate periodic account statements (monthly)319- Include all transactions within period with running balance320- Support statement retrieval via API321- Format for regulatory compliance322323ACCOUNT LIFECYCLE:324- Handle account opening, active, frozen, suspended, closed states325- Implement account closure with balance sweep326- Handle regulatory holds and freezes327- Maintain account history after closure (retention requirements)328329============================================================330PHASE 8: AUDIT LOGGING AND WEBHOOKS331============================================================332333Implement comprehensive audit trail and event system:334335AUDIT LOGGING:336- Log EVERY financial action: who, what, when, where, before, after337- Include: user_id, action, resource_type, resource_id, ip_address, user_agent,338 request_id, timestamp, changes (before/after), result (success/failure)339- Store audit logs in append-only table (no UPDATE or DELETE permissions)340- Implement audit log search and export for compliance341- Retain audit logs per regulatory requirements (5-7 years)342343WEBHOOK SYSTEM:344- Implement outbound webhook delivery for financial events:345 - `payment.completed`, `payment.failed`, `payment.refunded`346 - `transaction.created`, `transaction.settled`347 - `account.updated`, `account.frozen`348 - `kyc.verified`, `kyc.failed`349- Sign webhooks with HMAC-SHA256 for verification350- Implement retry with exponential backoff (max 5 attempts over 24 hours)351- Log all webhook delivery attempts and responses352- Support webhook endpoint registration and management353354IDEMPOTENCY IMPLEMENTATION:355- Store idempotency keys with request hash and response356- Return cached response for duplicate requests within window357- Use database-level unique constraints on idempotency keys358- Clean up expired idempotency records359360============================================================361PHASE 9: VERIFICATION362============================================================3633641. Run type checker — fix all errors.3652. Run linter — fix all warnings.3663. Run test suite — all tests must pass.3674. Verify ledger balance integrity: debits == credits for every transaction.3685. Verify idempotency: same request returns same response.3696. Verify the server starts and health check responds.3707. Verify OpenAPI spec loads at /api/docs.371372373============================================================374SELF-HEALING VALIDATION (max 3 iterations)375============================================================376377After completing the main phases, validate your work:3783791. Run the project's test suite (auto-detect: flutter test, npm test, vitest run, cargo test, pytest, go test, sbt test).3802. Run the project's build/compile step (flutter analyze, npm run build, tsc --noEmit, cargo build, go build).3813. If either fails, diagnose the failure from error output.3824. Apply a minimal targeted fix — do NOT refactor unrelated code.3835. Re-run the failing validation.3846. Repeat up to 3 iterations total.385386IF STILL FAILING after 3 iterations:387- Document what was attempted and what failed388- Include the error output in the final report389- Flag for manual intervention390391============================================================392OUTPUT393============================================================394395## Fintech API Scaffolded396397### Project: [name]398### Framework: [framework + version]399### Financial Service: [type]400401### Resources402| Resource | Endpoints | Auth Level | Idempotent |403|----------|-----------|------------|------------|404405### Financial Components406| Component | Implementation | Status |407|-----------|---------------|--------|408| Plaid Integration | [details] | [complete] |409| Payment Processing | [ACH/Wire/Card] | [complete] |410| Double-Entry Ledger | [details] | [complete] |411| KYC Workflow | [details] | [complete] |412| Multi-Currency | [currencies] | [complete] |413| Audit Logging | [details] | [complete] |414| Webhooks | [events] | [complete] |415| Idempotency | [details] | [complete] |416417### Database Models418| Model | Fields | Indexes | Sensitive Fields |419|-------|--------|---------|------------------|420421### How to Run4221. `docker-compose up -d` (start PostgreSQL + Redis)4232. `cp .env.example .env` and configure API keys (Plaid, payment processor)4243. [install command]4254. [migration command]4265. [seed command]4276. [start command]4287. Open http://localhost:3000/api/docs for API documentation429430### Validation431- Types: [clean]432- Lint: [clean]433- Tests: [X passing]434- Ledger integrity: [verified]435436============================================================437NEXT STEPS438============================================================439440After scaffolding:441- "Run `/financial-compliance` to review regulatory compliance."442- "Run `/pci-dss` to audit payment card data handling."443- "Run `/owasp` to security audit the API."444- "Run `/qa` to test all financial flows end-to-end."445- "Run `/ship` to add new financial features or endpoints."446- "Run `/nextjs` to build a client portal frontend."447448449============================================================450SELF-EVOLUTION TELEMETRY451============================================================452453After producing output, record execution metadata for the /evolve pipeline.454455Check if a project memory directory exists:456- Look for the project path in `~/.claude/projects/`457- If found, append to `skill-telemetry.md` in that memory directory458459Entry format:460```461### /fintech-api — {{YYYY-MM-DD}}462- Outcome: {{SUCCESS | PARTIAL | FAILED}}463- Self-healed: {{yes — what was healed | no}}464- Iterations used: {{N}} / {{N max}}465- Bottleneck: {{phase that struggled or "none"}}466- Suggestion: {{one-line improvement idea for /evolve, or "none"}}467```468469Only log if the memory directory exists. Skip silently if not found.470Keep entries concise — /evolve will parse these for skill improvement signals.471472============================================================473DO NOT474============================================================475476- Do NOT use floating-point arithmetic for monetary calculations. Always use integer minor units.477- Do NOT store sensitive data (PAN, CVV, SSN) in plain text. Encrypt at rest.478- Do NOT allow single-entry bookkeeping. Every movement requires debit AND credit.479- Do NOT make ledger entries mutable. Corrections create reversing entries.480- Do NOT skip idempotency on financial endpoints. All payment and transfer operations must be idempotent.481- Do NOT expose internal ledger account IDs in API responses.482- Do NOT return detailed error messages that expose system internals.483- Do NOT skip audit logging on any financial operation.484- Do NOT hardcode API keys, secrets, or credentials.485- Do NOT allow financial operations without authentication and authorization.