Skip to content

Latest commit

 

History

History
647 lines (569 loc) · 30.4 KB

SYSTEM_ARCHITECTURE.md

File metadata and controls

647 lines (569 loc) · 30.4 KB

System Architecture Documentation

Collateral Vault Management System


Table of Contents

  1. Overview
  2. Vault Structure Diagram
  3. PDA Derivation Scheme
  4. CPI Flow Diagram
  5. Security Model
  6. System Components
  7. Data Flow

Overview

The Collateral Vault Management System is a Solana-based DeFi application that enables users to deposit, manage, and lock collateral for trading positions. The system consists of:

  • On-chain Program (Anchor): Solana smart contract managing vault state
  • Off-chain Backend (Rust): REST API and database layer
  • Database (PostgreSQL): Transaction history and analytics
  • WebSocket Server: Real-time updates

Architecture Layers

┌─────────────────────────────────────────────────────────┐
│                   Client Applications                    │
│              (Trading Platforms, UIs)                    │
└────────────────────┬────────────────────────────────────┘
                     │
                     │ HTTP/WebSocket
                     ▼
┌─────────────────────────────────────────────────────────┐
│              Backend Service (Rust)                      │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐             │
│  │   REST   │  │ WebSocket│  │ Database │             │
│  │   API    │  │   Server │  │  Layer   │             │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘             │
│       │             │             │                     │
│  ┌────┴────────────────────────────┴─────┐            │
│  │     Business Logic Layer               │            │
│  │  • VaultManager  • BalanceTracker      │            │
│  │  • CPIManager    • VaultMonitor        │            │
│  │  • TransactionBuilder                  │            │
│  └──────────────┬─────────────────────────┘            │
└─────────────────┼──────────────────────────────────────┘
                  │ RPC/CPI
                  ▼
┌─────────────────────────────────────────────────────────┐
│           Solana Blockchain (Anchor Program)             │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐             │
│  │  Vault   │  │   SPL    │  │  System  │             │
│  │ Program  │◄─┤  Token   │  │ Program  │             │
│  │          │  │ Program  │  │          │             │
│  └──────────┘  └──────────┘  └──────────┘             │
└─────────────────────────────────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────────────┐
│              PostgreSQL Database                         │
│  • Vaults  • Transactions  • Balance Snapshots         │
│  • Audit Logs  • Reconciliation Logs                    │
└─────────────────────────────────────────────────────────┘

Vault Structure Diagram

On-Chain Vault Account

┌─────────────────────────────────────────────────────┐
│              Vault Account (PDA)                     │
├─────────────────────────────────────────────────────┤
│ Field           │ Type    │ Description             │
├─────────────────┼─────────┼─────────────────────────┤
│ discriminator   │ u8[8]   │ Anchor discriminator    │
│ user            │ Pubkey  │ Vault owner             │
│ vault_pda       │ Pubkey  │ Self-reference          │
│ usdt_ata        │ Pubkey  │ Token account address   │
│ free_balance    │ u64     │ Available for withdraw  │
│ locked_balance  │ u64     │ Locked in positions     │
│ total_deposited │ u64     │ Total ever deposited    │
│ bump            │ u8      │ PDA bump seed           │
└─────────────────┴─────────┴─────────────────────────┘

Balance Relationship

total_deposited = free_balance + locked_balance

┌─────────────────┐
│ total_deposited │
│   (10,000)      │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
┌───▼───┐ ┌──▼──────┐
│ free  │ │ locked  │
│(7,000)│ │ (3,000) │
└───────┘ └─────────┘

Off-Chain Database Schema

┌─────────────────────────────────────────────────────┐
│                  vaults table                        │
├─────────────────────────────────────────────────────┤
│ id                  BIGSERIAL PRIMARY KEY           │
│ user_pubkey         VARCHAR(44) UNIQUE              │
│ vault_pda           VARCHAR(44)                     │
│ total_balance       BIGINT                          │
│ locked_balance      BIGINT                          │
│ available_balance   BIGINT                          │
│ status              VARCHAR(20)                     │
│ created_at          TIMESTAMP                       │
│ last_updated        TIMESTAMP                       │
└─────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────┐
│              transactions table                      │
├─────────────────────────────────────────────────────┤
│ id                  BIGSERIAL PRIMARY KEY           │
│ user_pubkey         VARCHAR(44)                     │
│ transaction_type    VARCHAR(20)                     │
│ amount              BIGINT                          │
│ status              VARCHAR(20)                     │
│ signature           VARCHAR(88)                     │
│ created_at          TIMESTAMP                       │
└─────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────┐
│              audit_logs table                       │
├─────────────────────────────────────────────────────┤
│ id                  BIGSERIAL PRIMARY KEY           │
│ caller_program      VARCHAR(44)                     │
│ user_pubkey         VARCHAR(44)                     │
│ action              VARCHAR(20)                     │
│ signature           VARCHAR(88)                     │
│ authorized          BOOLEAN                         │
│ created_at          TIMESTAMP                       │
└─────────────────────────────────────────────────────┘

