TypeScript SDK
The Sardis TypeScript SDK provides a type-safe, modern JavaScript/TypeScript interface for integrating Sardis payment capabilities into your applications.Installation
npm install @sardis/sdk
yarn add @sardis/sdk
pnpm add @sardis/sdk
Quick Start
import { SardisClient } from '@sardis/sdk';
// Create client
const client = new SardisClient({
apiKey: process.env.SARDIS_API_KEY!,
});
// Create an agent
const agent = await client.agents.create({
name: 'my-agent',
description: 'AI agent for payments',
});
// Create a wallet
const wallet = await client.wallets.create({
agent_id: agent.agent_id,
mpc_provider: 'turnkey',
chain: 'base',
currency: 'USDC',
limit_per_tx: '100.00',
limit_total: '1000.00',
});
// Execute a payment
const result = await client.payments.executeMandate({
wallet_id: wallet.wallet_id,
mandate: {
intent: {
amount: '25.00',
currency: 'USDC',
recipient: 'openai.com',
purpose: 'API usage',
},
},
});
console.log('Payment result:', result);
Client Initialization
Basic Configuration
import { SardisClient } from '@sardis/sdk';
const client = new SardisClient({
apiKey: 'sk_live_...',
baseUrl: 'https://api.sardis.sh', // Optional
});
With Custom Retry Settings
const client = new SardisClient({
apiKey: 'sk_live_...',
maxRetries: 5,
retryDelay: 2000,
maxRetryDelay: 30000,
retryOn: [408, 429, 500, 502, 503, 504],
retryOnNetworkError: true,
});
With Custom Timeout
const client = new SardisClient({
apiKey: 'sk_live_...',
timeout: 60000, // 60 seconds
connectTimeout: 10000, // 10 seconds
});
With Token Refresh
const client = new SardisClient({
apiKey: 'sk_live_...',
tokenRefresh: {
refreshToken: async () => {
// Custom token refresh logic
const newToken = await fetchNewToken();
return newToken;
},
},
});
Basic Operations
Agent Management
// Create an agent
const agent = await client.agents.create({
name: 'payment-bot',
description: 'Automated payment agent',
metadata: { version: '1.0', environment: 'production' },
});
// Get an agent
const agent = await client.agents.get('agent_123');
// List agents
const agents = await client.agents.list({ limit: 100 });
// Update agent
const updated = await client.agents.update('agent_123', {
name: 'updated-name',
description: 'Updated description',
});
Wallet Operations
// Create a wallet
const wallet = await client.wallets.create({
agent_id: 'agent_123',
mpc_provider: 'turnkey',
chain: 'base',
currency: 'USDC',
limit_per_tx: '100.00',
limit_total: '1000.00',
});
// Get wallet
const wallet = await client.wallets.get('wallet_123');
// Get balance
const balance = await client.wallets.getBalance('wallet_123', {
chain: 'base',
token: 'USDC',
});
console.log(`Balance: ${balance.balance} ${balance.token}`);
// List wallets
const wallets = await client.wallets.list({
agent_id: 'agent_123',
limit: 50
});
// Transfer funds
const tx = await client.wallets.transfer('wallet_123', {
destination: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
amount: '100.00',
token: 'USDC',
chain: 'base',
memo: 'Transfer to external wallet',
});
Payment Execution
// Execute payment with mandate
const result = await client.payments.executeMandate({
wallet_id: 'wallet_123',
mandate: {
intent: {
amount: '25.50',
currency: 'USDC',
recipient: 'merchant.eth',
purpose: 'Payment for services',
},
},
});
if (result.success) {
console.log('Transaction hash:', result.tx_hash);
} else {
console.error('Payment failed:', result.error);
}
// Execute AP2 payment bundle
const ap2Result = await client.payments.executeAP2({
wallet_id: 'wallet_123',
bundle: {
intent: { /* ... */ },
cart: { /* ... */ },
payment: { /* ... */ },
},
});
Hold Operations
// Create a hold
const hold = await client.holds.create({
wallet_id: 'wallet_123',
amount: '100.00',
token: 'USDC',
expires_in: 3600, // 1 hour
metadata: { order_id: 'order_456' },
});
console.log('Hold ID:', hold.hold_id);
// Capture the hold
const capture = await client.holds.capture(hold.hold_id, {
amount: '75.00', // Partial capture
memo: 'Final payment',
});
// Void the hold
await client.holds.void(hold.hold_id);
// Get hold details
const hold = await client.holds.get('hold_123');
// List holds
const holds = await client.holds.list({
wallet_id: 'wallet_123',
status: 'active',
limit: 20,
});
Policy Validation
// Parse natural language policy
const parsed = await client.policies.parseNL(
'Max $100 per transaction, daily limit $500'
);
console.log('Parsed policy:', parsed);
// Check policy compliance
const check = await client.policies.check({
wallet_id: 'wallet_123',
amount: '150.00',
recipient: 'openai.com',
});
if (check.allowed) {
console.log('Payment allowed');
} else {
console.log('Blocked:', check.reason);
}
Group Management
// Create a group
const group = await client.groups.create({
name: 'ai-research-team',
budget: {
per_transaction: '500.00',
daily: '5000.00',
monthly: '50000.00',
},
merchant_policy: {
blocked_categories: ['gambling', 'adult'],
},
});
// Add agents
await client.groups.addAgent(group.group_id, 'agent_123');
// Get spending
const spending = await client.groups.getSpending(group.group_id);
console.log('Daily remaining:', spending.daily_remaining);
Request Cancellation
All API methods support AbortController for cancellation:const controller = new AbortController();
// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);
try {
const result = await client.payments.executeMandate(mandate, {
signal: controller.signal,
});
} catch (error) {
if (error instanceof AbortError) {
console.log('Request was cancelled');
}
}
Request/Response Interceptors
// Add request interceptor
const removeInterceptor = client.addRequestInterceptor({
onRequest: (config) => {
console.log(`${config.method} ${config.url}`);
// Modify config if needed
config.headers['X-Custom-Header'] = 'value';
return config;
},
onError: (error) => {
console.error('Request error:', error);
throw error;
},
});
// Add response interceptor
client.addResponseInterceptor({
onResponse: (response) => {
console.log(`Response: ${response.status}`);
return response;
},
onError: (error) => {
console.error('Response error:', error);
throw error;
},
});
// Remove interceptor when done
removeInterceptor();
Pagination
// Iterate through all pages
for await (const agent of client.paginate(
(params) => client.agents.list(params),
{ limit: 100 }
)) {
console.log(agent.name);
}
// Collect all results
const allAgents = await client.paginateAll(
(params) => client.agents.list(params)
);
console.log(`Found ${allAgents.length} agents`);
Batch Operations
const results = await client.batch([
{ method: 'GET', path: '/api/v2/wallets/wallet_1' },
{ method: 'GET', path: '/api/v2/wallets/wallet_2' },
{ method: 'GET', path: '/api/v2/wallets/wallet_3' },
], { concurrency: 3 });
results.forEach((result, i) => {
if (result.success) {
console.log(`Operation ${i}:`, result.data);
} else {
console.error(`Operation ${i} failed:`, result.error);
}
});
TypeScript Types
The SDK is fully typed:import type {
Wallet,
Agent,
Payment,
Hold,
Chain,
Token,
CreateWalletInput,
ExecutePaymentInput,
} from '@sardis/sdk';
const wallet: Wallet = await client.wallets.get('wallet_123');
const chains: Chain[] = ['base', 'ethereum', 'polygon'];
Framework Integrations
Vercel AI SDK
import { sardisTools } from '@sardis/sdk/integrations';
import { generateText } from 'ai';
const result = await generateText({
model: openai('gpt-4'),
tools: sardisTools({
apiKey: process.env.SARDIS_API_KEY!,
walletId: 'wallet_123',
}),
prompt: 'Pay $50 to OpenAI for API usage',
});
LangChain
import { SardisToolkit } from '@sardis/sdk/integrations';
import { ChatOpenAI } from '@langchain/openai';
const toolkit = new SardisToolkit({
apiKey: process.env.SARDIS_API_KEY!,
walletId: 'wallet_123',
});
const tools = toolkit.getTools();
const agent = createReactAgent({ llm: new ChatOpenAI(), tools });