> For the complete documentation index, see [llms.txt](https://docs.madhousewallet.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.madhousewallet.com/security/architecture.md).

# Architecture

This page describes the technical architecture of the Madhouse Wallet off-ramp platform.

***

## System Components

```
Partner / API Key Caller
        ↓
  API Gateway (TLS 1.2+)
        ↓
  withExternalAuth — JWT or API key validation
        ↓
  Rate Limiter (per-key, sliding window)
        ↓
  Handler Logic
        ↓
  ┌─────────────────────────┐
  │  MongoDB (UserSession,  │
  │  PayoutTransaction,     │
  │  RecipientOwnership)    │
  └─────────────────────────┘
        ↓
  FX & Routing Infrastructure
        ↓
  On-chain USDC detection (multi-chain)
        ↓
  Outgoing fiat transfer (local rails / SWIFT / SEPA)
```

***

## Request Authentication

Every API request passes through `withExternalAuth`, which:

1. Detects whether the `Authorization` header carries a JWT (dashboard session) or API key (`mw_live_...`)
2. For API keys: looks up the SHA-256 hash in MongoDB, stamps `lastUsedAt`, checks wallet requirement, enforces IP restriction if enabled
3. For JWTs: verifies ES256 signature against the app's own ECDSA keypair, checks MongoDB session record
4. Applies per-key rate limits before the handler runs

***

## Transfer Pipeline

Each transfer follows an immutable state machine:

```
pending → awaiting_deposit → deposit_sent → processing → completed
                                                       ↘ failed
```

Every state transition is written atomically to MongoDB. The deposit address is unique per transfer — on-chain deposits are matched to the correct `PayoutTransaction` record via the deposit address, not scanned from a shared pool.

***

## On-Chain Detection

The platform monitors deposits across all supported chains simultaneously:

* Arbitrum, Base, Optimism, Polygon (EVM-compatible)
* Ethereum Mainnet
* Solana

When a USDC transfer to a deposit address is confirmed on-chain, the associated transfer record is updated and the conversion pipeline begins.

***

## FX Conversion

Conversion uses institutional FX liquidity with real-time mid-market rates. Rates are locked at quote time for 5 minutes. No rate changes occur after a quote is accepted.

***

## Outgoing Settlement

The outgoing fiat transfer is created and funded automatically after conversion. Settlement rails used depend on the recipient's currency:

* **Local bank transfer** — instant to same-day (most currencies)
* **SEPA/IBAN** — same day (EUR, GBP, and other European currencies)
* **M-PESA** — instant (KES)
* **UPI** — instant (INR)
* **CLABE** — local (MXN)
* **ACH** — 1–2 business days (USD)
* **SWIFT** — 5–7 business days (global fallback)

***

## Data Storage

All transfer records, recipient ownership, and session data are stored in MongoDB hosted on AWS (us-east-1), with controls designed to meet GDPR and CCPA requirements for the protection of customer data and personally identifiable information (PII).

### Encryption

| Layer                       | Method                                                                      |
| --------------------------- | --------------------------------------------------------------------------- |
| Data at rest                | AES-256-GCM encryption applied to all stored records                        |
| Data in transit             | TLS 1.2 or higher enforced on all connections                               |
| API keys                    | SHA-256 hashed before storage — plaintext is never persisted                |
| Dashboard session responses | AES-256-GCM encrypted per-session                                           |
| Signing keys                | Held in AWS KMS; keys are generated and used within HSMs and never exported |

### PII Handling

Recipient banking details (account numbers, routing numbers, IBAN, and similar fields) are treated as PII and are:

* Encrypted at rest using AES-256-GCM
* Never logged in plaintext
* Accessible only to the authenticated partner or user who submitted them
* Not shared with third parties beyond the settlement rail required to complete the transfer

### Data Minimisation and Retention

Only data necessary to execute and audit a transfer is collected. Short-lived records (OTP codes, deposit challenges) are automatically purged using TTL indexes. Partners subject to GDPR may request deletion of personal data via the account dashboard or the support channel; requests are processed within the timeframes required by applicable law.

### Access Controls and Audit Trail

* Sparse indexes ensure per-user data is isolated and fast to retrieve without cross-tenant exposure
* Atomic `findOneAndUpdate` operations enforce state-machine transitions and prevent double-processing or race conditions that could expose stale data
* Every state change is written with a timestamp, creating an immutable audit trail for each transfer
* Access to production data stores is restricted to authorised personnel via IAM policies and is logged

***

## Smart Account Infrastructure

For dashboard users initiating transfers from the Madhouse Wallet UI, the platform uses ERC-4337 smart accounts (Safe v1.4.1 on Base). Signing keys are held in AWS KMS and never exposed. Gas is paid in USDC via an audited paymaster — no ETH balance required.

| Component                | Audit                                                                                                                                      |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Safe v1.4.1              | [Audit report](https://github.com/safe-global/safe-smart-account/blob/v1.4.0/docs/Safe_Audit_Report_1_4_0.pdf)                             |
| Pimlico ERC-20 Paymaster | [Quantstamp certificate](https://certificate.quantstamp.com/full/pimlico-erc-20-paymaster/ce056730-3f75-4711-9e81-c5dbfdfce74d/index.html) |
| USDC                     | [Circle transparency reports](https://www.circle.com/transparency)                                                                         |
