Latest Versions: All SDKs are kept in sync with our API. Check GitHub for the latest releases.
Official StateSet SDKs
Build on StateSet with our official SDKs available in multiple languages. Each SDK provides type-safe access to all StateSet APIs with built-in best practices.๐ Quick Install
Copy
npm install @stateset/sdk
๐ฆ Available SDKs
JavaScript/TypeScript
Full TypeScript support with async/await
Python
Pythonic API with type hints
Go
High-performance native Go client
Rust
Memory-safe Rust implementation
Ruby
Idiomatic Ruby with Rails integration
Java
Enterprise Java with Spring support
JavaScript/TypeScript
Installation & Setup
Copy
npm install @stateset/sdk
Basic Configuration
Copy
import { StateSet } from '@stateset/sdk';
// Initialize client
const stateset = new StateSet({
apiKey: process.env.STATESET_API_KEY,
network: 'mainnet', // 'mainnet' | 'testnet'
options: {
timeout: 30000, // 30 seconds
retries: 3,
webhookSecret: process.env.WEBHOOK_SECRET
}
});
Core Features
- Payments
- Orders
- Stablecoins
Copy
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console;
// Create a payment
const payment = await stateset.payments.create({
amount: 100.00,
currency: 'ssusd',
recipient: 'stateset1abc...',
memo: 'Invoice #1234'
});
// List payments with pagination
const payments = await stateset.payments.list({
limit: 20,
starting_after: 'pay_xyz789'
});
// Subscribe to payment events
stateset.payments.on('payment.succeeded', async (payment) => {
logger.info('Payment completed', { paymentId: payment.id });
});
Copy
// Create an order
const order = await stateset.orders.create({
items: [
{ sku: 'PROD-001', quantity: 2, price: 50.00 }
],
customer: 'cust_123',
shipping: {
address: { /* ... */ },
method: 'express'
}
});
// Update order status
await stateset.orders.update(order.id, {
status: 'processing',
tracking_number: '1Z999AA1234567890'
});
Copy
// Transfer ssUSD
const transfer = await stateset.stablecoin.transfer({
to: 'stateset1xyz...',
amount: '1000.00',
memo: 'Supplier payment'
});
// Check balance
const balance = await stateset.stablecoin.balance({
address: 'stateset1abc...'
});
// Batch transfers
const batch = await stateset.stablecoin.batchTransfer({
transfers: [
{ to: 'addr1', amount: '100.00' },
{ to: 'addr2', amount: '200.00' }
]
});
Advanced Features
Webhook Handling
Copy
import { verifyWebhookSignature } from '@stateset/sdk';
app.post('/webhooks/stateset', express.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['x-stateset-signature'];
try {
const event = verifyWebhookSignature(
req.body,
sig,
process.env.WEBHOOK_SECRET
);
// Handle event
switch(event.type) {
case 'payment.succeeded':
handlePaymentSuccess(event.data);
break;
// ... other events
}
res.status(200).send('OK');
} catch (err) {
res.status(400).send('Webhook Error');
}
});
Error Handling
Copy
import { StateSetError } from '@stateset/sdk';
// Replace with a structured logger (Winston, Pino, etc) in production
const logger = console;
try {
const payment = await stateset.payments.create({...});
} catch (error) {
if (error instanceof StateSetError) {
switch(error.type) {
case 'invalid_request_error':
logger.error('Invalid parameters', { param: error.param });
break;
case 'authentication_error':
logger.error('Authentication failed: check your API key');
break;
case 'rate_limit_error':
await sleep(error.retryAfter);
// Retry request
break;
}
}
}
Python
Installation
Copy
pip install stateset
Configuration
Copy
from stateset import StateSet
import os
# Initialize client
stateset = StateSet(
api_key=os.getenv('STATESET_API_KEY'),
network='mainnet', # 'mainnet' or 'testnet'
timeout=30,
max_retries=3
)
Usage Examples
- Async Support
- Pandas Integration
Copy
import asyncio
from stateset import AsyncStateSet
async def main():
# Async client for high-performance applications
async with AsyncStateSet(api_key=api_key) as client:
# Concurrent operations
tasks = [
client.payments.create(amount=100, currency='ssusd'),
client.orders.list(limit=10),
client.stablecoin.balance(address='stateset1...')
]
results = await asyncio.gather(*tasks)
print(f"Created {len(results)} operations concurrently")
asyncio.run(main())
Copy
import pandas as pd
# Export data to pandas DataFrame
payments = stateset.payments.list(limit=1000)
df = pd.DataFrame([p.to_dict() for p in payments])
# Analyze payment data
summary = df.groupby('status').agg({
'amount': ['sum', 'mean', 'count'],
'created': 'min'
})
print(summary)
Type Hints
Copy
from typing import List, Optional
from stateset.types import Payment, Order, Transfer
def process_payments(payments: List[Payment]) -> None:
"""Process a list of payments with full type safety."""
for payment in payments:
if payment.status == 'succeeded':
send_receipt(payment.recipient, payment.amount)
def create_order(
items: List[dict],
customer_id: str,
shipping_method: Optional[str] = 'standard'
) -> Order:
"""Create an order with type-checked parameters."""
return stateset.orders.create(
items=items,
customer=customer_id,
shipping={'method': shipping_method}
)
Go
Installation
Copy
go get github.com/stateset/stateset-go
Configuration
Copy
package main
import (
"github.com/stateset/stateset-go"
"github.com/stateset/stateset-go/payment"
)
func main() {
// Initialize client
client := stateset.NewClient(
os.Getenv("STATESET_API_KEY"),
stateset.WithNetwork("mainnet"),
stateset.WithTimeout(30 * time.Second),
stateset.WithRetries(3),
)
}
Usage Examples
Copy
// Create payment
payment, err := client.Payments.Create(&payment.CreateParams{
Amount: stateset.Float64(100.00),
Currency: stateset.String("ssusd"),
Recipient: stateset.String("stateset1abc..."),
})
if err != nil {
// Handle error
if statesetErr, ok := err.(*stateset.Error); ok {
log.Printf("StateSet error: %s (code: %s)",
statesetErr.Message, statesetErr.Code)
}
}
// Concurrent operations with goroutines
var wg sync.WaitGroup
payments := make([]*payment.Payment, 10)
for i := 0; i < 10; i++ {
wg.Add(1)
go func(index int) {
defer wg.Done()
p, _ := client.Payments.Create(&payment.CreateParams{
Amount: stateset.Float64(100.00),
})
payments[index] = p
}(i)
}
wg.Wait()
Framework Integrations
Next.js
Copy
// pages/api/create-payment.ts
import { StateSet } from '@stateset/sdk';
import type { NextApiRequest, NextApiResponse } from 'next';
const stateset = new StateSet({
apiKey: process.env.STATESET_SECRET_KEY
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const payment = await stateset.payments.create({
amount: req.body.amount,
currency: 'ssusd'
});
res.status(200).json(payment);
} catch (error) {
res.status(400).json({ error: error.message });
}
}
Django
Copy
# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from stateset import StateSet
import json
stateset = StateSet(api_key=settings.STATESET_API_KEY)
@csrf_exempt
def create_payment(request):
if request.method == 'POST':
data = json.loads(request.body)
try:
payment = stateset.payments.create(
amount=data['amount'],
currency='ssusd',
recipient=data['recipient']
)
return JsonResponse(payment.to_dict())
except Exception as e:
return JsonResponse({'error': str(e)}, status=400)
Express.js
Copy
const express = require('express');
const { StateSet } = require('@stateset/sdk');
const app = express();
const stateset = new StateSet({
apiKey: process.env.STATESET_API_KEY
});
app.post('/api/payments', async (req, res) => {
try {
const payment = await stateset.payments.create({
amount: req.body.amount,
currency: 'ssusd'
});
res.json(payment);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
๐งช Testing
Mock Mode
Copy
import { StateSet, MockStateSet } from '@stateset/sdk';
// Use mock client in tests
const stateset = process.env.NODE_ENV === 'test'
? new MockStateSet()
: new StateSet({ apiKey: process.env.STATESET_API_KEY });
// Mock client returns predictable responses
const payment = await stateset.payments.create({
amount: 100.00,
currency: 'ssusd'
});
// payment.id will look like 'pay_test_123'
Test Helpers
Copy
import { createTestPayment, createTestOrder } from '@stateset/sdk/test';
describe('Payment Processing', () => {
it('should process payment successfully', async () => {
// Create test data
const payment = createTestPayment({
amount: 100.00,
status: 'succeeded'
});
// Test your logic
const result = await processPayment(payment);
expect(result.success).toBe(true);
});
});