Skip to content

Quick Start (5 Minutes)

Get up and running with 4SEC API. No signup, no API keys — just your wallet.

Prerequisites

Before you start, make sure you have:

  • Node.js 18+ installed (recommended) or Python 3.9+
  • A crypto wallet with USDC on Base network
  • A small amount of ETH on Base for gas fees (~$0.01 per transaction)

New to Base?

Bridge ETH and USDC to Base via bridge.base.org or buy directly on Coinbase.

Step 1: Install the x402 SDK

bash
npm install @x402/fetch viem
bash
pip install httpx web3 eth-account
bash
# No SDK needed — use the x402 CLI
npm install -g x402-cli

Step 2: Setup Your Wallet

javascript
import { wrapFetchWithPayments } from "@x402/fetch";
import { privateKeyToAccount } from "viem/accounts";
import { createWalletClient, http } from "viem";
import { base } from "viem/chains";

// Your wallet private key (keep this secret!)
const account = privateKeyToAccount("0x_your_private_key_here");

// Create wallet client on Base network
const walletClient = createWalletClient({
  account,
  chain: base,
  transport: http("https://mainnet.base.org"),
});

// Create payment-enabled fetch function
const fetchWithPayment = wrapFetchWithPayments(fetch, {
  client: walletClient,
});
python
from eth_account import Account
from web3 import Web3
import httpx

# Your wallet private key (keep this secret!)
wallet = Account.from_key("0x_your_private_key_here")

# Connect to Base network
w3 = Web3(Web3.HTTPProvider("https://mainnet.base.org"))

# For Python, you need to manually handle the 402 flow
# See /integration/python for the full implementation
bash
# Save your private key as an environment variable
export WALLET_KEY="0x_your_private_key_here"

# The x402-cli will use this automatically

Security Warning

Never commit private keys to git or expose them in client-side code. Use environment variables or a secrets manager in production.

Step 3: Make Your First Request

Let's fetch the real-time price of ETH aggregated from 8+ DEXes:

javascript
// Fetch ETH price ($0.01 USDC, auto-paid by SDK)
const response = await fetchWithPayment(
  "https://api.foursec.xyz/price/ETH"
);
const data = await response.json();

console.log(`Symbol: ${data.symbol}`);
console.log(`Price: $${data.price_usd}`);
console.log(`24h Change: ${data.change_24h}%`);
console.log(`Sources: ${data.total_sources} DEXes`);
console.log(`Spread: ${data.spread}%`);
python
import httpx

response = httpx.get("https://api.foursec.xyz/price/ETH")

if response.status_code == 402:
    # Handle payment flow (see /integration/python)
    print("402 Payment Required — signing USDC transfer...")
elif response.status_code == 200:
    data = response.json()
    print(f"Symbol: {data['symbol']}")
    print(f"Price: ${data['price_usd']}")
    print(f"24h Change: {data['change_24h']}%")
bash
# Using x402-cli (handles payment automatically)
x402 fetch https://api.foursec.xyz/price/ETH --key $WALLET_KEY

Expected Response

json
{
  "symbol": "ETH",
  "price_usd": 2450.32,
  "change_24h": 2.45,
  "volume_24h_usd": 12500000,
  "total_sources": 3,
  "spread": 0.07,
  "sources": [
    {
      "dex": "Uniswap V3",
      "price": 2450.30,
      "liquidity_usd": 5200000
    },
    {
      "dex": "BaseSwap",
      "price": 2450.35,
      "liquidity_usd": 3100000
    },
    {
      "dex": "SushiSwap",
      "price": 2450.28,
      "liquidity_usd": 4200000
    }
  ]
}

Step 4: Try More Endpoints

Now let's explore other endpoints:

javascript
// Arbitrage opportunities across DEXes ($0.05)
const arb = await fetchWithPayment(
  "https://api.foursec.xyz/arbitrage-opportunity"
);
const arbData = await arb.json();
console.log("Arbitrage opportunities:", arbData.opportunities.length);

