Ready-to-use examples for common integration scenarios with InkyPump and InkySwap APIs.

Token Discovery Dashboard

Build a dashboard showing trending tokens and their metrics:
interface Token {
  address: string;
  name: string;
  ticker: string;
  market_cap: number;
  price_eth: number;
  volume_24h: number;
  price_change_24h: number;
}

async function getTrendingTokens(): Promise<Token[]> {
  const response = await fetch(
    'https://inkypump.com/api/tokens?' + 
    new URLSearchParams({
      sortBy: 'trending',
      status: 'live',
      page: '1'
    })
  );
  
  const data = await response.json();
  return data.tokens;
}

async function displayDashboard() {
  const tokens = await getTrendingTokens();
  
  tokens.forEach(token => {
    console.log(`
      ${token.name} (${token.ticker})
      Price: ${token.price_eth} ETH
      24h Volume: ${token.volume_24h} ETH
      24h Change: ${token.price_change_24h}%
    `);
  });
}

displayDashboard();

Price Tracker

Monitor token prices with automatic updates:
class PriceTracker {
  private tokenAddress: string;
  private interval: number;
  private timer?: NodeJS.Timeout;
  
  constructor(tokenAddress: string, intervalMs: number = 60000) {
    this.tokenAddress = tokenAddress;
    this.interval = intervalMs;
  }
  
  async getCurrentPrice() {
    const response = await fetch(
      `https://inkypump.com/api/token?address=${this.tokenAddress}`
    );
    const token = await response.json();
    return {
      price: token.price_eth,
      marketCap: token.market_cap,
      volume24h: token.volume_24h,
      timestamp: new Date().toISOString()
    };
  }
  
  start(callback: (price: any) => void) {
    this.timer = setInterval(async () => {
      try {
        const priceData = await this.getCurrentPrice();
        callback(priceData);
      } catch (error) {
        console.error('Failed to fetch price:', error);
      }
    }, this.interval);
    
    // Fetch immediately
    this.getCurrentPrice().then(callback);
  }
  
  stop() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
}

// Usage
const tracker = new PriceTracker('0x1234...', 30000); // Update every 30s
tracker.start((data) => {
  console.log(`Price: ${data.price} ETH at ${data.timestamp}`);
});

Emperor & King Monitor

Track the current Emperor of the INK (EOTI) and King of the INK (KOTI):
interface RoyaltyStatus {
  emperor: any;
  king: any;
  nextEmperor?: string;
  currentBid?: string;
}

async function getRoyaltyStatus(): Promise<RoyaltyStatus> {
  const [emperorResponse, kingResponse] = await Promise.all([
    fetch('https://inkypump.com/api/eoti?includeBidData=true'),
    fetch('https://inkypump.com/api/koti')
  ]);
  
  const emperor = await emperorResponse.json();
  const king = await kingResponse.json();
  
  return {
    emperor: emperor,
    king: king,
    nextEmperor: emperor.bidData?.nextBoostedToken,
    currentBid: emperor.bidData?.currentBid
  };
}

async function displayRoyalty() {
  const status = await getRoyaltyStatus();
  
  console.log('👑 Emperor of the INK:');
  console.log(`  ${status.emperor.name} (${status.emperor.ticker})`);
  console.log(`  Address: ${status.emperor.address}`);
  console.log(`  Market Cap: ${status.emperor.market_cap} ETH`);
  
  if (status.currentBid) {
    console.log(`  Current Bid for Tomorrow: ${status.currentBid} wei`);
  }
  
  console.log('\n🏆 King of the INK:');
  console.log(`  ${status.king.name} (${status.king.ticker})`);
  console.log(`  Funding Progress: ${(status.king.funding_progress * 100).toFixed(2)}%`);
}

displayRoyalty();

Swap Quote Calculator

Get swap quotes and build transactions:
import { ethers } from 'ethers';

