Official SDKs for integrating with StateSet Commerce Network
npm install @stateset/sdk
npm install @stateset/sdk
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
}
});
// 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) => {
console.log('Payment completed:', payment.id);
});
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');
}
});
import { StateSetError } from '@stateset/sdk';
try {
const payment = await stateset.payments.create({...});
} catch (error) {
if (error instanceof StateSetError) {
switch(error.type) {
case 'invalid_request_error':
console.error('Invalid parameters:', error.param);
break;
case 'authentication_error':
console.error('Check your API key');
break;
case 'rate_limit_error':
await sleep(error.retryAfter);
// Retry request
break;
}
}
}
pip install stateset
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
)
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())
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 get github.com/stateset/stateset-go
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),
)
}
// 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()
// 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 });
}
}
# 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)
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 });
}
});
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'
});
console.log(payment.id); // 'pay_test_123'
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);
});
});