PDA Derivation Scheme

Vault PDA Derivation

Every user has exactly one vault PDA (Program Derived Address) derived deterministically:

seeds = [b"vault", user_pubkey.as_ref()]
program_id = collateral_vault_program_id

(vault_pda, bump) = Pubkey::find_program_address(seeds, program_id)

Derivation Process

┌──────────────┐
│  User Pubkey │
│ (Base58)     │
└──────┬───────┘
       │
       ▼
┌─────────────────────────────────┐
│ PDA Derivation Function          │
│                                  │
│ seeds = ["vault", user_pubkey]  │
│ program_id = vault_program_id    │
│                                  │
│ Try bump = 255, 254, 253...     │
│ Until valid PDA found           │
└──────┬──────────────────────────┘
       │
       ▼
┌──────────────────────┐
│  Vault PDA + Bump    │
│  (Deterministic)     │
└──────────────────────┘

PDA Characteristics

  • Deterministic: Same user always gets same PDA
  • Unique: No two users share the same PDA
  • Program-owned: Vault PDA is owned by the vault program
  • Seed-based: Uses "vault" prefix + user pubkey
  • Bump stored: Bump seed stored in vault account for validation

Account Ownership Structure

User Wallet (Signer)
    │
    ├──► Vault PDA (Owned by Program)
    │         │
    │         └──► Vault Token Account (ATA)
    │                   │
    │                   └──► Holds USDT tokens
    │
    └──► User Token Account (ATA)
              │
              └──► User's USDT tokens

Validation in Instructions

#[account(
    seeds = [b"vault", user.key().as_ref()],
    bump = vault.bump
)]
pub vault: Account<'info, Vault>,

This constraint ensures:

  • PDA is correctly derived
  • User matches the vault owner
  • Bump seed is valid

CPI Flow Diagram

Cross-Program Invocation (CPI) Overview

CPIs allow the vault program to call other Solana programs (like SPL Token) securely.

Deposit Flow (SPL Token CPI)

┌──────────────┐
│ User         │
│ (Signer)     │
└──────┬───────┘
       │
       │ 1. deposit_collateral()
       ▼
┌──────────────────────────────────┐
│  Vault Program                   │
│  ┌────────────────────────────┐ │
│  │ deposit_collateral()       │ │
│  │  1. Validate accounts      │ │
│  │  2. Prepare CPI            │ │
│  │  3. Call SPL Token         │ │
│  └──────────┬─────────────────┘ │
└─────────────┼───────────────────┘
              │
              │ 2. CPI: token::transfer()
              ▼
┌──────────────────────────────────┐
│  SPL Token Program               │
│  ┌────────────────────────────┐ │
│  │ Transfer tokens:           │ │
│  │  from: user_token_account  │ │
│  │  to:   vault_token_account │ │
│  │  amount: specified         │ │
│  └──────────┬─────────────────┘ │
└─────────────┼───────────────────┘
              │
              │ 3. Transfer executed
              ▼
┌──────────────────────────────────┐
│  Token Accounts Updated          │
│  • User balance decreased        │
│  • Vault balance increased       │
└──────────┬───────────────────────┘
           │
           │ 4. Return to vault program
           ▼
┌──────────────────────────────────┐
│  Vault Program (continued)       │
│  ┌────────────────────────────┐ │
│  │ 5. Update vault state:     │ │
│  │    free_balance += amount  │ │
│  │    total_deposited += ...  │ │
│  │ 6. Emit DepositEvent       │ │
│  └────────────────────────────┘ │
└──────────────────────────────────┘

Lock Collateral Flow (Internal CPI)

┌──────────────────┐
│ Position Manager │
│   Program        │
│  (Caller)        │
└────────┬─────────┘
         │
         │ 1. lock_collateral()
         ▼
