← Back to Main Documentation

Architecture Documentation

This directory contains comprehensive documentation of the Plings system architecture, covering everything from high-level system design to detailed technical implementation decisions.

Contents

System Design

Revolutionary Payment Architecture

  • Solana Payment Architecture - Complete blockchain integration for direct object payments
    • Payment-to-object system design
    • HD wallet → Solana address mapping
    • Service marketplace infrastructure
    • Global payment scale analysis

Technical Implementation

Security & Guidelines

Migration Documentation

Overview

The Plings architecture represents a revolutionary approach to physical object commerce, transforming every physical item into an autonomous economic endpoint through blockchain integration and HD wallet infrastructure.

Core Architectural Principles

Objects as Economic Agents

  • Every physical object can receive payments via Solana blockchain
  • Instance keys are native Solana addresses enabling instant ownership transfer
  • Objects participate in global economy as first-class citizens

HD Wallet Infrastructure Foundation

  • Critical Choice: HD wallets instead of PKI specifically to enable financial transactions
  • Hierarchical paths map directly to Solana addresses (m/44’/501’/manufacturer/category/instance)
  • Program Derived Addresses (PDAs) secure payment routing while preserving manufacturer verification

Infrastructure Elimination

  • No POS systems, card readers, or payment terminals needed
  • Objects sell themselves with just QR codes/NFC tags
  • Same system scales from $1 candy bars to $50M corporate jets

Multi-Layer System Architecture

Three-Tier Platform Structure

The Plings ecosystem operates as three coordinated layers:

  1. Frontend Layer (React + TypeScript PWA)
    • Repository: Plings-Lovable-Frontend
    • URL: https://plings.io
    • Purpose: User interface for scanning, commerce, and object management
    • Future: Task-specific mobile applications
  2. Director Layer (Traffic Routing)
    • URL: https://s.plings.io
    • Purpose: Universal QR code entry point and routing service
    • Function: Directs scans to appropriate frontend applications
  3. Backend Layer (FastAPI + GraphQL)
    • Repository: Plings-Backend
    • URL: https://api.plings.io
    • Purpose: Core business logic, database coordination, blockchain integration
    • API: Single GraphQL endpoint for all frontend data needs

Dual Database System

  • PostgreSQL/Supabase: User authentication, object metadata, RLS security, business logic
  • Neo4j: Complex relationship traversal, variable-depth queries, graph analytics
  • Separation of Concerns: Business data vs. relationship data

GraphQL API Integration

  • Single Endpoint: https://api.plings.io/graphql
  • Technology: Ariadne GraphQL over FastAPI
  • Features: Object operations, relationship management, HD wallet integration
  • Security: JWT-based authentication with Supabase RLS

Blockchain Integration

  • Solana: Ultra-low fees ($0.00025), 400ms confirmation, 600K TPS with Firedancer
  • Program Derived Addresses: Prevent payment interception while preserving HD wallet benefits
  • NFT Ownership: Dynamic ownership transfer through blockchain-native certificates

Service Marketplace

  • Every object becomes a hub for rental, repair, insurance services
  • Multi-transaction economy beyond simple buy/sell
  • Provider registration and reputation system

Key Innovations

  1. Payment Interception Prevention: PDAs prevent manufacturers from stealing object payments
  2. Offline + Online Verification: HD wallets enable cryptographic verification without network
  3. Universal Commerce Scale: $0.00025 Solana fees enable transactions at any price point
  4. Graph + Relational Hybrid: Leverages strengths of both database paradigms

Security Model: Verification Authority

Fundamental Security Design: Controlled Verification

Critical Architectural Decision: The Plings system uses hardened HD wallet derivation at all levels, which creates an intentional verification authority model where only specific parties can cryptographically verify identifiers.

Who Can Verify What

Verification Authority Hierarchy:

Plings (Master Authority)
├── Authority: Master key at m/44'/501'/1'
├── Can Verify: Everything in ecosystem  
├── Role: Neutral verification service
└── Trust: Ecosystem coordinator

Manufacturers (Brand Authorities)
├── Authority: Brand-level keys (e.g., m/44'/501'/1'/3' for Coca-Cola)
├── Can Verify: Only their own products
├── Role: Brand authenticity experts  
└── Trust: Self-verification for their products

