Skip to content

JavaScript SDK

Installation

npm install @x402/client ethers

Basic Usage

import { X402Client } from '@x402/client';
import { Wallet } from 'ethers';

const wallet = new Wallet('0x_your_key');
const client = new X402Client({ wallet });

const response = await client.fetch('https://api.foursec.xyz/price/ETH');
const data = await response.json();
console.log('ETH: $' + data.price_usd);

Batch Requests

const symbols = ['BTC', 'ETH', 'SOL'];
const prices = await Promise.all(
  symbols.map(s =>
    client.fetch('https://api.foursec.xyz/price/' + s)
      .then(r => r.json())
  )
);
prices.forEach(p => console.log(p.symbol + ': $' + p.price_usd));

Error Handling

try {
  const res = await client.fetch('https://api.foursec.xyz/price/XYZ');
} catch (err) {
  if (err.status === 404) console.log('Symbol not found');
  if (err.status === 429) console.log('Rate limited, waiting...');
}

Retry with Backoff

async function fetchWithRetry(url, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const res = await client.fetch(url);
      return await res.json();
    } catch (err) {
      if (err.status !== 429) throw err;
      const wait = Math.pow(2, i) * 1000;
      console.log('Rate limited. Retry in ' + wait + 'ms');
      await new Promise(r => setTimeout(r, wait));
    }
  }
  throw new Error('Max retries exceeded');
}

Express.js Webhook Handler

const express = require('express');
const app = express();
app.use(express.json());

app.post('/webhook/price-alert', (req, res) => {
  const { symbol, current_price, condition } = req.body;
  console.log('ALERT: ' + symbol + ' hit $' + current_price);
  // Execute trading logic here
  res.status(200).send('OK');
});

app.listen(3000);

Released under the MIT License.