PRACTICAL EXAMPLES • REAL-WORLD IMPLEMENTATION

X402 API Usage Examples

Practical examples of how to use the Elsa X402 API for real blockchain execution with automatic payment handling.

[EX:01]

Token Swap Execution

SCENARIO

Execute a real token swap on Base network using the Elsa pipeline system with automatic X402 payment handling.

STEP 1: SETUP X402 CLIENT

setup.js
// Setup wallet and X402 payment interceptor
import { withPaymentInterceptor } from 'x402-axios';
import { createWalletClient, http, privateKeyToAccount } from 'viem';
import { base } from 'viem/chains';
import axios from 'axios';
const walletClient = createWalletClient({
chain: base,
transport: http(),
account: privateKeyToAccount('0x...')
});
const client = withPaymentInterceptor(
axios.create({ baseURL: 'http://localhost:3002' }),
walletClient
);

STEP 2: EXECUTE SWAP (DRY RUN)

swap-dryrun.js
// Execute swap USDC to WETH on Base (dry run)
const result = await client.post('/api/execute_swap', {
from_chain: 'base',
from_token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
from_amount: '10',
to_chain: 'base',
to_token: '0x4200000000000000000000000000000000000006', // WETH
wallet_address: walletClient.account.address,
slippage: 2.0,
dry_run: true // Test mode - no real transaction
});
// Response contains pipeline_id for tracking
console.log('Pipeline ID:', result.data.pipeline_id);
console.log('Estimated output:', result.data.tasks[0].estimate.to_amount);

STEP 3: EXECUTE REAL SWAP

swap-real.js
// Execute real swap (actual blockchain transaction)
const realSwap = await client.post('/api/execute_swap', {
from_chain: 'base',
from_token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
from_amount: '10',
to_chain: 'base',
to_token: '0x4200000000000000000000000000000000000006',
wallet_address: walletClient.account.address,
slippage: 2.0,
dry_run: false // Real execution!
});
// Monitor transaction status
const status = await client.post('/api/get_transaction_status', {
pipeline_id: realSwap.data.pipeline_id
});
if (status.data.tasks[0].status === 'sign_pending') {
// Sign and send the transaction
const tx = status.data.tasks[0].tx_data;
const hash = await walletClient.sendTransaction(tx);
console.log('Transaction sent:', hash);
}

COMPLETE IMPLEMENTATION

swap-executor.js
import { withPaymentInterceptor } from 'x402-axios';
import { createWalletClient, http, privateKeyToAccount } from 'viem';
import { base } from 'viem/chains';
import axios from 'axios';
class SwapExecutor {
constructor(privateKey) {
this.walletClient = createWalletClient({
chain: base,
transport: http(),
account: privateKeyToAccount(privateKey)
});
this.client = withPaymentInterceptor(
axios.create({ baseURL: 'http://localhost:3002' }),
this.walletClient
);
}
async executeSwap(params) {
// First do dry run to check estimate
const dryRun = await this.client.post('/api/execute_swap', {
...params, dry_run: true
});
console.log('Estimated output:', dryRun.data.tasks[0].estimate);
// Execute real swap
const result = await this.client.post('/api/execute_swap', {
...params, dry_run: false
});
// Monitor and sign transaction
return this.monitorPipeline(result.data.pipeline_id);
}
async monitorPipeline(pipelineId) {
while (true) {
const status = await this.client.post('/api/get_transaction_status', {
pipeline_id: pipelineId
});
const task = status.data.tasks[0];
if (task.status === 'sign_pending') {
const hash = await this.walletClient.sendTransaction(task.tx_data);
console.log('Transaction sent:', hash);
} else if (task.status === 'success') {
console.log('Swap completed!');
return status.data;
} else if (task.status === 'failed') {
throw new Error('Transaction failed: ' + task.error);
}
await new Promise(r => setTimeout(r, 2000));
}
}
}
// Usage
const executor = new SwapExecutor(process.env.PRIVATE_KEY);
await executor.executeSwap({
from_chain: 'base',
from_token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
from_amount: '10',
to_chain: 'base',
to_token: '0x4200000000000000000000000000000000000006',
wallet_address: executor.walletClient.account.address,
slippage: 2.0
});
[EX:02]

Portfolio Analysis

SCENARIO

Analyze wallet holdings across multiple chains and get comprehensive portfolio data.

GET PORTFOLIO DATA

const portfolio = await client.post('/api/get_portfolio', {
wallet_address: '0x742d35Cc6634C0532925a3b844Bc1e6A8B8C1F3D',
include_spam: false,
include_nfts: true
});
// Response includes token balances, values, and NFTs
console.log('Total value:', portfolio.data.total_value_usd);
console.log('Chains:', portfolio.data.chains);

GET TOKEN PRICES

const price = await client.post('/api/get_token_price', {
chain: 'base',
token_address: '0x4200000000000000000000000000000000000006' // WETH
});
console.log('WETH price:', price.data.price_usd);
[EX:03]

Limit Orders

CREATE LIMIT ORDER

// Create a limit order to sell USDC for WETH at specific price
const order = await client.post('/api/create_limit_order', {
from_chain: 'base',
from_token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
from_amount: '1000',
to_token: '0x4200000000000000000000000000000000000006', // WETH
limit_price: '2500', // Execute when 1 ETH = $2500
wallet_address: walletClient.account.address,
valid_for_hours: 24
});

MONITOR & CANCEL ORDERS

// Get all active limit orders
const orders = await client.post('/api/get_limit_orders', {
wallet_address: walletClient.account.address
});
// Cancel an order
await client.post('/api/cancel_limit_order', {
order_id: orders.data[0].order_id,
wallet_address: walletClient.account.address
});
[REF]

Quick API Reference

CORE ENDPOINTS

POST /api/execute_swap
Execute token swap with pipeline system
POST /api/get_transaction_status
Check pipeline status and get tx data for signing
POST /api/get_portfolio
Get comprehensive wallet portfolio data
POST /api/get_token_price
Get current token price in USD
POST /api/create_limit_order
Create limit order on CoWSwap
GET /health
Check server health and payment info

REQUIRED PARAMETERS

• wallet_address: Your wallet address (required for all transactions)
• from_chain / to_chain: Chain identifiers ('base', 'ethereum', etc.)
• from_token / to_token: Token contract addresses (not symbols)
• dry_run: true for testing, false for real execution
• slippage: Max slippage tolerance (e.g., 2.0 for 2%)

PAYMENT SYSTEM

• All requests require X402 micropayments in USDC on Base
• Use withPaymentInterceptor from x402-axios for automatic payments
• Payment recipient: 0x0D224DB2830A32bc75212A0ec6f0008C2B3ae5b5
• Costs range from $0.002 to $0.10 per request
[LIVE]

Built with X402 API

WalletRoast.com

LIVE PROJECT
Visit →

A fun AI-powered app that roasts your crypto wallet. Analyzes your portfolio holdings, transaction history, and DeFi positions using the Elsa X402 API, then generates a humorous roast of your crypto decisions.

Portfolio AnalysisTransaction HistoryX402 PaymentsAI Generated

Ready to Build?

These examples demonstrate real blockchain execution using the Elsa X402 API with automatic USDC micropayments on Base network.