Skip to content

Latest commit

 

History

History
447 lines (359 loc) · 15.7 KB

File metadata and controls

447 lines (359 loc) · 15.7 KB

Stellar Local — Architecture

This document describes the technical architecture of Stellar Local.


System Overview

┌─────────────────────────────────────────────────────────────┐
│                      CLIENT LAYER                           │
│  ┌──────────────┐          ┌──────────────┐                │
│  │  Web App     │          │ Mobile App   │                │
│  │  (Next.js)   │          │ (React Native│                │
│  └──────────────┘          └──────────────┘                │
└─────────────────────────────────────────────────────────────┘
                          │
                          │ HTTPS/WSS
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                   APPLICATION LAYER                         │
│                                                             │
│  ┌──────────────────────────────────────────────────────┐  │
│  │              API Gateway (Port 4000)                  │  │
│  │  - Request routing                                    │  │
│  │  - Authentication & Authorization                     │  │
│  │  - Rate limiting                                      │  │
│  └──────────────────────────────────────────────────────┘  │
│                          │                                  │
│     ┌────────────────────┼────────────────────┐            │
│     │                    │                    │            │
│     ▼                    ▼                    ▼            │
│  ┌──────┐          ┌──────┐          ┌──────────┐         │
│  │Market│          │ Fund │          │Community │         │
│  │place │          │Service          │  Service │         │
│  │:3001 │          │:3002 │          │  :3006   │         │
│  └──────┘          └──────┘          └──────────┘         │
│                                                             │
└─────────────────────────────────────────────────────────────┘
                          │
                          │ Contract Calls
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                   SMART CONTRACT LAYER                      │
│                                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐     │
│  │  Membership  │  │ Marketplace  │  │ Community    │     │
│  │  Contract    │  │  Contract    │  │ Fund         │     │
│  │              │  │              │  │ Contract     │     │
│  │ - Register   │  │ - Listings   │  │ - Deposits   │     │
│  │ - Verify     │  │ - Purchases  │  │ - Payments   │     │
│  │ - Manage     │  │ - Escrow     │  │ - Governance │     │
│  └──────────────┘  └──────────────┘  └──────────────┘     │
│                                                             │
│                    Soroban Runtime                          │
└─────────────────────────────────────────────────────────────┘
                          │
                          │ Transactions
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                   SETTLEMENT LAYER                          │
│                                                             │
│                     Stellar Network                         │
│                                                             │
│  - Payment processing                                       │
│  - Account management                                       │
│  - Asset transfers                                          │
│  - 3-5 second finality                                      │
│  - Sub-cent transaction fees                                │
│                                                             │
└─────────────────────────────────────────────────────────────┘
                          │
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                      DATA LAYER                             │
│                                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐     │
│  │  PostgreSQL  │  │   MongoDB    │  │    Redis     │     │
│  │              │  │              │  │              │     │
│  │ - Users      │  │ - Logs       │  │ - Sessions   │     │
│  │ - Listings   │  │ - Analytics  │  │ - Cache      │     │
│  │ - Orders     │  │ - Events     │  │ - Queues     │     │
│  └──────────────┘  └──────────────┘  └──────────────┘     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Layer Descriptions

1. Client Layer

Purpose: User interfaces for web and mobile

Components:

  • Web App (Next.js) — Desktop browser interface
  • Mobile App (React Native) — iOS/Android native app

Responsibilities:

  • Render UI
  • Handle user interactions
  • Connect Stellar wallets (Freighter, Albedo)
  • Sign transactions
  • Display real-time updates via WebSocket

2. Application Layer

Purpose: Business logic, API handling, and orchestration

API Gateway (Port 4000)

  • Routes requests to appropriate microservices
  • JWT-based authentication
  • Rate limiting and request validation
  • WebSocket connections for real-time updates

Microservices

Service Port Purpose
Marketplace 3001 Listing management, search, orders
Community Fund 3002 Fund deposits, payments, balance tracking
Resource Sharing 3003 Resource bookings, availability
Mutual Aid 3004 Aid requests, donations
Governance 3005 Proposals, voting
Reputation 3006 Trust scoring, event tracking

Tech Stack:

  • Node.js + Express
  • TypeScript
  • PostgreSQL (primary data)
  • MongoDB (logs/analytics)
  • Redis (sessions/cache)

3. Smart Contract Layer (Soroban)

Purpose: On-chain programmable logic for community rules

Membership Contract

pub trait MembershipContract {
    fn initialize(env: Env, admin: Address) -> Result<(), Error>;
    fn add_member(env: Env, admin: Address, member: Address) -> Result<(), Error>;
    fn is_member(env: Env, member: Address) -> bool;
    fn remove_member(env: Env, admin: Address, member: Address) -> Result<(), Error>;
}

Responsibilities:

  • Register communities
  • Add/remove members
  • Verify membership status
  • Manage community admins

Marketplace Contract

pub trait MarketplaceContract {
    fn create_listing(env: Env, seller: Address, title: String, price: i128) -> u32;
    fn get_listing(env: Env, listing_id: u32) -> Listing;
    fn purchase(env: Env, buyer: Address, listing_id: u32) -> Result<(), Error>;
    fn deactivate_listing(env: Env, seller: Address, listing_id: u32) -> Result<(), Error>;
}

Responsibilities:

  • Create and manage listings
  • Handle purchases
  • Escrow payments (future)
  • Enforce marketplace rules

Community Fund Contract

pub trait CommunityFundContract {
    fn initialize(env: Env, admin: Address, token: Address) -> Result<(), Error>;
    fn deposit(env: Env, contributor: Address, amount: i128) -> Result<(), Error>;
    fn get_balance(env: Env) -> i128;
    fn propose_payment(env: Env, admin: Address, recipient: Address, amount: i128, purpose: String) -> u32;
    fn execute_payment(env: Env, admin: Address, proposal_id: u32) -> Result<(), Error>;
}

Responsibilities:

  • Accept community contributions
  • Track fund balance
  • Propose payments
  • Execute approved disbursements
  • Transparent fund management

4. Settlement Layer (Stellar Network)

Purpose: Payment settlement and asset management

Stellar provides:

  • Fast settlement — 3-5 second transaction finality
  • Low cost — Fraction of a cent per transaction
  • Native assets — XLM and custom tokens
  • Account system — Public/private key pairs
  • Operations — Payments, trustlines, account management

Stellar SDK Usage:

import { Horizon, Keypair, TransactionBuilder, Operation, Asset } from '@stellar/stellar-sdk';

// Send payment
const payment = await sendPayment({
  fromSecretKey: sellerSecret,
  toPublicKey: buyerPublicKey,
  amount: "100",
  asset: Asset.native(),
  memo: `order:${orderId}`
});

5. Data Layer

Purpose: Off-chain data storage

PostgreSQL

  • Primary database for structured data
  • Users, communities, listings, orders, funds
  • ACID transactions
  • Relational queries

MongoDB

  • Secondary database for unstructured data
  • Event logs
  • Analytics
  • Audit trails

Redis

  • In-memory cache
  • User sessions
  • Rate limit counters
  • Real-time pub/sub

Data Flow Examples

Example 1: User Purchases a Listing

1. User clicks "Buy" on frontend
   ↓
2. Frontend calls API Gateway: POST /marketplace/orders
   ↓
3. API Gateway authenticates request, forwards to Marketplace Service
   ↓
4. Marketplace Service:
   a. Validates listing exists and is active
   b. Checks buyer membership via Membership Contract
   c. Creates order record in PostgreSQL
   ↓
5. Marketplace Service calls Marketplace Contract: purchase(buyer, listing_id)
   ↓
6. Marketplace Contract:
   a. Verifies buyer authorization
   b. Marks listing as sold
   c. Emits purchase event
   ↓
7. Stellar payment triggered:
   a. Frontend signs Stellar transaction
   b. Payment sent from buyer → seller
   c. Transaction hash recorded
   ↓
8. Order status updated to "paid"
   ↓
9. Reputation Service increases seller's score
   ↓
10. WebSocket pushes update to frontend
   ↓
11. Frontend displays success

Example 2: Community Fund Contribution

1. User contributes to fund on frontend
   ↓
2. Frontend calls API: POST /funds/contributions
   ↓
3. Community Fund Service validates request
   ↓
4. User signs Stellar payment transaction
   ↓
5. Payment sent to community fund account
   ↓
6. Community Fund Contract: deposit(contributor, amount)
   ↓
7. Contract updates fund balance
   ↓
8. Contribution recorded in PostgreSQL
   ↓
9. Reputation Service credits contributor
   ↓
10. Frontend displays updated fund balance

Security Architecture

Authentication & Authorization

  • JWT tokens for API authentication
  • Stellar wallet signatures for transaction authorization
  • Smart contract checks for membership verification
  • Role-based access control (RBAC) for admin actions

Contract Security

  • Authorization checks on all state-changing functions
  • Input validation for all parameters
  • Reentrancy protection where applicable
  • Event emission for transparency
  • Comprehensive test coverage

API Security

  • HTTPS only
  • Rate limiting per IP/user
  • Input sanitization
  • SQL injection prevention (parameterized queries)
  • CORS configuration
  • Helmet.js security headers

Scalability Considerations

Horizontal Scaling

  • Microservices can scale independently
  • Stateless services enable load balancing
  • Redis for distributed sessions
  • Message queues for async processing (future)

Database Optimization

  • Read replicas for PostgreSQL
  • Connection pooling
  • Indexed queries
  • Caching layer (Redis)

Contract Optimization

  • Efficient data structures in Soroban
  • Minimal storage usage
  • Gas optimization (future Stellar fees)

Monitoring & Observability

Logging

  • Structured logs (JSON format)
  • Centralized logging (ELK stack or similar)
  • Log levels (debug, info, warn, error)

Metrics

  • API response times
  • Contract call success rates
  • Database query performance
  • User activity metrics

Alerting

  • Service health checks
  • Error rate thresholds
  • Database connection failures
  • Contract call failures

Deployment Architecture

Development

  • Local Docker Compose stack
  • Hot reload for all services
  • Testnet Stellar network
  • Local databases

Staging

  • Kubernetes cluster
  • Separate namespace
  • Testnet Stellar network
  • Managed databases (AWS RDS)
  • CI/CD automated deployment

Production

  • Kubernetes cluster (multi-zone)
  • Mainnet Stellar network
  • Managed databases with backups
  • CDN for static assets
  • Load balancers
  • Auto-scaling enabled

Technology Stack Summary

Layer Technologies
Frontend Next.js 14, React 18, TypeScript, Tailwind CSS
Backend Node.js 20, Express, TypeScript
Smart Contracts Rust, Soroban SDK
Blockchain Stellar Network, Soroban Runtime
Databases PostgreSQL 16, MongoDB 7, Redis 7
Infrastructure Docker, Kubernetes, Terraform
CI/CD GitHub Actions
Monitoring (TBD - Prometheus, Grafana, ELK)

Future Architecture Enhancements

  • GraphQL API for flexible queries
  • Event-driven architecture with message queues
  • Caching layer with CDN
  • Multi-region deployment
  • Advanced analytics with data warehouse
  • Machine learning for reputation scoring

For implementation details, see: