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

# iCommerce Paper

> A technical paper on embedded, verifiable commerce systems for AI agents

# 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:

| Layer             | Component          | Function                        |
| ----------------- | ------------------ | ------------------------------- |
| **Compute**       | stateset-embedded  | In-process commerce engine      |
| **Coordination**  | stateset-sequencer | Distributed event ordering      |
| **Settlement**    | Set Chain (L2)     | On-chain verification           |
| **Payments**      | x402 Protocol      | HTTP-native stablecoin payments |
| **Communication** | Messaging Gateway  | 9-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:**

| Module            | Entities                    | Key Operations                        |
| ----------------- | --------------------------- | ------------------------------------- |
| **Customers**     | Customer, Address           | CRUD, profile management              |
| **Products**      | Product, Variant, Attribute | Catalog, pricing, inventory links     |
| **Inventory**     | Item, Balance, Reservation  | Multi-location tracking, reservations |
| **Orders**        | Order, OrderItem, Status    | Full lifecycle, fulfillment           |
| **Carts**         | Cart, CartItem              | Shopping, checkout flow               |
| **Payments**      | Payment, Refund, Method     | Multi-method processing               |
| **Returns**       | Return, ReturnItem, RMA     | Return authorization workflow         |
| **Shipments**     | Shipment, Event, Tracking   | Carrier integration                   |
| **Promotions**    | Promotion, Coupon, Rule     | Discounts, BOGO, tiered               |
| **Subscriptions** | Plan, Subscription, Cycle   | Recurring billing                     |

**Supply Chain & Warehouse:**

| Module              | Entities                                 | Key Operations                       |
| ------------------- | ---------------------------------------- | ------------------------------------ |
| **Warehouse**       | Warehouse, Zone, Location                | Location hierarchy, bin management   |
| **Receiving**       | Receipt, ReceiptItem, PutAway            | Inbound goods, put-away tracking     |
| **Fulfillment**     | Wave, PickTask, PackTask, ShipTask       | Pick/pack/ship workflow              |
| **Lot Tracking**    | Lot, LotCertificate, LotTransaction      | Traceability, COA/COC management     |
| **Serial Numbers**  | SerialNumber, SerialHistory              | Unit-level tracking, warranty lookup |
| **Backorders**      | Backorder, Allocation, Fulfillment       | Priority queuing, allocation         |
| **Manufacturing**   | BOM, WorkOrder, Task                     | Bill of materials                    |
| **Purchase Orders** | PO, Supplier                             | Procurement                          |
| **Quality**         | Inspection, NCR, QualityHold, DefectCode | Multi-stage QC, non-conformance      |

**Financial:**

| Module                  | Entities                                     | Key Operations                            |
| ----------------------- | -------------------------------------------- | ----------------------------------------- |
| **General Ledger**      | GlAccount, JournalEntry, GlPeriod            | Double-entry, auto-posting, trial balance |
| **Accounts Receivable** | CreditMemo, WriteOff, CollectionActivity     | AR aging, statements, collections         |
| **Accounts Payable**    | Bill, BillPayment, PaymentRun                | AP aging, payment scheduling              |
| **Invoices**            | Invoice, Item, AR                            | Accounts receivable                       |
| **Cost Accounting**     | CostLayer, CostAdjustment, CostVariance      | FIFO/LIFO/weighted average, valuation     |
| **Credit**              | CreditAccount, CreditApplication, CreditHold | Credit review, risk rating                |
| **Tax**                 | Jurisdiction, Rate, Exemption                | US/EU/CA multi-jurisdiction               |
| **Currency**            | ExchangeRate, Money                          | 35+ currencies                            |

**Platform:**

| Module            | Entities                                    | Key Operations                  |
| ----------------- | ------------------------------------------- | ------------------------------- |
| **x402**          | PaymentIntent, PaymentReceipt, PaymentBatch | HTTP-native stablecoin payments |
| **Vector Search** | VectorSearchResult, EmbeddingMetadata       | Hybrid semantic + BM25 search   |
| **Analytics**     | Summary, Forecast                           | Business intelligence           |
| **Warranties**    | Warranty, Claim                             | Coverage tracking               |
| **Forecasting**   | ForecastModel, DemandSignal                 | Demand planning                 |
| **Sync**          | Outbox, SyncState                           | Event 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:**

