Skip to content

Latest commit

ย 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

README.md

๐Ÿฆ Banking Transaction Example

Complexity: โญโญโญโญโญ (Expert) | Time to Learn: 3-4 hours

A comprehensive banking system demonstrating Railway Oriented Programming (ROP), Domain-Driven Design (DDD), and advanced security patterns including fraud detection, multi-factor authentication, and audit trails.

graph TB
    START[Create Account] --> DEPOSIT[Deposit Funds]
    DEPOSIT --> WITHDRAW[Withdraw Request]
    
    WITHDRAW --> FRAUD{Fraud Check}
    FRAUD -->|Suspicious| FREEZE[๐Ÿ”’ Freeze Account]
    FRAUD -->|Clean| LIMIT{Daily Limit OK?}
    
    LIMIT -->|Exceeded| DENY[โŒ Deny Transaction]
    LIMIT -->|OK| MFA{Amount > $1,000?}
    
    MFA -->|Yes| VERIFY[๐Ÿ“ฑ Require MFA]
    MFA -->|No| PROCESS[Process Withdrawal]
    
    VERIFY -->|Success| PROCESS
    VERIFY -->|Failed| DENY
    
    PROCESS --> NOTIFY[๐Ÿ“ง Send Notification]
    FREEZE --> ALERT[๐Ÿšจ Security Alert]
    
    style PROCESS fill:#90EE90
    style DENY fill:#FFB6C6
    style FREEZE fill:#FFD700
    style ALERT fill:#FF6B6B
    style VERIFY fill:#E1F5FF
Loading

๐ŸŽฏ What You'll Learn

This advanced example demonstrates enterprise-grade banking features:

  • ๐Ÿ” Security First - Multi-layered fraud detection and prevention
  • ๐Ÿšจ Real-time Monitoring - Pattern detection and anomaly alerts
  • โš–๏ธ Compliance - Daily limits, overdraft rules, audit trails
  • ๐Ÿ”„ Error Recovery - Automatic freeze on suspicious activity
  • ๐Ÿ“Š Parallel Processing - Concurrent fraud checks for transfers

๐Ÿ—๏ธ Architecture Overview

Domain Model

classDiagram
    class BankAccount {
        +AccountId Id
        +CustomerId CustomerId
        +AccountType Type
        +AccountStatus Status
        +Money Balance
        +Money DailyWithdrawalLimit
        +Money OverdraftLimit
        +List~Transaction~ Transactions
        +Deposit() Result~BankAccount~
        +Withdraw() Result~BankAccount~
        +Transfer() Result~BankAccount~
        +Freeze() Result~BankAccount~
        +CalculateInterest() Result~Money~
    }
    
    class Transaction {
        +TransactionId Id
        +TransactionType Type
        +Money Amount
        +DateTime Timestamp
        +string Description
    }
    
    class Money {
        +decimal Amount
        +string Currency
        +TryCreate() Result~Money~
    }
    
    BankAccount "1" *-- "many" Transaction
    BankAccount --> Money
    Transaction --> Money
    
    class FraudDetectionService {
        +AnalyzeTransactionAsync() Task~Result~bool~~
        +RequiresMFA() bool
        +DetectSuspiciousPattern() bool
    }
    
    class BankingWorkflow {
        +ProcessWithdrawalAsync() Task~Result~BankAccount~~
        +ProcessTransferAsync() Task~Result~(BankAccount, BankAccount)~~
    }
    
    BankingWorkflow --> BankAccount
    BankingWorkflow --> FraudDetectionService
Loading

Account Status State Machine

stateDiagram-v2
    [*] --> Active: Open Account
    
    Active --> Frozen: Fraud Detected
    Active --> Frozen: Manual Freeze
    
    Frozen --> Active: Review Complete
    Frozen --> Active: Manual Unfreeze
    
    Active --> Closed: Close Account
    Frozen --> Closed: Close Account
    
    Closed --> [*]
    
    note right of Frozen
        โš ๏ธ All transactions blocked
        Requires security review
        Notifications sent
    end note
    
    note right of Active
        โœ… Normal operations
        Daily limits enforced
        Fraud monitoring active
    end note
    
    note right of Closed
        โ„น๏ธ Balance must be $0
        Cannot reopen
        Archive transactions
    end note
Loading

Fraud Detection Flow

