Skip to main content

StateSet iCommerce: Infrastructure for Autonomous Commerce

A Technical Paper on Embedded, Verifiable Commerce Systems for AI Agents

Abstract

StateSet iCommerce is a comprehensive infrastructure stack enabling autonomous AI agents to conduct commerce operations with cryptographic verifiability. The system comprises five integrated components: (1) an embedded commerce engine providing 700+ API methods across 32 commerce domains, compiled to 10 language runtimes; (2) a distributed event sequencer implementing Verifiable Event Sync (VES) with Merkle commitments and end-to-end encryption; (3) Set Chain, an Ethereum Layer-2 optimistic rollup for on-chain settlement and proof verification; (4) the x402 HTTP-native payment protocol for stablecoin micropayments between AI agents; and (5) a multi-channel messaging gateway connecting commerce agents to 9 communication platforms. This paper presents the architecture, implementation details, and design rationale for building commerce infrastructure where AI agents are first-class participants in economic transactions. Keywords: embedded databases, event sourcing, AI agents, commerce, blockchain, Merkle trees, optimistic rollups, MCP, x402, vector search, messaging gateway

1. Introduction

1.1 The Problem

Traditional commerce platforms were designed for human operators accessing centralized services via network APIs. This architecture introduces several limitations for autonomous AI agents:
  1. Latency: Network round-trips add 50-500ms per operation
  2. Availability: Agents cannot operate without network connectivity
  3. Auditability: No cryptographic proof that operations occurred correctly
  4. Cost: Per-API-call pricing creates unpredictable marginal costs
  5. Trust: Agents must trust centralized providers for data integrity
  6. Payments: No native mechanism for agent-to-agent economic settlement
  7. Communication: No unified channel for agent-customer interaction across platforms
As AI agents increasingly participate in economic activity—managing inventory, processing orders, coordinating supply chains, handling customer service across messaging platforms—these limitations become critical barriers.

1.2 Our Contribution

We present StateSet iCommerce, a five-layer infrastructure stack addressing these challenges:
LayerComponentFunction
Computestateset-embeddedIn-process commerce engine
Coordinationstateset-sequencerDistributed event ordering
SettlementSet Chain (L2)On-chain verification
Paymentsx402 ProtocolHTTP-native stablecoin payments
CommunicationMessaging Gateway9-channel agent interaction
The system enables:
  • Offline-first operation: Complete commerce functionality without network
  • Cryptographic verifiability: Merkle proofs for any transaction
  • Multi-agent coordination: Deterministic ordering across distributed agents with end-to-end encryption
  • Settlement finality: Ethereum-backed proof anchoring
  • Native payments: Stablecoin micropayments via HTTP 402
  • Omnichannel presence: AI agents operating across WhatsApp, Telegram, Discord, Slack, and more
  • Semantic search: Hybrid vector + BM25 search across all commerce entities
  • Voice interaction: Speech-to-text and text-to-speech for conversational commerce

1.3 Paper Organization

Section 2 describes the embedded commerce engine architecture. Section 3 details the Verifiable Event Sync protocol. Section 4 presents Set Chain and on-chain settlement. Section 5 introduces the x402 payment protocol. Section 6 discusses the Model Context Protocol integration for AI agents. Section 7 covers the multi-channel messaging gateway. Section 8 presents operational infrastructure including heartbeat monitoring, permission sandboxing, and persistent memory. Section 9 evaluates performance and security properties. Section 10 surveys related work, and Section 11 concludes.

2. Embedded Commerce Engine

2.1 Design Philosophy

The embedded commerce engine follows the SQLite model: a library that runs in the application’s process, storing state in a local file with zero external dependencies. This architecture provides:
  • Deterministic execution: Same inputs always produce identical outputs
  • Portable state: Single file contains complete operational data
  • Zero marginal cost: No per-operation pricing
  • Instant availability: No network connection required

2.2 System Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                      stateset-icommerce                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   ┌─────────────────┐                                               │
│   │  stateset-core  │  Pure domain models (400+ types)              │
│   │   ~45,000 LOC   │  Zero I/O dependencies                       │
│   └────────┬────────┘  Business logic, traits, metrics              │
│            │                                                        │
│            ▼                                                        │
│   ┌─────────────────┐                                               │
│   │   stateset-db   │  Database abstraction layer                   │
│   │   ~55,000 LOC   │  SQLite + PostgreSQL backends                 │
│   └────────┬────────┘  70+ tables, 28 migrations                    │
│            │                                                        │
│            ▼                                                        │
│   ┌─────────────────┐                                               │
│   │stateset-embedded│  Unified high-level API                       │
│   │   ~39,000 LOC   │  700+ public methods                         │
│   └────────┬────────┘  Sync + Async, event emission, transactions   │
│            │                                                        │
├────────────┼────────────────────────────────────────────────────────┤
│            ▼                                                        │
│   ┌─────────────────────────────────────────────────────────────┐   │
│   │                    Language Bindings (10)                    │   │
│   │  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐   │   │
│   │  │Node.js │ │ Python │ │  WASM  │ │  Ruby  │ │  PHP   │   │   │
│   │  │ (NAPI) │ │ (PyO3) │ │(wasm)  │ │(Magnus)│ │(ext-rs)│   │   │
│   │  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘   │   │
│   │  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐   │   │
│   │  │  Java  │ │ Kotlin │ │ Swift  │ │  .NET  │ │   Go   │   │   │
│   │  │ (JNI)  │ │ (JNI)  │ │ (FFI)  │ │(P/Inv) │ │ (cgo)  │   │   │
│   │  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘   │   │
│   └─────────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────────┘

2.3 Domain Model

The core domain consists of 32 modules covering complete commerce and back-office operations: Commerce Operations:
ModuleEntitiesKey Operations
CustomersCustomer, AddressCRUD, profile management
ProductsProduct, Variant, AttributeCatalog, pricing, inventory links
InventoryItem, Balance, ReservationMulti-location tracking, reservations
OrdersOrder, OrderItem, StatusFull lifecycle, fulfillment
CartsCart, CartItemShopping, checkout flow
PaymentsPayment, Refund, MethodMulti-method processing
ReturnsReturn, ReturnItem, RMAReturn authorization workflow
ShipmentsShipment, Event, TrackingCarrier integration
PromotionsPromotion, Coupon, RuleDiscounts, BOGO, tiered
SubscriptionsPlan, Subscription, CycleRecurring billing
Supply Chain & Warehouse:
ModuleEntitiesKey Operations
WarehouseWarehouse, Zone, LocationLocation hierarchy, bin management
ReceivingReceipt, ReceiptItem, PutAwayInbound goods, put-away tracking
FulfillmentWave, PickTask, PackTask, ShipTaskPick/pack/ship workflow
Lot TrackingLot, LotCertificate, LotTransactionTraceability, COA/COC management
Serial NumbersSerialNumber, SerialHistoryUnit-level tracking, warranty lookup
BackordersBackorder, Allocation, FulfillmentPriority queuing, allocation
ManufacturingBOM, WorkOrder, TaskBill of materials
Purchase OrdersPO, SupplierProcurement
QualityInspection, NCR, QualityHold, DefectCodeMulti-stage QC, non-conformance
Financial:
ModuleEntitiesKey Operations
General LedgerGlAccount, JournalEntry, GlPeriodDouble-entry, auto-posting, trial balance
Accounts ReceivableCreditMemo, WriteOff, CollectionActivityAR aging, statements, collections
Accounts PayableBill, BillPayment, PaymentRunAP aging, payment scheduling
InvoicesInvoice, Item, ARAccounts receivable
Cost AccountingCostLayer, CostAdjustment, CostVarianceFIFO/LIFO/weighted average, valuation
CreditCreditAccount, CreditApplication, CreditHoldCredit review, risk rating
TaxJurisdiction, Rate, ExemptionUS/EU/CA multi-jurisdiction
CurrencyExchangeRate, Money35+ currencies
Platform:
ModuleEntitiesKey Operations
x402PaymentIntent, PaymentReceipt, PaymentBatchHTTP-native stablecoin payments
Vector SearchVectorSearchResult, EmbeddingMetadataHybrid semantic + BM25 search
AnalyticsSummary, ForecastBusiness intelligence
WarrantiesWarranty, ClaimCoverage tracking
ForecastingForecastModel, DemandSignalDemand planning
SyncOutbox, SyncStateEvent synchronization
Total: 400+ domain types with full serde serialization.

