JavaScript Examples
Custom implementation examples using JavaScript and popular libraries.
For production use, see the TypeScript SDK which provides full type safety, WebSocket streaming, and advanced features.
Setup
npm install axios ethers
Basic Request
Quick example using axios:
const axios = require('axios');
const client = axios.create({
baseURL: 'https://api.axol.io/api/v1',
headers: { 'X-API-Key': process.env.AXOL_API_KEY }
});
// Make requests
const gas = await client.get('/gas/ethereum/current');
console.log(gas.data);
WebSocket Connection
const WebSocket = require('ws');
function connectWebSocket() {
const ws = new WebSocket(`wss://api.axol.io/api/v1/ws/connect?token=${process.env.AXOL_API_KEY}`);
ws.on('open', () => {
ws.send(JSON.stringify({
type: 'subscribe',
channels: ['gas_prices_ethereum']
}));
});
ws.on('message', (data) => console.log('Update:', JSON.parse(data)));
ws.on('error', console.error);
return ws;
}
Transaction Monitoring
class TransactionMonitorError extends Error {
constructor(message, code) {
super(message);
this.name = 'TransactionMonitorError';
this.code = code;
}
}
async function monitorTransaction(txHash, chain = 'ethereum', options = {}) {
const {
confirmations = 12,
timeout = 300000, // 5 minutes
pollInterval = 5000
} = options;
const startTime = Date.now();
while (true) {
// Check timeout
if (Date.now() - startTime > timeout) {
throw new TransactionMonitorError(
`Timeout waiting for ${confirmations} confirmations`,
'TIMEOUT'
);
}
try {
const { data } = await client.get(`/blockchain/${chain}/tx/${txHash}`);
if (data.confirmations >= confirmations) {
console.log(`Transaction confirmed with ${data.confirmations} confirmations`);
return data;
}
console.log(`Confirmations: ${data.confirmations}/${confirmations}`);
} catch (error) {
if (error.response?.status === 404) {
console.log('Transaction pending, not yet in mempool...');
} else if (error.response?.status === 429) {
const retryAfter = error.response.headers['retry-after'] || 60;
console.warn(`Rate limited. Waiting ${retryAfter}s...`);
await new Promise(r => setTimeout(r, retryAfter * 1000));
continue;
} else {
console.error('Error fetching transaction:', error.message);
}
}
await new Promise(r => setTimeout(r, pollInterval));
}
}
// Usage with error handling
try {
const tx = await monitorTransaction('0x123...', 'ethereum', {
confirmations: 6,
timeout: 600000
});
console.log('Final transaction:', tx);
} catch (error) {
if (error.code === 'TIMEOUT') {
console.error('Transaction confirmation timed out');
} else {
console.error('Monitoring failed:', error.message);
}
}
Gas Price Oracle
class GasOracleError extends Error {
constructor(message, code) {
super(message);
this.name = 'GasOracleError';
this.code = code;
}
}
async function getOptimalGasPrice(chain = 'ethereum', retries = 3) {
let lastError;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
const { data } = await client.get(`/gas/${chain}/current`);
if (!data || typeof data.standard === 'undefined') {
throw new GasOracleError('Invalid gas price response', 'INVALID_RESPONSE');
}
return {
economy: data.slow,
normal: data.standard,
priority: data.fast,
timestamp: new Date().toISOString()
};
} catch (error) {
lastError = error;
if (error.response?.status === 429) {
const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
console.warn(`Rate limited. Attempt ${attempt}/${retries}. Waiting ${delay}ms...`);
await new Promise(r => setTimeout(r, delay));
continue;
}
if (error.response?.status === 401) {
throw new GasOracleError('Invalid API key', 'AUTH_ERROR');
}
// For other errors, retry with backoff
if (attempt < retries) {
const delay = attempt * 1000;
console.warn(`Request failed. Retrying in ${delay}ms...`);
await new Promise(r => setTimeout(r, delay));
}
}
}
throw new GasOracleError(
`Failed after ${retries} attempts: ${lastError?.message}`,
'MAX_RETRIES'
);
}
async function sendTransaction(wallet, to, value) {
try {
const gas = await getOptimalGasPrice();
const ethers = require('ethers');
console.log(`Using gas price: ${gas.normal} gwei`);
const tx = await wallet.sendTransaction({
to,
value: ethers.parseEther(value),
gasPrice: ethers.parseUnits(gas.normal.toString(), 'gwei')
});
console.log(`Transaction sent: ${tx.hash}`);
return tx;
} catch (error) {
if (error instanceof GasOracleError) {
console.error(`Gas oracle error: ${error.message}`);
} else {
console.error(`Transaction failed: ${error.message}`);
}
throw error;
}
}