// 24h trading volume ($0.02)
const vol = await fetchWithPayment(
  "https://api.foursec.xyz/volume/ETH"
);
const volData = await vol.json();
console.log(`24h Volume: $${volData.volume_usd}`);

// Bid/ask spread analysis ($0.02)
const spread = await fetchWithPayment(
  "https://api.foursec.xyz/spread/ETH-USDC"
);
const spreadData = await spread.json();
console.log(`Spread: ${spreadData.spread_percent}%`);

// Historical OHLCV data ($0.02)
const history = await fetchWithPayment(
  "https://api.foursec.xyz/price/history/ETH?interval=1h&limit=24"
);
const historyData = await history.json();
console.log(`Candles: ${historyData.candles.length}`);

// Risk metrics ($0.03)
const risk = await fetchWithPayment(
  "https://api.foursec.xyz/volatility-index/ETH"
);
const riskData = await risk.json();
console.log(`Volatility: ${riskData.volatility_30d}%`);
console.log(`VaR (95%): ${riskData.var_95}`);
console.log(`Sharpe: ${riskData.sharpe_ratio}`);

// Funding rate ($0.03)
const funding = await fetchWithPayment(
  "https://api.foursec.xyz/funding-rate/ETH"
);
const fundingData = await funding.json();
console.log(`Current funding rate: ${fundingData.funding_rate}%`);

// Extreme funding rates ($0.05)
const extreme = await fetchWithPayment(
  "https://api.foursec.xyz/funding-rate/extreme"
);
const extremeData = await extreme.json();
console.log(`Extreme rates: ${extremeData.symbols.length}`);

// Liquidation heatmap ($0.04)
const heatmap = await fetchWithPayment(
  "https://api.foursec.xyz/liquidation/heatmap/ETH"
);
const heatmapData = await heatmap.json();
console.log(`Liquidation levels: ${heatmapData.levels.length}`);

// Recent liquidations ($0.03)
const liqs = await fetchWithPayment(
  "https://api.foursec.xyz/liquidation/recent"
);
const liqsData = await liqs.json();
console.log(`Recent liquidations: ${liqsData.events.length}`);

// CEX market data ($0.03)
const market = await fetchWithPayment(
  "https://api.foursec.xyz/api/v1/market/bitcoin"
);
const marketData = await market.json();
console.log(`Market: ${marketData.name} - $${marketData.current_price}`);

// Free endpoints (no payment needed)
const health = await fetch("https://api.foursec.xyz/health");
const openapi = await fetch("https://api.foursec.xyz/openapi.json");

Endpoint Pricing Reference

EndpointCostUse Case
GET /price/:symbol$0.01Real-time price check
GET /volume/:symbol$0.02Trading volume analysis
GET /spread/:pair$0.02Liquidity assessment
GET /price/history/:symbol$0.02Charting and backtesting
POST /price-alert$0.04Create webhook price alert
GET /volatility-index/:symbol$0.03Risk management
GET /funding-rate/:symbol$0.03Perpetual funding data
GET /funding-rate/history/:symbol$0.04Historical funding rates
GET /funding-rate/extreme$0.05Trading signal discovery
GET /liquidation/heatmap/:symbol$0.04Risk level mapping
GET /liquidation/recent$0.03Cascade monitoring
GET /liquidation/alert$0.06Liquidation alert info
GET /arbitrage-opportunity$0.05Arbitrage trading
GET /api/v1/prices$0.02CEX price aggregation
GET /api/v1/market/:id$0.03CEX market details
GET /api/v1/market/:id/history$0.04CEX historical data
GET /healthFreeStatus check
GET /openapi.jsonFreeAPI specification

What Just Happened?

Here's the complete flow when you made your first request:

1. Request        Your app calls GET /price/ETH
                       |
                       v
2. 402 Response   API returns "402 Payment Required"
                  with X-PAYMENT header containing:
                  - Amount: 0.01 USDC
                  - Recipient: 0x09b00dFE1E9b09653191fE8b3EDab5f2f0504dFE
                  - Network: Base (Chain ID 8453)
                       |
                       v
