@sperax/sdk
v0.2.1
Published
Official TypeScript SDK for Sperax API Platform — DeFi Intelligence, AI Agent Runtime, ERC-8004 Registry
Maintainers
Readme
@sperax/sdk
Install
npm install @sperax/sdkOfficial TypeScript SDK for the Sperax API Platform.
Three products, one SDK:
| Product | Description | |---------|-------------| | Intel | 30+ DeFi/market data endpoints — prices, yields, derivatives, sentiment, news | | Agent | Run AI agents with tool-use, streaming, and human-in-the-loop approval | | ERC-8004 | On-chain agent identity, reputation, and metadata across 12+ EVM chains |
Installation
npm install @sperax/sdk
# or
pnpm add @sperax/sdk
# or
yarn add @sperax/sdkZero dependencies. Uses the native fetch() API (Node 18+, Deno, Bun, modern browsers).
Quick Start
import { createSperaxClient } from '@sperax/sdk';
const sperax = createSperaxClient({ apiKey: 'lb-xxxxxxxxxxxxxxxx' });
const trending = await sperax.intel.getTrending();
console.log(trending.data.coins[0].item.name); // e.g. 'Ethereum'That's it. Three lines after import.
Products
Intel — DeFi Intelligence
Access 30+ market data, DeFi analytics, derivatives, sentiment, and news endpoints.
import { IntelClient } from '@sperax/sdk/intel';
const intel = new IntelClient({ apiKey: 'lb-xxxxxxxxxxxxxxxx' });
// Market data
const coins = await intel.getCoins({ vs_currency: 'usd', per_page: 10 });
const markets = await intel.getMarkets({ order: 'market_cap_desc' });
const trending = await intel.getTrending();
// DeFi analytics
const yields = await intel.getDefiYields({ chain: 'arbitrum' });
const protocols = await intel.getTopProtocols({ limit: 20 });
const tvl = await intel.getChainTvl();
// Derivatives
const funding = await intel.getFundingRates({ symbol: 'BTC' });
const oi = await intel.getOpenInterest({ symbol: 'ETH' });
const liquidations = await intel.getLiquidations();
// Sentiment & Macro
const fearGreed = await intel.getFearGreed();
const macro = await intel.getMacroSignals();
const etf = await intel.getEtfFlows();
// Infrastructure
const gas = await intel.getGasTracker({ chain: 'ethereum' });
const stablecoins = await intel.getStablecoinDashboard();
// News & Social
const arxiv = await intel.getArxiv({ query: 'automated market makers' });
const hn = await intel.getHackerNews({ type: 'top' });
const github = await intel.getGithubTrending({ language: 'typescript' });| Method | Description |
|--------|-------------|
| getCoins() | CoinGecko top coins |
| getGlobalStats() | Global market cap and volume |
| getMarkets() | Market list with sorting |
| getTrending() | Trending coins, NFTs, categories |
| getDefiYields() | DeFi yields across protocols |
| getDefiStats() | DeFi global TVL and volume |
| getTopProtocols() | Top DeFi protocols by TVL |
| getChainTvl() | TVL by chain |
| getDexTrending() | Trending DEX pairs |
| getDexVolume() | Aggregate DEX volume |
| getProtocolRevenue() | Protocol fee revenue |
| getDefiFees() | DeFi protocol fees |
| getFundingRates() | Perp futures funding rates |
| getOpenInterest() | Open interest data |
| getLongShortRatio() | Long/short ratio |
| getLiquidations() | Recent liquidations |
| getFearGreed() | Fear & Greed Index |
| getMacroSignals() | Macro economic indicators |
| getEtfFlows() | Bitcoin ETF flows |
| getExchangeFlow() | Exchange inflow/outflow |
| getWalletTracker() | Wallet transaction history |
| getGasTracker() | EVM gas prices |
| getStablecoinMarkets() | Stablecoin market data |
| getStablecoinDashboard() | Stablecoin supply dashboard |
| getPolymarket() | Prediction market data |
| getYahooFinance() | Traditional finance data |
| getFinnhub() | Finnhub OHLC data |
| getArxiv() | Academic papers |
| getHackerNews() | Hacker News stories |
| getGithubTrending() | GitHub trending repos |
| getTechEvents() | Tech conferences |
| getServiceStatus() | Data source uptime |
| getStatus() | API health check |
Agent — AI Agent Runtime
Run AI agents with tool-use, streaming, and human-in-the-loop approval.
Synchronous (simple queries)
import { AgentClient } from '@sperax/sdk/agent';
const agent = new AgentClient({ apiKey: 'lb-xxxxxxxxxxxxxxxx' });
const result = await agent.run({
prompt: 'What is the TVL of Aave on Arbitrum?',
maxSteps: 5,
});
console.log(result.data.messages.at(-1)?.content);
console.log(`Cost: ${result.data.cost.totalCost} ${result.data.cost.currency}`);Async + Polling (long-running tasks)
const op = await agent.runAsync({
prompt: 'Analyze the top 10 yield opportunities on Arbitrum',
maxSteps: 15,
});
const final = await agent.waitForCompletion(op.data.operationId, {
pollIntervalMs: 3000,
timeoutMs: 120_000,
});
console.log(final.messages?.at(-1)?.content);Streaming (real-time output)
const op = await agent.runAsync({ prompt: 'Summarize DeFi news today' });
for await (const event of agent.stream(op.data.operationId)) {
switch (event.event) {
case 'message':
process.stdout.write(event.data.content); // TypeScript narrows .content
break;
case 'tool_call':
console.log('\n[tool]', event.data.toolName);
break;
case 'done':
console.log('\nCompleted in', event.data.stepCount, 'steps');
break;
case 'error':
console.error('\nAgent error:', event.data.error);
break;
}
}Human-in-the-Loop
const final = await agent.waitForCompletion(operationId);
if (final.status === 'waiting_for_human' && final.pendingTools) {
for (const tool of final.pendingTools) {
console.log(`Approve ${tool.function.name}?`, tool.function.arguments);
await agent.approve(operationId, tool.id);
// or: await agent.reject(operationId, tool.id, 'Amount too high');
}
}ERC-8004 — On-Chain Agent Registry
Interact with agent identities across 12+ EVM chains.
import { ERC8004Client } from '@sperax/sdk/erc8004';
const erc8004 = new ERC8004Client({ apiKey: 'lb-xxxxxxxxxxxxxxxx' });
// Discover agents
const agents = await erc8004.listAgents({ chain: 'arbitrum', limit: 10 });
const results = await erc8004.searchAgents({ query: 'DeFi yield', limit: 5 });
// Inspect an agent
const agent = await erc8004.getAgent({ agentId: '42', chain: 'arbitrum' });
const rep = await erc8004.getReputation('42', { chain: 'arbitrum' });
console.log(`Trust score: ${rep.data.trustScore}/100`);
// Register a new agent (returns unsigned transaction for your wallet to sign)
const tx = await erc8004.registerAgent({
name: 'My DeFi Agent',
description: 'Optimizes yield across protocols',
uri: 'ipfs://Qm...',
chain: 'arbitrum',
tags: ['defi', 'yield'],
});
// Sign tx.data with ethers.js / viem / wagmi and broadcastConfiguration
import { createSperaxClient } from '@sperax/sdk';
const sperax = createSperaxClient({
apiKey: 'lb-xxxxxxxxxxxxxxxx', // required
baseUrl: 'https://chat.sperax.io', // optional, for self-hosted
timeout: 30_000, // ms per request (agent default: 120_000)
maxRetries: 3, // retries for 429/5xx
debug: true, // log requests to stderr
fetch: customFetch, // custom fetch (for proxies or testing)
});| Option | Type | Default | Description |
|--------|------|---------|-------------|
| apiKey | string | required | API key from the Sperax dashboard |
| baseUrl | string | 'https://chat.sperax.io' | API base URL |
| timeout | number | 30_000 (agent: 120_000) | Request timeout in ms |
| maxRetries | number | 3 | Max retries for 429/5xx responses |
| debug | boolean | false | Log all requests/responses to stderr |
| fetch | typeof fetch | globalThis.fetch | Custom fetch implementation |
Debug Mode
Enable request/response logging with debug: true or the DEBUG env var:
// Code
const sperax = createSperaxClient({ apiKey: 'lb-xxxxxxxxxxxxxxxx', debug: true });
// Environment variable (no code change)
DEBUG=sperax node your-script.js
DEBUG=sperax:sdk node your-script.jsExample output:
sperax:sdk 2024-01-15T12:00:00.000Z → GET /api/v1/intel/trending
sperax:sdk 2024-01-15T12:00:00.042Z ← 200 OK (42ms) [req_abc123]Error Handling
All SDK errors extend SperaxError. Use the specific subclass for targeted handling:
import {
SperaxError,
SperaxAuthError,
SperaxRateLimitError,
SperaxNotFoundError,
SperaxNetworkError,
SperaxValidationError,
} from '@sperax/sdk';
try {
await sperax.intel.getCoins();
} catch (err) {
if (err instanceof SperaxAuthError) {
// HTTP 401 — bad or expired API key
console.error('Check your API key:', err.message);
} else if (err instanceof SperaxRateLimitError) {
// HTTP 429 — SDK retries automatically; this fires after all retries exhausted
console.error(`Rate limited. Retry after ${err.retryAfter}s`);
} else if (err instanceof SperaxNotFoundError) {
// HTTP 404
console.error('Resource not found:', err.message);
} else if (err instanceof SperaxValidationError) {
// HTTP 400/422 — bad request parameters
console.error('Invalid parameters:', err.message);
} else if (err instanceof SperaxNetworkError) {
// DNS / TCP failure
console.error('Network error:', err.message);
} else if (err instanceof SperaxError) {
// Any other SDK error
console.error(`[${err.code}] HTTP ${err.status}: ${err.message}`);
if (err.requestId) {
console.error('Request ID (for support):', err.requestId);
}
}
}Error Properties
Every SperaxError instance exposes:
| Property | Type | Description |
|----------|------|-------------|
| message | string | Human-readable description |
| code | string | Machine-readable code, e.g. 'UNAUTHORIZED' |
| status | number | HTTP status code (0 for network/timeout) |
| retryable | boolean | Whether the SDK retried this error |
| requestId | string \| undefined | Server-assigned request ID for support |
SperaxRateLimitError additionally exposes retryAfter: number | undefined (seconds).
Error Hierarchy
SperaxError (base)
├── SperaxAuthError (401 — invalid API key)
├── SperaxPermissionError (403 — insufficient scope)
├── SperaxCreditsError (402 — account credits exhausted)
├── SperaxNotFoundError (404 — resource not found)
├── SperaxRateLimitError (429 — rate limited, has .retryAfter)
├── SperaxValidationError (400/422 — bad request parameters)
├── SperaxNetworkError (network failure)
├── SperaxTimeoutError (request timed out)
├── SperaxStreamError (SSE stream failed)
└── SperaxPollingTimeoutError (waitForCompletion exceeded deadline)Retry Behavior
The SDK automatically retries:
- 429 Too Many Requests — respects
Retry-Afterheader if present - 5xx Server Errors — exponential backoff: 1s, 2s, 4s … (max 10s) + jitter
Configure with maxRetries (default: 3). Set to 0 to disable retries.
Tree Shaking
Import only the client you need:
import { IntelClient } from '@sperax/sdk/intel'; // ~12 KB
import { AgentClient } from '@sperax/sdk/agent'; // ~8 KB
import { ERC8004Client } from '@sperax/sdk/erc8004'; // ~6 KBTypeScript
All request parameters and response types are exported:
import type { CoinData, DefiYield, TrendingData } from '@sperax/sdk/intel';
import type { AgentStreamEvent, RunAgentParams } from '@sperax/sdk/agent';
import type { AgentIdentity, ChainInfo } from '@sperax/sdk/erc8004';
import type { ApiResponse, SperaxClientOptions } from '@sperax/sdk';AgentStreamEvent is a discriminated union — switch on .event and TypeScript
automatically narrows .data to the correct shape.
Common Patterns
Parallel data fetching
const [global, fear, gas] = await Promise.all([
sperax.intel.getGlobalStats(),
sperax.intel.getFearGreed(),
sperax.intel.getGasTracker({ chain: 'ethereum' }),
]);Paginating results
const page1 = await sperax.intel.getCoins({ per_page: 100, page: 1 });
const page2 = await sperax.intel.getCoins({ per_page: 100, page: 2 });Cancelling a stream
const controller = new AbortController();
setTimeout(() => controller.abort(), 30_000); // cancel after 30s
for await (const event of sperax.agent.stream(operationId, controller.signal)) {
// ...
}Using a custom fetch (e.g. Node 16, proxies)
import { createSperaxClient } from '@sperax/sdk';
import nodeFetch from 'node-fetch';
const sperax = createSperaxClient({
apiKey: 'lb-xxxxxxxxxxxxxxxx',
fetch: nodeFetch as typeof fetch,
});Examples
See examples/ for runnable scripts:
| File | Description |
|------|-------------|
| quickstart.ts | 5-line hello world |
| intel-dashboard.ts | Parallel market data snapshot |
| agent-streaming.ts | Stream agent responses |
| error-handling.ts | Typed errors and debug mode |
| self-hosted.ts | Connect to a self-hosted instance |
Platform Support
| Runtime | Min Version | Notes |
|---------|-------------|-------|
| Node.js | 18 | Native fetch available |
| Bun | any | |
| Deno | any | |
| Browser | modern | Chrome 66+, Firefox 63+, Safari 12.1+ |
Contributing
See CONTRIBUTING.md in the monorepo root.
License
Apache-2.0
License
sdk is released under the Apache-2.0 license.