| Feature                  | Description                                                         |
| ------------------------ | ------------------------------------------------------------------- |
| **Saga Orchestration**   | Multi-step distributed transactions with rollback                   |
| **Backup & Restore**     | Full backups (VACUUM INTO), SHA256 verification, retention policies |
| **Idempotency Keys**     | Deduplication at the database level                                 |
| **Performance Indexes**  | Dedicated migration for query optimization                          |
| **Parse Helpers**        | Type-safe row parsing with proper error propagation                 |
| **Repository Macros**    | Code generation to eliminate duplicate implementations              |
| **32 Repository Traits** | One trait per domain with full CRUD + domain operations             |

### 2.5 Vector Search

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:**

```rust theme={null}
// 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:

| Runtime     | Technology     | Use Case                           |
| ----------- | -------------- | ---------------------------------- |
| Native Rust | Direct linking | High-performance backends          |
| Node.js     | NAPI-RS        | JavaScript/TypeScript applications |
| Python      | PyO3 + Maturin | Data science, ML pipelines         |
| Browser     | wasm-pack      | Client-side applications           |
| Edge        | WASM           | Cloudflare Workers, Vercel Edge    |
| **Ruby**    | Magnus         | Rails applications                 |
| **PHP**     | ext-php-rs     | Laravel/WordPress integrations     |
| **Java**    | JNI            | Enterprise JVM applications        |
| **Kotlin**  | JNI            | Android, server-side Kotlin        |
| **Swift**   | C FFI          | iOS/macOS applications             |
| **.NET/C#** | P/Invoke       | ASP.NET, Unity applications        |
| **Go**      | cgo            | Go 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:

```rust theme={null}
// 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:

```rust theme={null}
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:**

```rust theme={null}
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:

| Strategy        | Behavior                 | Use Case                 |
| --------------- | ------------------------ | ------------------------ |
| **Remote-wins** | Accept sequencer version | Default for inventory    |
| **Local-wins**  | Prefer local agent state | Agent-authoritative data |
| **Merge**       | Field-level merge        | Non-conflicting updates  |
| **Manual**      | Queue for human review   | High-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:**

| Policy      | Trigger               | Description                       |
| ----------- | --------------------- | --------------------------------- |
| Time-based  | Configurable interval | Rotate keys every N hours/days    |
| Usage-based | Operation count       | Rotate after N signing operations |
| Manual      | Admin action          | Force rotation on demand          |

### 3.9 Local Outbox Pattern

Each agent maintains a local SQLite outbox:

```sql theme={null}
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:**

| Parameter        | Value                      |
| ---------------- | -------------------------- |
| Chain ID         | 84532001                   |
| Block Time       | 2 seconds                  |
| Gas Limit        | 30M per block              |
| Settlement Layer | Ethereum (Sepolia/Mainnet) |
| Native Token     | ETH                        |

### 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:

```solidity theme={null}
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:

```rust theme={null}
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:

| Stage            | Latency  | Guarantee                |
| ---------------- | -------- | ------------------------ |
| Local SQLite     | \~1ms    | Single-agent consistency |
| Sequencer        | \~100ms  | Global ordering          |
| L2 Block         | \~2s     | Chain inclusion          |
| L1 Batch         | \~10min  | Optimistic finality      |
| Challenge Period | \~7 days | Cryptographic 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

| Network   | Chain ID | Assets      | Status     |
| --------- | -------- | ----------- | ---------- |
| Set Chain | 84532001 | ssUSD, USDC | Production |
| Arc       | —        | ssUSD       | Production |
| Base      | 8453     | USDC        | Production |
| Ethereum  | 1        | USDC, USDT  | Production |
| Arbitrum  | 42161    | USDC        | Production |
| Optimism  | 10       | USDC        | Production |
| Solana    | —        | USDC        | Production |

Testnets are supported for all networks.

### 5.4 Core Types

```rust theme={null}
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:**

