Code Examples

Ready-to-use code examples to get you started with the Swap API. Copy, paste, and customize for your needs.

4
Examples
3
Languages
100%
Production Ready
24/7
Support

Get Token Quote

Get a swap quote for any token pair with slippage protection

GET /v1/quote

Essential for swap interfaces and price displays

JavaScript (Node.js)
// Get swap quote
const getQuote = async (fromToken, toToken, amount) => {
  const response = await fetch(
    'https://your-endpoint.../v1/quote?' + 
    new URLSearchParams({
      quotetarget: 'base',
      from_token: fromToken,
      to_token: toToken,
      amount: amount.toString(),
      slippage: '0.005'
    })
  );

  const quote = await response.json();
  
  console.log('Price:', quote.execution_price);
  console.log('You receive:', quote.output.amount, quote.output.token.symbol);
  console.log('Slippage:', (quote.slippage * 100).toFixed(2) + '%');
  
  return quote;
};

// Usage
const quote = await getQuote(
  '0x940181a94A35A4569E4529A3CDfB74e38FD98631', // AERO
  '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
  1.0
);

Search Tokens

Find tokens by symbol or address for autocomplete interfaces

GET /v1/tokens/search

Perfect for token picker dropdowns and search interfaces

JavaScript (Node.js)
// Search for tokens
const searchTokens = async (query, limit = 10) => {
  const response = await fetch(
    'https://your-endpoint.../v1/tokens/search?' +
    new URLSearchParams({
      target: 'base',
      query: query,
      limit: limit.toString()
    })
  );
  
  const data = await response.json();
  
  return data.tokens.map(token => ({
    symbol: token.symbol,
    name: token.name,
    address: token.address,
    decimals: token.decimals
  }));
};

// Usage examples
const aeroTokens = await searchTokens('AERO');
const usdcTokens = await searchTokens('USDC');
const addressSearch = await searchTokens('0x940181');

console.log('AERO tokens:', aeroTokens);

Get Token Prices

Fetch real-time prices for portfolio tracking and displays

GET /v1/prices

Essential for portfolio apps, price tickers, and analytics

JavaScript (Node.js)
// Get multiple token prices
const getTokenPrices = async (symbols) => {
  const response = await fetch(
    'https://your-endpoint.../v1/prices?' +
    new URLSearchParams({
      target: 'aero',
      symbols: symbols.join(','),
      limit: '50'
    })
  );
  
  const data = await response.json();
  
  // Convert to simple price map
  const prices = {};
  Object.entries(data.prices).forEach(([address, info]) => {
    prices[info.token.symbol] = {
      price: info.price,
      address: info.token.address,
      decimals: info.token.decimals
    };
  });
  
  return prices;
};

// Usage
const prices = await getTokenPrices(['AERO', 'USDC', 'WETH']);

console.log('AERO Price:', prices.AERO?.price);
console.log('USDC Price:', prices.USDC?.price);
console.log('WETH Price:', prices.WETH?.price);

// Calculate portfolio value
const portfolio = [
  { symbol: 'AERO', amount: 100 },
  { symbol: 'USDC', amount: 1000 },
  { symbol: 'WETH', amount: 0.5 }
];

const totalValue = portfolio.reduce((total, holding) => {
  const price = prices[holding.symbol]?.price || 0;
  return total + (holding.amount * price);
}, 0);

console.log('Portfolio Value: $' + totalValue.toFixed(2));

Build Swap Transaction

Create ready-to-sign transactions for wallet execution

POST /v1/swap/build

Final step in swap interfaces - creates transaction for user to sign

JavaScript (Node.js)
// Build swap transaction
const buildSwapTransaction = async (fromToken, toToken, amount, walletAddress) => {
  const response = await fetch("https://your-endpoint.../v1/swap/build?target=base", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from_token: fromToken,
      to_token: toToken,
      amount: amount,
      wallet_address: walletAddress,
      slippage: 0.005
    }),
  });

  const transaction = await response.json();

  console.log("Transaction built successfully:");
  console.log("To:", transaction.to);
  console.log("Data:", transaction.data);
  console.log("Value:", transaction.value);
  console.log("Gas Limit:", transaction.gasLimit);

  return transaction;
};

// Usage with Web3 wallet
const executeSwap = async () => {
  try {
    const transaction = await buildSwapTransaction(
      "0x940181a94A35A4569E4529A3CDfB74e38FD98631", // AERO
      "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC
      1.0,
      "0xYourWalletAddress"
    );

    // Send transaction with wallet (MetaMask, etc.)
    if (window.ethereum) {
      const txHash = await window.ethereum.request({
        method: "eth_sendTransaction",
        params: [transaction],
      });

      console.log("Transaction sent:", txHash);
      return txHash;
    }
  } catch (error) {
    console.error("Swap failed:", error);
  }
};

Ready to Start Building?

Get your API key and start integrating these examples into your application today.