> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vultlocal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> Complete system architecture reference for OLIVE

# Architecture Reference

OLIVE is a three-tier payment processing system designed for high security, scalability, and AI-powered decision making.

## System Components

<CardGroup cols={3}>
  <Card title="Gateway" icon="server">
    **Go + Gin**

    Public REST API, authentication, rate limiting
  </Card>

  <Card title="Wallet-Core" icon="database">
    **Go + gRPC**

    Financial engine, ledger, ACID transactions
  </Card>

  <Card title="Agent-TS" icon="bot">
    **TypeScript + OpenAI**

    Conversational AI, WhatsApp integration
  </Card>
</CardGroup>

***

## High-Level Architecture

```mermaid theme={null}
graph TB
    subgraph External["External Clients"]
        POS[POS Terminals]
        WA[WhatsApp Users]
        Admin[Admin Dashboard]
        API[Third-party APIs]
    end

    subgraph Gateway["Gateway Layer"]
        GW[Gateway Service]
        Auth[Auth Middleware]
        Rate[Rate Limiter]
    end

    subgraph Core["Core Services"]
        Agent[Agent-TS]
        WC[Wallet-Core]
        Ledger[Ledger Engine]
    end

    subgraph Data["Data Layer"]
        DB[(PostgreSQL)]
        S3[(S3 Storage)]
    end

    subgraph Ext["External Services"]
        OAI[OpenAI API]
        VULT[VULT Processor]
    end

    POS -->|HTTPS + HMAC| GW
    WA -->|Webhook| Agent
    Admin -->|HTTPS + JWT| GW
    API -->|HTTPS + API Key| GW

    GW --> Auth
    Auth --> Rate
    Rate -->|gRPC + mTLS| WC
    Agent -->|HTTP| GW
    Agent --> OAI

    WC --> Ledger
    Ledger --> DB
    Agent --> S3
    WC --> VULT
```

***

## Communication Protocols

### External to Gateway

| From            | Protocol   | Authentication    | Format |
| --------------- | ---------- | ----------------- | ------ |
| POS Terminal    | HTTPS/REST | HMAC Signature    | JSON   |
| Admin Dashboard | HTTPS/REST | JWT Bearer Token  | JSON   |
| Third-party API | HTTPS/REST | API Key           | JSON   |
| WhatsApp        | Webhook    | HMAC Verification | JSON   |

### Internal Communication

| From     | To          | Protocol | Authentication |
| -------- | ----------- | -------- | -------------- |
| Gateway  | Wallet-Core | gRPC     | mTLS           |
| Agent-TS | Gateway     | HTTPS    | Service Auth   |
| Agent-TS | OpenAI      | HTTPS    | API Key        |

***

## Data Flow Patterns

### Payment Request Flow

<Steps>
  <Step title="Request Received">
    Client sends payment request to Gateway (HTTPS + Auth)
  </Step>

  <Step title="Authentication">
    Gateway validates API key, JWT, or HMAC signature
  </Step>

  <Step title="Rate Limiting">
    Request checked against rate limits
  </Step>

  <Step title="Forward to Core">
    Gateway calls Wallet-Core via gRPC
  </Step>

  <Step title="Transaction Execution">
    Wallet-Core executes atomic DB transaction
  </Step>

  <Step title="Audit Logging">
    Transaction logged to audit table
  </Step>

  <Step title="Response">
    Success/failure returned through the chain
  </Step>
</Steps>

### Agent Conversation Flow

```mermaid theme={null}
sequenceDiagram
    participant U as User (WhatsApp)
    participant A as Agent-TS
    participant O as OpenAI
    participant G as Gateway
    participant W as Wallet-Core

    U->>A: "Check my balance"
    A->>O: Chat Completion Request
    O-->>A: Function Call: check_balance
    A->>G: GET /balance/{user_id}
    G->>W: gRPC: GetBalance
    W-->>G: Balance Response
    G-->>A: Balance JSON
    A->>O: Function Result
    O-->>A: Natural Language Response
    A-->>U: "Your balance is 5,000 SLE"
```

***

## Database Schema

### Core Tables

