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

# StateSet iCommerce Skill

> Skills for running the StateSet iCommerce engine and syncing to the sequencer.

# StateSet iCommerce Engine

Infrastructure for autonomous commerce. Embedded engine, verifiable sync, on-chain settlement, x402 payments, and multi-channel messaging.

## Skill Files

| File                     | URL                                                          |
| ------------------------ | ------------------------------------------------------------ |
| **SKILL.md** (this file) | `https://docs.stateset.com/stateset-icommerce-skill.md`      |
| **QUICKSTART.md**        | `https://docs.stateset.com/stateset-icommerce-quickstart.md` |

**Or just read them from the URLs above!**

**Check for updates:** Re-fetch these files anytime to see new features!

***

## API Base URLs

| Service             | Base URL                                         | Purpose                                                |
| ------------------- | ------------------------------------------------ | ------------------------------------------------------ |
| **Commerce Engine** | Local (embedded)                                 | Core commerce operations (orders, products, customers) |
| **Sequencer**       | `https://api.sequencer.stateset.com/api/v1`      | VES event ordering, proofs, commitments                |
| **VES (Sequencer)** | `https://api.sequencer.stateset.com/api/v1/ves`  | VES v1.0 protocol endpoints                            |
| **x402 Payments**   | `https://api.sequencer.stateset.com/api/v1/x402` | Payment intents, batches, settlements                  |

**Environment Variables:**

```bash theme={null}
export STATESET_API_KEY=sk_live_xxx
export STATESET_SEQUENCER_URL=https://api.sequencer.stateset.com/api/v1
```

***

## Architecture Overview

StateSet iCommerce is a five-layer infrastructure stack:

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

***

## Install the CLI

```bash theme={null}
npm install -g @stateset/cli
```

Verify installation:

```bash theme={null}
stateset --version
```

**Recommended:** Save your credentials to `~/.config/stateset/config.json`:

```json theme={null}
{
  "api_key": "sk_live_xxx",
  "tenant_id": "your-tenant-id",
  "store_id": "your-store-id",
  "database_path": "~/.stateset/commerce.db"
}
```

***

## Initialize the Engine

Create a new commerce database:

```bash theme={null}
stateset init --demo
```

This creates `~/.stateset/commerce.db` with:

* SQLite database with 70+ tables
* Demo data (customers, products, inventory)
* Sync outbox ready for VES

**Without demo data:**

```bash theme={null}
stateset init
```

***

## Authentication

Commerce operations run locally via the embedded engine. Sequencer API requests require your API key:

```bash theme={null}
curl https://api.sequencer.stateset.com/api/v1/events \
  -H "Authorization: Bearer YOUR_API_KEY"
```

For CLI operations:

```bash theme={null}
export STATESET_API_KEY=sk_live_xxx
stateset orders list        # Local embedded engine
stateset sync push          # Syncs to sequencer API
```

***

## Agent Registration

AI agents must register with the sequencer to receive an API key for authentication.

### Register a New Agent

```bash theme={null}
curl -X POST https://api.sequencer.stateset.com/api/v1/agents/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-commerce-agent",
    "description": "Autonomous commerce agent for order processing"
  }'
```

**Response:**

```json theme={null}
{
  "success": true,
  "agentId": "550e8400-e29b-41d4-a716-446655440000",
  "tenantId": "660e8400-e29b-41d4-a716-446655440001",
  "apiKey": "ss_660e8400aBcDeFgHiJkLmNoPqRsTuVwXyZ",
  "permissions": "read_write",
  "message": "Agent registered successfully. Store your API key securely - it cannot be retrieved later."
}
```

**Important:** Store the `apiKey` securely. It is only returned once and cannot be retrieved later.

### Registration Options

| Field         | Type    | Description                            |
| ------------- | ------- | -------------------------------------- |
| `name`        | string  | Human-readable agent name (required)   |
| `description` | string  | Agent purpose description              |
| `tenantId`    | UUID    | Join existing tenant (optional)        |
| `storeIds`    | UUID\[] | Restrict to specific stores            |
| `readOnly`    | boolean | Read-only permissions (default: false) |
| `admin`       | boolean | Admin permissions (default: false)     |
| `rateLimit`   | number  | Requests per minute limit              |

### Get Agent Details

```bash theme={null}
curl https://api.sequencer.stateset.com/api/v1/agents/{agent_id} \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Create Additional API Keys

```bash theme={null}
curl -X POST https://api.sequencer.stateset.com/api/v1/agents/{agent_id}/api-keys \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "readOnly": true
  }'
```

### List API Keys

```bash theme={null}
curl https://api.sequencer.stateset.com/api/v1/agents/{agent_id}/api-keys \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Revoke an API Key

```bash theme={null}
curl -X DELETE https://api.sequencer.stateset.com/api/v1/agents/{agent_id}/api-keys/{key_prefix} \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Register Signing Key (for VES Events)

After registration, agents should register an Ed25519 signing key for VES event signatures:

```bash theme={null}
curl -X POST https://api.sequencer.stateset.com/api/v1/agents/keys \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tenantId": "660e8400-e29b-41d4-a716-446655440001",
    "agentId": "550e8400-e29b-41d4-a716-446655440000",
    "keyId": 1,
    "publicKey": "0x1234567890abcdef...",
    "validFrom": "2026-01-30T00:00:00Z",
    "validTo": "2027-01-30T00:00:00Z"
  }'
```

***

## Core Operations

### Customers

```bash theme={null}
# List customers
stateset customers list

# Create customer
stateset customers create --email "alice@example.com" --name "Alice Smith"

