home / skills / zhanghandong / rust-skills / domain-fintech

domain-fintech skill

/skills/domain-fintech

This skill helps you design and implement immutable, precise fintech transactions using rust_decimal, event sourcing, and audit trails for compliance.

npx playbooks add skill zhanghandong/rust-skills --skill domain-fintech

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.6 KB
---
name: domain-fintech
description: "Use when building fintech apps. Keywords: fintech, trading, decimal, currency, financial, money, transaction, ledger, payment, exchange rate, precision, rounding, accounting, 金融, 交易系统, 货币, 支付"
user-invocable: false
---

# FinTech Domain

> **Layer 3: Domain Constraints**

## Domain Constraints → Design Implications

| Domain Rule | Design Constraint | Rust Implication |
|-------------|-------------------|------------------|
| Audit trail | Immutable records | Arc<T>, no mutation |
| Precision | No floating point | rust_decimal |
| Consistency | Transaction boundaries | Clear ownership |
| Compliance | Complete logging | Structured tracing |
| Reproducibility | Deterministic execution | No race conditions |

---

## Critical Constraints

### Financial Precision

```
RULE: Never use f64 for money
WHY: Floating point loses precision
RUST: Use rust_decimal::Decimal
```

### Audit Requirements

```
RULE: All transactions must be immutable and traceable
WHY: Regulatory compliance, dispute resolution
RUST: Arc<T> for sharing, event sourcing pattern
```

### Consistency

```
RULE: Money can't disappear or appear
WHY: Double-entry accounting principles
RUST: Transaction types with validated totals
```

---

## Trace Down ↓

From constraints to design (Layer 2):

```
"Need immutable transaction records"
    ↓ m09-domain: Model as Value Objects
    ↓ m01-ownership: Use Arc for shared immutable data

"Need precise decimal math"
    ↓ m05-type-driven: Newtype for Currency/Amount
    ↓ rust_decimal: Use Decimal type

"Need transaction boundaries"
    ↓ m12-lifecycle: RAII for transaction scope
    ↓ m09-domain: Aggregate boundaries
```

---

## Key Crates

| Purpose | Crate |
|---------|-------|
| Decimal math | rust_decimal |
| Date/time | chrono, time |
| UUID | uuid |
| Serialization | serde |
| Validation | validator |

## Design Patterns

| Pattern | Purpose | Implementation |
|---------|---------|----------------|
| Currency newtype | Type safety | `struct Amount(Decimal);` |
| Transaction | Atomic operations | Event sourcing |
| Audit log | Traceability | Structured logging with trace IDs |
| Ledger | Double-entry | Debit/credit balance |

## Code Pattern: Currency Type

```rust
use rust_decimal::Decimal;

#[derive(Clone, Debug, PartialEq)]
pub struct Amount {
    value: Decimal,
    currency: Currency,
}

impl Amount {
    pub fn new(value: Decimal, currency: Currency) -> Self {
        Self { value, currency }
    }

    pub fn add(&self, other: &Amount) -> Result<Amount, CurrencyMismatch> {
        if self.currency != other.currency {
            return Err(CurrencyMismatch);
        }
        Ok(Amount::new(self.value + other.value, self.currency))
    }
}
```

---

## Common Mistakes

| Mistake | Domain Violation | Fix |
|---------|-----------------|-----|
| Using f64 | Precision loss | rust_decimal |
| Mutable transaction | Audit trail broken | Immutable + events |
| String for amount | No validation | Validated newtype |
| Silent overflow | Money disappears | Checked arithmetic |

---

## Trace to Layer 1

| Constraint | Layer 2 Pattern | Layer 1 Implementation |
|------------|-----------------|------------------------|
| Immutable records | Event sourcing | Arc<T>, Clone |
| Transaction scope | Aggregate | Owned children |
| Precision | Value Object | rust_decimal newtype |
| Thread-safe sharing | Shared immutable | Arc (not Rc) |

---

## Related Skills

| When | See |
|------|-----|
| Value Object design | m09-domain |
| Ownership for immutable | m01-ownership |
| Arc for sharing | m02-resource |
| Error handling | m13-domain-error |

Overview

This skill captures FinTech domain constraints and concrete Rust design guidance for building secure, auditable financial systems. It focuses on precision, immutability, transaction boundaries, and reproducibility to meet regulatory and correctness requirements. The content maps rules to Rust patterns, crates, and coding patterns that enforce financial guarantees.

How this skill works

The skill inspects domain rules (precision, audit trail, consistency) and translates them into implementation constraints and idiomatic Rust choices. It recommends crates (rust_decimal, chrono, uuid, serde) and patterns (value objects, newtypes, event sourcing, RAII transaction scopes) to ensure deterministic, traceable behavior. It highlights common pitfalls and gives small code patterns for Amount and ledger design.

When to use it

  • Building payment, ledger, or trading systems that handle real money
  • Designing transaction processing with strict audit and traceability requirements
  • Enforcing exact monetary arithmetic and preventing precision loss
  • Sharing immutable transaction data across threads or services
  • Implementing double-entry accounting and validated balances

Best practices

  • Never use floating-point (f32/f64) for money—use rust_decimal::Decimal or a validated newtype
  • Model money as a typed value object (Amount/Currency) to prevent currency mixing
  • Keep transactions immutable and traceable—use event sourcing and share with Arc<T>
  • Use RAII or explicit transaction scope types to enforce atomic boundaries
  • Perform checked arithmetic and validation to avoid silent overflows and inconsistencies
  • Log structured events with trace IDs and serialize with serde for auditability

Example use cases

  • Implementing a settlement engine that must preserve cent-level precision and full audit logs
  • Designing a ledger with double-entry bookkeeping to guarantee money conservation
  • Creating thread-safe immutable transaction records shared across services via Arc
  • Building APIs that validate currency and amount types to avoid accidental currency mixing
  • Instrumenting financial flows with structured tracing for compliance and dispute resolution

FAQ

Why not use f64 for monetary values?

Floating point loses exactness and can introduce rounding errors; use rust_decimal or an integer-based scaled newtype for deterministic precision.

How do I ensure transactions are auditable?

Model state changes as immutable events, record structured logs with trace IDs, and store events in an append-only store or ledger; share read-only views with Arc<T> to avoid mutation.