External Clients (No Authority)
├── Authority: None (by design)
├── Can Verify: Nothing independently
├── Role: Verification consumers
└── Trust: Must rely on authorized authorities

Why External Clients Cannot Verify Independently

Hardened Key Requirement:

Example Path: 1.3.1255.C2.5847.90000
HD Derivation: m/44'/501'/1'/3'/1255'/2'/5847'/90000'
               └──────────────────────────────────────┘
                ALL HARDENED - requires private keys

Missing Keys: External clients lack:

  • Plings master private key
  • Manufacturer private keys
  • Plant-level private keys
  • Batch-level private keys

Result: Cannot perform cryptographic verification independently.

Trust Network Architecture

Verification Flow Design

graph TD A[User Scans Object] --> B[Client App] B --> C{Network Available?} C -->|Yes| D[Request Verification] C -->|No| E[Show Limited Info] D --> F[Plings API] D --> G[Manufacturer API] F --> H[Cryptographic Verification] G --> I[Brand Verification] H --> J[Return Attestation] I --> J J --> K[Display Verified Result] E --> L[Path Parsing Only] L --> M[Basic Manufacturer Info]

Security Benefits of Authority Model

Controlled Brand Verification:

  • Prevents Unauthorized Claims: External parties cannot forge verification results
  • Manufacturer Control: Brands maintain authority over product authentication
  • Trusted Network: Creates reliable ecosystem of verification authorities
  • Anti-Counterfeiting: Cryptographically impossible to fake verification without keys

System Integrity:

  • Authority Accountability: Verification sources are known and accountable
  • Network Trust: Users trust established authorities rather than unknown validators
  • Audit Trail: All verifications logged and traceable
  • Reputation Stakes: Authorities stake reputation on verification accuracy

Implementation Implications

For Backend Architecture:

  • Verification APIs: Provide verification-as-a-service to clients
  • Key Security: Implement multi-tier key management (Vercel → SoftHSM → Hardware HSM)
  • Authority Management: Track and manage verification authority relationships
  • Cross-Verification: Enable multiple authority confirmation for high-value items

For Frontend Architecture:

  • API Integration: Always use verification APIs, never attempt independent verification
  • Trust Indicators: Show verification sources clearly to users
  • Offline Handling: Graceful degradation when verification unavailable
  • Error States: Handle verification failures and network issues appropriately

For Client Applications:

// Correct approach - use verification authorities
async function verifyProduct(path, instanceKey) {
    const verification = await fetch('/api/verify', {
        method: 'POST',
        body: JSON.stringify({ path, instanceKey })
    });
    return verification.json();
}

// ❌ INCORRECT - clients cannot verify independently
function attemptLocalVerification(path, instanceKey) {
    // This cannot work - requires private keys
    return cryptoVerify(path, instanceKey); 
}

Security vs Decentralization Trade-off

Why Centralized Verification Is Intentional

Alternative Considered: Fully decentralized verification where anyone could verify Problem: Would undermine manufacturer brand control and enable verification chaos Solution: Controlled authority model that balances security with manufacturer needs

Benefits of Authority Model:

  • Brand Protection: Manufacturers control their authentication narrative
  • Quality Assurance: Verification results come from accountable sources
  • Business Model: Enables verification services as value proposition
  • Trust Building: Users know who they’re trusting

Threat Model and Mitigations

Potential Attack Vectors

Authority Compromise:

  • Risk: Plings or manufacturer keys compromised
  • Mitigation: Multi-tier key storage, HSM protection, incident response procedures

False Verification:

  • Risk: Malicious verification responses
  • Mitigation: Cross-verification, audit trails, reputation systems

Network Attacks:

  • Risk: Man-in-the-middle attacks on verification APIs
  • Mitigation: TLS encryption, certificate pinning, API authentication

Social Engineering:

  • Risk: Users trust fake verification sources
  • Mitigation: Clear authority indicators, education, official app channels

Defense in Depth

Layer 1: Cryptographic verification by authorities Layer 2: Cross-verification between multiple authorities Layer 3: Audit trails and anomaly detection Layer 4: User education and trust indicators Layer 5: Incident response and key rotation procedures