| Domain              | Examples                                          |
| ------------------- | ------------------------------------------------- |
| Customers           | list\_customers, get\_customer, create\_customer  |
| Orders              | create\_order, ship\_order, cancel\_order         |
| Products            | list\_products, create\_product                   |
| Inventory           | get\_stock, adjust\_inventory, reserve\_inventory |
| Returns             | create\_return, approve\_return                   |
| Carts/Checkout      | create\_cart, add\_cart\_item, complete\_checkout |
| Payments            | create\_payment, process\_refund                  |
| Analytics           | get\_sales\_summary, get\_demand\_forecast        |
| Currency            | convert\_currency, set\_exchange\_rate            |
| Tax                 | calculate\_tax, calculate\_cart\_tax              |
| Promotions          | create\_promotion, validate\_coupon               |
| Subscriptions       | create\_subscription, pause\_subscription         |
| Warehouse           | create\_warehouse, assign\_location               |
| Fulfillment         | create\_wave, assign\_pick\_task                  |
| Quality             | create\_inspection, record\_ncr                   |
| Lots/Serials        | create\_lot, assign\_serial                       |
| General Ledger      | post\_journal\_entry, get\_trial\_balance         |
| Accounts Payable    | create\_bill, schedule\_payment                   |
| Accounts Receivable | apply\_payment, generate\_statement               |
| Cost Accounting     | record\_cost\_layer, get\_valuation               |
| **Sync**            | sync\_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:

| Provider   | Models                           | MCP Tools | Mode              |
| ---------- | -------------------------------- | --------- | ----------------- |
| **Claude** | claude-sonnet-4-20250514         | Full      | Agent SDK + MCP   |
| **OpenAI** | gpt-4o, gpt-4, o1                | None      | Chat-only         |
| **Gemini** | gemini-2.0-flash, gemini-2.0-pro | None      | Chat-only         |
| **Ollama** | llama3, mistral, etc.            | None      | Chat-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
```

| Component          | Provider            | Description                   |
| ------------------ | ------------------- | ----------------------------- |
| Speech-to-Text     | OpenAI Whisper      | Audio transcription           |
| Text-to-Speech     | ElevenLabs          | Natural voice synthesis       |
| Session Management | VoiceModeController | Per-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:

```javascript theme={null}
// 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:

```javascript theme={null}
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:

```javascript theme={null}
// 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

| Channel         | Protocol         | Status       | Features                             |
| --------------- | ---------------- | ------------ | ------------------------------------ |
| **WhatsApp**    | Cloud API        | GA           | Rich media, templates, quick replies |
| **Telegram**    | Bot API          | GA           | Inline keyboards, commands, groups   |
| **Discord**     | Gateway + REST   | GA           | Slash commands, embeds, threads      |
| **Slack**       | Events + Web API | GA           | Blocks, modals, slash commands       |
| **Signal**      | signal-cli       | GA           | Encrypted messaging                  |
| **Google Chat** | Spaces API       | GA           | Cards, dialogs                       |
| **WebChat**     | WebSocket        | GA           | Embeddable widget, real-time         |
| **iMessage**    | AppleScript      | Experimental | macOS only                           |
| **Teams**       | Bot Framework    | Experimental | Adaptive 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:

```bash theme={null}
# 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:**

| Checker              | Trigger               | Action                  |
| -------------------- | --------------------- | ----------------------- |
| `low-stock`          | Stock below threshold | Alert, auto-reorder     |
| `abandoned-carts`    | Cart idle > timeout   | Recovery notification   |
| `revenue-milestone`  | Target reached/missed | Dashboard alert         |
| `pending-returns`    | Return aging > days   | Escalation              |
| `overdue-invoices`   | Invoice past due      | Collection notification |
| `subscription-churn` | Cancellation spike    | Retention 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:

| Feature                        | Description                             |
| ------------------------------ | --------------------------------------- |
| **Per-conversation summaries** | Automatic summarization of interactions |
| **Fact extraction**            | Key facts stored for future reference   |
| **Token tracking**             | Usage monitoring per conversation       |
| **Keyword search**             | Find relevant past interactions         |
| **Vector retrieval**           | Semantic similarity search over memory  |
| **Auto-cleanup**               | Configurable 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:

```bash theme={null}
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:

```bash theme={null}
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):

```rust theme={null}
// 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:**