2.4 Database Layer

The database layer provides a unified interface over multiple backends: SQLite (Embedded)
  • Zero-configuration deployment
  • Single-file state portability
  • ACID transactions via WAL mode
  • ~200μs typical query latency
  • FTS5 full-text search for BM25 ranking
  • BLOB-based vector embedding storage
PostgreSQL (Enterprise)
  • Horizontal scalability
  • Advanced query optimization
  • Point-in-time recovery
  • Connection pooling
  • True async operations via AsyncCommerce API
Schema Design Principles:
  1. Normalized core entities: Customers, products, orders
  2. Denormalized analytics: Pre-aggregated summary tables
  3. Event tables: Append-only for audit trail
  4. Version columns: Optimistic concurrency control
  5. Vector tables: Embedding storage with metadata for semantic search
  6. FTS5 tables: Full-text search indexes for BM25 ranking
Database Infrastructure:
FeatureDescription
Saga OrchestrationMulti-step distributed transactions with rollback
Backup & RestoreFull backups (VACUUM INTO), SHA256 verification, retention policies
Idempotency KeysDeduplication at the database level
Performance IndexesDedicated migration for query optimization
Parse HelpersType-safe row parsing with proper error propagation
Repository MacrosCode generation to eliminate duplicate implementations
32 Repository TraitsOne trait per domain with full CRUD + domain operations
The embedded engine supports hybrid semantic + keyword search, feature-gated behind the vector flag:
┌─────────────────────────────────────────────────────────────────────┐
│                       Hybrid Search Pipeline                         │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Query: "red running shoes under $100"                              │
│              │                                                      │
│              ├──────────────────┬───────────────────┐               │
│              ▼                  ▼                   ▼               │
│   ┌──────────────┐   ┌──────────────┐    ┌──────────────┐         │
│   │   Semantic    │   │     BM25     │    │   Filters    │         │
│   │   (Cosine)    │   │    (FTS5)    │    │  (price<100) │         │
│   │  1536-dim     │   │  Tokenized   │    │  Structured  │         │
│   └──────┬───────┘   └──────┬───────┘    └──────┬───────┘         │
│          │                  │                   │                  │
│          └──────────────────┼───────────────────┘                  │
│                             ▼                                      │
│                  ┌──────────────────┐                               │
│                  │ Reciprocal Rank  │                               │
│                  │   Fusion (RRF)   │                               │
│                  └────────┬─────────┘                               │
│                           ▼                                        │
│                    Ranked Results                                   │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
Components:
  • Embedding Service: OpenAI text-embedding-3-small (1536 dimensions) for generating vectors
  • Vector Store: Pure Rust cosine similarity computation over SQLite BLOB columns
  • BM25 Store: SQLite FTS5 full-text search for keyword relevance
  • RRF Fusion: Reciprocal Rank Fusion combines semantic and keyword scores
  • Entity Coverage: Products, customers, orders, and inventory items
API:
// Index a product for search
commerce.vector().index_product(&product_id).await?;

// Hybrid search
let results = commerce.vector().search_products("red shoes", 10).await?;

2.6 Multi-Runtime Compilation

The Rust core compiles to 10 target runtimes:
RuntimeTechnologyUse Case
Native RustDirect linkingHigh-performance backends
Node.jsNAPI-RSJavaScript/TypeScript applications
PythonPyO3 + MaturinData science, ML pipelines
Browserwasm-packClient-side applications
EdgeWASMCloudflare Workers, Vercel Edge
RubyMagnusRails applications
PHPext-php-rsLaravel/WordPress integrations
JavaJNIEnterprise JVM applications
KotlinJNIAndroid, server-side Kotlin
SwiftC FFIiOS/macOS applications
.NET/C#P/InvokeASP.NET, Unity applications
GocgoGo microservices
Each binding exposes the full 700+ method API with native type mappings.

2.7 Async Commerce API

For PostgreSQL deployments, a fully async API is provided:
// Feature-gated behind `postgres`
let commerce = AsyncCommerce::builder()
    .postgres_url("postgresql://localhost/stateset")
    .max_connections(20)
    .build()
    .await?;

let orders = commerce.orders().list(None, Some(50)).await?;
let customer = commerce.customers().get(&customer_id).await?;
The AsyncCommerce struct mirrors the synchronous Commerce API, providing AsyncOrders, AsyncCustomers, AsyncInventory, and all 32 domain accessors with true non-blocking I/O.

3. Verifiable Event Sync (VES)

3.1 Motivation

When multiple AI agents operate on commerce data—one managing inventory, another processing orders, a third handling returns—they must coordinate without central authority. VES provides:
  1. Canonical ordering: Global sequence numbers eliminate ambiguity
  2. Eventual consistency: Offline agents sync when reconnected
  3. Conflict detection: Optimistic concurrency with explicit handling
  4. Cryptographic proofs: Merkle trees enable verification
  5. End-to-end encryption: Agent-to-agent encrypted communication groups
  6. Key management: Ed25519/X25519 key generation, rotation, and registration

3.2 Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                         VES Architecture                             │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌───────────────┐     ┌───────────────┐     ┌───────────────┐     │
│  │  Agent A      │     │  Agent B      │     │  Agent C      │     │
│  │  (Orders)     │     │  (Inventory)  │     │  (Returns)    │     │
│  │  ┌─────────┐  │     │  ┌─────────┐  │     │  ┌─────────┐  │     │
│  │  │ SQLite  │  │     │  │ SQLite  │  │     │  │ SQLite  │  │     │
│  │  │ Outbox  │  │     │  │ Outbox  │  │     │  │ Outbox  │  │     │
│  │  └────┬────┘  │     │  └────┬────┘  │     │  └────┬────┘  │     │
│  │  ┌────┴────┐  │     │  ┌────┴────┐  │     │  ┌────┴────┐  │     │
│  │  │Ed25519  │  │     │  │Ed25519  │  │     │  │Ed25519  │  │     │
│  │  │Keystore │  │     │  │Keystore │  │     │  │Keystore │  │     │
│  │  └────┬────┘  │     │  └────┬────┘  │     │  └────┬────┘  │     │
│  └───────┼───────┘     └───────┼───────┘     └───────┼───────┘     │
│          │                     │                     │             │
│          └─────────────────────┼─────────────────────┘             │
│                                │                                    │
│                    Encrypted Push/Pull                              │
│                                │                                    │
│                                ▼                                    │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                    stateset-sequencer                        │   │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │   │
│  │  │   Ingest    │  │  Sequencer  │  │  Commitment Engine  │  │   │
│  │  │  (Dedup)    │──│  (Order)    │──│  (Merkle Roots)     │  │   │
│  │  └─────────────┘  └─────────────┘  └─────────────────────┘  │   │
│  │  ┌─────────────┐  ┌─────────────┐                           │   │
│  │  │Key Registry │  │  Encryption │                           │   │
│  │  │ (Ed25519)   │  │   Groups    │                           │   │
│  │  └─────────────┘  └─────────────┘                           │   │
│  │                          │                    │              │   │
│  │                          ▼                    ▼              │   │
│  │  ┌─────────────────────────────────────────────────────┐    │   │
│  │  │              PostgreSQL Event Store                  │    │   │
│  │  │  events │ sequence_counters │ commitments            │    │   │
│  │  └─────────────────────────────────────────────────────┘    │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

