Skip to main content

Integration Examples

This page provides comprehensive integration examples for different programming languages and frameworks using the x402 payment protocol.

JavaScript/Node.js with x402-fetch

import { wrapFetchWithPayment, decodeXPaymentResponse } from "x402-fetch";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { baseSepolia } from "viem/chains";

// Create wallet account
const account = privateKeyToAccount(process.env.PRIVATE_KEY);

// Wrap fetch with x402 payment handling
const fetchWithPayment = wrapFetchWithPayment(fetch, account);

// Make paid API request
fetchWithPayment('https://api.cortex402.xyz/token/0x.../1', {
method: 'GET',
})
.then(async response => {
const data = await response.json();
console.log('Token info:', data.data);

// Decode payment response if needed
const paymentResponse = decodeXPaymentResponse(response.headers.get("x-payment-response"));
console.log('Payment details:', paymentResponse);
})
.catch(error => {
console.error('Error:', error.response?.data?.error);
});

JavaScript/Node.js with x402-axios

import { withPaymentInterceptor, decodeXPaymentResponse } from "x402-axios";
import axios from "axios";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";

// Create wallet account
const account = privateKeyToAccount(process.env.PRIVATE_KEY);

// Create Axios instance with payment handling
const api = withPaymentInterceptor(
axios.create({
baseURL: 'https://api.cortex402.xyz',
}),
account,
);

// Make paid API request
api.get('/token/0x.../1')
.then(response => {
console.log('Token info:', response.data.data);

// Decode payment response if needed
const paymentResponse = decodeXPaymentResponse(response.headers["x-payment-response"]);
console.log('Payment details:', paymentResponse);
})
.catch(error => {
console.error('Error:', error.response?.data?.error);
});

Python with x402-httpx

import asyncio
import os
from x402.clients.httpx import x402HttpxClient
from eth_account import Account

# Create wallet account
account = Account.from_key(os.getenv("PRIVATE_KEY"))

# Make paid API request
async def get_token_info():
async with x402HttpxClient(account=account, https://api.cortex402.xyz="https://api.cortex402.xyz") as client:
response = await client.get("/token/0x.../1")
data = await response.aread()
print("Token info:", data)

# Run the async function
asyncio.run(get_token_info())

Python with x402-requests

import os
from x402.clients.requests import x402_requests
from eth_account import Account

# Create wallet account
account = Account.from_key(os.getenv("PRIVATE_KEY"))

# Create session with payment handling
session = x402_requests(account)

# Make paid API request
response = session.get("https://api.cortex402.xyz/token/0x.../1")
data = response.json()
print("Token info:", data['data'])

MCP Integration (for AI Agents)

import { convertToModelMessages, stepCountIs, streamText } from "ai";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { experimental_createMCPClient as createMCPClient } from "ai";
import { withPayment } from "x402-mcp";

// Create MCP client with payment capabilities
const mcpClient = await createMCPClient({
transport: new StreamableHTTPClientTransport("https://api.cortex402.xyz"),
}).then((client) => withPayment(client, {
account, // Your wallet account
network: "base" // or "base-sepolia" for testnet
}));

// Get available tools and use with AI model
const tools = await mcpClient.tools();
const result = streamText({
model: "gpt-4",
tools,
messages: convertToModelMessages(messages),
stopWhen: stepCountIs(5),
system: "ALWAYS prompt the user to confirm before authorizing payments",
});

Complete Examples

Token Research Workflow

// Complete token research example
async function researchToken(tokenAddress, networkId) {
try {
// Get token information
const tokenInfo = await fetchWithPayment(`https://api.cortex402.xyz/token/${tokenAddress}/${networkId}`);
const tokenData = await tokenInfo.json();

// Get current price
const priceInfo = await fetchWithPayment(`https://api.cortex402.xyz/token/${tokenAddress}/${networkId}/price`);
const priceData = await priceInfo.json();

// Search for similar tokens
const searchResults = await fetchWithPayment(`https://api.cortex402.xyz/tokens/search?q=${tokenData.data.symbol}&limit=5`);
const searchData = await searchResults.json();

return {
token: tokenData.data,
price: priceData.data,
similar: searchData.data
};
} catch (error) {
console.error('Research failed:', error);
throw error;
}
}

Portfolio Analysis

// Portfolio analysis example
async function analyzePortfolio(walletAddress, networks) {
try {
// Get wallet balances
const balancesResponse = await fetchWithPayment('https://api.cortex402.xyz/balances', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
walletAddress,
networks
})
});