Development Strategy for New Developers

Understanding Our Backend Architecture

Key Insight: Plings uses a sophisticated multi-layer architecture with clear separation of concerns:

API Strategy

  • Single GraphQL Endpoint: All frontend data needs served through api.plings.io/graphql
  • No REST APIs: GraphQL provides type-safe, efficient data fetching
  • Interactive Documentation: GraphiQL explorer available at the endpoint
  • JWT Authentication: Secure user sessions with Supabase integration

Repository Structure

  • Frontend Repository: Plings-Lovable-Frontend (React + TypeScript)
  • Backend Repository: Plings-Backend (FastAPI + GraphQL + Python)
  • Cross-Repository Development: Claude Code coordinates full-stack features

Development Flow

  1. Frontend Development: Query GraphQL API for all data operations
  2. Backend Development: Implement business logic in FastAPI GraphQL resolvers
  3. Database Operations: Use PostgreSQL for security/metadata, Neo4j for relationships
  4. Blockchain Integration: Solana operations abstracted through GraphQL mutations

For Frontend Developers

The architecture enables revolutionary commerce features:

  1. Scan-to-Pay: Instant object purchase through QR code scanning
  2. Service Discovery: Find rental, repair, insurance for any object
  3. Real-time Ownership: Live blockchain-based ownership updates
  4. Offline Verification: Authenticate objects without network connectivity
  5. Payment Integration: Seamless Solana wallet integration
  6. GraphQL Integration: Type-safe data fetching with automatic caching

Key Integration Points:

  • API Endpoint: https://api.plings.io/graphql
  • Authentication: JWT tokens from Supabase auth
  • Real-time Updates: GraphQL subscriptions for live data
  • Error Handling: Standardized GraphQL error responses

For Backend Developers

Architecture requires careful implementation of:

  1. HD Wallet Security: Multi-tier key management (Vercel → SoftHSM → Hardware HSM)
  2. Dual Database Sync: Maintain consistency between PostgreSQL and Neo4j
  3. Blockchain Integration: Solana program development and PDA management
  4. Payment Routing: Secure transaction flow through smart contracts
  5. Service Orchestration: Marketplace provider coordination
  6. GraphQL Schema: Type-safe API design with Ariadne

Key Implementation Areas:

  • FastAPI Setup: Serverless deployment on Vercel
  • Database Coordination: Ensure PostgreSQL and Neo4j consistency
  • Cryptographic Operations: HD wallet path generation and verification
  • Blockchain Abstraction: Hide Solana complexity behind GraphQL mutations

Integration Points

Architecture integrates with:

  • Blockchain Layer: Solana validators and smart contracts
  • Payment Systems: Multi-wallet support and transaction processing
  • GraphQL Schema: Unified API for complex architecture
  • HD Wallet System: Cryptographic verification and key management
  • Service Providers: External rental, repair, insurance services

Revolutionary Impact

Global Commerce Transformation

Vision: Replace Visa/Mastercard by making every physical object a payment terminal Path: Build through niche use cases → expand to universal commerce infrastructure Timeline: 5-10 years to global payment infrastructure significance

Market Disruption Potential

  • Total Addressable Market: $100B+ POS terminals + $200B+ payment processing
  • Competitive Advantage: First system enabling direct object payments
  • Network Effects: Every object strengthens the ecosystem
  • Infrastructure Lock-in: Replaces traditional payment systems

Status Legend

  • Complete - Fully documented and implemented
  • 🏗️ In Progress - Documentation exists, implementation ongoing
  • 📋 Stub - Outlined structure, content to follow
  • 🔄 Migration - Legacy system being updated

Detailed Technical Architecture

Core Components Layer Architecture

Layer Function Technologies
Object Metadata Stores basic identity, type, properties PostgreSQL (e.g., Supabase)
Graph Engine Tracks semantic and structural relationships Neo4j Aura
Vector Search Enables semantic matching and similarity search Qdrant
Embedding Generator Transforms text/images into vector space OpenAI / HuggingFace / CLIP
Geospatial Data Handles physical containment and geolocation PostGIS + Graph
External Integrations Data from marketplaces, manufacturers, catalogs API connectors