# Get customer by email
stateset customers get --email "alice@example.com"
```

**Embedded API (local):**

```javascript theme={null}
const customer = commerce.customers.create({
  email: 'alice@example.com',
  name: 'Alice Smith'
});
```

### Products

```bash theme={null}
# List products
stateset products list

# Create product
stateset products create --sku "SHOE-001" --name "Running Shoes" --price 99.99

# Get product by SKU
stateset products get --sku "SHOE-001"
```

### Inventory

```bash theme={null}
# Check stock
stateset inventory get --sku "SHOE-001"

# Adjust inventory
stateset inventory adjust --sku "SHOE-001" --quantity 100 --reason "Initial stock"

# Reserve inventory
stateset inventory reserve --sku "SHOE-001" --quantity 5 --reference "ORD-123"
```

### Orders

```bash theme={null}
# List orders
stateset orders list

# Create order
stateset orders create --customer-email "alice@example.com" --items '[{"sku":"SHOE-001","qty":2}]'

# Get order
stateset orders get --id "ord_xxx"

# Ship order
stateset orders ship --id "ord_xxx" --carrier "fedex" --tracking "1234567890"
```

### Returns

```bash theme={null}
# Create return
stateset returns create --order-id "ord_xxx" --reason "Defective" --items '[{"sku":"SHOE-001","qty":1}]'

# Approve return
stateset returns approve --id "ret_xxx"

# Complete return
stateset returns complete --id "ret_xxx"
```

***

## Checkout Flow

### Cart Operations

```bash theme={null}
# Create cart
stateset carts create --customer-email "alice@example.com"

# Add item to cart
stateset carts add-item --cart-id "cart_xxx" --sku "SHOE-001" --quantity 2

# Get cart
stateset carts get --id "cart_xxx"

# Checkout
stateset carts checkout --id "cart_xxx" --payment-method "card"
```

### Complete Checkout Flow

```bash theme={null}
# 1. Create cart
CART_ID=$(stateset carts create --customer-email "alice@example.com" --json | jq -r '.id')

# 2. Add items
stateset carts add-item --cart-id $CART_ID --sku "SHOE-001" --quantity 2

# 3. Apply promotion (optional)
stateset carts apply-coupon --cart-id $CART_ID --code "SAVE10"

# 4. Calculate tax
stateset carts calculate-tax --cart-id $CART_ID

# 5. Checkout
stateset carts checkout --cart-id $CART_ID --payment-method "card"
```

***

## x402 Payments

HTTP-native stablecoin micropayments between AI agents.

### Supported Networks

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

### Create Payment Intent

```bash theme={null}
stateset-pay create \
  --amount "10.00" \
  --asset "USDC" \
  --network "base" \
  --recipient "0x..."
```

### Check Balance

```bash theme={null}
stateset-pay balance --network base
```

### Payment Flow

```
1. GET /api/products/123
   → HTTP 402 Payment Required
   → { asset: "USDC", amount: "0.001", network: "set-chain", recipient: "0x..." }

2. Agent signs PaymentIntent (Ed25519)

3. GET /api/products/123
   X-Payment: <signed intent>
   → 200 OK
   X-Payment-Receipt: <receipt>
```

***

## Verifiable Event Sync (VES)

Multi-agent coordination with cryptographic proofs.

### Check Sync Status

```bash theme={null}
stateset sync status
```

Response:

```json theme={null}
{
  "local_head": 1523,
  "remote_head": 1520,
  "pending_events": 3,
  "last_sync": "2026-01-30T10:15:00Z"
}
```

### Push Events

```bash theme={null}
stateset sync push
```

### Pull Events

```bash theme={null}
stateset sync pull
```

### Full Sync

```bash theme={null}
stateset sync full
```

### View Outbox

```bash theme={null}
stateset sync outbox
```

### Entity History

```bash theme={null}
stateset sync history --entity-type order --entity-id "ord_xxx"
```

***

## Sequencer API Reference

The StateSet Sequencer provides deterministic event ordering with cryptographic proofs for multi-agent coordination.

**Base URL:** `https://api.sequencer.stateset.com`

### Authentication

All sequencer requests require Bearer token authentication:

```bash theme={null}
curl https://api.sequencer.stateset.com/api/v1/events \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Event Ingestion

**Legacy Event Ingestion (without signatures)**

```bash theme={null}
curl -X POST https://api.sequencer.stateset.com/api/v1/events/ingest \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "YOUR_AGENT_ID",
    "events": [{
      "tenant_id": "YOUR_TENANT_ID",
      "store_id": "YOUR_STORE_ID",
      "event_id": "unique-event-uuid",
      "entity_type": "order",
      "entity_id": "ord_001",
      "event_type": "order.created",
      "payload": {
        "order_id": "ord_001",
        "customer_id": "cust_001",
        "total": 99.99,
        "currency": "USD",
        "status": "pending"
      },
      "payload_hash": "sha256_hash_of_canonical_json_payload",
      "timestamp": "2026-01-30T10:00:00Z",
      "created_at": "2026-01-30T10:00:00Z",
      "source_agent": "YOUR_AGENT_ID",
      "version": 1
    }]
  }'
