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
Ask AI
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
Ask AI
npm install @stateset/sdk
Basic Configuration
Copy
Ask AI
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
Copy
Ask AI
// 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);
});
Advanced Features
Webhook Handling
Copy
Ask AI
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
Ask AI
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;
}
}
}
Python
Installation
Copy
Ask AI
pip install stateset
Configuration
Copy
Ask AI
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
Copy
Ask AI
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())
Type Hints
Copy
Ask AI
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
Ask AI
go get github.com/stateset/stateset-go
Configuration
Copy
Ask AI
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
Ask AI
// 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
Ask AI
// 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
Ask AI
# 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
Ask AI
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
Ask AI
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'
Test Helpers
Copy
Ask AI
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);
});
});