3.3 Event Envelope

Every operation emits an event envelope:
pub struct EventEnvelope {
    // Identity
    pub event_id: Uuid,           // Global idempotency key
    pub command_id: Option<Uuid>, // Intent-level deduplication

    // Routing
    pub tenant_id: TenantId,      // Organization isolation
    pub store_id: StoreId,        // Store within tenant

    // Classification
    pub entity_type: EntityType,  // order, product, inventory...
    pub entity_id: String,        // Entity identifier
    pub event_type: EventType,    // order.created, inventory.adjusted...

    // Payload
    pub payload: serde_json::Value, // JSON event data
    pub payload_hash: Hash256,      // SHA-256 of canonical JSON

    // Ordering
    pub base_version: Option<u64>,  // OCC version at authoring
    pub sequence_number: Option<u64>, // Assigned by sequencer

    // Provenance
    pub created_at: DateTime<Utc>,
    pub source_agent: AgentId,
    pub signature: Option<Vec<u8>>,
}

3.4 Sequencing Algorithm

The sequencer assigns canonical sequence numbers:
Algorithm: EventSequencing
Input: EventBatch from agent
Output: IngestReceipt with assigned sequences

1. DEDUPLICATION
   for each event in batch:
     if event.event_id exists in events table:
       reject as DuplicateEventId
     if event.command_id exists in events table:
       reject as DuplicateCommandId

2. VALIDATION
   for each event in batch:
     computed_hash = SHA256(canonical_json(event.payload))
     if computed_hash != event.payload_hash:
       reject as InvalidPayloadHash
     validate schema for event.entity_type, event.event_type

3. SEQUENCE ALLOCATION (atomic)
   count = batch.events.length
   (start, end) = UPDATE sequence_counters
                  SET current_sequence = current_sequence + count
                  WHERE tenant_id = ? AND store_id = ?
                  RETURNING current_sequence - count, current_sequence - 1

4. STORAGE (atomic)
   for i, event in enumerate(batch.events):
     event.sequence_number = start + i
     INSERT INTO events (event)
       ON CONFLICT (event_id) DO NOTHING

5. RETURN IngestReceipt {
     batch_id: new_uuid(),
     events_accepted: count - rejected_count,
     assigned_sequence_start: start,
     assigned_sequence_end: end,
     head_sequence: end
   }

3.5 Merkle Commitment

Events are batched into Merkle trees for cryptographic commitment:
Merkle Tree Construction:

                    Root Hash
                   /         \
                  /           \
             H(01)             H(23)
            /     \           /     \
         H(0)     H(1)     H(2)     H(3)
          |        |        |        |
        Leaf0   Leaf1    Leaf2    Leaf3

Leaf[i] = SHA256(payload_hash || sequence || entity_type || entity_id)
BatchCommitment Structure:
pub struct BatchCommitment {
    pub batch_id: Uuid,
    pub tenant_id: TenantId,
    pub store_id: StoreId,
    pub prev_state_root: Hash256,  // State before batch
    pub new_state_root: Hash256,   // State after batch
    pub events_root: Hash256,      // Merkle root of events
    pub event_count: u32,
    pub sequence_range: (u64, u64),
    pub committed_at: DateTime<Utc>,
    pub chain_tx_hash: Option<Hash256>, // On-chain anchor
}

3.6 Optimistic Concurrency Control

VES uses optimistic concurrency without blocking:
OCC Flow:

1. Agent authors event with base_version = 5 (current entity version)
2. Event pushed to sequencer, stored with base_version = 5
3. Projector applies event:
   - Get current entity version (now = 7)
   - Check: base_version (5) != current (7)
   - CONFLICT DETECTED
4. Projector emits: event.rejected { reason: VersionConflict }
5. Event log remains immutable; rejection tracked
6. Agent receives rejection notification
Key Principle: Events are never rejected at sequencing time due to version conflicts. The event log is immutable. Conflicts are detected and recorded at projection time.

3.7 Conflict Resolution Strategies

When conflicts are detected, VES supports multiple resolution strategies:
StrategyBehaviorUse Case
Remote-winsAccept sequencer versionDefault for inventory
Local-winsPrefer local agent stateAgent-authoritative data
MergeField-level mergeNon-conflicting updates
ManualQueue for human reviewHigh-value transactions
Conflict resolution is configurable per entity type, allowing different strategies for different domains.

3.8 Key Management and Encryption

VES includes a complete cryptographic key management system: Key Generation and Registration:
Agent Key Lifecycle:

1. GENERATE: Ed25519 signing key + X25519 encryption key
2. REGISTER: Publish public keys to sequencer key registry
3. ROTATE: Time-based or usage-based rotation policies
4. REVOKE: Mark keys as revoked in registry
Encryption Groups:
  • Multi-agent groups with shared encryption contexts
  • X25519 key exchange for group secret derivation
  • Per-message encryption for sensitive commerce data (payment details, PII)
  • Group membership management (add/remove agents)
Rotation Policies:
PolicyTriggerDescription
Time-basedConfigurable intervalRotate keys every N hours/days
Usage-basedOperation countRotate after N signing operations
ManualAdmin actionForce rotation on demand

3.9 Local Outbox Pattern

Each agent maintains a local SQLite outbox:
CREATE TABLE outbox (
    local_seq INTEGER PRIMARY KEY AUTOINCREMENT,
    event_id TEXT UNIQUE NOT NULL,
    command_id TEXT,
    tenant_id TEXT NOT NULL,
    store_id TEXT NOT NULL,
    entity_type TEXT NOT NULL,
    entity_id TEXT NOT NULL,
    event_type TEXT NOT NULL,
    payload TEXT NOT NULL,
    payload_hash TEXT NOT NULL,
    base_version INTEGER,
    source_agent TEXT NOT NULL,
    created_at TEXT NOT NULL,
    -- Sync tracking
    sync_status TEXT DEFAULT 'pending',
    remote_sequence INTEGER,
    synced_at TEXT,
    rejection_reason TEXT
);
Sync Flow:
  1. Mutation occurs locally → event appended to outbox
  2. Agent pushes pending events to sequencer
  3. Sequencer returns IngestReceipt with sequence numbers
  4. Agent updates outbox with remote_sequence, synced_at
  5. Agent pulls events from other agents
  6. Events applied locally, entity versions updated

4. Set Chain: On-Chain Settlement

4.1 Overview