const balances = await balancesResponse.json();

// Get top holders for each token
const topHoldersPromises = balances.data.map(async (balance) => {
if (balance.balance > 0) {
const tokenId = `${balance.networkName}:${balance.address}`;
const holdersResponse = await fetchWithPayment(`https://api.cortex402.xyz/token/${tokenId}/top10holders`);
return await holdersResponse.json();
}
return null;
});

const topHolders = await Promise.all(topHoldersPromises);

return {
balances: balances.data,
topHolders: topHolders.filter(Boolean)
};
} catch (error) {
console.error('Portfolio analysis failed:', error);
throw error;
}
}

Market Analysis

// Market analysis example
async function analyzeMarket(symbol, days = 30) {
try {
const now = Math.floor(Date.now() / 1000);
const from = now - (days * 24 * 60 * 60);

// Get price history
const barsResponse = await fetchWithPayment(
`https://api.cortex402.xyz/bars?symbol=${symbol}&from=${from}&to=${now}&resolution=1D`
);
const bars = await barsResponse.json();

// Get all supported networks
const networksResponse = await fetchWithPayment('https://api.cortex402.xyz/networks');
const networks = await networksResponse.json();

return {
priceHistory: bars.data,
supportedNetworks: networks.data
};
} catch (error) {
console.error('Market analysis failed:', error);
throw error;
}
}

Error Handling Best Practices

// Comprehensive error handling
async function makeApiRequest(url, options = {}) {
try {
const response = await fetchWithPayment(url, options);

if (!response.ok) {
const errorData = await response.json();

switch (response.status) {
case 402:
console.error('Payment required:', errorData);
break;
case 429:
console.error('Rate limited. Retry after:', errorData.retryAfter);
// Implement exponential backoff
break;
case 400:
console.error('Bad request:', errorData.error);
break;
default:
console.error('API error:', errorData);
}

throw new Error(`API request failed: ${response.status}`);
}

return await response.json();
} catch (error) {
if (error.name === 'PaymentError') {
console.error('Payment processing failed:', error.message);
} else if (error.name === 'NetworkError') {
console.error('Network error:', error.message);
} else {
console.error('Unexpected error:', error);
}
throw error;
}
}

Environment Setup

Node.js Project Setup

# Install dependencies
npm install x402-fetch viem
# or
npm install x402-axios viem

# Environment variables
echo "PRIVATE_KEY=your_private_key_here" > .env
echo "https://api.cortex402.xyz=https://api.cortex.com/v1" >> .env

Python Project Setup

# Install dependencies
pip install x402 eth-account httpx requests

# Environment variables
export PRIVATE_KEY="your_private_key_here"
export https://api.cortex402.xyz="https://api.cortex.com/v1"

Testing

Unit Test Example

// Jest test example
describe('Cortex API Integration', () => {
test('should fetch token information', async () => {
const mockAccount = { address: '0x...' };
const mockFetch = jest.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ data: { symbol: 'ETH' } })
});

const fetchWithPayment = wrapFetchWithPayment(mockFetch, mockAccount);

const result = await fetchWithPayment('https://api.cortex402.xyz/token/0x.../1');
const data = await result.json();

expect(data.data.symbol).toBe('ETH');
});
});

Performance Optimization

// Caching example
class CortexAPIClient {
constructor(account, baseURL) {
this.account = account;
this.baseURL = baseURL;
this.cache = new Map();
this.fetchWithPayment = wrapFetchWithPayment(fetch, account);
}

async getTokenInfo(address, networkId, useCache = true) {
const cacheKey = `token-${address}-${networkId}`;

if (useCache && this.cache.has(cacheKey)) {
const cached = this.cache.get(cacheKey);
// Check if cache is still valid (e.g., less than 5 minutes old)
if (Date.now() - cached.timestamp < 5 * 60 * 1000) {
return cached.data;
}
}

const response = await this.fetchWithPayment(`${this.baseURL}/token/${address}/${networkId}`);
const data = await response.json();

if (useCache) {
this.cache.set(cacheKey, {
data: data.data,
timestamp: Date.now()
});
}

return data.data;
}
}

These examples provide a solid foundation for integrating with the Cortex API using the x402 payment protocol across different programming languages and use cases.