Orders API: The Foundation of Digital Commerce

The Orders API is the core of StateSet Commerce Network, providing comprehensive order lifecycle management from creation to fulfillment. With native USDC integration, real-time tracking, and enterprise-grade automation, it’s designed to handle millions of orders with sub-second latency.

πŸš€ Quick Start

import { StateSetClient } from '@stateset/commerce-sdk';

const client = new StateSetClient({
  endpoint: 'https://api.stateset.network',
  apiKey: process.env.STATESET_API_KEY
});

// Create and pay for order in one transaction
const order = await client.orders.createAndPay({
  items: [{
    sku: 'LAPTOP-001',
    quantity: 1,
    price: '999.99'
  }],
  customer: {
    id: 'cust_123',
    email: 'customer@example.com'
  },
  payment: {
    method: 'usdc',
    amount: '999.99'
  },
  shipping: {
    address: '123 Main St, San Francisco, CA 94105',
    method: 'standard'
  }
});

console.log(`Order ${order.id} created and paid!`);

🎯 Key Features

Native USDC Payments

  • Pay fees in USDC (no gas token required)
  • Instant settlement with Circle integration
  • Built-in refund and partial payment support
  • Cross-chain transfers via IBC

Enterprise Automation

  • Smart contract workflows
  • Automated fraud detection
  • Inventory management integration
  • Real-time webhook notifications

Global Scale

  • 10,000+ orders per second
  • Sub-second transaction finality
  • 99.99% uptime SLA
  • Multi-region data replication

πŸ“Š Order Lifecycle

Order States

StateDescriptionNext States
CREATEDOrder created, awaiting paymentPAID, CANCELLED
PAIDPayment confirmedFULFILLED, HELD, REFUNDED
FULFILLEDItems prepared for shippingSHIPPED, CANCELLED
SHIPPEDOrder in transitDELIVERED, RETURNED
DELIVEREDOrder completed successfullyRETURNED
HELDOrder temporarily pausedRELEASED, CANCELLED
CANCELLEDOrder cancelledTerminal state
RETURNEDOrder returned by customerREFUNDED
REFUNDEDRefund processedTerminal state
DISPUTEDOrder under disputeRESOLVED

πŸ’» API Reference

Create Order

POST /v1/orders

Request Body:

{
  "customer_id": "cust_123",
  "items": [
    {
      "sku": "LAPTOP-001",
      "quantity": 1,
      "unit_price": "999.99",
      "description": "MacBook Pro 16-inch"
    }
  ],
  "shipping_address": {
    "name": "John Doe",
    "address_line_1": "123 Main St",
    "city": "San Francisco",
    "state": "CA",
    "postal_code": "94105",
    "country": "US"
  },
  "metadata": {
    "channel": "web",
    "campaign_id": "summer_sale_2024"
  }
}

Response:

{
  "id": "ord_7x9kPm2nQ1",
  "customer_id": "cust_123",
  "status": "CREATED",
  "items": [
    {
      "sku": "LAPTOP-001",
      "quantity": 1,
      "unit_price": "999.99",
      "total_price": "999.99"
    }
  ],
  "subtotal": "999.99",
  "tax": "87.49",
  "shipping": "9.99",
  "total": "1096.47",
  "currency": "USDC",
  "created_at": "2024-06-25T12:00:00Z",
  "payment_url": "https://pay.stateset.network/ord_7x9kPm2nQ1"
}

Pay Order

POST /v1/orders/{order_id}/pay

Request Body:

{
  "payment_method": {
    "type": "usdc",
    "wallet_address": "stateset1abc123...",
    "amount": "1096.47"
  },
  "billing_address": {
    "name": "John Doe",
    "address_line_1": "123 Main St",
    "city": "San Francisco",
    "state": "CA",
    "postal_code": "94105",
    "country": "US"
  }
}

Response:

{
  "payment_id": "pay_8y4mQr5oP2",
  "order_id": "ord_7x9kPm2nQ1",
  "status": "PAID",
  "amount": "1096.47",
  "currency": "USDC",
  "transaction_hash": "0x742d35Cc6634C0532925a3b8D097C00D4dfece08",
  "paid_at": "2024-06-25T12:05:00Z",
  "fees": {
    "network_fee": "0.01",
    "processing_fee": "0.00"
  }
}

Get Order

GET /v1/orders/{order_id}

Response:

