> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stateset.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SDKs & Libraries

> Official SDKs for integrating with StateSet Commerce Network

<Info>
  **Latest Versions**: All SDKs are kept in sync with our API. Check [GitHub](https://github.com/stateset) for the latest releases.
</Info>

# 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

<CodeGroup>
  ```bash npm theme={null}
  npm install @stateset/sdk
  ```

  ```bash yarn theme={null}
  yarn add @stateset/sdk
  ```

  ```bash pip theme={null}
  pip install stateset
  ```

  ```bash go theme={null}
  go get github.com/stateset/stateset-go
  ```

  ```bash cargo theme={null}
  cargo add stateset
  ```

  ```bash gem theme={null}
  gem install stateset
  ```
</CodeGroup>

## 📦 Available SDKs

<CardGroup cols={3}>
  <Card title="JavaScript/TypeScript" icon="js" href="#javascript-typescript">
    Full TypeScript support with async/await
  </Card>

  <Card title="Python" icon="python" href="#python">
    Pythonic API with type hints
  </Card>

  <Card title="Go" icon="golang" href="#go">
    High-performance native Go client
  </Card>

  <Card title="Rust" icon="rust" href="#rust">
    Memory-safe Rust implementation
  </Card>

  <Card title="Ruby" icon="gem" href="#ruby">
    Idiomatic Ruby with Rails integration
  </Card>

  <Card title="Java" icon="java" href="#java">
    Enterprise Java with Spring support
  </Card>
</CardGroup>

## JavaScript/TypeScript

### Installation & Setup

```bash theme={null}
npm install @stateset/sdk
```

### Basic Configuration

```typescript theme={null}
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

<Tabs>
  <Tab title="Payments">
    ```typescript theme={null}
    // 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 });
    });
    ```
  </Tab>

  <Tab title="Orders">
    ```typescript theme={null}
    // 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'
    });
    ```
  </Tab>

  <Tab title="Stablecoins">
    ```typescript theme={null}
    // 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' }
      ]
    });
    ```
  </Tab>
</Tabs>

### Advanced Features

#### Webhook Handling

```typescript theme={null}
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

```typescript theme={null}
	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

```bash theme={null}
pip install stateset
```

### Configuration

```python theme={null}
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

<Tabs>
  <Tab title="Async Support">
    ```python theme={null}
    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())
    ```
  </Tab>

  <Tab title="Pandas Integration">
    ```python theme={null}
    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)
    ```
  </Tab>
</Tabs>

### Type Hints

```python theme={null}
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

```bash theme={null}
go get github.com/stateset/stateset-go
```

### Configuration

```go theme={null}
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

```go theme={null}
// 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

```typescript theme={null}
// 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

```python theme={null}
# 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

```javascript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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);
  });
});
```

## 📚 Resources

<CardGroup cols={2}>
  <Card title="API Reference" icon="book" href="/api-reference">
    Complete API documentation
  </Card>

  <Card title="GitHub Examples" icon="github" href="https://github.com/stateset/examples">
    Sample applications and code
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/stateset">
    Get help from developers
  </Card>

  <Card title="SDK Changelog" icon="list" href="https://github.com/stateset/sdk/releases">
    Latest updates and releases
  </Card>
</CardGroup>