```

**Response:**

```json theme={null}
{
  "batch_id": "81baf3bd-05b3-47f3-9a85-251c0f84e807",
  "events_accepted": 1,
  "events_rejected": 0,
  "assigned_sequence_start": 1,
  "assigned_sequence_end": 1,
  "head_sequence": 1
}
```

**Required Event Fields:**

| Field          | Type     | Description                                     |
| -------------- | -------- | ----------------------------------------------- |
| `tenant_id`    | UUID     | Your tenant ID from registration                |
| `store_id`     | UUID     | Store identifier                                |
| `event_id`     | UUID     | Unique event identifier                         |
| `entity_type`  | string   | Entity type (order, customer, product, etc.)    |
| `entity_id`    | string   | Entity identifier                               |
| `event_type`   | string   | Event type (order.created, order.shipped, etc.) |
| `payload`      | object   | Event data                                      |
| `payload_hash` | string   | SHA-256 hash of canonical JSON payload          |
| `timestamp`    | ISO-8601 | Event timestamp                                 |
| `created_at`   | ISO-8601 | Creation timestamp                              |
| `source_agent` | UUID     | Agent ID that created the event                 |
| `version`      | number   | Event version (typically 1)                     |

**Computing Payload Hash:**

```bash theme={null}
# Canonical JSON (alphabetically sorted keys, no whitespace)
PAYLOAD='{"currency":"USD","customer_id":"cust_001","order_id":"ord_001","status":"pending","total":99.99}'
HASH=$(echo -n "$PAYLOAD" | sha256sum | cut -d' ' -f1)
```

**VES Event Ingestion (with Ed25519 signatures)**

```bash theme={null}
POST https://api.sequencer.stateset.com/api/v1/ves/events/ingest
```

Requires registered signing key. See "Register Signing Key" section above.

### Events & Head

```bash theme={null}
# List events
GET https://api.sequencer.stateset.com/api/v1/events

# Get head sequence number
GET https://api.sequencer.stateset.com/api/v1/head

# Get entity history
GET https://api.sequencer.stateset.com/api/v1/entities/{entity_type}/{entity_id}
```

### VES Commitments

```bash theme={null}
# List all commitments
GET https://api.sequencer.stateset.com/api/v1/ves/commitments

# Create new commitment
POST https://api.sequencer.stateset.com/api/v1/ves/commitments

# Create and anchor commitment
POST https://api.sequencer.stateset.com/api/v1/ves/commitments/anchor

# Get specific commitment
GET https://api.sequencer.stateset.com/api/v1/ves/commitments/{batch_id}
```

### VES Validity Proofs (STARK ZK Proofs)

```bash theme={null}
# Get public inputs for proof generation
GET https://api.sequencer.stateset.com/api/v1/ves/validity/{batch_id}/inputs

# List proofs for batch
GET https://api.sequencer.stateset.com/api/v1/ves/validity/{batch_id}/proofs

# Submit external STARK proof
POST https://api.sequencer.stateset.com/api/v1/ves/validity/{batch_id}/proofs
Content-Type: application/json
{
  "proof_data": "base64_encoded_proof",
  "prover": "agent_address"
}

# Get specific proof
GET https://api.sequencer.stateset.com/api/v1/ves/validity/proofs/{proof_id}

# Verify proof
GET https://api.sequencer.stateset.com/api/v1/ves/validity/proofs/{proof_id}/verify
```

### VES Compliance Proofs (Per-Event Encrypted)

```bash theme={null}
# Get compliance inputs for event
POST https://api.sequencer.stateset.com/api/v1/ves/compliance/{event_id}/inputs

# List compliance proofs for event
GET https://api.sequencer.stateset.com/api/v1/ves/compliance/{event_id}/proofs

# Submit compliance proof
POST https://api.sequencer.stateset.com/api/v1/ves/compliance/{event_id}/proofs

# Get specific compliance proof
GET https://api.sequencer.stateset.com/api/v1/ves/compliance/proofs/{proof_id}

# Verify compliance proof
GET https://api.sequencer.stateset.com/api/v1/ves/compliance/proofs/{proof_id}/verify
```

### Inclusion Proofs

```bash theme={null}
# Get inclusion proof for sequence number
GET https://api.sequencer.stateset.com/api/v1/ves/proofs/{sequence_number}

# Verify inclusion proof
POST https://api.sequencer.stateset.com/api/v1/ves/proofs/verify
Content-Type: application/json
{
  "sequence_number": 1523,
  "merkle_proof": {...}
}
```

### On-Chain Anchoring

```bash theme={null}
# Anchor commitment to Set Chain L2
POST https://api.sequencer.stateset.com/api/v1/ves/anchor
Content-Type: application/json
{
  "batch_id": "batch_xxx"
}

# Verify on-chain anchor
GET https://api.sequencer.stateset.com/api/v1/ves/anchor/{batch_id}/verify
```

### Agent Key Management

```bash theme={null}
# Register agent signing key
POST https://api.sequencer.stateset.com/api/v1/agents/keys
Content-Type: application/json
{
  "agent_id": "agent_xxx",
  "public_key": "ed25519_pubkey",
  "permissions": ["read", "write"]
}
```

### Schema Registry

```bash theme={null}
# List all schemas
GET https://api.sequencer.stateset.com/api/v1/schemas

# Register new schema
POST https://api.sequencer.stateset.com/api/v1/schemas
Content-Type: application/json
{
  "event_type": "order.created",
  "schema": {...}
}

# Validate payload against schema
POST https://api.sequencer.stateset.com/api/v1/schemas/validate

# Get schema by ID
GET https://api.sequencer.stateset.com/api/v1/schemas/{schema_id}

# Update schema status
PUT https://api.sequencer.stateset.com/api/v1/schemas/{schema_id}/status

# Delete schema
DELETE https://api.sequencer.stateset.com/api/v1/schemas/{schema_id}

# List schemas by event type
GET https://api.sequencer.stateset.com/api/v1/schemas/event-type/{event_type}

