> For the complete documentation index, see [llms.txt](https://wally-3.gitbook.io/wally-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wally-3.gitbook.io/wally-docs/technical/tech-spec.md).

# Tech Spec

> Detailed technical specification for implementation reference.

***

## Backend (apps/api)

### Modules

| Module             | Responsibility                               |
| ------------------ | -------------------------------------------- |
| `AuthModule`       | JWT, magic links, Google OAuth, guards       |
| `UserModule`       | CRUD users, KYC, profile                     |
| `VaultModule`      | Encrypted key storage                        |
| `BlockchainModule` | Stellar operations (Horizon)                 |
| `BlendModule`      | Pool info, Soroban tx submission             |
| `SavingsModule`    | DeFi vaults, deposits, withdrawals           |
| `ProjectModule`    | Projects with goals, escrow, savings-enabled |
| `ProviderModule`   | Verified provider network                    |
| `MerchantModule`   | API keys, payment requests                   |
| `WhatsAppModule`   | WhatsApp bot (transfers, balance)            |

### Design Patterns

* **GraphQL code-first**: entities as types, DTOs as inputs
* **Guards**: `GqlAuthGuard` for protected endpoints, public queries without guard
* **Service layer**: business logic in services, resolvers only routing
* **Prisma transactions**: atomic operations with `$transaction`

***

## Frontend (apps/web)

### Route Structure

```
app/
├── page.tsx                    # Public landing
├── login/page.tsx              # Auth
├── register/page.tsx
├── providers/page.tsx          # Public
├── (authenticated)/
│   ├── dashboard/page.tsx
│   ├── send/page.tsx           # QuickSend
│   ├── remittance/new/page.tsx # Remittance with escrow
│   ├── projects/page.tsx
│   ├── projects/[id]/page.tsx
│   ├── savings/page.tsx        # Savings vaults
│   ├── beneficiaries/page.tsx
│   └── wallet/page.tsx
```

### Transaction Signing Flow

```
User action → Build XDR (API) → Prompt PIN → Decrypt secret (client)
  → Sign XDR → Submit (API or Soroban RPC) → Confirm → Update DB
```

***

## Wallet Core (packages/wallet-core)

### StellarClient

* `sendPayment(from, to, amount, asset)`
* `getBalance(publicKey)`
* `createTrustline(publicKey, asset)`

### SorobanClient

* `simulateTransaction(xdr)`
* `prepareTransaction(xdr)`
* `sendTransaction(signedXdr)`
* `submitAndPoll(signedXdr)` — submit + polling until confirmation

### BlendClient

* `buildSupplyXdr(publicKey, amount)` → XDR for pool deposit
* `buildWithdrawXdr(publicKey, amount)` → XDR for withdrawal
* `getUserPosition(publicKey)` → `{ deposited, bTokenBalance }`
* `getPoolInfo()` → `{ supplyApy, borrowApy, totalSupply }`

### CryptoUtils

* `encryptSecret(secret, pin)` → `{ encrypted, salt, iv }`
* `decryptSecret(encrypted, pin, salt, iv)` → secret
* AES-256-GCM + PBKDF2 (100K iterations, SHA-256)
* Web Crypto API (browser-native, no dependencies)

***

## Blockchain Integration

### Stellar (Horizon)

* **Networks**: testnet (`horizon-testnet.stellar.org`) / mainnet (`horizon.stellar.org`)
* **Asset**: USDC (Circle)
* **Operations**: payments, trustlines, account creation, path payments

### Soroban (Smart Contracts)

* **RPC**: `soroban-testnet.stellar.org` / mainnet equivalent
* **Contracts**: TrustlessWork escrow (deployed per-escrow), Blend Capital pool

### TrustlessWork API

* Endpoints: create escrow, fund, release, dispute
* Auth: API key

### Blend Capital SDK

* `@blend-capital/blend-sdk` v3.2.2
* `PoolContractV2.submit()` → returns base64 `xdr.Operation`
* `PoolV2.load()` → pool state (reserves, APY)
* Amounts scaled by 1e7 (Stellar 7-decimal precision)

***

## Database

### Data Model (Prisma)

```
User ─┬── Vault[] (encrypted keys)
      ├── Remittance[] → Provider
      ├── Project[] → Contribution[]
      │             → SavingsVault?
      ├── SavingsVault[] → SavingsTransaction[]
      ├── Beneficiary[] → QuickSend[]
      ├── WhatsAppLink?
      └── PendingTransaction[]

Provider ── Remittance[]
MerchantApiKey ── PaymentRequest[]
```

***

## Security

| Layer            | Implementation                    |
| ---------------- | --------------------------------- |
| Authentication   | JWT (7 days) + refresh            |
| Key encryption   | AES-256-GCM + PBKDF2              |
| Transport        | HTTPS + CORS whitelisted          |
| Rate limiting    | Per IP + per user                 |
| Audit logging    | All actions with risk score       |
| Idempotency      | Webhooks + transactions           |
| Input validation | Class-validator (DTOs)            |
| SQL injection    | Prisma parameterized queries      |
| XSS              | React auto-escaping + CSP headers |

***

## Testing

| Type               | Framework           | Coverage                       |
| ------------------ | ------------------- | ------------------------------ |
| Unit (API)         | Jest                | Services: Blend, Savings       |
| Unit (wallet-core) | Vitest              | SorobanClient, BlendClient     |
| E2E (testnet)      | Vitest              | Blend pool info, user position |
| Build verification | Next.js build + tsc | All apps                       |

### Running Tests

```bash
# API
cd apps/api && npx jest --no-coverage

# wallet-core
cd packages/wallet-core && npx vitest run
```