Set Chain is an Ethereum Layer-2 optimistic rollup built on the OP Stack, providing cryptographic finality for commerce events. Chain Parameters:
ParameterValue
Chain ID84532001
Block Time2 seconds
Gas Limit30M per block
Settlement LayerEthereum (Sepolia/Mainnet)
Native TokenETH

4.2 Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                        Set Chain Architecture                        │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                    stateset-sequencer                          │ │
│  │                    (Batch Commitments)                         │ │
│  └────────────────────────────┬──────────────────────────────────┘ │
│                               │                                     │
│                     GET /v1/commitments/pending                     │
│                               │                                     │
│                               ▼                                     │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                      set-anchor                                │ │
│  │                    (Rust Service)                              │ │
│  │  ┌─────────────────────────────────────────────────────────┐  │ │
│  │  │ Poll → Validate → Submit → Notify                       │  │ │
│  │  │  │         │         │         │                        │  │ │
│  │  │  │         │         │         └─► POST /anchored       │  │ │
│  │  │  │         │         └─► SetRegistry.commitBatch()      │  │ │
│  │  │  │         └─► Min events, hash verification            │  │ │
│  │  │  └─► Sequencer API                                      │  │ │
│  │  └─────────────────────────────────────────────────────────┘  │ │
│  └────────────────────────────┬──────────────────────────────────┘ │
│                               │                                     │
│                    Ethereum Transaction                             │
│                               │                                     │
│                               ▼                                     │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                   Set Chain L2 (OP Stack)                      │ │
│  │  ┌─────────────────────────────────────────────────────────┐  │ │
│  │  │                    SetRegistry.sol                       │  │ │
│  │  │  - commitBatch(batchId, roots, sequences)               │  │ │
│  │  │  - verifyInclusion(batchId, leafHash, proof)            │  │ │
│  │  │  - getLatestStateRoot(tenantId, storeId)                │  │ │
│  │  └─────────────────────────────────────────────────────────┘  │ │
│  │  ┌─────────────────────────────────────────────────────────┐  │ │
│  │  │                   SetPaymaster.sol                       │  │ │
│  │  │  - Gas sponsorship for merchants                        │  │ │
│  │  │  - Tiered limits (Starter/Growth/Enterprise)            │  │ │
│  │  └─────────────────────────────────────────────────────────┘  │ │
│  └────────────────────────────┬──────────────────────────────────┘ │
│                               │                                     │
│                     Batch Submission (L2 → L1)                      │
│                               │                                     │
│                               ▼                                     │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                 Ethereum L1 (Sepolia/Mainnet)                  │ │
│  │  OptimismPortal │ L2OutputOracle │ SystemConfig                │ │
│  └───────────────────────────────────────────────────────────────┘ │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

4.3 SetRegistry Contract

The SetRegistry stores batch commitments and enables proof verification:
contract SetRegistry is UUPSUpgradeable, OwnableUpgradeable {

    struct BatchCommitment {
        bytes32 eventsRoot;      // Merkle root of events
        bytes32 prevStateRoot;   // State root before batch
        bytes32 newStateRoot;    // State root after batch
        uint64 sequenceStart;    // First sequence in batch
        uint64 sequenceEnd;      // Last sequence in batch
        uint32 eventCount;       // Number of events
        uint256 committedAt;     // Block timestamp
    }

    // Storage
    mapping(bytes32 => BatchCommitment) public batches;
    mapping(bytes32 => bytes32) public latestStateRoot;  // tenant+store → root
    mapping(bytes32 => uint64) public headSequence;      // tenant+store → seq
    mapping(address => bool) public authorizedSequencers;

    function commitBatch(
        bytes32 batchId,
        bytes32 tenantId,
        bytes32 storeId,
        bytes32 eventsRoot,
        bytes32 prevStateRoot,
        bytes32 newStateRoot,
        uint64 sequenceStart,
        uint64 sequenceEnd,
        uint32 eventCount
    ) external onlyAuthorizedSequencer {
        // Validate state continuity
        bytes32 key = keccak256(abi.encodePacked(tenantId, storeId));
        require(prevStateRoot == latestStateRoot[key], "State discontinuity");

        // Store commitment
        batches[batchId] = BatchCommitment({
            eventsRoot: eventsRoot,
            prevStateRoot: prevStateRoot,
            newStateRoot: newStateRoot,
            sequenceStart: sequenceStart,
            sequenceEnd: sequenceEnd,
            eventCount: eventCount,
            committedAt: block.timestamp
        });

        // Update latest state
        latestStateRoot[key] = newStateRoot;
        headSequence[key] = sequenceEnd;

        emit BatchCommitted(batchId, tenantId, storeId, eventsRoot);
    }

    function verifyInclusion(
        bytes32 batchId,
        bytes32 leafHash,
        bytes32[] calldata proof,
        uint256 leafIndex
    ) external view returns (bool) {
        bytes32 computedRoot = leafHash;
        for (uint256 i = 0; i < proof.length; i++) {
            if (leafIndex % 2 == 0) {
                computedRoot = keccak256(abi.encodePacked(computedRoot, proof[i]));
            } else {
                computedRoot = keccak256(abi.encodePacked(proof[i], computedRoot));
            }
            leafIndex /= 2;
        }
        return computedRoot == batches[batchId].eventsRoot;
    }
}

4.4 Anchor Service

The Rust anchor service bridges sequencer to chain:
pub struct AnchorService {
    sequencer_client: SequencerClient,
    registry_client: SetRegistryClient,
    config: AnchorConfig,
}

impl AnchorService {
    pub async fn run(&self) -> Result<()> {
        loop {
            // 1. Fetch pending commitments
            let pending = self.sequencer_client
                .get_pending_commitments()
                .await?;

            // 2. Filter by minimum events threshold
            let eligible: Vec<_> = pending
                .into_iter()
                .filter(|c| c.event_count >= self.config.min_events)
                .collect();

            // 3. Submit each to SetRegistry
            for commitment in eligible {
                match self.submit_commitment(&commitment).await {
                    Ok(tx_hash) => {
                        // 4. Notify sequencer of success
                        self.sequencer_client
                            .notify_anchored(&commitment.batch_id, &tx_hash)
                            .await?;

                        self.metrics.anchored_batches.inc();
                    }
                    Err(e) => {
                        self.metrics.failed_anchors.inc();
                        // Retry on next iteration
                    }
                }
            }

            tokio::time::sleep(self.config.poll_interval).await;
        }
    }
}

4.5 Settlement Finality

The system provides progressive finality guarantees:
StageLatencyGuarantee
Local SQLite~1msSingle-agent consistency
Sequencer~100msGlobal ordering
L2 Block~2sChain inclusion
L1 Batch~10minOptimistic finality
Challenge Period~7 daysCryptographic finality
Verification Flow:
  1. User requests proof for event E
  2. Sequencer returns Merkle proof from batch B
  3. User calls SetRegistry.verifyInclusion(B, E.leafHash, proof)
  4. Contract recomputes root, compares to stored eventsRoot
  5. Returns true if event is included in anchored batch

5. x402 Payment Protocol

5.1 Overview

The x402 protocol enables HTTP-native stablecoin micropayments between AI agents. Using the HTTP 402 (Payment Required) status code, agents can negotiate and settle payments inline with commerce API calls.

5.2 Protocol Flow