flowchart TB
    TX[New Transaction] --> AMOUNT{Amount > $5,000?}
    
    AMOUNT -->|Yes| MANUAL[๐Ÿ” Manual Review Required]
    AMOUNT -->|No| FREQ{High Frequency?}
    
    FREQ -->|>10/hour| FREEZE[๐Ÿ”’ Auto-Freeze]
    FREQ -->|Normal| PATTERN{Unusual Pattern?}
    
    PATTERN -->|Yes| MFA[๐Ÿ“ฑ Require MFA]
    PATTERN -->|No| APPROVE[โœ… Approve]
    
    MANUAL --> REVIEW[Security Team Review]
    REVIEW --> APPROVE
    
    MFA -->|Verified| APPROVE
    MFA -->|Failed| DENY[โŒ Deny]
    
    FREEZE --> ALERT[๐Ÿšจ Alert Security]
    
    style APPROVE fill:#90EE90
    style DENY fill:#FFB6C6
    style FREEZE fill:#FFD700
    style ALERT fill:#FF6B6B
Loading

๐Ÿ“ฆ Key Components

Value Objects

  • AccountId: Unique identifier for bank accounts
  • TransactionId: Unique identifier for transactions
  • CustomerId: Unique identifier for customers
  • Money: Represents monetary amounts with precision

Entities

  • Transaction: Represents individual account transactions (deposit, withdrawal, transfer, fee, interest)

Aggregates

  • BankAccount: Aggregate root managing account state, balance, and transaction history

Domain Services

  • FraudDetectionService: Analyzes transactions for suspicious patterns and validates customer identity

Workflows

  • BankingWorkflow: Orchestrates complex banking operations with fraud detection and validation

๐ŸŽจ Features Demonstrated

1. ๐Ÿš‚ Account Operations with Railway Pattern

Clean transaction processing with automatic validation:

return await account.Deposit(amount, "Salary")
    .Ensure(acc => acc.Status == AccountStatus.Active, 
           Error.Validation("Account not active"))
    .Bind(acc => acc.Withdraw(withdrawAmount, "Rent"))
    .Match(
        onSuccess: acc => $"Balance: {acc.Balance} โœ…",
        onFailure: err => $"Failed: {err.Detail} โŒ"
    );

What's happening:

  1. Deposit salary (validates amount, updates balance)
  2. Ensure account is active (business rule check)
  3. Withdraw rent (checks limits, validates funds)
  4. Match result (handle success or failure)

If any check fails, subsequent operations are skipped! ๐ŸŽฏ

2. ๐Ÿ” Multi-Layered Fraud Detection

Real-time security analysis integrated into the transaction flow:

return await account.ToResult()
    .EnsureAsync(
        async acc => await _fraudDetection.AnalyzeTransactionAsync(
            acc, amount, "withdrawal", cancellationToken),
        Error.Forbidden("Fraud check failed - transaction blocked")
    )
    .Bind(acc => acc.Withdraw(amount, description))
    .RecoverOnFailureAsync(
        predicate: error => error.Code == "fraud.detected",
        func: async () => {
            await account.Freeze("Suspicious activity detected");
            await _notificationService.AlertSecurityTeam(account.Id);
            return account;
        }
    );

Fraud Detection Rules:

Rule Threshold Action
๐Ÿ’ฐ Large Amount > $5,000 Manual review required
โšก High Frequency > 10 transactions/hour Auto-freeze account
๐ŸŽฏ Pattern Detection 3+ round amounts in 24h Trigger MFA
๐Ÿ“ฑ MFA Required Withdrawal > $1,000 Require verification code

3. ๐Ÿ”„ Parallel Fraud Checks for Transfers

Concurrent validation for performance and security:

var result = await ValidateFromAccountAsync(fromAccount, amount, ct)
    .ParallelAsync(ValidateToAccountAsync(toAccount, amount, ct))
    .WhenAllAsync()
    .BindAsync((fromValid, toValid) => 
        ProcessTransferAsync(fromAccount, toAccount, amount, ct), ct);

Benefits:

  • โšก Faster - Both accounts checked simultaneously
  • ๐Ÿ”’ Secure - All checks must pass before transfer
  • ๐ŸŽฏ Atomic - Transfer fails if any check fails

4. ๐Ÿ“Š Daily Withdrawal Limits

Automatic tracking and enforcement:

account.Withdraw(amount, "ATM")
    .Ensure(acc => acc.GetDailyWithdrawalTotal() + amount <= acc.DailyWithdrawalLimit,
           Error.Validation($"Daily limit ${acc.DailyWithdrawalLimit} exceeded"))