| Operation                     | SQLite | PostgreSQL |
| ----------------------------- | ------ | ---------- |
| Create Order                  | 1.2ms  | 3.5ms      |
| List Orders (100)             | 0.8ms  | 2.1ms      |
| Inventory Adjustment          | 0.9ms  | 2.8ms      |
| Tax Calculation               | 0.3ms  | 0.3ms      |
| Cart Checkout                 | 4.5ms  | 8.2ms      |
| Vector Search (1000 products) | \~15ms | \~20ms     |
| Hybrid Search (RRF)           | \~25ms | \~30ms     |

**Sequencer Throughput:**

| Metric                    | Value             |
| ------------------------- | ----------------- |
| Events/second (sustained) | 10,000+           |
| Batch size                | 100-1000 events   |
| Sequencing latency (p99)  | 50ms              |
| Merkle tree construction  | \~5ms/1000 events |

**L2 Settlement:**

| Metric              | Value        |
| ------------------- | ------------ |
| Block time          | 2 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:**

| Attack                 | Mitigation                            |
| ---------------------- | ------------------------------------- |
| Event replay           | UUID event\_id deduplication          |
| Intent replay          | command\_id deduplication             |
| Payment replay         | Nonce-based x402 intent deduplication |
| Sequencer equivocation | State root chain verification         |
| Data tampering         | Merkle proofs, on-chain anchoring     |
| Agent impersonation    | Ed25519 signing with key registry     |
| Unauthorized access    | Permission sandboxing, API key auth   |
| Channel injection      | Middleware content filtering          |

### 9.3 Scalability

**Horizontal Scaling:**

| Component         | Strategy                             |
| ----------------- | ------------------------------------ |
| Embedded Engine   | Per-agent instances, no coordination |
| Sequencer         | Read replicas, partition by tenant   |
| Event Store       | PostgreSQL partitioning by sequence  |
| L2 Settlement     | OP Stack inherent scalability        |
| Messaging Gateway | Per-channel horizontal scaling       |

**State Growth:**

| Timeframe | Events | Storage (est.) |
| --------- | ------ | -------------- |
| 1 month   | 10M    | 5 GB           |
| 1 year    | 120M   | 60 GB          |
| 5 years   | 600M   | 300 GB         |

Event archival and pruning strategies maintain operational efficiency.

***

## 10. Related Work

### 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](https://sqlite.org)
2. Ethereum Foundation. "Optimistic Rollups." [https://ethereum.org/en/developers/docs/scaling/optimistic-rollups/](https://ethereum.org/en/developers/docs/scaling/optimistic-rollups/)
3. Anthropic. "Model Context Protocol Specification." [https://modelcontextprotocol.io](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](https://www.x402.org)
7. OpenAI. "Text Embedding Models." [https://platform.openai.com/docs/guides/embeddings](https://platform.openai.com/docs/guides/embeddings)

***

## Appendix A: System Statistics

| Component             | Metric        | Value      |
| --------------------- | ------------- | ---------- |
| stateset-core         | Lines of Code | \~45,000   |
| stateset-db           | Lines of Code | \~55,000   |
| stateset-embedded     | Lines of Code | \~39,000   |
| Total Rust (3 crates) | Lines of Code | \~139,000  |
| Node.js binding       | Technology    | NAPI-RS    |
| Python binding        | Technology    | PyO3       |
| Ruby binding          | Technology    | Magnus     |
| PHP binding           | Technology    | ext-php-rs |
| Java binding          | Technology    | JNI        |
| Kotlin binding        | Technology    | JNI        |
| Swift binding         | Technology    | C FFI      |
| .NET binding          | Technology    | P/Invoke   |
| Go binding            | Technology    | cgo        |
| WASM binding          | Technology    | wasm-pack  |
| CLI (mcp-server)      | Size          | 221 KB     |
| CLI (harness)         | Size          | 62 KB      |
| Domain Modules        | Count         | 32         |
| Domain Types          | Count         | 400+       |
| Database Tables       | Count         | 70+        |
| Database Migrations   | Count         | 28         |
| API Methods           | Count         | 700+       |
| Language Bindings     | Count         | 10         |
| Commerce Skills       | Count         | 38         |
| AI Providers          | Count         | 4          |
| Messaging Channels    | Count         | 9          |
| Heartbeat Checkers    | Count         | 6          |
| CLI Programs          | Count         | 26+        |
| Sequencer             | Lines of Code | \~5,000    |
| Set Chain Contracts   | Lines of Code | \~1,000    |
| Anchor Service        | Lines 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*