3. Sign Payment   x402 SDK automatically signs
                  USDC transfer from your wallet
                       |
                       v
4. Retry          SDK retries request with payment
                  proof in X-PAYMENT-PROOF header
                       |
                       v
5. Verify         API verifies payment on-chain
                  (takes ~2 seconds on Base)
                       |
                       v
6. Data Returned  API returns 200 OK with data
                  Total cost: $0.01 USDC

Cache Bonus

The same request within 30 seconds is free — served from cache with X-Cache: HIT header. Use this aggressively to reduce costs!

Cost Optimization Tips

1. Leverage the 30-Second Cache

javascript
// First request: $0.01 (cache MISS)
const price1 = await fetchWithPayment(
  "https://api.foursec.xyz/price/ETH"
);

// Same request 5 seconds later: $0.00 (cache HIT!)
const price2 = await fetchWithPayment(
  "https://api.foursec.xyz/price/ETH"
);

// Same request 35 seconds later: $0.01 (cache expired)
const price3 = await fetchWithPayment(
  "https://api.foursec.xyz/price/ETH"
);

2. Implement Local Caching

javascript
const cache = new Map();
const CACHE_TTL = 28 * 1000; // 28s (slightly less than API's 30s)

async function getPrice(symbol) {
  const cached = cache.get(symbol);
  if (cached && Date.now() - cached.time < CACHE_TTL) {
    return cached.data; // Free! No API call needed
  }
  
  const res = await fetchWithPayment(
    `https://api.foursec.xyz/price/${symbol}`
  );
  const data = await res.json();
  
  cache.set(symbol, { data, time: Date.now() });
  return data;
}

3. Batch Requests Efficiently

javascript
// BAD: Sequential requests (slow)
for (const symbol of ['BTC', 'ETH', 'SOL']) {
  await fetchWithPayment(`/price/${symbol}`);
}

// GOOD: Parallel requests (fast)
const prices = await Promise.all(
  ['BTC', 'ETH', 'SOL'].map(s =>
    fetchWithPayment(`https://api.foursec.xyz/price/${s}`)
      .then(r => r.json())
  )
);

4. Use Multi-Symbol CEX Endpoint

javascript
// Instead of 3 separate calls, use one batch call
const prices = await fetchWithPayment(
  "https://api.foursec.xyz/api/v1/prices?symbols=btc,eth,sol"
);
const data = await prices.json();
// Returns all 3 prices in one request ($0.02 total)

Common Errors and Solutions

ErrorMeaningSolution
402 Payment RequiredNeed to payUse x402 SDK or handle payment flow
400 Insufficient BalanceNot enough USDCAdd USDC to wallet on Base
400 Insufficient GasNot enough ETH for gasAdd ETH to wallet on Base
404 Not FoundInvalid symbol/endpointCheck endpoint spelling
429 Too Many RequestsRate limited (500/min)Implement retry with backoff
500 Internal ErrorServer issueRetry after a few seconds

Next Steps

Now that you've made your first request, explore further:

ResourceWhat You'll Learn
API ReferenceAll endpoints, parameters, and response formats
JavaScript SDKAdvanced usage, batch requests, error handling
Python SDKPython integration guide with manual payment flow
How x402 WorksDeep dive into the x402 payment protocol
PricingComplete pricing table and cost optimization
Wallet SetupDetailed wallet configuration guide

Quick Reference Card

BASE_URL:       https://api.foursec.xyz
NETWORK:        Base (Chain ID 8453)
PAYMENT:        USDC (0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913)
PROTOCOL:       x402 v2
CACHE_TTL:      30 seconds
RATE_LIMIT:     100 requests/minute
CHEAPEST:       /price/:symbol ($0.01)
MOST_EXPENSIVE: /liquidation/alert ($0.06)
FREE:           /health, /api/v1/status, /price-alerts, /liquidation/alerts
MOST_EXPENSIVE: /liquidation/alert ($0.06)
FREE:           /health, /, /openapi.json, /.well-known/x402.json

Need Help?

Check the FAQ or Troubleshooting guides for common issues.

Built with x402 protocol on Base