How it works:

  • Tracks all withdrawals for current day
  • Resets at midnight
  • Configurable per account type
  • Different limits for Checking vs Savings

5. ๐Ÿ’ณ Overdraft Protection

Controlled negative balance with limits:

account.Withdraw(amount, "Emergency")
    .Ensure(acc => acc.Balance - amount >= -acc.OverdraftLimit,
           Error.Validation($"Overdraft limit ${acc.OverdraftLimit} exceeded"))

Rules:

  • โœ… Checking: $500 overdraft allowed
  • โœ… Savings: No overdraft (must maintain positive balance)
  • โœ… Money Market: $1,000 overdraft with fee

6. ๐Ÿ” Security Features

Enterprise-grade security patterns:

graph LR
    A[Transaction] --> B{MFA Required?}
    B -->|Yes| C[Send Code]
    C --> D{Verify}
    D -->|โœ…| E[Process]
    D -->|โŒ| F[Deny]
    B -->|No| G{Pattern Check}
    G -->|Suspicious| H[Flag for Review]
    G -->|Normal| E
    
    style E fill:#90EE90
    style F fill:#FFB6C6
    style H fill:#FFD700
Loading

Security Layers:

  1. Multi-Factor Authentication - For large transactions
  2. Behavioral Analysis - Pattern detection
  3. Real-time Monitoring - High-frequency alerts
  4. Automatic Freeze - Suspicious activity response
  5. Audit Trail - Complete transaction history

๐Ÿ’ผ Business Rules Implemented

Account Types & Characteristics

graph TB
    subgraph Checking["๐Ÿ’ต Checking Account"]
        C1[Daily Limit: $2,000]
        C2[Overdraft: $500]
        C3[No Interest]
        C4[Unlimited Transactions]
    end
    
    subgraph Savings["๐Ÿ’ฐ Savings Account"]
        S1[Daily Limit: $1,000]
        S2[No Overdraft]
        S3[Interest: 2% APY]
        S4[6 Withdrawals/Month]
    end
    
    subgraph MoneyMarket["๐Ÿ“ˆ Money Market"]
        M1[Daily Limit: $5,000]
        M2[Overdraft: $1,000]
        M3[Interest: 3% APY]
        M4[Min Balance: $2,500]
    end
    
    style Checking fill:#E1F5FF
    style Savings fill:#90EE90
    style MoneyMarket fill:#FFD700
Loading

Transaction Validation Rules

Validation Rule Error Type
Amount Must be > $0 ValidationError
Account Status Must be Active DomainError
Daily Limit Total โ‰ค daily limit ValidationError
Balance Balance - amount โ‰ฅ -overdraft ValidationError
Fraud Check Must pass all fraud rules ForbiddenError
MFA Required if amount > $1,000 UnauthorizedError

Fraud Detection Thresholds

pie title Transaction Risk Levels
    "Low Risk (<$1,000)" : 70
    "Medium Risk ($1,000-$5,000)" : 20
    "High Risk (>$5,000)" : 10
Loading

Risk Actions:

  • ๐ŸŸข Low Risk: Automatic approval
  • ๐ŸŸก Medium Risk: MFA required
  • ๐Ÿ”ด High Risk: Manual review + MFA

๐Ÿš€ Running the Examples

๐Ÿ“‹ Available Examples

# Example What It Demonstrates Security Features
1๏ธโƒฃ Basic Operations Deposits, withdrawals, domain events โœ… Balance validation
2๏ธโƒฃ Account Transfer Transfer between accounts โœ… Parallel fraud checks
3๏ธโƒฃ Fraud Detection Blocking suspicious transactions โœ… Pattern detection, auto-freeze
4๏ธโƒฃ Daily Limits Enforcement of withdrawal limits โœ… Limit tracking, denial
5๏ธโƒฃ Interest Payment Calculating and applying interest โœ… Rate validation
6๏ธโƒฃ Domain Events Event sourcing and change tracking โœ… Audit trail

๐ŸŽฎ Run All Examples

await BankingExamples.RunExamplesAsync();

Expected Output:

โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
Example 1: Basic Account Operations โœ…
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
Account created: CHK-12345
Deposited: $1,500.00
Withdrawn: $200.00
Balance: $1,300.00
Domain Events: 3

โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
Example 2: Account Transfer โœ…
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
Transfer from CHK-12345 to SAV-67890
Amount: $500.00
Fraud Check (From): โœ… Passed
Fraud Check (To): โœ… Passed
Transfer Complete!

โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
Example 3: Fraud Detection ๐Ÿšจ
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
Large withdrawal attempted: $7,500.00
โš ๏ธ FRAUD DETECTED: Amount exceeds threshold
Account Status: FROZEN
Security Team Notified: โœ…

... (continues for all 6 examples)

๐ŸŽ“ Key Learnings

๐Ÿ’ก What This Example Teaches

Concept What You Learn Real-World Application
๐Ÿ” Security-First Build fraud detection into domain logic Banking, finance, payments
โš–๏ธ Business Rules Enforce complex rules with types Regulatory compliance
๐Ÿ”„ Error Recovery Automatic rollback on security issues Fraud prevention systems
๐Ÿ“Š Parallel Operations Concurrent validation for performance High-volume transactions
๐Ÿ“ก Event Sourcing Complete audit trail via events Regulatory reporting
๐ŸŽฏ Pattern Detection Identify suspicious behavior Anti-money laundering
๐Ÿ’ฐ Precision Money type prevents rounding errors Financial calculations

๐Ÿ› ๏ธ How to Run

Option 1: Command Line (Recommended)

# Navigate to example directory
cd Examples/BankingExample

# Run all 6 examples
dotnet run

Option 2: Visual Studio

  1. Set Startup Project

    • Right-click BankingExample in Solution Explorer
    • Select "Set as Startup Project"
  2. Run

    • Press F5 (Debug) or Ctrl+F5 (Run without debugging)
    • Watch console output with security alerts

Option 3: Run Specific Examples

Edit Program.cs:

using BankingExample;

// Run all examples
await BankingExamples.RunExamplesAsync();

// OR run individual examples
await BankingExamples.Example1_BasicAccountOperations();
await BankingExamples.Example2_TransferBetweenAccounts();
await BankingExamples.Example3_FraudDetection();
await BankingExamples.Example4_DailyWithdrawalLimit();
await BankingExamples.Example5_InterestPayment();
await BankingExamples.Example6_DomainEventsAndChangeTracking();

๐Ÿ“š Learning Path

graph LR
    A[๐Ÿ“– Read This README] --> B[โ–ถ๏ธ Run Examples]
    B --> C[๐Ÿ‘€ Study Security Code]
    C --> D{Comfortable?}
    
    D -->|No| E[๐Ÿ“ Review Fraud Detection]
    E --> F[๐Ÿ” Explore Patterns]
    F --> B
    
    D -->|Yes| G[๐Ÿ›’ Try E-Commerce Example]
    G --> H[๐ŸŽฏ Build Your Own]
    
    style A fill:#E1F5FF
    style B fill:#90EE90
    style C fill:#FFF4E1
    style G fill:#FFE1F5
    style H fill:#FFB6C6
Loading

Recommended Study Order

  1. Start Here โ†’ Read this README thoroughly

  2. Run Examples โ†’ Execute dotnet run and observe security features

  3. Study Code โ†’ Open files in this order:

    • ValueObjects/Money.cs - Precision arithmetic
    • Aggregates/BankAccount.cs - Account logic & rules
    • Services/FraudDetectionService.cs - Security patterns
    • Workflows/BankingWorkflow.cs - Orchestration
    • BankingExamples.cs - See it all working
  4. Compare โ†’ Check E-Commerce Example for different domain

  5. Extend โ†’ Add features (see Extensions below)


๐Ÿ”ง Possible Extensions

Consider implementing these features to practice:

Feature Complexity What You'd Learn
Account Statements โญโญ Reporting, date ranges
Standing Orders โญโญโญ Recurring transactions, scheduling
Multiple Currencies โญโญโญโญ Foreign exchange, conversion rates
Joint Accounts โญโญโญ Multiple owners, authorization
Transaction Categories โญโญ Categorization, budgeting
Credit Cards โญโญโญโญโญ Credit limits, interest, payments
Loan Accounts โญโญโญโญ Amortization, payment schedules

๐Ÿ”— Related Examples & Resources

Other Examples

Documentation


๐ŸŽฏ Next Steps

After completing this example:

โœ… You understand advanced security patterns
โœ… You can implement fraud detection
โœ… You know parallel validation techniques
โœ… You've built a domain-rich aggregate
โœ… You understand event sourcing for audit trails

Now try:


Questions? Check the main documentation or open an issue on GitHub.