┌─────────────────────────────────────────────────────────────────────┐
│                       x402 Payment Flow                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  Agent A (Buyer)                    Agent B (Seller)                │
│       │                                  │                          │
│       │  1. GET /api/products/123         │                          │
│       │─────────────────────────────────►│                          │
│       │                                  │                          │
│       │  2. HTTP 402 Payment Required    │                          │
│       │  {                               │                          │
│       │    asset: "USDC",                │                          │
│       │    amount: "0.001",              │                          │
│       │    network: "set-chain",         │                          │
│       │    recipient: "0x...",           │                          │
│       │    validity: 300                 │                          │
│       │  }                               │                          │
│       │◄─────────────────────────────────│                          │
│       │                                  │                          │
│       │  3. Sign PaymentIntent           │                          │
│       │  (Ed25519 signature)             │                          │
│       │                                  │                          │
│       │  4. GET /api/products/123        │                          │
│       │  X-Payment: <signed intent>      │                          │
│       │─────────────────────────────────►│                          │
│       │                                  │                          │
│       │  5. Verify → Settle → Respond    │                          │
│       │  X-Payment-Receipt: <receipt>    │                          │
│       │◄─────────────────────────────────│                          │
│       │                                  │                          │
└─────────────────────────────────────────────────────────────────────┘

5.3 Supported Networks

NetworkChain IDAssetsStatus
Set Chain84532001ssUSD, USDCProduction
ArcssUSDProduction
Base8453USDCProduction
Ethereum1USDC, USDTProduction
Arbitrum42161USDCProduction
Optimism10USDCProduction
SolanaUSDCProduction
Testnets are supported for all networks.

5.4 Core Types

pub struct X402PaymentIntent {
    pub version: String,              // "x402/1.0"
    pub asset: X402Asset,             // USDC, ssUSD, etc.
    pub amount: String,               // Decimal amount
    pub network: X402Network,         // Target chain
    pub recipient: String,            // Recipient address
    pub validity_seconds: u64,        // Payment window
    pub nonce: String,                // Replay protection
    pub domain_separator: String,     // EIP-712 domain
    pub signature: Vec<u8>,           // Ed25519 signature
}

pub struct X402PaymentReceipt {
    pub intent_hash: Hash256,         // Hash of signed intent
    pub tx_hash: Option<Hash256>,     // On-chain settlement tx
    pub settled_at: DateTime<Utc>,
    pub network: X402Network,
    pub status: PaymentStatus,        // Pending, Settled, Failed
}

pub struct X402PaymentBatch {
    pub batch_id: Uuid,
    pub intents: Vec<X402PaymentIntent>,
    pub merkle_root: Hash256,         // Batch Merkle root
    pub total_amount: String,
}

5.5 Agent Wallet Integration

Agent wallets are derived from VES signing keys, enabling unified identity across event signing and payment settlement:
VES Ed25519 Key → Derive payment address
                → Sign x402 intents
                → Verify receipts
Multi-chain balance checking allows agents to inspect their holdings across all supported networks via the stateset-pay CLI.

6. Model Context Protocol Integration

6.1 MCP Architecture

The CLI exposes commerce operations via the Model Context Protocol (MCP), enabling AI agents to invoke tools directly:
┌─────────────────────────────────────────────────────────────────────┐
│                   Agent SDK Integration (v0.3.1)                     │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                    @stateset/cli                               │ │
│  │  ┌─────────────────────────────────────────────────────────┐  │ │
│  │  │              claude-harness.js (62KB)                    │  │ │
│  │  │  - Multi-agent routing + skills injection               │  │ │
│  │  │  - Session management + persistent memory               │  │ │
│  │  │  - Voice mode + multi-provider switching                │  │ │
│  │  │  - Sync integration + event capture                     │  │ │
│  │  └─────────────────────────────────────────────────────────┘  │ │
│  │  ┌─────────────────────────────────────────────────────────┐  │ │
│  │  │              mcp-server.js (221KB)                       │  │ │
│  │  │  - MCP tools across 32 domains                          │  │ │
│  │  │  - Permission gating (--apply flag)                     │  │ │
│  │  │  - Schema validation + tool composition                 │  │ │
│  │  │  - Telemetry integration                                │  │ │
│  │  └─────────────────────────────────────────────────────────┘  │ │
│  └───────────────────────────────────────────────────────────────┘ │
│                                                                     │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                    Specialized Agents                          │ │
│  │  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐      │ │
│  │  │checkout│ │ orders │ │  inv   │ │returns │ │  sync  │      │ │
│  │  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘      │ │
│  │  ┌────────┐ ┌────────┐ ┌────────┐ ┌─────────┐                │ │
│  │  │ promo  │ │  subs  │ │  tax   │ │analytics│                │ │
│  │  └────────┘ └────────┘ └────────┘ └─────────┘                │ │
│  └───────────────────────────────────────────────────────────────┘ │
│                                                                     │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                    Skills System (38)                          │ │
│  │  Domain knowledge injected per-agent from SKILL.md files      │ │
│  │  accounts-payable │ fulfillment │ general-ledger │ quality    │ │
│  │  warehouse │ receiving │ lots-and-serials │ vector-search     │ │
│  │  cost-accounting │ credit │ backorders │ autonomous-engine    │ │
│  │  ... and 26 more                                              │ │
│  └───────────────────────────────────────────────────────────────┘ │
│                                                                     │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │                    AI Providers (4)                            │ │
│  │  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐                 │ │
│  │  │ Claude │ │ OpenAI │ │ Gemini │ │ Ollama │                 │ │
│  │  │ (Full) │ │ (Chat) │ │ (Chat) │ │(Local) │                 │ │
│  │  └────────┘ └────────┘ └────────┘ └────────┘                 │ │
│  └───────────────────────────────────────────────────────────────┘ │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

6.2 Tool Categories

MCP Tools by Domain:
DomainExamples
Customerslist_customers, get_customer, create_customer
Orderscreate_order, ship_order, cancel_order
Productslist_products, create_product
Inventoryget_stock, adjust_inventory, reserve_inventory
Returnscreate_return, approve_return
Carts/Checkoutcreate_cart, add_cart_item, complete_checkout
Paymentscreate_payment, process_refund
Analyticsget_sales_summary, get_demand_forecast
Currencyconvert_currency, set_exchange_rate
Taxcalculate_tax, calculate_cart_tax
Promotionscreate_promotion, validate_coupon
Subscriptionscreate_subscription, pause_subscription
Warehousecreate_warehouse, assign_location
Fulfillmentcreate_wave, assign_pick_task
Qualitycreate_inspection, record_ncr
Lots/Serialscreate_lot, assign_serial
General Ledgerpost_journal_entry, get_trial_balance
Accounts Payablecreate_bill, schedule_payment
Accounts Receivableapply_payment, generate_statement
Cost Accountingrecord_cost_layer, get_valuation
Syncsync_status, sync_push, sync_pull

6.3 Skills System