Architectural Rationale: Why a Dual-Database System?

The Plings architecture intentionally uses a polyglot persistence model, leveraging two different types of databases to handle specific tasks for which they are best suited. This design is a deliberate choice to maximize security, performance, and scalability.

1. Neo4j Aura (The Graph Engine):

  • Purpose: To manage the complex, interconnected web of relationships between objects.
  • Strengths: Its graph-native structure is ideal for deep, variable-depth queries, such as traversing component hierarchies (PART_OF), class structures (SUBCLASS_OF), and intricate spatial relationships (IN, ON). It answers the question: “How are things connected?”

2. Supabase - PostgreSQL (The Ownership & Security Engine):

  • Purpose: To manage object metadata, user ownership, and enforce security.
  • Strengths: Its primary role is to leverage Supabase’s powerful Row-Level Security (RLS) engine, which is tightly integrated with user authentication (auth.uid()). This provides a robust, declarative security model that is difficult and inefficient to replicate in a graph database. It answers the question: “Who owns this and who is allowed to see it?”
  • UI Performance Cache: The data in Postgres also serves as a highly performant cache for the UI. When displaying a simple list of a user’s objects, querying the relational object_instances table is significantly faster and more efficient than performing a broad graph traversal.

In summary, the system is designed so that Neo4j manages the graph’s complexity, while Supabase manages the users’ security. The unified ID system provides the critical link between these two specialized systems.

Object Model

ObjectClass and ObjectInstance

The UOGS distinguishes between an object’s blueprint (ObjectClass) and its physical manifestation (ObjectInstance). In Neo4j, these are represented as nodes with labels and properties.

ObjectClass (The Template Node): A node with the label :ObjectClass.

{
  "name": "Mountain Bike",
  "description": "A bicycle designed for off-road cycling.",
  "version": 1,
  "owner": "Plings",
  "capabilities": ["off-road", "sport"]
}

ObjectInstance (The Physical Item Node): A node with the label :ObjectInstance.

{
  "owner": "user:123"
}

PlingsIdentifier (The Pointer Node): A node with the label :PlingsIdentifier.

{
    "value": "plg:44-10012-22-7890-Qmx3D",
    "identifier_type": "QR",
    "status": "active"
}

Key Graph Relations

Relationships in Neo4j are first-class citizens, connecting nodes directly with a specific type.

  • Spatial (e.g., IN): A direct relationship between two ObjectInstance nodes.
    • (:ObjectInstance {name: 'MyBike'})-[:IN]->(:ObjectInstance {name: 'HomeGarage'})
  • Expected Spatial (e.g., SHOULD_BE_IN): The object’s assigned or “home” location.
    • (:ObjectInstance {name: 'MyBike'})-[:SHOULD_BE_IN]->(:ObjectInstance {name: 'WorkshopShelf3'})
  • Identifies: A PlingsIdentifier node IDENTIFIES an ObjectInstance node.
    • (:PlingsIdentifier {value: '...'})-[:IDENTIFIES]->(:ObjectInstance {name: 'MyBike'})
  • Instance Of: An ObjectInstance node is an INSTANCE_OF an ObjectClass node.
    • (:ObjectInstance {name: 'MyBike'})-[:INSTANCE_OF]->(:ObjectClass {name: 'Mountain Bike'})
  • Scan Event: A ScanEvent node records the interaction, linked to an identifier.
    • (:ScanEvent)-[:SCANNED]->(:PlingsIdentifier)
  • Part Of: An ObjectInstance can be PART_OF another ObjectInstance.
    • (:ObjectInstance {name: 'MySaddle'})-[:PART_OF]->(:ObjectInstance {name: 'MyBike'})
  • Subclass Of: An ObjectClass can be a SUBCLASS_OF another ObjectClass.
    • (:ObjectClass {name: 'Mountain Bike'})-[:SUBCLASS_OF]->(:ObjectClass {name: 'Bicycle'})
  • Capabilities: An object’s potential uses are stored as properties on the ObjectClass node.
    • (:ObjectClass {name: 'Lamp'}) has property capabilities: ["BikeLamp", "HelmetLamp"]

For detailed schema information, see ../database/neo4j-core-schema.md.