async function getSwapQuote(
  tokenIn: string,
  tokenOut: string,
  amountIn: string,
  slippageBps: number = 100
) {
  const params = new URLSearchParams({
    tokenIn,
    tokenOut,
    amount: amountIn,
    slippage: slippageBps.toString(),
    buildTx: 'true',
    userAddress: '0xYourAddress' // Replace with actual address
  });
  
  const response = await fetch(
    `https://inkyswap.com/api/quote?${params}`
  );
  
  return response.json();
}

async function executeSwap() {
  // Get quote for swapping 1 ETH to USDC
  const quote = await getSwapQuote(
    '0x0000000000000000000000000000000000000000', // ETH
    '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
    ethers.parseEther('1').toString(),
    100 // 1% slippage
  );
  
  console.log(`Input: ${ethers.formatEther(quote.amountIn)} ETH`);
  console.log(`Output: ${quote.amountOut / 1e6} USDC`);
  console.log(`Price Impact: ${(quote.priceImpact * 100).toFixed(2)}%`);
  
  if (quote.transaction) {
    // Use with ethers.js or web3.js to send transaction
    const tx = {
      to: quote.transaction.to,
      data: quote.transaction.data,
      value: quote.transaction.value,
      gasLimit: quote.transaction.gas
    };
    
    // const signer = ... // Get signer from wallet
    // const txResponse = await signer.sendTransaction(tx);
  }
}

Leaderboard Display

Create a leaderboard widget:
interface LeaderboardEntry {
  address: string;
  points: number;
  rank?: number;
}

async function getLeaderboard(page: number = 1): Promise<{
  entries: LeaderboardEntry[];
  totalPages: number;
}> {
  const response = await fetch(
    `https://inkypump.com/api/leaderboard?page=${page}`
  );
  
  const data = await response.json();
  
  // Add ranks
  const entries = data.leaderboard.map((entry: LeaderboardEntry, index: number) => ({
    ...entry,
    rank: (page - 1) * 10 + index + 1
  }));
  
  return {
    entries,
    totalPages: data.totalPages
  };
}

async function displayLeaderboard() {
  const { entries, totalPages } = await getLeaderboard(1);
  
  console.log('🏆 LEADERBOARD');
  console.log('================');
  
  entries.forEach(entry => {
    const shortAddress = `${entry.address.slice(0, 6)}...${entry.address.slice(-4)}`;
    console.log(`#${entry.rank} ${shortAddress}: ${entry.points.toLocaleString()} points`);
  });
  
  console.log(`\nPage 1 of ${totalPages}`);
}

displayLeaderboard();

Error Handling

Implement robust error handling for API calls:
class APIClient {
  private baseUrl: string;
  private maxRetries: number = 3;
  private retryDelay: number = 1000;
  
  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }
  
  async fetchWithRetry(
    endpoint: string,
    options?: RequestInit,
    retryCount: number = 0
  ): Promise<any> {
    try {
      const response = await fetch(`${this.baseUrl}${endpoint}`, options);
      
      // Handle rate limiting
      if (response.status === 429) {
        if (retryCount < this.maxRetries) {
          const delay = Math.min(
            this.retryDelay * Math.pow(2, retryCount),
            30000
          );
          
          console.log(`Rate limited. Retrying in ${delay}ms...`);
          await new Promise(resolve => setTimeout(resolve, delay));
          
          return this.fetchWithRetry(endpoint, options, retryCount + 1);
        }
        throw new Error('Max retries exceeded for rate limit');
      }
      
      // Handle other errors
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || `HTTP ${response.status}`);
      }
      
      return response.json();
      
    } catch (error) {
      // Network errors
      if (retryCount < this.maxRetries) {
        console.log(`Network error. Retrying (${retryCount + 1}/${this.maxRetries})...`);
        await new Promise(resolve => setTimeout(resolve, this.retryDelay));
        return this.fetchWithRetry(endpoint, options, retryCount + 1);
      }
      
      throw error;
    }
  }
}

// Usage
const client = new APIClient('https://inkypump.com');
const token = await client.fetchWithRetry('/api/token?address=0x...');

Best Practices

Pro Tips for production applications:

Next Steps