The CLI includes a skills system that injects domain-specific knowledge into agent prompts:
┌─────────────────────────────────────────────────────────────────────┐
│                        Skills Architecture                           │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  skills/                                                            │
│  ├── general-ledger/                                                │
│  │   └── SKILL.md          # GL domain expertise, double-entry      │
│  │                           accounting rules, period management    │
│  ├── fulfillment/                                                   │
│  │   └── SKILL.md          # Pick/pack/ship workflows, wave         │
│  │                           planning, carrier integration          │
│  ├── quality/                                                       │
│  │   └── SKILL.md          # Inspection types, NCR handling,        │
│  │                           quality hold procedures                │
│  └── ... (38 total)                                                 │
│                                                                     │
│  Infrastructure:                                                    │
│  ├── loader.js             # Load skills from filesystem            │
│  ├── parser.js             # Parse SKILL.md files                   │
│  ├── registry.js           # In-memory skill registry               │
│  ├── injector.js           # Inject into agent system prompts       │
│  └── marketplace.js        # Browse/install community skills        │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
Each SKILL.md file contains structured domain knowledge: entity descriptions, workflow steps, troubleshooting guides, and usage examples. When an agent is routed to handle a request, its relevant skills are injected into the system prompt, giving it deep domain expertise. 38 Built-in Skills: accounts-payable, accounts-receivable, analytics, autonomous-engine, autonomous-runbook, backorders, checkout, cost-accounting, credit, currency, customer-service, customers, embedded-sdk, engine-setup, events, fulfillment, general-ledger, inventory, invoices, lots-and-serials, manufacturing, mcp-tools, orders, payments, products, promotions, quality, receiving, returns, shipments, storefront, subscriptions, suppliers, sync, tax, vector-search, warehouse, warranties.

6.4 Multi-Provider AI Support

The CLI supports multiple AI providers with a unified interface:
ProviderModelsMCP ToolsMode
Claudeclaude-sonnet-4-20250514FullAgent SDK + MCP
OpenAIgpt-4o, gpt-4, o1NoneChat-only
Geminigemini-2.0-flash, gemini-2.0-proNoneChat-only
Ollamallama3, mistral, etc.NoneChat-only (local)
Claude operates as the primary agent with full MCP tool access. Non-Claude providers operate in chat-only mode, providing conversational assistance without direct commerce operations. This allows users to choose their preferred model while maintaining full functionality through Claude.

6.5 Voice Mode

The CLI supports voice-based interaction for conversational commerce:
stateset-chat --voice --tts-provider elevenlabs --stt-provider whisper
ComponentProviderDescription
Speech-to-TextOpenAI WhisperAudio transcription
Text-to-SpeechElevenLabsNatural voice synthesis
Session ManagementVoiceModeControllerPer-session state, 30-min TTL
Voice sessions maintain state with automatic cleanup of stale sessions.

6.6 Permission Model

All write operations require explicit opt-in:
// Read operations - always allowed
stateset "list orders"
stateset "what's my inventory for SKU-001?"

// Write operations - blocked by default
stateset "create an order for alice@example.com"
// → Shows preview, does not execute

// Write operations - enabled with --apply
stateset --apply "create an order for alice@example.com"
// → Executes operation, captures event to outbox

6.7 Agent Routing

The harness automatically routes requests to specialized agents:
const AGENT_KEYWORDS = {
  'checkout': ['cart', 'checkout', 'add to cart', 'buy'],
  'orders': ['order', 'ship', 'tracking', 'fulfill'],
  'inventory': ['stock', 'inventory', 'reserve'],
  'returns': ['return', 'rma', 'refund'],
  'sync': ['sync', 'push events', 'outbox', 'sequencer'],
  // ...
};

function routeToAgent(request) {
  // Score each agent based on keyword matches
  // Return agent with highest score
  // Default to 'customer-service' (all tools)
}

6.8 Event Capture Integration

When sync is configured, commerce operations automatically emit events:
// In claude-harness.js
const rawSyncConfig = loadSyncConfig();
if (rawSyncConfig) {
  commerce = wrapCommerceWithEvents(commerce, syncConfig);
}

// Every mutation now:
// 1. Executes the operation
// 2. Appends event to _ves_outbox
// 3. Available for sync_push to sequencer

7. Multi-Channel Messaging Gateway

7.1 Overview

The messaging gateway enables AI commerce agents to operate across 9 communication platforms, providing omnichannel customer service, order management, and proactive notifications.

7.2 Architecture

┌─────────────────────────────────────────────────────────────────────┐
│                    Messaging Gateway Architecture                    │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐           │
│  │WhatsApp│ │Telegram│ │Discord │ │ Slack  │ │ Signal │           │
│  └───┬────┘ └───┬────┘ └───┬────┘ └───┬────┘ └───┬────┘           │
│      │          │          │          │          │                 │
│  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐                      │
│  │ GChat  │ │WebChat │ │iMessage│ │ Teams  │                      │
│  └───┬────┘ └───┬────┘ └───┬────┘ └───┬────┘                      │
│      │          │          │          │                            │
│      └──────────┴──────────┴──────────┘                            │
│                         │                                          │
│                         ▼                                          │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                     Gateway Core                             │   │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │   │
│  │  │ Session  │  │Middleware│  │ Identity │  │  Reply   │    │   │
│  │  │  Store   │  │  Stack   │  │ Resolver │  │ Pipeline │    │   │
│  │  └──────────┘  └──────────┘  └──────────┘  └──────────┘    │   │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │   │
│  │  │  Event   │  │ Handoff  │  │  Rich    │  │ Command  │    │   │
│  │  │  Bridge  │  │  Queue   │  │ Messages │  │ Registry │    │   │
│  │  └──────────┘  └──────────┘  └──────────┘  └──────────┘    │   │
│  └──────────────────────────┬──────────────────────────────────┘   │
│                             │                                      │
│                             ▼                                      │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                  Commerce Engine + MCP                       │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

7.3 Channel Support

ChannelProtocolStatusFeatures
WhatsAppCloud APIGARich media, templates, quick replies
TelegramBot APIGAInline keyboards, commands, groups
DiscordGateway + RESTGASlash commands, embeds, threads
SlackEvents + Web APIGABlocks, modals, slash commands
Signalsignal-cliGAEncrypted messaging
Google ChatSpaces APIGACards, dialogs
WebChatWebSocketGAEmbeddable widget, real-time
iMessageAppleScriptExperimentalmacOS only
TeamsBot FrameworkExperimentalAdaptive cards

7.4 Gateway Infrastructure

Session Store: SQLite-backed persistent sessions with per-conversation state, allowing agents to maintain context across messages and platform reconnections. Middleware Stack: Koa-style onion model with composable middleware:
  • Rate limiting (per-user, per-channel)
  • Content filtering (profanity, PII detection)
  • Language detection
  • Request logging and metrics
Identity Resolution: Maps platform-specific user IDs to commerce customer records, enabling personalized service across channels. Event Bridge: Connects commerce engine events to channel notifications—when an order ships, the customer receives a notification on their preferred channel. Handoff Queue: AI-to-human escalation system for cases requiring human judgment, with full conversation context transfer. Plugin System: Extensible architecture allowing custom plugins for channel-specific functionality.

7.5 Orchestrator

The multi-channel orchestrator launches and manages gateway instances from configuration:
# Launch all configured channels
stateset-channels

# Launch specific channels
stateset-whatsapp
stateset-discord
stateset-telegram
stateset-slack

8. Operational Infrastructure

8.1 Heartbeat Monitor