{
  "id": "ord_7x9kPm2nQ1",
  "customer_id": "cust_123",
  "status": "SHIPPED",
  "items": [
    {
      "sku": "LAPTOP-001",
      "quantity": 1,
      "unit_price": "999.99",
      "total_price": "999.99",
      "status": "SHIPPED"
    }
  ],
  "payment": {
    "id": "pay_8y4mQr5oP2",
    "status": "PAID",
    "amount": "1096.47",
    "method": "USDC",
    "paid_at": "2024-06-25T12:05:00Z"
  },
  "shipping": {
    "carrier": "FedEx",
    "tracking_number": "1234567890",
    "estimated_delivery": "2024-06-27T17:00:00Z",
    "shipped_at": "2024-06-26T09:00:00Z"
  },
  "timeline": [
    {
      "status": "CREATED",
      "timestamp": "2024-06-25T12:00:00Z"
    },
    {
      "status": "PAID",
      "timestamp": "2024-06-25T12:05:00Z"
    },
    {
      "status": "FULFILLED",
      "timestamp": "2024-06-26T08:00:00Z"
    },
    {
      "status": "SHIPPED",
      "timestamp": "2024-06-26T09:00:00Z"
    }
  ]
}

List Orders

GET /v1/orders?customer_id=cust_123&status=PAID&limit=50&offset=0

Query Parameters:

ParameterTypeDescription
customer_idstringFilter by customer ID
statusstringFilter by order status
created_afterstringOrders created after this date (ISO 8601)
created_beforestringOrders created before this date (ISO 8601)
amount_minstringMinimum order amount
amount_maxstringMaximum order amount
limitintegerNumber of orders to return (max 100)
offsetintegerNumber of orders to skip

Response:

{
  "orders": [
    {
      "id": "ord_7x9kPm2nQ1",
      "customer_id": "cust_123",
      "status": "PAID",
      "total": "1096.47",
      "currency": "USDC",
      "created_at": "2024-06-25T12:00:00Z"
    }
  ],
  "total_count": 1,
  "has_more": false
}

πŸ”„ Advanced Features

Bulk Order Operations

// Create multiple orders atomically
const bulkOrders = await client.orders.createBulk([
  {
    customer_id: 'cust_123',
    items: [{ sku: 'WIDGET-001', quantity: 10 }]
  },
  {
    customer_id: 'cust_456', 
    items: [{ sku: 'GADGET-002', quantity: 5 }]
  }
]);

// Process bulk payments
const payments = await client.orders.payBulk([
  { order_id: 'ord_1', amount: '100.00' },
  { order_id: 'ord_2', amount: '50.00' }
]);

Subscription Orders

// Create recurring subscription orders
const subscription = await client.orders.createSubscription({
  customer_id: 'cust_123',
  items: [{ sku: 'COFFEE-MONTHLY', quantity: 1 }],
  schedule: {
    interval: 'monthly',
    start_date: '2024-07-01',
    end_date: '2025-07-01'
  },
  payment_method: {
    type: 'usdc',
    wallet_address: 'stateset1abc123...'
  }
});

// Manage subscription
await client.orders.pauseSubscription(subscription.id);
await client.orders.resumeSubscription(subscription.id);

Smart Contract Integration

// Create order with smart contract conditions
const conditionalOrder = await client.orders.createConditional({
  customer_id: 'cust_123',
  items: [{ sku: 'PRESALE-ITEM', quantity: 1 }],
  conditions: {
    contract_address: 'stateset1contract...',
    method: 'checkInventory',
    params: ['PRESALE-ITEM'],
    expected_result: true
  },
  auto_execute: true
});

Multi-Party Orders

// Create order with multiple parties (dropshipping)
const multiPartyOrder = await client.orders.createMultiParty({
  customer_id: 'cust_123',
  merchant_id: 'merch_456',
  supplier_id: 'supp_789',
  items: [{ sku: 'DROP-SHIP-001', quantity: 1 }],
  revenue_split: {
    merchant: 70,
    supplier: 25,
    platform: 5
  },
  fulfillment_by: 'supplier'
});

πŸ“‘ Webhooks & Events

Event Types

EventDescriptionPayload
order.createdNew order created{ order, customer }
order.paidPayment completed{ order, payment }
order.fulfilledOrder fulfilled{ order, items }
order.shippedOrder shipped{ order, tracking }
order.deliveredOrder delivered{ order, delivery }
order.cancelledOrder cancelled{ order, reason }
order.refundedRefund processed{ order, refund }
order.disputedDispute opened{ order, dispute }

Webhook Configuration

// Configure webhook endpoints
const webhook = await client.webhooks.create({
  url: 'https://your-api.com/webhooks/stateset',
  events: ['order.paid', 'order.shipped'],
  secret: 'your-webhook-secret',
  headers: {
    'Authorization': 'Bearer your-api-token'
  }
});

