Skip to main content

TypeScript/JavaScript SDK

Official TypeScript/JavaScript client for Axol API with full type safety and modern JavaScript features.

Installation

# npm
npm install @axol/api-client

# yarn
yarn add @axol/api-client

# pnpm
pnpm add @axol/api-client

Quick Start

import { AxolClient } from '@axol/api-client';

const client = new AxolClient({
apiKey: 'your_api_key'
});

// Get gas prices
const gas = await client.gasPrices('ethereum');
console.log(gas);

Configuration

import { AxolClient } from '@axol/api-client';

const client = new AxolClient({
apiKey: process.env.AXOL_API_KEY,
baseUrl: 'https://api.axol.io', // Optional
timeout: 30000, // Request timeout in ms
retryCount: 3, // Auto-retry on failure
cache: {
enabled: true,
ttl: 60 // Cache TTL in seconds
}
});

TypeScript Support

Full TypeScript support with comprehensive type definitions:

import { 
AxolClient,
Block,
Transaction,
GasPrice,
Chain
} from '@axol/api-client';

const client = new AxolClient({ apiKey: 'your_key' });

// All responses are fully typed
const block: Block = await client.getBlock('ethereum', 'latest');
const tx: Transaction = await client.getTransaction('ethereum', '0x...');
const gas: GasPrice = await client.gasPrices('ethereum');

Core Methods

Blockchain Data

// Get latest block
const block = await client.getBlock('ethereum', 'latest');

// Get specific block by number
const block = await client.getBlock('ethereum', 18500000);

// Get transaction
const tx = await client.getTransaction('ethereum', '0x...');

// Get balance
const balance = await client.getBalance('ethereum', '0x...');

// Get token balances
const tokens = await client.getTokenBalances('0x...', 'ethereum');

// Get transaction receipt
const receipt = await client.getTransactionReceipt('ethereum', '0x...');

Gas Prices

// Single chain
const gas = await client.gasPrices('ethereum');

// Multiple chains
const gas = await client.gasPrices(['ethereum', 'polygon', 'arbitrum']);

// With prediction
const predicted = await client.predictGasPrices('ethereum', {
minutesAhead: 10
});

// Historical gas prices
const history = await client.gasHistory('ethereum', {
from: new Date('2024-01-01'),
to: new Date('2024-01-31')
});

Multi-chain Operations

// Check balances across chains
const balances = await client.getMultiChainBalances({
address: '0x...',
chains: ['ethereum', 'polygon', 'arbitrum', 'optimism']
});

// Search transactions across chains
const transactions = await client.searchTransactions({
address: '0x...',
chains: ['ethereum', 'bsc', 'polygon'],
limit: 100,
offset: 0
});

// Get cross-chain activity
const activity = await client.getCrossChainActivity('0x...');

WebSocket Streaming

import { AxolWebSocket } from '@axol/api-client';

const ws = new AxolWebSocket({
apiKey: 'your_key'
});

// Connect to WebSocket
await ws.connect();

// Subscribe to real-time updates
ws.subscribe('gas_prices', (data) => {
console.log('Gas prices updated:', data);
});

ws.subscribe('blocks:ethereum', (block) => {
console.log('New Ethereum block:', block);
});

ws.subscribe('transactions:0x...', (tx) => {
console.log('New transaction for address:', tx);
});

// Unsubscribe
ws.unsubscribe('gas_prices');

// Disconnect
ws.disconnect();

Error Handling

import {
AxolError,
RateLimitError,
CUPoolExhaustedError,
AuthenticationError,
ValidationError
} from '@axol/api-client';

try {
const result = await client.getBlock('ethereum', 'latest');
} catch (error) {
if (error instanceof RateLimitError) {
// Exceeded CUPs (throughput limit)
console.log(`Rate limited (CUPs exceeded). Reset at: ${error.resetTime}`);
console.log(`CUPs limit: ${error.cupsLimit}, Current: ${error.currentCups}`);
console.log(`Retry after: ${error.retryAfter} seconds`);
// Implement exponential backoff
} else if (error instanceof CUPoolExhaustedError) {
// Exceeded monthly CU pool
console.log(`Monthly CU pool exhausted. Reset: ${error.resetDate}`);
console.log(`CU limit: ${error.cuLimit}, Used: ${error.cuUsed}`);
// Options: wait for reset, enable overage billing, or upgrade tier
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof ValidationError) {
console.log('Invalid parameters:', error.details);
} else if (error instanceof AxolError) {
console.log('API error:', error.message);
}
}

// Check CU usage proactively
const response = await client.getBlock('ethereum', 'latest');
const cuRemaining = response.headers['x-ratelimit-cu-remaining'];
console.log(`CUs remaining this month: ${cuRemaining}`);