The heartbeat monitor provides proactive health checking for commerce operations:
┌─────────────────────────────────────────────────────────────────────┐
│                      Heartbeat Monitor                               │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌────────────────┐                                                 │
│  │ HeartbeatMonitor│  (EventEmitter, configurable interval)         │
│  └───────┬────────┘                                                 │
│          │                                                          │
│          ├── low-stock          Items below threshold                │
│          ├── abandoned-carts    Stale carts past timeout            │
│          ├── revenue-milestone  Revenue target monitoring            │
│          ├── pending-returns    Returns aging beyond threshold       │
│          ├── overdue-invoices   Overdue B2B invoices                 │
│          └── subscription-churn Cancellation rate monitoring         │
│                    │                                                │
│                    ▼                                                │
│          ┌─────────────────┐                                        │
│          │AutonomousEngine │  Trigger automated responses           │
│          └────────┬────────┘                                        │
│                   ▼                                                 │
│          ┌─────────────────┐                                        │
│          │  Event Bridge   │  Route to notification channels        │
│          └────────┬────────┘                                        │
│                   ▼                                                 │
│          ┌─────────────────┐                                        │
│          │Channel Notifier │  WhatsApp, Slack, Discord, etc.        │
│          └─────────────────┘                                        │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘
6 Built-in Commerce Checkers:
CheckerTriggerAction
low-stockStock below thresholdAlert, auto-reorder
abandoned-cartsCart idle > timeoutRecovery notification
revenue-milestoneTarget reached/missedDashboard alert
pending-returnsReturn aging > daysEscalation
overdue-invoicesInvoice past dueCollection notification
subscription-churnCancellation spikeRetention campaign
HTTP API:
GET  /heartbeat/status              - Overall health
GET  /heartbeat/checks              - All checker states
POST /heartbeat/checks/:id/run      - Trigger immediate check
POST /heartbeat/checks/:id/enable   - Enable checker
POST /heartbeat/checks/:id/disable  - Disable checker

8.2 Permission Sandboxing

Fine-grained permission control for API access: Permission Levels:
none (0) < read (1) < preview (2) < write (3) < delete (4) < admin (5)
Features:
  • API key authentication (Bearer token + query parameter)
  • Per-route permission levels with longest-prefix matching
  • Per-HTTP-method overrides
  • Sandbox mode blocking dangerous operations (browser automation, shell execution)
  • Timing-safe key comparison
  • Every MCP tool mapped to a required permission level

8.3 Persistent Memory

SQLite-backed conversation memory for maintaining context across sessions:
FeatureDescription
Per-conversation summariesAutomatic summarization of interactions
Fact extractionKey facts stored for future reference
Token trackingUsage monitoring per conversation
Keyword searchFind relevant past interactions
Vector retrievalSemantic similarity search over memory
Auto-cleanupConfigurable retention policies

8.4 Browser Automation

Chrome DevTools Protocol (CDP) integration for web interaction:
  • Headless Chrome spawning and lifecycle management
  • Navigation, DOM queries, JavaScript evaluation
  • Screenshot capture
  • No Puppeteer dependency (pure CDP implementation)
  • Use cases: storefront testing, catalog sync, web scraping

8.5 Daemon Mode

Systemd service manager for production deployments:
stateset-daemon start     # Launch gateway as service
stateset-daemon stop      # Stop service
stateset-daemon logs      # View logs
stateset-daemon health    # Health check
Includes Tailscale VPN management and SSH tunnel support for secure remote access.

8.6 Scaffold Server

Code generation system for bootstrapping e-commerce storefronts:
stateset scaffold --template next-commerce
Generates complete, runnable storefronts with commerce engine integration, reducing time-to-first-store.

8.7 Prometheus Metrics

Feature-gated observability (metrics feature flag):
// Operation latency histograms
pub static ref OPERATION_LATENCY: HistogramVec;
// Operation counters (total + failed)
pub static ref OPERATION_TOTAL: CounterVec;
pub static ref OPERATION_FAILED: CounterVec;
// Active reservation gauges
pub static ref ACTIVE_RESERVATIONS: Gauge;
Metrics are exported in Prometheus text format for integration with Grafana, Datadog, and other monitoring tools.

9. Evaluation

9.1 Performance

Embedded Engine Benchmarks:
OperationSQLitePostgreSQL
Create Order1.2ms3.5ms
List Orders (100)0.8ms2.1ms
Inventory Adjustment0.9ms2.8ms
Tax Calculation0.3ms0.3ms
Cart Checkout4.5ms8.2ms
Vector Search (1000 products)~15ms~20ms
Hybrid Search (RRF)~25ms~30ms
Sequencer Throughput:
MetricValue
Events/second (sustained)10,000+
Batch size100-1000 events
Sequencing latency (p99)50ms
Merkle tree construction~5ms/1000 events
L2 Settlement:
MetricValue
Block time2 seconds
commitBatch gas~150,000
verifyInclusion gas~30,000
L1 batch submission~10 minutes

9.2 Security Properties

Cryptographic Guarantees:
  1. Event Integrity: SHA-256 payload hashes prevent tampering
  2. Inclusion Proofs: Merkle trees enable O(log n) verification
  3. Ordering Finality: Sequence numbers are immutable once assigned
  4. State Continuity: Each batch links to previous state root
  5. Agent Authentication: Ed25519 signatures with key rotation
  6. Encryption Groups: X25519-based end-to-end encryption for sensitive data
  7. Payment Security: x402 signed intents with replay protection via nonces
Attack Resistance:
AttackMitigation
Event replayUUID event_id deduplication
Intent replaycommand_id deduplication
Payment replayNonce-based x402 intent deduplication
Sequencer equivocationState root chain verification
Data tamperingMerkle proofs, on-chain anchoring
Agent impersonationEd25519 signing with key registry
Unauthorized accessPermission sandboxing, API key auth
Channel injectionMiddleware content filtering

9.3 Scalability

Horizontal Scaling:
ComponentStrategy
Embedded EnginePer-agent instances, no coordination
SequencerRead replicas, partition by tenant
Event StorePostgreSQL partitioning by sequence
L2 SettlementOP Stack inherent scalability
Messaging GatewayPer-channel horizontal scaling
State Growth:
TimeframeEventsStorage (est.)
1 month10M5 GB
1 year120M60 GB
5 years600M300 GB
Event archival and pruning strategies maintain operational efficiency.

10.1 Embedded Databases

SQLite pioneered the embedded database model, demonstrating that client-server architecture is unnecessary for most applications. iCommerce applies this principle to commerce. DuckDB extends embedded analytics, inspiring our embedded forecasting capabilities.

10.2 Event Sourcing

EventStore and Kafka provide event streaming infrastructure. VES differs by:
  • Targeting agent-to-agent coordination
  • Providing cryptographic commitments
  • Supporting offline-first operation
  • Including end-to-end encryption groups

10.3 Commerce Platforms

Shopify, Stripe, and BigCommerce provide SaaS commerce infrastructure. iCommerce differs by:
  • Embedded architecture (no network dependency)
  • Agent-first design (MCP tools, not dashboards)
  • Verifiable execution (Merkle proofs)
  • Native stablecoin payments (x402)

10.4 Layer-2 Solutions

Optimism and Arbitrum provide general-purpose L2 scaling. Set Chain specializes for commerce with:
  • SetRegistry for event anchoring
  • SetPaymaster for merchant gas sponsorship
  • Integration with off-chain sequencer
  • x402 payment settlement

10.5 Agent Payment Protocols

x402 builds on the HTTP 402 status code to enable machine-to-machine payments. Unlike traditional payment processors that require human-facing checkout flows, x402 operates entirely at the protocol level, enabling autonomous agents to negotiate and settle payments as part of standard HTTP request/response cycles.

10.6 Conversational Commerce