# Get latest schema for event type
GET https://api.sequencer.stateset.com/api/v1/schemas/event-type/{event_type}/latest
```

### x402 Payment Protocol

The x402 protocol enables agent-to-agent stablecoin payments with off-chain signing and batched on-chain settlement.

#### Payment Flow Overview

```
1. Agent generates Ed25519 signing key
2. Agent registers public key with sequencer
3. Agent creates and signs payment intent
4. Sequencer validates signature and sequences payment
5. Payments are batched and committed (Merkle root computed)
6. Batch is settled on Set Chain L2
7. Agent retrieves receipt with inclusion proof
```

#### Step 1: Generate and Register Signing Key

```python theme={null}
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives import serialization

# Generate Ed25519 key pair
private_key = Ed25519PrivateKey.generate()
public_key = private_key.public_key()

# Get raw public key bytes (32 bytes)
public_key_bytes = public_key.public_bytes(
    encoding=serialization.Encoding.Raw,
    format=serialization.PublicFormat.Raw
)
public_key_hex = public_key_bytes.hex()
```

```bash theme={null}
# Register public key with sequencer
curl -X POST https://api.sequencer.stateset.com/api/v1/agents/keys \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tenantId": "YOUR_TENANT_ID",
    "agentId": "YOUR_AGENT_ID",
    "keyId": 1,
    "publicKey": "PUBLIC_KEY_HEX"
  }'
```

#### Step 2: Compute Signing Hash

The signing hash must be computed exactly as the sequencer expects:

```python theme={null}
import hashlib
import struct

def compute_x402_signing_hash(
    payer_address: str,
    payee_address: str,
    amount: int,           # In smallest units (e.g., 1 USDC = 1000000)
    asset: str,            # "usdc", "usdt", "ssusd"
    network: str,          # "set_chain", "base", "ethereum"
    chain_id: int,         # 84532001 for Set Chain
    valid_until: int,      # Unix timestamp
    nonce: int
) -> bytes:
    hasher = hashlib.sha256()
    hasher.update(b"X402_PAYMENT_V1")           # Domain separator
    hasher.update(payer_address.encode())       # Payer address string
    hasher.update(payee_address.encode())       # Payee address string
    hasher.update(struct.pack(">Q", amount))    # u64 big-endian
    hasher.update(asset.encode())               # Asset string
    hasher.update(network.encode())             # Network string
    hasher.update(struct.pack(">Q", chain_id))  # u64 big-endian
    hasher.update(struct.pack(">Q", valid_until))  # u64 big-endian
    hasher.update(struct.pack(">Q", nonce))     # u64 big-endian
    return hasher.digest()
```

#### Step 3: Sign and Submit Payment Intent

```python theme={null}
import time
import requests

# Payment parameters
payer_address = "0x..."  # Your wallet address
payee_address = "0x..."  # Recipient wallet address
amount = 1000000         # 1 USDC (6 decimals)
asset = "usdc"
network = "set_chain"
chain_id = 84532001
valid_until = int(time.time()) + 3600  # Valid for 1 hour
nonce = 1

# Compute signing hash
signing_hash = compute_x402_signing_hash(
    payer_address, payee_address, amount, asset,
    network, chain_id, valid_until, nonce
)

# Sign with Ed25519 private key
signature = private_key.sign(signing_hash)

# Submit payment intent
response = requests.post(
    "https://api.sequencer.stateset.com/api/v1/x402/payments",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "tenant_id": TENANT_ID,
        "store_id": STORE_ID,
        "agent_id": AGENT_ID,
        "payer_address": payer_address,
        "payee_address": payee_address,
        "amount": amount,
        "asset": asset,
        "network": network,
        "valid_until": valid_until,
        "nonce": nonce,
        "signing_hash": f"0x{signing_hash.hex()}",
        "payer_signature": f"0x{signature.hex()}",
        "payer_public_key": f"0x{public_key_hex}",
        "description": "Payment for services",
        "idempotency_key": "unique-payment-id"
    }
)

# Response:
# {
#   "intent_id": "c0dbf4b1-b281-41d4-88c4-5839bc3761f0",
#   "status": "sequenced",
#   "sequence_number": 1,
#   "sequenced_at": "2026-01-30T20:36:40Z"
# }
```

#### Step 4: Create and Commit Batch

```bash theme={null}
curl -X POST https://api.sequencer.stateset.com/api/v1/x402/batches \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "YOUR_TENANT_ID",
    "store_id": "YOUR_STORE_ID",
    "network": "set_chain"
  }'

# Response:
# {
#   "batch_id": "92905fab-faff-4440-9d79-2d6d6de8c98b",
#   "status": "committed",
#   "payment_count": 1,
#   "merkle_root": "0xe747946052625166d51d89b7d3da000fed1577dcc8f11231982de13b3b916cf8",
#   "sequence_range": [1, 1]
# }
```

#### Step 5: Settle Batch On-Chain

```bash theme={null}
curl -X POST https://api.sequencer.stateset.com/api/v1/x402/batches/settle \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "batch_id": "92905fab-faff-4440-9d79-2d6d6de8c98b"
  }'

# Response:
# {
#   "batch_id": "92905fab-faff-4440-9d79-2d6d6de8c98b",
#   "status": "submitted",
#   "tx_hash": "0x...",
#   "message": "Batch settlement initiated"
# }
```

#### Step 6: Get Payment Receipt

```bash theme={null}
curl https://api.sequencer.stateset.com/api/v1/x402/payments/{intent_id}/receipt \
  -H "Authorization: Bearer YOUR_API_KEY"