┌──────────────────────────────────┐
│  Vault Program                   │
│  ┌────────────────────────────┐ │
│  │ lock_collateral()          │ │
│  │  1. Validate caller        │ │
│  │  2. Check free_balance     │ │
│  │  3. Update balances:       │ │
│  │     free -= amount         │ │
│  │     locked += amount       │ │
│  │  4. Emit LockEvent         │ │
│  └────────────────────────────┘ │
└──────────────────────────────────┘

CPI Security Model

┌─────────────────────────────────────────┐
│         CPI Authorization                │
├─────────────────────────────────────────┤
│                                          │
│  Lock/Unlock Operations:                │
│  ┌───────────────────────────────────┐ │
│  │ Only authorized programs can call │ │
│  │ • Position Manager (for locking)  │ │
│  │ • Liquidation Engine (unlocking)  │ │
│  └───────────────────────────────────┘ │
│                                          │
│  Validation:                             │
│  ┌───────────────────────────────────┐ │
│  │ ctx.accounts.caller.key() must    │ │
│  │ be in authorized_programs list    │ │
│  └───────────────────────────────────┘ │
│                                          │
└─────────────────────────────────────────┘

CPI Account Requirements

For SPL Token transfers:

  • token_program: SPL Token Program ID
  • from: Source token account (must be signer's)
  • to: Destination token account (vault's)
  • authority: Signer of the transfer

Security Model

Multi-Layer Security

┌─────────────────────────────────────────────┐
│         Layer 1: On-Chain Security          │
├─────────────────────────────────────────────┤
│ • PDA-based ownership                       │
│ • Authority validation                      │
│ • Arithmetic overflow protection            │
│ • Account constraints                       │
│ • CPI caller validation                     │
└─────────────────────────────────────────────┘
                    │
                    ▼
┌─────────────────────────────────────────────┐
│         Layer 2: Backend Security           │
├─────────────────────────────────────────────┤
│ • Database transaction atomicity            │
│ • Balance validation                        │
│ • Input sanitization                        │
│ • Error handling                            │
│ • Audit logging                             │
└─────────────────────────────────────────────┘
                    │
                    ▼
┌─────────────────────────────────────────────┐
│         Layer 3: Monitoring Security        │
├─────────────────────────────────────────────┤
│ • VaultMonitor reconciliation               │
│ • Anomaly detection                         │
│ • Balance mismatch alerts                   │
│ • Unauthorized access detection             │
└─────────────────────────────────────────────┘

Authority Model

┌─────────────────────────────────────────────┐
│           Vault Operations                   │
├─────────────────────────────────────────────┤
│                                              │
│  User-Initiated (Requires User Signature):  │
│  • initialize_vault                         │
│  • deposit_collateral                       │
│  • withdraw_collateral                      │
│  • transfer_collateral                      │
│                                              │
│  Program-Initiated (CPI from authorized):   │
│  • lock_collateral    (Position Manager)    │
│  • unlock_collateral  (Liquidation Engine)  │
│                                              │
└─────────────────────────────────────────────┘

Access Control Matrix

Operation Requires Validated By
Initialize User signer user == ctx.accounts.user.key()
Deposit User signer user_token_account.owner == user
Withdraw User signer vault.user == user
Lock CPI caller caller in authorized_programs
Unlock CPI caller caller in authorized_programs
Transfer User signer from_vault.user == user

System Components

On-Chain Program Components

┌─────────────────────────────────────────────┐
│         Anchor Program Structure             │
├─────────────────────────────────────────────┤
│                                              │
│  Instructions:                               │
│  ┌───────────────────────────────────────┐ │
│  │ initialize_vault.rs                   │ │
│  │ deposit_collateral.rs                 │ │
│  │ withdraw_collateral.rs                │ │
│  │ lock_collateral.rs                    │ │
│  │ unlock_collateral.rs                  │ │
│  │ transfer_collateral.rs                │ │
│  └───────────────────────────────────────┘ │
│                                              │
│  State:                                      │
│  ┌───────────────────────────────────────┐ │
│  │ Vault account structure               │ │
│  └───────────────────────────────────────┘ │
│                                              │
│  Events:                                     │
│  ┌───────────────────────────────────────┐ │
│  │ DepositEvent, WithdrawEvent           │ │
│  │ LockEvent, UnlockEvent                │ │
│  │ TransferEvent                         │ │
│  └───────────────────────────────────────┘ │
│                                              │
│  Errors:                                     │
│  ┌───────────────────────────────────────┐ │
│  │ VaultError enum                       │ │
│  │ (Unauthorized, InvalidAmount, etc.)   │ │
│  └───────────────────────────────────────┘ │
└─────────────────────────────────────────────┘

Off-Chain Backend Components

┌─────────────────────────────────────────────┐
│         Backend Service Modules              │
├─────────────────────────────────────────────┤
│                                              │
│  Core Services:                              │
│  ┌───────────────────────────────────────┐ │
│  │ VaultManager                          │ │
│  │   • Vault lifecycle                   │ │
│  │   • Transaction building              │ │
│  └───────────────────────────────────────┘ │
│                                              │
│  ┌───────────────────────────────────────┐ │
│  │ BalanceTracker                        │ │
│  │   • Real-time balance cache           │ │
│  │   • Chain reconciliation              │ │
│  └───────────────────────────────────────┘ │
│                                              │
│  ┌───────────────────────────────────────┐ │
│  │ CPIManager                            │ │
│  │   • CPI authorization                 │ │
│  │   • Lock/unlock operations            │ │
│  └───────────────────────────────────────┘ │
│                                              │
│  ┌───────────────────────────────────────┐ │
│  │ VaultMonitor                          │ │
│  │   • Periodic scanning                 │ │
│  │   • Anomaly detection                 │ │
│  └───────────────────────────────────────┘ │
│                                              │
│  ┌───────────────────────────────────────┐ │
│  │ TransactionBuilder                    │ │
│  │   • Solana transaction construction   │ │
│  │   • Account metadata                  │ │
│  └───────────────────────────────────────┘ │
└─────────────────────────────────────────────┘

Data Flow

Complete Deposit Flow

User Request
    │
    ▼
Backend API (POST /vault/deposit)
    │
    ├──► Validate input
    │
    ├──► Check vault exists (Database)
    │
    ├──► Build Solana transaction
    │       │
    │       ├──► TransactionBuilder
    │       │       • Create deposit instruction
    │       │       • Add account metadata
    │       │
    │       └──► VaultManager
    │
    ├──► Send transaction to Solana
    │       │
    │       └──► Solana RPC → Program
    │               │
    │               ├──► Validate accounts
    │               ├──► CPI to SPL Token
    │               ├──► Update vault state
    │               └──► Emit event
    │
    ├──► Receive signature
    │
    ├──► Update database (atomic transaction)
    │       │
    │       ├──► Update vaults table
    │       ├──► Insert into transactions
    │       └──► Update balance tracker cache
    │
    ├──► Broadcast WebSocket event
    │
    └──► Return response to user

Lock/Unlock Flow (CPI)

External Program (Position Manager)
    │
    ▼
Backend Internal API (POST /internal/lock)
    │
    ├──► Validate caller program
    │
    ├──► Check vault balance (Database)
    │
    ├──► Update database (atomic)
    │       │
    │       ├──► Decrease available_balance
    │       ├──► Increase locked_balance
    │       ├──► Insert transaction record
    │       └──► Log to audit_logs
    │
    ├──► (Optional) Build CPI transaction
    │       │
    │       └──► CPIManager → Program
    │               │
    │               └──► Update on-chain state
    │
    ├──► Broadcast WebSocket event
    │
    └──► Return success response

Balance Query Flow

User Request (GET /vault/balance/:user)
    │
    ▼
Backend API
    │
    ├──► Check BalanceTracker cache
    │       │
    │       └──► If fresh (< 5s old) → return cache
    │
    ├──► If cache miss/stale:
    │       │
    │       ├──► Query database
    │       │
    │       └──► (Optional) Fetch from chain
    │               │
    │               └──► Reconcile if mismatch
    │
    └──► Return balance data

System Interactions

Component Communication

┌─────────────┐
│   Client    │
└──────┬──────┘
       │ HTTP/WS
       ▼
┌─────────────────┐      ┌──────────────┐
│   API Server    │◄────►│  Database    │
│  (Actix-web)    │      │ (PostgreSQL) │
└────────┬────────┘      └──────────────┘
         │
         │ RPC
         ▼
┌─────────────────┐
│  Solana RPC     │
│  (Local/Remote) │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Vault Program  │◄────►┌──────────────┐
│  (On-Chain)     │ CPI  │ SPL Token    │
└─────────────────┘      │ Program      │
                         └──────────────┘

Summary

This architecture provides:

✅ Scalability: PDA-based design supports unlimited vaults
✅ Security: Multi-layer validation and authorization
✅ Efficiency: Caching and optimized queries
✅ Reliability: Atomic operations and reconciliation
✅ Transparency: Complete audit trail

The system separates concerns cleanly:

  • On-chain: State and critical operations
  • Off-chain: Analytics, history, and API layer
  • Database: Performance and complex queries