// Webhook payload example
{
  "event": "order.paid",
  "data": {
    "order": {
      "id": "ord_7x9kPm2nQ1",
      "status": "PAID",
      "total": "1096.47"
    },
    "payment": {
      "id": "pay_8y4mQr5oP2",
      "amount": "1096.47",
      "method": "USDC"
    }
  },
  "timestamp": "2024-06-25T12:05:00Z"
}

πŸ” Analytics & Reporting

Order Analytics

// Get order analytics
const analytics = await client.analytics.orders({
  start_date: '2024-06-01',
  end_date: '2024-06-30',
  group_by: 'day',
  metrics: ['count', 'revenue', 'avg_order_value']
});

// Response
{
  "data": [
    {
      "date": "2024-06-25",
      "order_count": 1247,
      "revenue": "125847.32",
      "avg_order_value": "100.92"
    }
  ],
  "summary": {
    "total_orders": 38562,
    "total_revenue": "3856892.45",
    "avg_order_value": "100.04"
  }
}

Custom Reports

// Generate custom reports
const report = await client.reports.generate({
  type: 'order_performance',
  filters: {
    status: ['DELIVERED'],
    created_after: '2024-01-01'
  },
  dimensions: ['customer_segment', 'product_category'],
  metrics: ['count', 'revenue', 'fulfillment_time'],
  format: 'csv'
});

// Download report
const downloadUrl = await client.reports.download(report.id);

πŸ›‘οΈ Security & Compliance

Fraud Detection

// Built-in fraud detection
const order = await client.orders.create({
  // ... order details
  fraud_check: {
    enabled: true,
    rules: ['velocity', 'geolocation', 'device_fingerprint'],
    threshold: 'medium'
  }
});

// Fraud check result
if (order.fraud_score > 0.7) {
  await client.orders.hold(order.id, 'fraud_review');
}

PCI DSS Compliance

// Tokenized payment data
const payment = await client.orders.createPayment({
  order_id: 'ord_123',
  payment_method: {
    type: 'card',
    token: 'tok_secure_token', // PCI-compliant tokenization
    last4: '4242',
    brand: 'visa'
  }
});

// Sensitive data is never stored
// All card data is tokenized via PCI DSS compliant processor

GDPR Compliance

// Data subject rights
const dataExport = await client.compliance.exportCustomerData('cust_123');
const dataDeleted = await client.compliance.deleteCustomerData('cust_123');

// Privacy-preserving analytics
const analytics = await client.analytics.orders({
  anonymized: true,
  retention_policy: '7_years'
});

🌍 Global Commerce Features

Multi-Currency Support

// Orders in different currencies
const euroOrder = await client.orders.create({
  items: [{ sku: 'EU-PRODUCT', quantity: 1 }],
  currency: 'EUR',
  exchange_rate: {
    from: 'EUR',
    to: 'USDC',
    rate: '1.09',
    source: 'coinbase'
  }
});

// Automatic currency conversion on payment
const payment = await client.orders.pay(euroOrder.id, {
  amount: '100.00',
  currency: 'USDC', // Auto-converted from EUR
  exchange_rate_locked: true
});

Cross-Border Tax Calculation

// Automatic tax calculation for international orders
const order = await client.orders.create({
  items: [{ sku: 'INT-PRODUCT', quantity: 1, price: '100.00' }],
  shipping_address: {
    country: 'DE', // Germany
    postal_code: '10115'
  },
  tax_calculation: {
    enabled: true,
    provider: 'avalara',
    include_duties: true
  }
});

// Automatic tax and duty calculation
// VAT: 19% (Germany)
// Import duty: 5.2%
// Total tax: €24.20

Regulatory Compliance

// Automatic compliance checks
const order = await client.orders.create({
  // ... order details
  compliance: {
    export_control: true, // Check export restrictions
    sanctions_screening: true, // OFAC sanctions list
    restricted_products: true, // Country-specific restrictions
    aml_check: true // Anti-money laundering
  }
});

// Compliance result
if (order.compliance_status === 'RESTRICTED') {
  throw new Error('Order violates export controls');
}

πŸ”§ SDK Examples

Node.js / TypeScript

import { StateSetClient } from '@stateset/commerce-sdk';

const client = new StateSetClient({
  endpoint: 'https://api.stateset.network',
  apiKey: process.env.STATESET_API_KEY,
  network: 'mainnet'
});