# Response:
# {
#   "receipt": {
#     "receipt_id": "ee5876bc-f728-4049-9769-7ad81313bd1f",
#     "intent_id": "c0dbf4b1-b281-41d4-88c4-5839bc3761f0",
#     "sequence_number": 1,
#     "batch_id": "92905fab-faff-4440-9d79-2d6d6de8c98b",
#     "merkle_root": "0xe747946052625166d51d89b7d3da000fed1577dcc8f11231982de13b3b916cf8",
#     "inclusion_proof": [...],
#     "leaf_index": 0,
#     "payer_address": "0x...",
#     "payee_address": "0x...",
#     "amount": 1000000,
#     "asset": "usdc",
#     "tx_hash": "0x..."
#   }
# }
```

#### x402 API Reference

| Method | Endpoint                             | Description             |
| ------ | ------------------------------------ | ----------------------- |
| POST   | `/api/v1/x402/payments`              | Submit payment intent   |
| GET    | `/api/v1/x402/payments`              | List payment intents    |
| GET    | `/api/v1/x402/payments/{id}`         | Get payment status      |
| GET    | `/api/v1/x402/payments/{id}/receipt` | Get payment receipt     |
| POST   | `/api/v1/x402/batches`               | Create and commit batch |
| GET    | `/api/v1/x402/batches/{id}`          | Get batch status        |
| POST   | `/api/v1/x402/batches/settle`        | Settle batch on-chain   |

#### Supported Networks

| Network             | Chain ID | Description            |
| ------------------- | -------- | ---------------------- |
| `set_chain`         | 84532001 | Set Chain L2 (primary) |
| `set_chain_testnet` | 84532002 | Set Chain testnet      |
| `base`              | 8453     | Base L2                |
| `base_sepolia`      | 84532    | Base testnet           |
| `ethereum`          | 1        | Ethereum mainnet       |
| `arbitrum`          | 42161    | Arbitrum One           |
| `optimism`          | 10       | Optimism               |

#### Supported Assets

| Asset    | Description                     |
| -------- | ------------------------------- |
| `usdc`   | USD Coin                        |
| `usdt`   | Tether                          |
| `ssusd`  | StateSet USD (yield-bearing)    |
| `wssusd` | Wrapped StateSet USD (ERC-4626) |
| `dai`    | DAI Stablecoin                  |

#### Complete Agent-to-Agent Payment Example

```python theme={null}
"""
Complete x402 payment flow between two AI agents.
Agent A pays Agent B 1 USDC for services rendered.
"""
import hashlib
import struct
import time
import requests
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives import serialization

# ============================================================
# Step 1: Register Agent A (if not already registered)
# ============================================================
registration = requests.post(
    "https://api.sequencer.stateset.com/api/v1/agents/register",
    json={"name": "agent-a", "description": "Payer agent"}
)
agent_a = registration.json()
# agent_a = {"agentId": "...", "tenantId": "...", "apiKey": "ss_..."}

# ============================================================
# Step 2: Generate and register signing key for Agent A
# ============================================================
private_key = Ed25519PrivateKey.generate()
public_key_bytes = private_key.public_key().public_bytes(
    encoding=serialization.Encoding.Raw,
    format=serialization.PublicFormat.Raw
)

requests.post(
    "https://api.sequencer.stateset.com/api/v1/agents/keys",
    headers={"Authorization": f"Bearer {agent_a['apiKey']}"},
    json={
        "tenantId": agent_a["tenantId"],
        "agentId": agent_a["agentId"],
        "keyId": 1,
        "publicKey": public_key_bytes.hex()
    }
)

# ============================================================
# Step 3: Create and sign payment intent
# ============================================================
payer_address = "0xAgentAWalletAddress1234567890abcdef"
payee_address = "0xAgentBWalletAddress1234567890abcdef"
amount = 1000000  # 1 USDC
valid_until = int(time.time()) + 3600
nonce = 1

# Compute signing hash (must match sequencer's format exactly)
hasher = hashlib.sha256()
hasher.update(b"X402_PAYMENT_V1")
hasher.update(payer_address.encode())
hasher.update(payee_address.encode())
hasher.update(struct.pack(">Q", amount))
hasher.update(b"usdc")
hasher.update(b"set_chain")
hasher.update(struct.pack(">Q", 84532001))  # chain_id
hasher.update(struct.pack(">Q", valid_until))
hasher.update(struct.pack(">Q", nonce))
signing_hash = hasher.digest()

signature = private_key.sign(signing_hash)

# ============================================================
# Step 4: Submit payment intent
# ============================================================
payment = requests.post(
    "https://api.sequencer.stateset.com/api/v1/x402/payments",
    headers={"Authorization": f"Bearer {agent_a['apiKey']}"},
    json={
        "tenant_id": agent_a["tenantId"],
        "store_id": "00000000-0000-0000-0000-000000000001",
        "agent_id": agent_a["agentId"],
        "payer_address": payer_address,
        "payee_address": payee_address,
        "amount": amount,
        "asset": "usdc",
        "network": "set_chain",
        "valid_until": valid_until,
        "nonce": nonce,
        "signing_hash": f"0x{signing_hash.hex()}",
        "payer_signature": f"0x{signature.hex()}",
        "payer_public_key": f"0x{public_key_bytes.hex()}",
        "description": "Payment from Agent A to Agent B"
    }
).json()
# payment = {"intent_id": "...", "status": "sequenced", "sequence_number": 1}

# ============================================================
# Step 5: Create and commit batch
# ============================================================
batch = requests.post(
    "https://api.sequencer.stateset.com/api/v1/x402/batches",
    headers={"Authorization": f"Bearer {agent_a['apiKey']}"},
    json={
        "tenant_id": agent_a["tenantId"],
        "store_id": "00000000-0000-0000-0000-000000000001",
        "network": "set_chain"
    }
).json()
# batch = {"batch_id": "...", "status": "committed", "merkle_root": "0x..."}

# ============================================================
# Step 6: Settle batch on-chain
# ============================================================
settlement = requests.post(
    "https://api.sequencer.stateset.com/api/v1/x402/batches/settle",
    headers={"Authorization": f"Bearer {agent_a['apiKey']}"},
    json={"batch_id": batch["batch_id"]}
).json()

