Skip to Content

Advanced

Hooks / Observability

Use hooks to log requests, collect metrics, or integrate with APM tools.

const spectrum = new Spectrum({ api: 'https://your-endpoint.simplystaking.xyz/YOUR_API_KEY/', hooks: { onRequest: ({ method, path }) => { console.log(`→ ${method} ${path}`); }, onResponse: ({ status, duration, path }) => { // Log to your metrics system metrics.histogram('spectrum.request.duration', duration, { status, endpoint: path, }); }, onError: ({ message, path }) => { sentry.captureException(new Error(message), { extra: { path } }); }, }, });

Cache control

Disable caching

const spectrum = new Spectrum({ api: 'https://your-endpoint.simplystaking.xyz/YOUR_API_KEY/', cache: { enabled: false }, });

Custom TTL

const spectrum = new Spectrum({ api: 'https://your-endpoint.simplystaking.xyz/YOUR_API_KEY/', cache: { ttl: 30000, // 30s global TTL maxEntries: 2048, // larger cache }, });

The cache uses LRU (Least Recently Used) eviction. When maxEntries is reached, the oldest unused entries are evicted first.

Parallel execution

Use spectrum.parallel() to execute multiple independent calls concurrently:

const [ethBlock, polyBlock, gas] = await spectrum.parallel( spectrum.core.getBlockHeight('ethereum'), spectrum.core.getBlockHeight('polygon'), spectrum.core.getGasComparison(), );

This is a convenience wrapper around Promise.all. For a single HTTP batch request, use spectrum.jsonRpc() with an array of JSON-RPC requests.

Historical reads

Most read methods accept an optional { blockHeight } parameter to pin the query to a specific EVM block (requires an archive node for older blocks):

// Balance at a specific block const balance = await spectrum.tokens.getBalance('ethereum', '0xd8dA...', { blockHeight: 19834521 }); // Token balance at a specific block const tokenBal = await spectrum.tokens.getTokenBalance('ethereum', '0xd8dA...', '0xA0b8...', { blockHeight: 19834521 }); // NFT balance at a specific block const nftBal = await spectrum.nfts.getBalance('ethereum', contactAddr, walletAddr, { blockHeight: 19834521 }); // Approvals at a specific block const approvals = await spectrum.defi.getApprovals('ethereum', '0xd8dA...', { blockHeight: 19834521 }); // Portfolio at a specific block const portfolio = await spectrum.data.getPortfolio('ethereum', '0xd8dA...', { blockHeight: 19834521 }); // Contract code at a specific block const code = await spectrum.contracts.getCode('ethereum', '0xA0b8...', { blockHeight: 19834521 }); // Allowance at a specific block (blockHeight is inside the params object) const allowance = await spectrum.data.getAllowance('ethereum', '0xA0b8...', { owner: '0xd8dA...', spender: '0x68b3...', blockHeight: 19834521, });

Swap quotes (getUniswapV3Quote, getUniswapV4Quote) also accept blockHeight directly in their params object.

Per-request options

Every SDK method accepts an optional RequestOptions object as the last parameter:

// Skip cache for this request await spectrum.core.getBlockHeight('ethereum', { cacheTtl: 0 }); // Disable retries for this request await spectrum.tokens.getBalance('ethereum', addr, { noRetry: true }); // Abort a request const controller = new AbortController(); await spectrum.prices.getPrice('ETH', { signal: controller.signal });

SDK metrics

Access internal SDK metrics for monitoring:

const metrics = spectrum.getMetrics(); console.log(metrics); // { // totalRequests: 150, // cacheHits: 42, // cacheMisses: 108, // errors: 3, // avgResponseTime: 145.2, // }

Lifecycle management

Clean up SDK resources when your application shuts down:

// Clear all cached responses spectrum.clearCache(); // Release internal resources (timers, queued promises) spectrum.destroy();

Browser usage

The SDK works in browsers that support fetch and AbortController. However, your assigned endpoint URL will be exposed in client-side code. Use a backend proxy in production:

// Backend proxy setup const spectrum = new Spectrum({ api: '/api/spectrum', // proxy through your backend });

TypeScript exports

Key types you can import:

import type { ChainSlug, EvmChainSlug, ChainType, ChainInfo, SpectrumConfig, CacheConfig, Hooks, RequestOptions, HistoricalQueryOptions, } from '@spectrum-nodes/sdk';

Error classes

All error classes are also exported from the SDK root:

import { SpectrumError, // Base class ApiError, // Non-2xx response (status, body, path) RateLimitError, // HTTP 429 (retryAfter, path) ChainNotFoundError, // Unknown chain (chain) TimeoutError, // Request timeout (path) NetworkError, // Connection/DNS failure (cause, path) ValidationError, // Invalid parameter (param, path) } from '@spectrum-nodes/sdk';