Twilio, MessageBird, and Vonage provide messaging APIs. The StateSet messaging gateway differs by:
  • Deep commerce engine integration (not just messaging)
  • AI-native design (agents as first-class participants)
  • Event-driven notifications from commerce operations
  • Identity resolution across platforms

11. Conclusion

StateSet iCommerce represents a new paradigm for commerce infrastructure: embedded, verifiable, and agent-first. The five-layer architecture provides:
  1. Local autonomy via the embedded engine with 32 commerce domains
  2. Global coordination via Verifiable Event Sync with end-to-end encryption
  3. Cryptographic finality via Set Chain settlement
  4. Native payments via the x402 HTTP payment protocol
  5. Omnichannel presence via the 9-channel messaging gateway
As AI agents become primary participants in economic activity, infrastructure must evolve beyond human-operated dashboards and rate-limited APIs. iCommerce provides the foundation for this autonomous commerce future—from warehouse operations and quality control to general ledger accounting and stablecoin payments, all accessible to AI agents through a unified, verifiable, embedded engine.

11.1 Future Work

Near-term (2026):
  • Zero-knowledge validity proofs for event batches
  • Agent-to-agent negotiation protocol
  • Cross-chain settlement bridges
  • Expanded vector search with custom embedding models
  • Additional messaging channels (Matrix, RCS)
Medium-term (2026-2027):
  • Decentralized identity integration
  • Federated learning across tenants
  • On-device ML models for demand prediction
  • Real-time collaborative editing of commerce data
Long-term (2027+):
  • Fully autonomous supply chain orchestration
  • Cross-border compliance automation
  • Global commerce network federation
  • Autonomous agent marketplaces with x402 settlement

References

  1. SQLite Consortium. “SQLite: A Self-Contained SQL Database Engine.” https://sqlite.org
  2. Ethereum Foundation. “Optimistic Rollups.” https://ethereum.org/en/developers/docs/scaling/optimistic-rollups/
  3. Anthropic. “Model Context Protocol Specification.” https://modelcontextprotocol.io
  4. Merkle, R.C. “A Digital Signature Based on a Conventional Encryption Function.” CRYPTO 1987.
  5. Lamport, L. “Time, Clocks, and the Ordering of Events in a Distributed System.” CACM 1978.
  6. Coinbase. “x402: HTTP-Native Payments Protocol.” https://www.x402.org
  7. OpenAI. “Text Embedding Models.” https://platform.openai.com/docs/guides/embeddings

Appendix A: System Statistics

ComponentMetricValue
stateset-coreLines of Code~45,000
stateset-dbLines of Code~55,000
stateset-embeddedLines of Code~39,000
Total Rust (3 crates)Lines of Code~139,000
Node.js bindingTechnologyNAPI-RS
Python bindingTechnologyPyO3
Ruby bindingTechnologyMagnus
PHP bindingTechnologyext-php-rs
Java bindingTechnologyJNI
Kotlin bindingTechnologyJNI
Swift bindingTechnologyC FFI
.NET bindingTechnologyP/Invoke
Go bindingTechnologycgo
WASM bindingTechnologywasm-pack
CLI (mcp-server)Size221 KB
CLI (harness)Size62 KB
Domain ModulesCount32
Domain TypesCount400+
Database TablesCount70+
Database MigrationsCount28
API MethodsCount700+
Language BindingsCount10
Commerce SkillsCount38
AI ProvidersCount4
Messaging ChannelsCount9
Heartbeat CheckersCount6
CLI ProgramsCount26+
SequencerLines of Code~5,000
Set Chain ContractsLines of Code~1,000
Anchor ServiceLines of Code~2,250

Appendix B: API Summary

Embedded Engine (per domain)

Commerce Operations:
customers:       list, get, getByEmail, create, update, delete, count
products:        list, get, getBySku, create, update, delete, listVariants
inventory:       getStock, create, adjust, reserve, release, confirm
orders:          list, get, create, updateStatus, ship, cancel, addItem
carts:           list, get, create, addItem, updateItem, removeItem, checkout
payments:        list, get, create, markCompleted, markFailed, refund
returns:         list, get, create, approve, reject, complete
promotions:      list, get, create, activate, deactivate, validateCoupon
subscriptions:   listPlans, createPlan, subscribe, pause, resume, cancel
shipments:       list, get, create, addEvent, updateTracking
Supply Chain & Warehouse:
warehouse:       list, get, create, addZone, addLocation, getInventory, move
receiving:       list, get, create, receiveItems, putAway, complete
fulfillment:     createWave, listWaves, assignPick, completePick, pack, ship
lots:            list, get, create, split, merge, transfer, traceForward, traceBack
serials:         list, get, create, bulkCreate, transfer, lookupWarranty
backorders:      list, get, create, allocate, fulfill, getSummary
manufacturing:   listBOMs, createBOM, createWorkOrder, completeTask
purchase_orders: list, get, create, receive, close
quality:         createInspection, recordResult, createNCR, placeHold, releaseHold
Financial:
general_ledger:  createAccount, postEntry, getTrialBalance, getBalanceSheet,
                 getIncomeStatement, openPeriod, closePeriod
accounts_recv:   getAging, createCreditMemo, writeOff, applyPayment,
                 generateStatement, createCollection
accounts_pay:    createBill, schedulePay, createPaymentRun, getAging
invoices:        list, get, create, markPaid, markVoid
cost_accounting: recordLayer, adjust, getValuation, getVariance
credit:          createAccount, applyCredit, reviewApplication, placeHold
tax:             calculate, calculateCart, getRate, listJurisdictions
currency:        convert, getRate, setRate, format
Platform:
x402:            createIntent, signIntent, verifyReceipt, batchSettle
vector:          indexProduct, searchProducts, indexCustomer, searchCustomers
analytics:       getSales, getTopProducts, getForecast, getHealth
warranties:      list, get, create, fileClaim, resolveClaim
forecasting:     getDemand, generateForecast, getSeasonality
sync:            status, push, pull, outbox, retryFailed, entityHistory, full

Sequencer API

POST /api/v1/events/ingest        - Batch event ingestion
GET  /api/v1/events               - List events by sequence
GET  /api/v1/head                 - Get current head sequence
GET  /api/v1/commitments/:id      - Get batch commitment
GET  /api/v1/commitments/:id/proof - Get inclusion proof
GET  /api/v1/entities/:type/:id   - Get entity history
POST /api/v1/keys/register        - Register agent public key
GET  /api/v1/keys/:agent_id       - Get agent public key
POST /api/v1/groups/create        - Create encryption group
POST /api/v1/groups/:id/members   - Add group member

MCP Sync Tools

sync_status         - Get sync health and statistics
sync_push           - Push pending events to sequencer
sync_pull           - Pull events from sequencer
sync_outbox         - List local outbox events
sync_retry_failed   - Reset failed events for retry
sync_entity_history - Get entity event history
sync_full           - Push then pull (full sync)

Heartbeat API

GET  /heartbeat/status             - Overall health status
GET  /heartbeat/checks             - All checker states
POST /heartbeat/checks/:id/run     - Trigger immediate check
POST /heartbeat/checks/:id/enable  - Enable checker
POST /heartbeat/checks/:id/disable - Disable checker

Gateway API

POST /gateway/send                 - Send message to channel
GET  /gateway/sessions             - List active sessions
GET  /gateway/sessions/:id         - Get session details
POST /gateway/handoff              - Escalate to human agent
GET  /gateway/metrics              - Channel metrics

StateSet iCommerce v0.3.1 January 2026