// Complete e-commerce flow
async function processOrder() {
  // 1. Create order
  const order = await client.orders.create({
    customer_id: 'cust_123',
    items: [{
      sku: 'PRODUCT-001',
      quantity: 2,
      price: '29.99'
    }]
  });

  // 2. Process payment
  const payment = await client.orders.pay(order.id, {
    payment_method: {
      type: 'usdc',
      amount: order.total
    }
  });

  // 3. Fulfill order
  await client.orders.fulfill(order.id, {
    tracking_number: 'FEDEX123456',
    carrier: 'fedex',
    items: order.items
  });

  // 4. Mark as shipped
  await client.orders.ship(order.id);

  return order;
}

Python

from stateset import StateSetClient

client = StateSetClient(
    endpoint='https://api.stateset.network',
    api_key=os.environ['STATESET_API_KEY']
)

# Create and process order
order = client.orders.create({
    'customer_id': 'cust_123',
    'items': [{
        'sku': 'PYTHON-COURSE',
        'quantity': 1,
        'price': '199.99'
    }]
})

# Pay with USDC
payment = client.orders.pay(order['id'], {
    'payment_method': {
        'type': 'usdc',
        'amount': order['total']
    }
})

print(f"Order {order['id']} paid successfully!")

Go

package main

import (
    "github.com/stateset/stateset-go"
)