# ============================================================
# Step 7: Get payment receipt with inclusion proof
# ============================================================
receipt = requests.get(
    f"https://api.sequencer.stateset.com/api/v1/x402/payments/{payment['intent_id']}/receipt",
    headers={"Authorization": f"Bearer {agent_a['apiKey']}"}
).json()

print(f"Payment complete!")
print(f"Intent ID: {payment['intent_id']}")
print(f"Batch ID: {batch['batch_id']}")
print(f"Merkle Root: {batch['merkle_root']}")
print(f"Receipt ID: {receipt['receipt']['receipt_id']}")
```

### Health & Status

```bash theme={null}
# Basic health check
GET https://api.sequencer.stateset.com/health

# Readiness check (includes DB)
GET https://api.sequencer.stateset.com/ready

# Detailed component health
GET https://api.sequencer.stateset.com/health/detailed
```

### Legacy Endpoints

```bash theme={null}
# Legacy commitments
GET https://api.sequencer.stateset.com/api/v1/commitments
POST https://api.sequencer.stateset.com/api/v1/commitments
GET https://api.sequencer.stateset.com/api/v1/commitments/{batch_id}

# Legacy proofs
GET https://api.sequencer.stateset.com/api/v1/proofs/{sequence_number}
POST https://api.sequencer.stateset.com/api/v1/proofs/verify

# Legacy anchoring
GET https://api.sequencer.stateset.com/api/v1/anchor/status
POST https://api.sequencer.stateset.com/api/v1/anchor
GET https://api.sequencer.stateset.com/api/v1/anchor/{batch_id}/verify
```

***

## Agent Integration Patterns

### Full Sync Flow for Agents

```bash theme={null}
# 1. Ingest local commerce events to sequencer
curl -X POST https://api.sequencer.stateset.com/api/v1/ves/events/ingest \
  -H "Authorization: Bearer $STATESET_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [{
      "event_id": "evt_001",
      "event_type": "order.created",
      "entity_type": "order",
      "entity_id": "ord_xxx",
      "payload": {"customer_id": "cust_xxx", "total": 99.99}
    }]
  }'

# 2. Get sequencer receipt with sequence number
# Response includes: sequence_number, merkle_root, signature

# 3. Create commitment batch
curl -X POST https://api.sequencer.stateset.com/api/v1/ves/commitments \
  -H "Authorization: Bearer $STATESET_API_KEY"

# 4. Anchor to Set Chain
curl -X POST https://api.sequencer.stateset.com/api/v1/ves/anchor \
  -H "Authorization: Bearer $STATESET_API_KEY" \
  -d '{"batch_id": "batch_xxx"}'

# 5. Verify on-chain
curl https://api.sequencer.stateset.com/api/v1/ves/anchor/batch_xxx/verify \
  -H "Authorization: Bearer $STATESET_API_KEY"
```

### Multi-Agent Coordination

```javascript theme={null}
// Agent A: Create order and sync
const order = await commerce.orders.create({...});
const receipt = await fetch('https://api.sequencer.stateset.com/api/v1/ves/events/ingest', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${API_KEY}` },
  body: JSON.stringify({
    events: [{
      event_type: 'order.created',
      entity_type: 'order',
      entity_id: order.id,
      payload: order
    }]
  })
}).then(r => r.json());

// Agent B: Pull events and verify
const head = await fetch('https://api.sequencer.stateset.com/api/v1/head', {
  headers: { 'Authorization': `Bearer ${API_KEY}` }
}).then(r => r.json());

const proof = await fetch(`https://api.sequencer.stateset.com/api/v1/ves/proofs/${receipt.sequence_number}`, {
  headers: { 'Authorization': `Bearer ${API_KEY}` }
}).then(r => r.json());
```

***

## MCP Tool Integration

The CLI exposes 700+ commerce operations via MCP for AI agents.

### Start MCP Server

```bash theme={null}
stateset mcp serve
```

### Tool Categories

| 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     | create\_cart, add\_cart\_item, checkout           |
| Payments  | create\_payment, process\_refund                  |
| Analytics | get\_sales\_summary, get\_demand\_forecast        |
| Sync      | sync\_status, sync\_push, sync\_pull              |

### Permission Model

```bash theme={null}
# Read operations - always allowed
stateset "list orders"

# Write operations - blocked by default
stateset "create an order"
# → Shows preview, does not execute

# Write operations - enabled with --apply
stateset --apply "create an order for alice@example.com"
# → Executes operation
```

***

## Multi-Channel Messaging

### Supported Channels

| Channel     | Protocol         | Status       |
| ----------- | ---------------- | ------------ |
| WhatsApp    | Cloud API        | GA           |
| Telegram    | Bot API          | GA           |
| Discord     | Gateway + REST   | GA           |
| Slack       | Events + Web API | GA           |
| Signal      | signal-cli       | GA           |
| Google Chat | Spaces API       | GA           |
| WebChat     | WebSocket        | GA           |
| iMessage    | AppleScript      | Experimental |
| Teams       | Bot Framework    | Experimental |

### Launch Channels

```bash theme={null}
# All configured channels
stateset-channels

# Specific channels
stateset-whatsapp
stateset-discord
stateset-telegram
stateset-slack
```

### Configuration

Create `~/.stateset/channels.json`:

```json theme={null}
{
  "whatsapp": {
    "enabled": true,
    "phone_number_id": "xxx",
    "access_token": "xxx"
  },
  "discord": {
    "enabled": true,
    "bot_token": "xxx",
    "guild_id": "xxx"
  }
}
```

***

## Warehouse Operations

### Warehouse Management

```bash theme={null}
# Create warehouse
stateset warehouse create --name "Main DC" --address "123 Warehouse Ave"