| Table          | Purpose                    | Key Fields                       |
| -------------- | -------------------------- | -------------------------------- |
| `accounts`     | User balances per currency | `user_id`, `currency`, `balance` |
| `transactions` | Central ledger             | `request_id`, `amount`, `status` |
| `subscribers`  | User profiles + KYC        | `phone`, `kyc_level`, `status`   |
| `nfc_cards`    | Card-subscriber mapping    | `serial`, `subscriber_id`        |
| `agents`       | Agent float accounts       | `phone`, `float_balance`         |
| `audit_log`    | Transaction events         | `transaction_id`, `event_type`   |
| `api_keys`     | Integration keys           | `key_hash`, `scopes`             |

### Schema Details

<Accordion title="Accounts Table">
  ```sql theme={null}
  CREATE TABLE accounts (
      id TEXT PRIMARY KEY,
      user_id TEXT NOT NULL,
      currency TEXT NOT NULL,
      balance INTEGER NOT NULL DEFAULT 0,
      created_at TIMESTAMP,
      updated_at TIMESTAMP,
      UNIQUE(user_id, currency)
  );
  ```
</Accordion>

<Accordion title="Transactions Table">
  ```sql theme={null}
  CREATE TABLE transactions (
      id TEXT PRIMARY KEY,
      request_id TEXT UNIQUE NOT NULL,
      user_id TEXT NOT NULL,
      recipient_id TEXT NOT NULL,
      amount INTEGER NOT NULL,
      currency TEXT NOT NULL,
      status TEXT NOT NULL,
      memo TEXT,
      metadata JSONB,
      created_at TIMESTAMP,
      completed_at TIMESTAMP
  );
  ```
</Accordion>

<Accordion title="Audit Log Table">
  ```sql theme={null}
  CREATE TABLE audit_log (
      id SERIAL PRIMARY KEY,
      transaction_id TEXT NOT NULL,
      event_type TEXT NOT NULL,
      actor TEXT,
      details JSONB,
      timestamp TIMESTAMP DEFAULT NOW()
  );
  ```
</Accordion>

***

## Idempotency

All payment operations are idempotent using `request_id`:

1. Client generates unique UUID for `request_id`
2. Wallet-Core checks for existing transaction with that ID
3. If found, returns cached result (no duplicate execution)
4. If not found, executes transaction
5. Result cached for idempotency window (24 hours default)

<Warning>
  Always generate unique `request_id` values. Duplicate IDs will return the original transaction instead of creating a new one.
</Warning>

***

## Error Handling

### Gateway Errors

* Input validation with detailed error messages
* Standard HTTP status codes
* Sanitized error responses (no internal details)
* All errors logged with request context

### Wallet-Core Errors

* Automatic transaction rollback on any failure
* gRPC error codes with structured details
* Database consistency guaranteed

### Agent Errors

* Graceful degradation to safe defaults
* Timeout protection for OpenAI calls
* Policy violations logged but non-fatal

***

## Scalability

<CardGroup cols={2}>
  <Card title="Horizontal Scaling" icon="arrows-left-right">
    * **Gateway**: Unlimited instances behind load balancer
    * **Agent-TS**: Stateless, unlimited scaling
    * **Wallet-Core**: Limited by database connections
  </Card>

  <Card title="Vertical Scaling" icon="arrows-up-down">
    * Increase memory for caching
    * Database optimization with indexes
    * Connection pooling tuning
  </Card>
</CardGroup>

### Database Scaling Options

* **Read replicas** for balance queries and reporting
* **Connection pooling** with PgBouncer
* **Partitioning** by date for transaction history
* **Sharding** by user\_id for write distribution

***

## Failure Modes

| Component   | Failure Impact       | Recovery Strategy                           |
| ----------- | -------------------- | ------------------------------------------- |
| Gateway     | Client requests fail | Load balancer routes to healthy instances   |
| Wallet-Core | Payments fail        | Backup instance, transaction rollback       |
| Agent-TS    | WhatsApp bot offline | Restart, conversation continues             |
| Database    | All services down    | Restore from backup, point-in-time recovery |

***

## Related

<CardGroup cols={2}>
  <Card title="Gateway Architecture" icon="server" href="/gateway/architecture">
    Detailed Gateway internals
  </Card>

  <Card title="Wallet-Core Ledger" icon="coins" href="/wallet-core/ledger">
    Transaction processing details
  </Card>

  <Card title="Security Reference" icon="shield" href="/reference/security">
    Security configuration
  </Card>

  <Card title="Deployment Guide" icon="rocket" href="/reference/deployment">
    Production deployment
  </Card>
</CardGroup>
