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.com',
apiKey: process.env.STATESET_API_KEY
});
// Create the order with the SDK...
const order = await client.orders.create({
items: [{
sku: 'LAPTOP-001',
quantity: 1,
price: '999.99'
}],
customer: {
id: 'cust_123',
email: 'customer@example.com'
},
shipping: {
address: '123 Main St, San Francisco, CA 94105',
method: 'standard'
}
});
// ...then pay for it via the documented REST endpoint
await fetch(`https://api.stateset.com/api/v1/orders/${order.id}/pay`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ payment: { method: 'usdc', amount: '999.99' } })
});
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
- Sub-second transaction finality
- Horizontal scaling — throughput grows by adding nodes
- Multi-region data replication
📊 Order Lifecycle
Order States
| State | Description | Next States |
|---|---|---|
CREATED | Order created, awaiting payment | PAID, CANCELLED |
PAID | Payment confirmed | FULFILLED, HELD, REFUNDED |
FULFILLED | Items prepared for shipping | SHIPPED, CANCELLED |
SHIPPED | Order in transit | DELIVERED, RETURNED |
DELIVERED | Order completed successfully | RETURNED |
HELD | Order temporarily paused | RELEASED, CANCELLED |
CANCELLED | Order cancelled | Terminal state |
RETURNED | Order returned by customer | REFUNDED |
REFUNDED | Refund processed | Terminal state |
DISPUTED | Order under dispute | RESOLVED |
💻 API Reference
Create Order
POST /api/v1/orders
{
"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"
}
}
{
"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.com/ord_7x9kPm2nQ1"
}
Pay Order
POST /api/v1/orders/{order_id}/pay
{
"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"
}
}
{
"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 /api/v1/orders/{order_id}
{
"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 /api/v1/orders?customer_id=cust_123&status=PAID&limit=50&offset=0
| Parameter | Type | Description |
|---|---|---|
customer_id | string | Filter by customer ID |
status | string | Filter by order status |
created_after | string | Orders created after this date (ISO 8601) |
created_before | string | Orders created before this date (ISO 8601) |
amount_min | string | Minimum order amount |
amount_max | string | Maximum order amount |
limit | integer | Number of orders to return (max 100) |
offset | integer | Number of orders to skip |
{
"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 — one POST /api/v1/orders per order
curl -X POST https://api.stateset.com/api/v1/orders \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "customer_id": "cust_123", "items": [{ "sku": "WIDGET-001", "quantity": 10 }] }'
curl -X POST https://api.stateset.com/api/v1/orders \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "customer_id": "cust_456", "items": [{ "sku": "GADGET-002", "quantity": 5 }] }'
# Pay each order — POST /api/v1/orders/{order_id}/pay
curl -X POST https://api.stateset.com/api/v1/orders/ord_1/pay \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "amount": "100.00" }'
curl -X POST https://api.stateset.com/api/v1/orders/ord_2/pay \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "amount": "50.00" }'
Subscription Orders
# Create a recurring subscription order
curl -X POST https://api.stateset.com/api/v1/orders/subscriptions \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"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 the subscription
curl -X POST https://api.stateset.com/api/v1/orders/subscriptions/{subscription_id}/pause \
-H "Authorization: Bearer $STATESET_API_KEY"
curl -X POST https://api.stateset.com/api/v1/orders/subscriptions/{subscription_id}/resume \
-H "Authorization: Bearer $STATESET_API_KEY"
Smart Contract Integration
# Create an order with smart contract conditions
curl -X POST https://api.stateset.com/api/v1/orders \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"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 an order with multiple parties (dropshipping)
curl -X POST https://api.stateset.com/api/v1/orders \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"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
| Event | Description | Payload |
|---|---|---|
order.created | New order created | { order, customer } |
order.paid | Payment completed | { order, payment } |
order.fulfilled | Order fulfilled | { order, items } |
order.shipped | Order shipped | { order, tracking } |
order.delivered | Order delivered | { order, delivery } |
order.cancelled | Order cancelled | { order, reason } |
order.refunded | Refund processed | { order, refund } |
order.disputed | Dispute opened | { order, dispute } |
Webhook Configuration
# Configure a webhook endpoint — POST /v1/webhooks
curl -X POST https://api.stateset.com/v1/webhooks \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-api.com/webhooks/stateset",
"events": ["order.paid", "order.shipped"],
"secret": "your-webhook-secret",
"headers": { "Authorization": "Bearer your-api-token" }
}'
{
"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
curl "https://api.stateset.com/v1/analytics/orders?start_date=2024-06-01&end_date=2024-06-30&group_by=day&metrics=count,revenue,avg_order_value" \
-H "Authorization: Bearer $STATESET_API_KEY"
{
"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 a custom report
curl -X POST https://api.stateset.com/v1/reports \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"type": "order_performance",
"filters": { "status": ["DELIVERED"], "created_after": "2024-01-01" },
"dimensions": ["customer_segment", "product_category"],
"metrics": ["count", "revenue", "fulfillment_time"],
"format": "csv"
}'
# Download the report
curl https://api.stateset.com/v1/reports/{report_id}/download \
-H "Authorization: Bearer $STATESET_API_KEY"
🛡️ 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) {
// Hold is REST-only today — the JS SDK does not ship orders.hold
await fetch(`https://api.stateset.com/api/v1/orders/${order.id}/hold`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ reason: 'fraud_review' })
});
}
PCI DSS Compliance
# Pay an order with tokenized card data — POST /api/v1/orders/{order_id}/pay
curl -X POST https://api.stateset.com/api/v1/orders/ord_123/pay \
-H "Authorization: Bearer $STATESET_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"payment_method": {
"type": "card",
"token": "tok_secure_token",
"last4": "4242",
"brand": "visa"
}
}'
# Sensitive data is never stored
# All card data is tokenized via PCI DSS compliant processor
GDPR Compliance
# Data subject rights
curl -X POST https://api.stateset.com/v1/compliance/customers/cust_123/export \
-H "Authorization: Bearer $STATESET_API_KEY"
curl -X DELETE https://api.stateset.com/v1/compliance/customers/cust_123/data \
-H "Authorization: Bearer $STATESET_API_KEY"
# Privacy-preserving analytics
curl "https://api.stateset.com/v1/analytics/orders?anonymized=true&retention_policy=7_years" \
-H "Authorization: Bearer $STATESET_API_KEY"
🌍 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
// Pay via the documented REST endpoint (the JS SDK does not ship orders.pay)
const payment = await fetch(`https://api.stateset.com/api/v1/orders/${euroOrder.id}/pay`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
amount: '100.00',
currency: 'USDC', // Auto-converted from EUR
exchange_rate_locked: true
})
}).then((r) => r.json());
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.com',
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 via the documented REST endpoint
const payment = await fetch(`https://api.stateset.com/api/v1/orders/${order.id}/pay`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ payment_method: { type: 'usdc', amount: order.total } })
}).then((r) => r.json());
// 3. Record fulfillment
await client.orders.addFulfillmentEvent(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 Stateset
client = Stateset(
endpoint='https://api.stateset.com',
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 via the documented REST endpoint
# (the Python SDK does not ship orders.pay)
import requests
payment = requests.post(
f"https://api.stateset.com/api/v1/orders/{order['id']}/pay",
headers={'Authorization': f"Bearer {os.environ['STATESET_API_KEY']}"},
json={'payment_method': {'type': 'usdc', 'amount': order['total']}}
).json()
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.com",
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.com",
&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
| Operation | Throughput | Latency (p95) | Cost |
|---|---|---|---|
| Create Order | 10,000 ops/sec | 45ms | $0.001 |
| Pay Order | 8,000 ops/sec | 65ms | $0.01 |
| Update Status | 15,000 ops/sec | 25ms | $0.0005 |
| Query Order | 50,000 ops/sec | 5ms | Free |
Scaling Patterns
// Horizontal scaling with sharding
const client = new StatesetClient({
endpoint: 'https://api.stateset.com',
shard_key: 'customer_id', // Distribute by customer
read_replicas: 3, // Read from nearest replica
write_concern: 'majority' // Ensure consistency
});
// Batch operations for high throughput — issue creates in parallel
const orders = await Promise.all(
orderRequests.map((req) => client.orders.create(req))
);
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 — emit through your own metrics pipeline
import StatsD from 'hot-shots';
const metrics = new StatsD({ prefix: 'stateset.' });
metrics.increment('orders.created', 1, {
customer_segment: 'enterprise',
product_category: 'software'
});
metrics.histogram('order.processing_time', processingTime);
metrics.gauge('orders.pending', pendingOrderCount);
Health Checks
# Built-in health monitoring
curl https://api.stateset.com/api/v1/health \
-H "Authorization: Bearer $STATESET_API_KEY"
{
"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"
}
🔗 Related APIs
- Orders Create - Create new orders
- Orders Pay - Process payments
- Orders Ship - Handle shipping
- Orders Refund - Process refunds
- Finance API - Financial instruments
- USDC Guide - Native USDC integration
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;
}
Ready to get started? Create your first order →