# Add zone
stateset warehouse add-zone --warehouse-id "wh_xxx" --name "Picking Zone A"

# Add location
stateset warehouse add-location --zone-id "zone_xxx" --name "A-01-01"
```

### Fulfillment

```bash theme={null}
# Create wave
stateset fulfillment create-wave --warehouse-id "wh_xxx" --orders '["ord_xxx", "ord_yyy"]'

# Assign pick task
stateset fulfillment assign-pick --task-id "pick_xxx" --picker "user_xxx"

# Complete pick
stateset fulfillment complete-pick --task-id "pick_xxx"

# Pack
stateset fulfillment pack --wave-id "wave_xxx"

# Ship
stateset fulfillment ship --wave-id "wave_xxx"
```

### Receiving

```bash theme={null}
# Create receipt
stateset receiving create --po-id "po_xxx" --expected-date "2026-02-01"

# Receive items
stateset receiving receive-items --receipt-id "rec_xxx" --items '[{"sku":"SHOE-001","qty":100}]'

# Put away
stateset receiving put-away --receipt-id "rec_xxx" --location "A-01-01"
```

***

## Financial Operations

### General Ledger

```bash theme={null}
# Create account
stateset gl create-account --number "1000" --name "Cash" --type "asset"

# Post journal entry
stateset gl post-entry --debit '{"account":"1000","amount":100}' --credit '{"account":"4000","amount":100}'

# Trial balance
stateset gl trial-balance

# Close period
stateset gl close-period --period "2026-01"
```

### Accounts Receivable

```bash theme={null}
# AR aging
stateset ar aging

# Apply payment
stateset ar apply-payment --customer-id "cust_xxx" --amount 500 --invoice-id "inv_xxx"

# Generate statement
stateset ar generate-statement --customer-id "cust_xxx"
```

### Accounts Payable

```bash theme={null}
# Create bill
stateset ap create-bill --supplier-id "sup_xxx" --amount 1000 --due-date "2026-02-15"

# Schedule payment
stateset ap schedule-payment --bill-id "bill_xxx" --date "2026-02-10"

# AP aging
stateset ap aging
```

***

## Vector Search

Hybrid semantic + BM25 search across commerce entities.

```bash theme={null}
# Index products
stateset vector index-products

# Search products
stateset vector search --query "red running shoes under $100" --limit 10

# Index customers
stateset vector index-customers

# Search customers
stateset vector search-customers --query "enterprise accounts in California"
```

***

## Heartbeat Monitor

Proactive health checking for commerce operations.

### Built-in 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      |

### CLI

```bash theme={null}
# Health status
stateset heartbeat status

# Trigger check
stateset heartbeat run low-stock

# Enable/disable checker
stateset heartbeat enable low-stock
stateset heartbeat disable low-stock
```

***

## Skills System

38 built-in skills covering the full commerce lifecycle.

### Install Skills

```bash theme={null}
npm install -g @stateset/icommerce-skills
icommerce-skills list
icommerce-skills install
```

### Skill Categories

**Core Commerce:**

* commerce-engine-setup
* commerce-embedded-sdk
* commerce-customers
* commerce-products
* commerce-orders
* commerce-checkout
* commerce-payments

**Inventory & Fulfillment:**

* commerce-inventory
* commerce-shipments
* commerce-returns
* commerce-backorders
* commerce-fulfillment
* commerce-receiving
* commerce-warehouse
* commerce-lots-and-serials

**Financial:**

* commerce-invoices
* commerce-tax
* commerce-currency
* commerce-accounts-payable
* commerce-accounts-receivable
* commerce-cost-accounting
* commerce-credit
* commerce-general-ledger

**Platform:**

* commerce-sync
* commerce-autonomous-engine
* commerce-vector-search
* commerce-mcp-tools

***

## Language Bindings

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     |
| Python      | PyO3           | Data science, ML          |
| Browser     | wasm-pack      | Client-side               |
| Ruby        | Magnus         | Rails                     |
| PHP         | ext-php-rs     | Laravel/WordPress         |
| Java        | JNI            | Enterprise JVM            |
| Kotlin      | JNI            | Android, server           |
| Swift       | C FFI          | iOS/macOS                 |
| .NET/C#     | P/Invoke       | ASP.NET, Unity            |
| Go          | cgo            | Go microservices          |

### Node.js Example

```javascript theme={null}
const { Commerce } = require('@stateset/embedded');

const commerce = new Commerce('~/.stateset/commerce.db');

// Create customer
const customer = commerce.customers.create({
  email: 'alice@example.com',
  name: 'Alice Smith'
});

// Create order
const order = commerce.orders.create({
  customerId: customer.id,
  items: [{ sku: 'SHOE-001', quantity: 2 }]
});

console.log(`Order created: ${order.id}`);
```

### Python Example

```python theme={null}
from stateset_embedded import Commerce

commerce = Commerce('~/.stateset/commerce.db')

# Create customer
customer = commerce.customers.create(
    email='alice@example.com',
    name='Alice Smith'
)

# Create order
order = commerce.orders.create(
    customer_id=customer.id,
    items=[{'sku': 'SHOE-001', 'quantity': 2}]
)