Pagination

// Using async iterators
for await (const tx of client.getTransactionIterator({
address: '0x...',
chain: 'ethereum'
})) {
console.log(tx);
}

// Manual pagination
let page = 1;
let hasMore = true;

while (hasMore) {
const result = await client.getTransactions({
address: '0x...',
chain: 'ethereum',
page,
limit: 100
});

result.data.forEach(tx => console.log(tx));

hasMore = result.hasNextPage;
page++;
}

Batch Requests

// Batch multiple requests
const results = await client.batch([
client.getBlock('ethereum', 'latest'),
client.getBlock('polygon', 'latest'),
client.gasPrices(['ethereum', 'polygon']),
client.getBalance('ethereum', '0x...')
]);

// With error handling per request
const results = await client.batchWithErrors([
{ method: 'getBlock', params: ['ethereum', 'latest'] },
{ method: 'getBlock', params: ['polygon', 'latest'] },
{ method: 'gasPrices', params: [['ethereum', 'polygon']] }
]);

results.forEach(result => {
if (result.success) {
console.log(result.data);
} else {
console.error(result.error);
}
});

Caching

// Configure cache
const client = new AxolClient({
apiKey: 'your_key',
cache: {
enabled: true,
ttl: 300, // 5 minutes
maxSize: 100 // Max cached items
}
});

// Clear cache
client.clearCache();

// Bypass cache for specific request
const block = await client.getBlock('ethereum', 'latest', {
cache: false
});

// Force cache refresh
const block = await client.getBlock('ethereum', 'latest', {
cacheRefresh: true
});

Request Interceptors

// Add request interceptor
client.addRequestInterceptor(async (config) => {
console.log('Request:', config);
// Modify request config if needed
return config;
});

// Add response interceptor
client.addResponseInterceptor(async (response) => {
console.log('Response:', response);
// Process response if needed
return response;
});

Custom Requests

// Make custom API calls
const response = await client.request({
method: 'GET',
endpoint: '/custom/endpoint',
params: {
key: 'value'
},
headers: {
'X-Custom-Header': 'value'
}
});

Utilities

import { utils } from '@axol/api-client';

// Format addresses
const formatted = utils.formatAddress('0xabc...');
const checksummed = utils.toChecksumAddress('0xabc...');

// Unit conversions
const eth = utils.weiToEth('1000000000000000000');
const gwei = utils.weiToGwei('1000000000');
const wei = utils.ethToWei('1.5');

// Validation
const isValid = utils.isValidAddress('0x...');
const isContract = await utils.isContract('0x...', client);

// Hashing
const hash = utils.keccak256('data');
const txHash = utils.hashTransaction(txObject);

Browser Usage

For browser environments, use the UMD build:

<script src="https://unpkg.com/@axol/api-client/dist/axol.min.js"></script>
<script>
const client = new Axol.AxolClient({
apiKey: 'your_key'
});

client.gasPrices('ethereum').then(gas => {
console.log(gas);
});
</script>

Node.js Specific Features

// File-based caching (Node.js only)
const client = new AxolClient({
apiKey: 'your_key',
cache: {
enabled: true,
type: 'file',
directory: './cache'
}
});

// Environment variable support
const client = new AxolClient({
apiKey: process.env.AXOL_API_KEY,
baseUrl: process.env.AXOL_API_URL
});

React Hooks (Optional Package)

import { useAxol, AxolProvider } from '@axol/react';

// Provider setup
function App() {
return (
<AxolProvider apiKey="your_key">
<YourComponents />
</AxolProvider>
);
}

// Using hooks
function GasPrices() {
const { data, loading, error } = useAxol('gasPrices', ['ethereum']);

if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;

return <div>Gas: {data.fast} Gwei</div>;
}

Testing

import { createMockClient } from '@axol/api-client/testing';

// Create mock client for testing
const mockClient = createMockClient();

// Set mock responses
mockClient.setMockResponse('getBlock', {
number: 18500000,
hash: '0x...',
timestamp: Date.now()
});

// Use in tests
describe('MyComponent', () => {
it('should fetch block', async () => {
const block = await mockClient.getBlock('ethereum', 'latest');
expect(block.number).toBe(18500000);
});
});

Migration Guide

From v1 to v2

// v1
const client = new AxolClient('api_key');
client.getBlock('ethereum', 'latest', (err, block) => {
// callback style
});

// v2
const client = new AxolClient({ apiKey: 'api_key' });
const block = await client.getBlock('ethereum', 'latest');
// Promise-based, async/await

Next Steps