func main() {
    client := stateset.NewClient(&stateset.Config{
        Endpoint: "https://api.stateset.network",
        APIKey:   os.Getenv("STATESET_API_KEY"),
    })

    // Create order
    order, err := client.Orders.Create(&stateset.CreateOrderRequest{
        CustomerID: "cust_123",
        Items: []stateset.Item{
            {
                SKU:      "GO-WORKSHOP",
                Quantity: 1,
                Price:    "299.99",
            },
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    // Process payment
    payment, err := client.Orders.Pay(order.ID, &stateset.PayOrderRequest{
        PaymentMethod: stateset.PaymentMethod{
            Type:   "usdc",
            Amount: order.Total,
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Order %s paid: %s\n", order.ID, payment.ID)
}

Rust

use stateset_sdk::{StateSetClient, CreateOrderRequest, PayOrderRequest};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = StateSetClient::new(
        "https://api.stateset.network",
        &std::env::var("STATESET_API_KEY")?
    );

    // Create order
    let order = client.orders().create(CreateOrderRequest {
        customer_id: "cust_123".to_string(),
        items: vec![Item {
            sku: "RUST-BOOTCAMP".to_string(),
            quantity: 1,
            price: "399.99".to_string(),
        }],
        ..Default::default()
    }).await?;

    // Process payment
    let payment = client.orders().pay(&order.id, PayOrderRequest {
        payment_method: PaymentMethod {
            r#type: "usdc".to_string(),
            amount: order.total.clone(),
        },
        ..Default::default()
    }).await?;

    println!("Order {} paid: {}", order.id, payment.id);
    Ok(())
}

πŸš€ Performance & Scale

Benchmarks

OperationThroughputLatency (p95)Cost
Create Order10,000 ops/sec45ms$0.001
Pay Order8,000 ops/sec65ms$0.01
Update Status15,000 ops/sec25ms$0.0005
Query Order50,000 ops/sec5msFree

Scaling Patterns

// Horizontal scaling with sharding
const client = new StateSetClient({
  endpoint: 'https://api.stateset.network',
  shard_key: 'customer_id', // Distribute by customer
  read_replicas: 3, // Read from nearest replica
  write_concern: 'majority' // Ensure consistency
});

// Batch operations for high throughput
const orders = await client.orders.createBatch(orderRequests, {
  batch_size: 100,
  parallel: true,
  timeout: 30000
});

Caching Strategy

// Multi-level caching
const client = new StateSetClient({
  cache: {
    // L1: In-memory cache
    memory: {
      ttl: 60, // 1 minute
      max_size: 1000
    },
    // L2: Redis cache
    redis: {
      url: 'redis://localhost:6379',
      ttl: 300, // 5 minutes
      key_prefix: 'stateset:'
    },
    // L3: CDN cache
    cdn: {
      enabled: true,
      ttl: 3600, // 1 hour
      regions: ['us-east-1', 'eu-west-1', 'ap-southeast-1']
    }
  }
});

// Cache-aware queries
const order = await client.orders.get('ord_123', {
  cache: 'prefer', // Try cache first
  max_age: 300 // Accept cached data up to 5 minutes old
});

πŸ“ˆ Monitoring & Observability

Metrics

// Built-in metrics collection
const client = new StateSetClient({
  metrics: {
    enabled: true,
    endpoint: 'https://metrics.stateset.network',
    tags: {
      environment: 'production',
      service: 'order-service'
    }
  }
});

// Custom metrics
client.metrics.increment('orders.created', 1, {
  customer_segment: 'enterprise',
  product_category: 'software'
});

client.metrics.histogram('order.processing_time', processingTime);
client.metrics.gauge('orders.pending', pendingOrderCount);

Health Checks

// Built-in health monitoring
const healthCheck = await client.health.check();

// Response
{
  "status": "healthy",
  "checks": {
    "database": {
      "status": "healthy",
      "response_time": "2ms"
    },
    "blockchain": {
      "status": "healthy",
      "block_height": 1542389,
      "sync_status": "synced"
    },
    "cache": {
      "status": "healthy",
      "hit_rate": 0.94
    },
    "external_apis": {
      "status": "degraded",
      "details": "Tax service responding slowly"
    }
  },
  "timestamp": "2024-06-25T12:00:00Z"
}

Cross-Chain Payment Integration

StateSet Orders module natively integrates with the CCTP module to enable seamless cross-chain USDC payments. Customers can pay for orders on any supported chain, and the funds are automatically transferred to StateSet for settlement.

Accepting Cross-Chain Payments

// Process order payment from any supported chain
func (k Keeper) ProcessCrossChainPayment(
    ctx sdk.Context,
    orderID string,
    sourceChain uint32,
    messageHash []byte,
) error {
    // Verify the CCTP message has been received
    cctpMsg, found := k.cctpKeeper.GetReceivedMessage(ctx, messageHash)
    if !found {
        return ErrCCTPMessageNotFound
    }
    
    // Extract payment details from message body
    payment := DecodeCCTPPayment(cctpMsg.MessageBody)
    if payment.OrderID != orderID {
        return ErrPaymentOrderMismatch
    }
    
    // Update order with payment
    order, found := k.GetOrder(ctx, orderID)
    if !found {
        return ErrOrderNotFound
    }
    
    order.PaymentInfo = PaymentInfo{
        Type:          "cross_chain_usdc",
        SourceChain:   sourceChain,
        Amount:        payment.Amount,
        TransactionID: hex.EncodeToString(messageHash),
        Timestamp:     ctx.BlockTime(),
    }
    order.Status = StatusPaid
    
    return k.SetOrder(ctx, order)
}

Automated Cross-Chain Settlement

// Automatically process incoming CCTP payments for orders
func (k Keeper) OnCCTPMessageReceived(
    ctx sdk.Context,
    message types.CCTPMessage,
) error {
    // Check if this is an order payment
    if !IsOrderPayment(message.MessageBody) {
        return nil // Not an order payment
    }
    
    payment := DecodeOrderPayment(message.MessageBody)
    
    // Process the payment
    return k.ProcessCrossChainPayment(
        ctx,
        payment.OrderID,
        message.SourceDomain,
        message.Hash(),
    )
}

Cross-Chain Refunds

// Refund order payment to original chain
func (k Keeper) RefundCrossChain(
    ctx sdk.Context,
    orderID string,
) error {
    order, found := k.GetOrder(ctx, orderID)
    if !found {
        return ErrOrderNotFound
    }
    
    if order.PaymentInfo.Type != "cross_chain_usdc" {
        return ErrNotCrossChainPayment
    }
    
    // Initiate CCTP refund to source chain
    msg := &cctp.MsgDepositForBurn{
        From:              k.GetModuleAddress(),
        Amount:            order.PaymentInfo.Amount,
        DestinationDomain: order.PaymentInfo.SourceChain,
        MintRecipient:     order.Customer.GetCCTPAddress(),
        BurnToken:         "usdc",
    }
    
    _, err := k.cctpKeeper.DepositForBurn(ctx, msg)
    if err != nil {
        return err
    }
    
    // Update order status
    order.Status = StatusRefunded
    return k.SetOrder(ctx, order)
}

Events

Additional events for cross-chain payments:

// Emitted when a cross-chain payment is received
message EventCrossChainPaymentReceived {
    string order_id = 1;
    uint32 source_chain = 2;
    string amount = 3;
    string message_hash = 4;
}

// Emitted when a cross-chain refund is initiated
message EventCrossChainRefundInitiated {
    string order_id = 1;
    uint32 destination_chain = 2;
    string amount = 3;
    string message_hash = 4;
}

For detailed CCTP integration, see the CCTP Module documentation and Integration Guide.


Ready to get started? Create your first order β†’