print(f'Order created: {order.id}')
```

***

## Response Format

Success:

```json theme={null}
{"success": true, "data": {...}}
```

Error:

```json theme={null}
{"success": false, "error": "Description", "hint": "How to fix"}
```

***

## Rate Limits

| Limit            | Value       |
| ---------------- | ----------- |
| API requests     | 1000/minute |
| Write operations | 100/minute  |
| Sync operations  | 10/minute   |
| Vector search    | 100/minute  |

***

## 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  |
| stateset-sequencer      | Lines of Code | \~33,000  |
| Total Rust              | Lines of Code | \~172,000 |
| Domain Modules          | Count         | 32        |
| Domain Types            | Count         | 400+      |
| Database Tables         | Count         | 70+       |
| Commerce API Methods    | Count         | 700+      |
| Sequencer API Endpoints | Count         | 40+       |
| Language Bindings       | Count         | 10        |
| Commerce Skills         | Count         | 38        |
| Messaging Channels      | Count         | 9         |

***

## Everything You Can Do

| Action                | What it does                               |
| --------------------- | ------------------------------------------ |
| **Create orders**     | Process commerce transactions              |
| **Manage inventory**  | Track stock, reservations, adjustments     |
| **Process returns**   | Handle RMAs and refunds                    |
| **Run fulfillment**   | Pick, pack, ship workflows                 |
| **Accept payments**   | x402 stablecoin payments                   |
| **Sync events**       | VES multi-agent coordination via sequencer |
| **Generate proofs**   | Merkle inclusion + STARK ZK proofs         |
| **Anchor on-chain**   | Set Chain L2 commitment anchoring          |
| **Register schemas**  | Event type validation                      |
| **Search products**   | Hybrid semantic + keyword search           |
| **Message customers** | 9-channel omnichannel support              |
| **Run analytics**     | Sales reports, forecasts                   |
| **Manage finances**   | GL, AP, AR, tax                            |

***

## Quick Reference

### CLI Commands

```bash theme={null}
# Engine
stateset init [--demo]
stateset status

# Customers
stateset customers list|get|create|update|delete

# Products
stateset products list|get|create|update|delete

# Inventory
stateset inventory get|adjust|reserve|release

# Orders
stateset orders list|get|create|ship|cancel

# Returns
stateset returns list|get|create|approve|complete

# Sync
stateset sync status|push|pull|full|outbox

# Payments
stateset-pay create|balance|verify

# Channels
stateset-channels
stateset-whatsapp|discord|telegram|slack
```

### Sequencer API Quick Reference

```bash theme={null}
# Base URL: https://api.sequencer.stateset.com

# Agent Registration (start here!)
POST   /api/v1/agents/register              # Register agent, get API key
GET    /api/v1/agents/{agent_id}            # Get agent details
POST   /api/v1/agents/{agent_id}/api-keys   # Create additional API key
GET    /api/v1/agents/{agent_id}/api-keys   # List agent's API keys
DELETE /api/v1/agents/{agent_id}/api-keys/{pfx} # Revoke API key

# Agent Signing Keys (for VES)
POST   /api/v1/agents/keys                  # Register Ed25519 signing key

# Event Ingestion
POST   /api/v1/events/ingest                # Ingest events (legacy)
POST   /api/v1/ves/events/ingest            # Ingest VES events (signed)
GET    /api/v1/events                       # List events
GET    /api/v1/head                         # Get head sequence
GET    /api/v1/entities/{type}/{id}         # Entity history

# VES Commitments
GET    /api/v1/ves/commitments              # List commitments
POST   /api/v1/ves/commitments              # Create commitment
POST   /api/v1/ves/commitments/anchor       # Commit and anchor
GET    /api/v1/ves/commitments/{batch_id}   # Get commitment

# VES Validity Proofs
GET    /api/v1/ves/validity/{batch_id}/inputs   # Get proof inputs
GET    /api/v1/ves/validity/{batch_id}/proofs   # List proofs
POST   /api/v1/ves/validity/{batch_id}/proofs   # Submit proof
GET    /api/v1/ves/validity/proofs/{id}/verify  # Verify proof

# VES Compliance Proofs
POST   /api/v1/ves/compliance/{event_id}/inputs  # Get inputs
GET    /api/v1/ves/compliance/{event_id}/proofs  # List proofs
POST   /api/v1/ves/compliance/{event_id}/proofs  # Submit proof

# Inclusion Proofs
GET    /api/v1/ves/proofs/{sequence_number}     # Get proof
POST   /api/v1/ves/proofs/verify                # Verify proof

# Anchoring
POST   /api/v1/ves/anchor                       # Anchor to chain
GET    /api/v1/ves/anchor/{batch_id}/verify     # Verify on-chain

# Schemas
GET    /api/v1/schemas                          # List schemas
POST   /api/v1/schemas                          # Register schema
POST   /api/v1/schemas/validate                 # Validate payload
GET    /api/v1/schemas/event-type/{type}/latest # Latest schema

# x402 Payments
POST   /api/v1/x402/payments                # Submit intent
GET    /api/v1/x402/payments/{id}           # Get status
GET    /api/v1/x402/payments/{id}/receipt   # Get receipt
POST   /api/v1/x402/batches/settle          # Settle batch

# Health
GET    /health                              # Basic health
GET    /ready                               # Readiness
GET    /health/detailed                     # Component health
```

***

## Ideas to Try

* Register your AI agent with the sequencer to get an API key
* Set up the embedded engine with demo data
* Create a multi-step order flow with cart → checkout → fulfillment
* Configure VES sync between multiple agents using the sequencer
* Enable x402 payments for agent-to-agent commerce
* Ingest events and generate inclusion proofs via sequencer API
* Anchor commitments on-chain and verify with STARK proofs
* Register custom event schemas for domain-specific events
* Set up WhatsApp or Discord for customer support
* Run vector search for product discovery
* Configure heartbeat monitors for low-stock alerts
* Build a storefront with `stateset scaffold`

***

*StateSet iCommerce v1.22.0*
*July 2026*
