🚀 Quick Start
1. Get Your API Keys
1
Create Account
Sign up at dashboard.stateset.com
2
Complete KYC
Submit required documents for compliance (takes ~5 minutes)
3
Generate API Keys
Navigate to Settings → API Keys → Create New Key
2. Install SDK
npm install @stateset/sdk
yarn add @stateset/sdk
pip install stateset-python
3. Initialize Client
import { Stateset } from '@stateset/sdk';
const stateset = new StatesetClient({
apiKey: process.env.STATESET_API_KEY,
network: 'mainnet' // or 'testnet' for development
});
// Test connection — the stablecoin endpoints are REST-only today
const res = await fetch('https://api.stateset.com/v1/stablecoin/balance/your_wallet_address', {
headers: { Authorization: `Bearer ${process.env.STATESET_API_KEY}` }
});
const balance = await res.json();
console.log('ssUSD Balance:', balance.balances.total);
💳 Common Use Cases
E-Commerce Payments
Accept ssUSD payments with instant settlement and no chargebacks:// Create payment request
async function createPayment(amount, orderId) {
const payment = await stateset.payments.create({
amount: amount,
currency: 'ssusd',
metadata: {
order_id: orderId,
customer_email: 'customer@example.com'
},
webhook_url: 'https://yoursite.com/webhooks/payment'
});
return payment.payment_address;
}
// Verify payment received
async function verifyPayment(paymentId) {
const payment = await stateset.payments.get(paymentId);
if (payment.status === 'completed') {
// Process order fulfillment
await fulfillOrder(payment.metadata.order_id);
}
}
Payroll & Disbursements
Send bulk payments efficiently:// Batch payroll payments
async function processPayroll(employees) {
const transfers = employees.map(emp => ({
to: emp.wallet_address,
amount: emp.salary_ssusd,
memo: `Payroll ${new Date().toISOString().slice(0, 7)}`
}));
const batch = await fetch('https://api.stateset.com/v1/stablecoin/transfer/batch', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ transfers, idempotency_key: `payroll_${Date.now()}` })
}).then(r => r.json());
// Send notifications
for (const result of batch.results) {
if (result.success) {
await notifyEmployee(result.to, result.transaction_hash);
}
}
return batch;
}
Treasury Management
Hold and manage corporate ssUSD reserves:// Corporate treasury dashboard
class TreasuryManager {
api(path) {
return fetch(`https://api.stateset.com/v1${path}`, {
headers: { Authorization: `Bearer ${process.env.STATESET_API_KEY}` }
}).then(r => r.json());
}
async getOverview() {
const [balance, reserves, transactions] = await Promise.all([
this.api(`/stablecoin/balance/${this.treasuryAddress}`),
this.api('/stablecoin/reserves'),
this.api(`/stablecoin/transactions?address=${this.treasuryAddress}&limit=100`)
]);
return {
current_balance: balance.balances.total,
reserve_backing: reserves.total_usd,
recent_activity: transactions,
health_score: this.calculateHealthScore(balance, transactions)
};
}
async optimizeYield(amount) {
// Check available yield opportunities
const opportunities = await this.api(
`/finance/yield-opportunities?asset=ssusd&amount=${amount}&risk_level=low`
);
// Deploy to best opportunity
if (opportunities[0].apy > 0.03) { // 3% APY threshold
return await fetch('https://api.stateset.com/v1/finance/capital-deployments', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ opportunity_id: opportunities[0].id, amount })
}).then(r => r.json());
}
}
}
🔐 Security Best Practices
API Key Management
Never expose your secret API key in client-side code or public repositories!
// ❌ WRONG - Never do this
const stateset = new StatesetClient({
apiKey: 'sk_live_your_actual_key_here' // Hardcoded key (never do this)
});
// ✅ CORRECT - Use environment variables
const stateset = new StatesetClient({
apiKey: process.env.STATESET_API_KEY
});
// ✅ CORRECT - Use restricted keys for client-side
const publicClient = new StatesetClient({
apiKey: process.env.STATESET_PUBLIC_KEY // pk_ prefix
});
Transaction Security
Implement proper validation and limits:class SecureTransferService {
constructor() {
this.dailyLimit = 100000; // $100k daily limit
this.perTxLimit = 10000; // $10k per transaction
}
async transfer(to, amount, memo) {
// Validate amount
if (amount > this.perTxLimit) {
throw new Error('Transaction exceeds limit');
}
// Check daily volume
const dailyVolume = await this.getDailyVolume();
if (dailyVolume + amount > this.dailyLimit) {
throw new Error('Daily limit exceeded');
}
// Validate recipient
if (!this.isValidAddress(to)) {
throw new Error('Invalid recipient address');
}
// Execute with idempotency
return await fetch('https://api.stateset.com/v1/stablecoin/transfer', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ to, amount, memo, idempotency_key: `transfer_${Date.now()}_${to}` })
}).then(r => r.json());
}
}
📊 Monitoring & Analytics
Real-Time Balance Monitoring
// WebSocket subscription for balance updates
const ws = new WebSocket(`wss://api.stateset.com/v1/subscriptions?token=${process.env.STATESET_API_KEY}`);
ws.onopen = () => ws.send(JSON.stringify({ subscribe: ['balance.updated'] }));
ws.onmessage = async (msg) => {
const event = JSON.parse(msg.data);
console.log('New balance:', event.balance);
// Alert on large changes
if (Math.abs(event.change) > 10000) {
await sendAlert({
type: 'large_balance_change',
amount: event.change,
new_balance: event.balance
});
}
};
// Historical balance tracking
async function getBalanceHistory(days = 30) {
const history = [];
const now = Date.now();
for (let i = 0; i < days; i++) {
const timestamp = now - (i * 24 * 60 * 60 * 1000);
const balance = await fetch(
`https://api.stateset.com/v1/stablecoin/balance/${treasuryAddress}?at_timestamp=${new Date(timestamp).toISOString()}`,
{ headers: { Authorization: `Bearer ${process.env.STATESET_API_KEY}` } }
).then(r => r.json());
history.push({
date: new Date(timestamp).toISOString().slice(0, 10),
balance: balance.balances.total
});
}
return history;
}
Transaction Analytics
// Analyze transaction patterns
async function analyzeTransactions(address, period = '30d') {
const transactions = await fetch(
`https://api.stateset.com/v1/stablecoin/transactions?address=${address}&period=${period}&limit=1000`,
{ headers: { Authorization: `Bearer ${process.env.STATESET_API_KEY}` } }
).then(r => r.json());
const analytics = {
total_volume: 0,
transaction_count: transactions.length,
average_size: 0,
largest_transaction: 0,
counterparties: new Set(),
daily_pattern: {}
};
transactions.forEach(tx => {
analytics.total_volume += tx.amount;
analytics.largest_transaction = Math.max(
analytics.largest_transaction,
tx.amount
);
analytics.counterparties.add(
tx.from === address ? tx.to : tx.from
);
const date = new Date(tx.timestamp).toISOString().slice(0, 10);
analytics.daily_pattern[date] =
(analytics.daily_pattern[date] || 0) + tx.amount;
});
analytics.average_size =
analytics.total_volume / analytics.transaction_count;
analytics.unique_counterparties = analytics.counterparties.size;
return analytics;
}
🌐 Multi-Chain Integration
Bridge to Other Chains
// Bridge ssUSD to Base
async function bridgeToBase(amount) {
const bridge = await fetch('https://api.stateset.com/v1/stablecoin/bridge', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from_chain: 'stateset',
to_chain: 'base',
asset: 'ssusd',
amount,
recipient: baseAddress
})
}).then(r => r.json());
// Monitor bridge progress
const status = await fetch(`https://api.stateset.com/v1/stablecoin/bridge/${bridge.id}`, {
headers: { Authorization: `Bearer ${process.env.STATESET_API_KEY}` }
}).then(r => r.json());
console.log('Bridge status:', status);
return bridge;
}
// Cross-chain balance aggregation
async function getTotalBalance(addresses) {
const headers = { Authorization: `Bearer ${process.env.STATESET_API_KEY}` };
const balances = await Promise.all([
fetch(`https://api.stateset.com/v1/stablecoin/balance/${addresses.stateset}?chains=stateset`, { headers }).then(r => r.json()),
fetch(`https://api.stateset.com/v1/stablecoin/balance/${addresses.base}?chains=base`, { headers }).then(r => r.json()),
fetch(`https://api.stateset.com/v1/stablecoin/balance/${addresses.solana}?chains=solana`, { headers }).then(r => r.json())
]);
return balances.reduce((sum, b) => sum + parseFloat(b.balances.total), 0);
}
🧪 Testing
Test Mode
Use test mode for development:const testClient = new StatesetClient({
apiKey: process.env.STATESET_TEST_KEY,
network: 'testnet'
});
// Get test ssUSD
async function getTestFunds() {
const faucet = await testClient.faucet.request({
asset: 'ssusd',
amount: 10000, // $10k test ssUSD
address: testAddress
});
return faucet;
}
Integration Tests
describe('ssUSD Integration', () => {
it('should transfer funds successfully', async () => {
const initialBalance = await getBalance(senderAddress);
const transfer = await fetch('https://api.stateset.com/v1/stablecoin/transfer', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ to: recipientAddress, amount: '100.00' })
}).then(r => r.json());
expect(transfer.status).toBe('completed');
const finalBalance = await getBalance(senderAddress);
expect(finalBalance).toBe(initialBalance - 100);
});
it('should handle insufficient funds', async () => {
const res = await fetch('https://api.stateset.com/v1/stablecoin/transfer', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ to: recipientAddress, amount: '1000000.00' }) // More than balance
});
expect(res.status).toBe(400);
const { error } = await res.json();
expect(error.code).toBe('insufficient_funds');
});
});
🚨 Error Handling
Common Errors and Solutions
const res = await fetch('https://api.stateset.com/v1/stablecoin/transfer', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.STATESET_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ to, amount, memo })
});
if (!res.ok) {
const { error } = await res.json();
switch (error.code) {
case 'insufficient_funds':
// Handle low balance
console.error('Not enough ssUSD');
break;
case 'invalid_address':
// Handle bad recipient
console.error('Check recipient address format');
break;
case 'compliance_block':
// Handle compliance issues
console.error('Transaction blocked for compliance');
await handleComplianceBlock(error.details);
break;
case 'rate_limit':
// Handle rate limiting
console.error('Too many requests');
await sleep(error.retry_after * 1000);
break;
default:
console.error('Unknown error:', error);
}
}
📚 Next Steps
API Reference
Complete API documentation
Examples
Sample applications
Webhooks Guide
Real-time event handling
Support
Get help from our team