Integration Guide

Comprehensive guide for integrating with MemeTrade platform. Learn how to build applications, interact with smart contracts, and leverage our APIs for creating powerful DeFi experiences.

Quick Start Integration

Choose Your Integration Method

🔗 API Integration - REST APIs and WebSocket for market data 📱 Mobile Integration - Deep linking and smart account interactions ⚙️ Smart Contract Integration - Direct blockchain interactions 🌐 Web3 Integration - Frontend dApp development

Prerequisites

Development Environment:

Node.js 18+ and npm/yarn
Git for version control
Code editor (VS Code recommended)
Base network RPC access

Required Accounts:

  • MemeTrade developer account

  • Base Sepolia testnet ETH

  • Discord for developer support

SDK Integration

JavaScript/TypeScript SDK

Installation:

npm install @memetrade/sdk
# or
yarn add @memetrade/sdk

Basic Setup:

import { MemeTrade, Chain } from "@memetrade/sdk";

const memetrade = new MemeTrade({
  chain: Chain.BASE_SEPOLIA, // or Chain.BASE_MAINNET
  apiKey: process.env.MEMETRADE_API_KEY,
  rpcUrl: process.env.BASE_RPC_URL,
});

Fetching Token Data:

// Get token information
const token = await memetrade.tokens.getToken("0x742d35Cc62D5...");

// Get token price and stats
const stats = await memetrade.tokens.getStats("0x742d35Cc62D5...");

// Get trading pairs
const pairs = await memetrade.tokens.getPairs("0x742d35Cc62D5...");

console.log({
  name: token.name,
  symbol: token.symbol,
  price: stats.price,
  volume24h: stats.volume24h,
  marketCap: stats.marketCap,
});

Creating Trading Transactions:

// Get quote for trade
const quote = await memetrade.trading.getQuote({
  tokenIn: "0x0000000000000000000000000000000000000000", // ETH
  tokenOut: "0x742d35Cc62D5...", // Target token
  amountIn: "1000000000000000000", // 1 ETH in wei
  slippage: 0.01, // 1% slippage
});

// Build transaction
const txData = await memetrade.trading.buildSwapTransaction({
  quote,
  recipient: userAddress,
  deadline: Math.floor(Date.now() / 1000) + 300, // 5 minute deadline
});

// Send with your wallet/signer
const tx = await signer.sendTransaction(txData);
await tx.wait();

Python SDK

Installation:

pip install memetrade-sdk

Basic Usage:

from memetrade import MemeTrade, Chain

# Initialize client
mt = MemeTrade(
    chain=Chain.BASE_SEPOLIA,
    api_key=os.getenv('MEMETRADE_API_KEY'),
    rpc_url=os.getenv('BASE_RPC_URL')
)

# Get token data
token = mt.tokens.get_token('0x742d35Cc62D5...')
stats = mt.tokens.get_stats('0x742d35Cc62D5...')

print(f"Token: {token['name']} ({token['symbol']})")
print(f"Price: ${stats['price']}")
print(f"24h Volume: ${stats['volume24h']}")

API Integration

REST API Integration

Base URLs:

Testnet: https://api-sepolia.memetrade.com
Mainnet: https://api.memetrade.com

Authentication:

// Get API key from developer dashboard
const headers = {
  Authorization: `Bearer ${API_KEY}`,
  "Content-Type": "application/json",
};

Market Data Examples:

// Get all tokens with pagination
async function getAllTokens(page = 1, limit = 50) {
  const response = await fetch(
    `${BASE_URL}/api/v1/tokens?page=${page}&limit=${limit}`,
    { headers }
  );
  return response.json();
}

// Get trending tokens
async function getTrendingTokens() {
  const response = await fetch(`${BASE_URL}/api/v1/tokens/trending`, {
    headers,
  });
  return response.json();
}

// Get token price history
async function getPriceHistory(tokenAddress, timeframe = "1h") {
  const response = await fetch(
    `${BASE_URL}/api/v1/tokens/${tokenAddress}/price-history?timeframe=${timeframe}`,
    { headers }
  );
  return response.json();
}

Trading API Examples:

// Get swap quote
async function getSwapQuote(tokenIn, tokenOut, amountIn) {
  const response = await fetch(`${BASE_URL}/api/v1/trading/quote`, {
    method: "POST",
    headers,
    body: JSON.stringify({
      tokenIn,
      tokenOut,
      amountIn,
      slippage: 0.01,
    }),
  });
  return response.json();
}

// Get liquidity pools
async function getLiquidityPools(tokenAddress) {
  const response = await fetch(
    `${BASE_URL}/api/v1/liquidity/pools?token=${tokenAddress}`,
    { headers }
  );
  return response.json();
}

WebSocket Integration

Real-time Price Updates:

import WebSocket from "ws";

const ws = new WebSocket("wss://api.memetrade.com/ws");

ws.on("open", () => {
  // Subscribe to token price updates
  ws.send(
    JSON.stringify({
      type: "subscribe",
      channel: "prices",
      tokens: ["0x742d35Cc62D5...", "0x8f7a3b2c1d..."],
    })
  );

  // Subscribe to new token notifications
  ws.send(
    JSON.stringify({
      type: "subscribe",
      channel: "new_tokens",
    })
  );
});

ws.on("message", (data) => {
  const message = JSON.parse(data.toString());

  switch (message.type) {
    case "price_update":
      console.log(`${message.symbol}: $${message.price}`);
      break;

    case "new_token":
      console.log(`New token: ${message.name} (${message.symbol})`);
      break;

    case "trade":
      console.log(
        `Trade: ${message.amountIn} ${message.tokenIn} → ${message.amountOut} ${message.tokenOut}`
      );
      break;
  }
});

WebSocket Channels:

// Available subscription channels
const channels = [
  "prices", // Real-time price updates
  "trades", // Live trade feed
  "new_tokens", // New token notifications
  "liquidity", // Liquidity pool updates
  "volume", // Volume statistics
  "governance", // Governance proposals and votes
];

Smart Contract Integration

Direct Contract Interaction

Contract Addresses (Base Sepolia):

const CONTRACTS = {
  FACTORY: "0x742d35Cc62D51C846fDa67F9e3c4b65e45E2F4Aa",
  TEMPLATE_MODULE: "0x8f7a3b2c1d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s",
  ECONOMIC_MODULE: "0x1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t",
  GOVERNANCE: "0x9s8r7q6p5o4n3m2l1k0j9i8h7g6f5e4d3c2b1a0z",
  MODERATION: "0xf1e2d3c4b5a6978869788796857483726150493a",
};

Using ethers.js:

import { ethers } from "ethers";

// Contract ABIs (import from @memetrade/contracts or copy from docs)
import { FactoryABI, TemplateABI } from "@memetrade/contracts";

// Initialize provider and contracts
const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
const factory = new ethers.Contract(CONTRACTS.FACTORY, FactoryABI, provider);

// Get token information
async function getTokenInfo(tokenAddress) {
  const template = new ethers.Contract(tokenAddress, TemplateABI, provider);

  const [name, symbol, totalSupply, creator] = await Promise.all([
    template.name(),
    template.symbol(),
    template.totalSupply(),
    template.creator(),
  ]);

  return { name, symbol, totalSupply: totalSupply.toString(), creator };
}

// Listen for new token creation
factory.on("TokenCreated", (tokenAddress, creator, name, symbol) => {
  console.log(
    `New token created: ${name} (${symbol}) at ${tokenAddress} by ${creator}`
  );
});

Creating Tokens Programmatically:

// Connect with signer for write operations
const signer = new ethers.Wallet(PRIVATE_KEY, provider);
const factoryWithSigner = factory.connect(signer);

async function createToken(params) {
  const tx = await factoryWithSigner.createToken(
    params.name, // Token name
    params.symbol, // Token symbol
    params.description, // Token description
    params.imageUrl, // Token image URL
    params.creatorFee, // Creator fee (0-500 = 0-5%)
    params.templateType, // Template type (0 = basic, 1 = viral)
    {
      value: ethers.utils.parseEther("0.001"), // Creation fee
      gasLimit: 500000,
    }
  );

  const receipt = await tx.wait();

  // Extract token address from events
  const event = receipt.events?.find((e) => e.event === "TokenCreated");
  const tokenAddress = event?.args?.token;

  return { tokenAddress, txHash: receipt.transactionHash };
}

Uniswap V4 Integration

Pool Manager Integration:

import { PoolManagerABI } from "@memetrade/contracts";

const poolManager = new ethers.Contract(
  CONTRACTS.POOL_MANAGER,
  PoolManagerABI,
  provider
);

// Get pool information
async function getPoolInfo(tokenA, tokenB, fee) {
  const poolKey = {
    currency0: tokenA < tokenB ? tokenA : tokenB,
    currency1: tokenA < tokenB ? tokenB : tokenA,
    fee: fee,
    tickSpacing: 60,
    hooks: CONTRACTS.HOOK_ADDRESS,
  };

  const poolId = await poolManager.getPoolId(poolKey);
  const slot0 = await poolManager.getSlot0(poolId);

  return {
    poolId,
    sqrtPriceX96: slot0.sqrtPriceX96,
    tick: slot0.tick,
    liquidity: await poolManager.getLiquidity(poolId),
  };
}

Mobile App Integration

Deep Linking

URL Scheme:

memetrade://action?params

Supported Actions:

// Open specific token
memetrade://token?address=0x742d35Cc62D5...

// Pre-fill token creation
memetrade://create?name=MyToken&symbol=MTK&description=My%20Token

// Pre-fill trade
memetrade://trade?token=0x742d35Cc62D5...&amount=1.0

// Open liquidity pool
memetrade://liquidity?token0=ETH&token1=0x742d35Cc62D5...

Web Integration:

<!-- Fallback to app store if app not installed -->
<a
  href="memetrade://token?address=0x742d35Cc62D5..."
  onclick="setTimeout(() => window.location = 'https://testflight.apple.com/join/wknfh88W', 500)"
>
  Open in MemeTrade App
</a>

Smart Account Integration

Detecting Smart Account Support:

// Check if user is on MemeTrade mobile app
function isMemeTradeMobile() {
  return navigator.userAgent.includes("MemeTrade");
}

// Request smart account address
async function getSmartAccountAddress() {
  if (isMemeTradeMobile() && window.memetrade) {
    return await window.memetrade.getAddress();
  }
  return null;
}

// Request transaction signing
async function signTransaction(txData) {
  if (isMemeTradeMobile() && window.memetrade) {
    return await window.memetrade.signTransaction(txData);
  }
  throw new Error("MemeTrade mobile app required");
}

Frontend Integration

React Integration

Token Price Component:

import React, { useState, useEffect } from "react";
import { MemeTrade } from "@memetrade/sdk";

interface TokenPriceProps {
  tokenAddress: string;
}

export const TokenPrice: React.FC<TokenPriceProps> = ({ tokenAddress }) => {
  const [price, setPrice] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const memetrade = new MemeTrade({
      chain: Chain.BASE_SEPOLIA,
      apiKey: process.env.REACT_APP_MEMETRADE_API_KEY!,
    });

    async function fetchPrice() {
      try {
        const stats = await memetrade.tokens.getStats(tokenAddress);
        setPrice(stats.price);
      } catch (error) {
        console.error("Failed to fetch price:", error);
      } finally {
        setLoading(false);
      }
    }

    fetchPrice();

    // Set up real-time updates
    const ws = new WebSocket("wss://api.memetrade.com/ws");
    ws.onopen = () => {
      ws.send(
        JSON.stringify({
          type: "subscribe",
          channel: "prices",
          tokens: [tokenAddress],
        })
      );
    };

    ws.onmessage = (event) => {
      const message = JSON.parse(event.data);
      if (message.type === "price_update" && message.token === tokenAddress) {
        setPrice(message.price);
      }
    };

    return () => ws.close();
  }, [tokenAddress]);

  if (loading) return <div>Loading price...</div>;
  if (!price) return <div>Price unavailable</div>;

  return <div className="token-price">${price.toFixed(6)}</div>;
};

Trading Component:

import React, { useState } from "react";
import { useWeb3React } from "@web3-react/core";
import { MemeTrade } from "@memetrade/sdk";

export const TradeWidget: React.FC = () => {
  const { account, library } = useWeb3React();
  const [tokenAddress, setTokenAddress] = useState("");
  const [amount, setAmount] = useState("");
  const [loading, setLoading] = useState(false);

  const handleTrade = async () => {
    if (!account || !library) return;

    setLoading(true);
    try {
      const memetrade = new MemeTrade({
        chain: Chain.BASE_SEPOLIA,
        signer: library.getSigner(),
      });

      const quote = await memetrade.trading.getQuote({
        tokenIn: "0x0000000000000000000000000000000000000000", // ETH
        tokenOut: tokenAddress,
        amountIn: ethers.utils.parseEther(amount).toString(),
        slippage: 0.01,
      });

      const txData = await memetrade.trading.buildSwapTransaction({
        quote,
        recipient: account,
        deadline: Math.floor(Date.now() / 1000) + 300,
      });

      const tx = await library.getSigner().sendTransaction(txData);
      await tx.wait();

      alert("Trade successful!");
    } catch (error) {
      console.error("Trade failed:", error);
      alert("Trade failed: " + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="trade-widget">
      <input
        type="text"
        placeholder="Token address"
        value={tokenAddress}
        onChange={(e) => setTokenAddress(e.target.value)}
      />
      <input
        type="number"
        placeholder="Amount (ETH)"
        value={amount}
        onChange={(e) => setAmount(e.target.value)}
      />
      <button onClick={handleTrade} disabled={loading}>
        {loading ? "Trading..." : "Trade"}
      </button>
    </div>
  );
};

Vue.js Integration

Token List Component:

<template>
  <div class="token-list">
    <div v-for="token in tokens" :key="token.address" class="token-item">
      <img :src="token.imageUrl" :alt="token.name" />
      <div>
        <h3>{{ token.name }} ({{ token.symbol }})</h3>
        <p>${{ token.price.toFixed(6) }}</p>
        <span :class="priceChangeClass(token.change24h)">
          {{ token.change24h > 0 ? "+" : "" }}{{ token.change24h.toFixed(2) }}%
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { MemeTrade, Chain } from "@memetrade/sdk";

export default {
  name: "TokenList",
  data() {
    return {
      tokens: [],
      loading: true,
    };
  },
  async mounted() {
    const memetrade = new MemeTrade({
      chain: Chain.BASE_SEPOLIA,
      apiKey: process.env.VUE_APP_MEMETRADE_API_KEY,
    });

    try {
      const response = await memetrade.tokens.getTrending();
      this.tokens = response.tokens;
    } catch (error) {
      console.error("Failed to fetch tokens:", error);
    } finally {
      this.loading = false;
    }
  },
  methods: {
    priceChangeClass(change) {
      return {
        "price-up": change > 0,
        "price-down": change < 0,
        "price-neutral": change === 0,
      };
    },
  },
};
</script>

Backend Integration

Node.js Express API

Token Proxy Service:

import express from "express";
import { MemeTrade, Chain } from "@memetrade/sdk";

const app = express();
const memetrade = new MemeTrade({
  chain: Chain.BASE_SEPOLIA,
  apiKey: process.env.MEMETRADE_API_KEY!,
});

// Get token information
app.get("/api/tokens/:address", async (req, res) => {
  try {
    const { address } = req.params;
    const [token, stats] = await Promise.all([
      memetrade.tokens.getToken(address),
      memetrade.tokens.getStats(address),
    ]);

    res.json({
      ...token,
      ...stats,
    });
  } catch (error) {
    res.status(404).json({ error: "Token not found" });
  }
});

// Search tokens
app.get("/api/tokens/search/:query", async (req, res) => {
  try {
    const { query } = req.params;
    const results = await memetrade.tokens.search(query);
    res.json(results);
  } catch (error) {
    res.status(500).json({ error: "Search failed" });
  }
});

// Webhook for new tokens
app.post("/api/webhooks/new-token", (req, res) => {
  const { token, creator, txHash } = req.body;

  // Process new token notification
  console.log(`New token: ${token.name} created by ${creator}`);

  // Add to database, send notifications, etc.

  res.json({ success: true });
});

app.listen(3000);

Python Flask Integration

Price Alert Service:

from flask import Flask, jsonify, request
from memetrade import MemeTrade, Chain
import asyncio

app = Flask(__name__)
mt = MemeTrade(
    chain=Chain.BASE_SEPOLIA,
    api_key=os.getenv('MEMETRADE_API_KEY')
)

# Price alert storage (use Redis/database in production)
price_alerts = {}

@app.route('/api/alerts', methods=['POST'])
def create_alert():
    data = request.json
    alert_id = len(price_alerts) + 1

    price_alerts[alert_id] = {
        'token': data['token'],
        'target_price': float(data['target_price']),
        'condition': data['condition'],  # 'above' or 'below'
        'webhook_url': data.get('webhook_url'),
        'active': True
    }

    return jsonify({'alert_id': alert_id})

@app.route('/api/alerts/<int:alert_id>', methods=['DELETE'])
def delete_alert(alert_id):
    if alert_id in price_alerts:
        del price_alerts[alert_id]
        return jsonify({'success': True})
    return jsonify({'error': 'Alert not found'}), 404

async def check_price_alerts():
    for alert_id, alert in price_alerts.items():
        if not alert['active']:
            continue

        try:
            stats = mt.tokens.get_stats(alert['token'])
            current_price = stats['price']

            should_trigger = (
                (alert['condition'] == 'above' and current_price >= alert['target_price']) or
                (alert['condition'] == 'below' and current_price <= alert['target_price'])
            )

            if should_trigger:
                # Send notification
                print(f"Alert triggered: {alert['token']} is {alert['condition']} ${alert['target_price']}")
                alert['active'] = False  # Trigger once

        except Exception as e:
            print(f"Error checking alert {alert_id}: {e}")

if __name__ == '__main__':
    app.run(debug=True)

Advanced Integration Patterns

Batch Operations

Smart Account Batch Transactions:

// Build complex batch operation
async function buildPortfolioRebalance(
  userAddress: string,
  targetAllocations: Record<string, number>
) {
  const memetrade = new MemeTrade({
    chain: Chain.BASE_SEPOLIA,
    apiKey: process.env.MEMETRADE_API_KEY!,
  });

  // Get current portfolio
  const portfolio = await memetrade.portfolio.getPortfolio(userAddress);

  // Calculate required trades
  const trades = calculateRebalanceTrades(portfolio, targetAllocations);

  // Build batch transaction
  const batchOps = [];

  for (const trade of trades) {
    if (trade.type === "sell") {
      batchOps.push(
        await memetrade.trading.buildSellTransaction({
          token: trade.token,
          amount: trade.amount,
          recipient: userAddress,
        })
      );
    } else if (trade.type === "buy") {
      batchOps.push(
        await memetrade.trading.buildBuyTransaction({
          token: trade.token,
          amountIn: trade.amountIn,
          recipient: userAddress,
        })
      );
    }
  }

  return memetrade.batch.buildBatchTransaction(batchOps);
}

Event Monitoring

Real-time Event Processing:

import { ethers } from "ethers";

class MemeTradEventMonitor {
  private provider: ethers.providers.Provider;
  private factory: ethers.Contract;

  constructor(rpcUrl: string) {
    this.provider = new ethers.providers.JsonRpcProvider(rpcUrl);
    this.factory = new ethers.Contract(
      CONTRACTS.FACTORY,
      FactoryABI,
      this.provider
    );
  }

  async startMonitoring() {
    // Listen for new token creation
    this.factory.on(
      "TokenCreated",
      async (tokenAddress, creator, name, symbol, event) => {
        await this.handleNewToken({
          address: tokenAddress,
          creator,
          name,
          symbol,
          blockNumber: event.blockNumber,
          txHash: event.transactionHash,
        });
      }
    );

    // Listen for trades (on pool manager)
    const poolManager = new ethers.Contract(
      CONTRACTS.POOL_MANAGER,
      PoolManagerABI,
      this.provider
    );

    poolManager.on(
      "Swap",
      async (
        id,
        sender,
        amount0,
        amount1,
        sqrtPriceX96,
        liquidity,
        tick,
        event
      ) => {
        await this.handleTrade({
          poolId: id,
          trader: sender,
          amount0,
          amount1,
          newPrice: sqrtPriceX96,
          blockNumber: event.blockNumber,
          txHash: event.transactionHash,
        });
      }
    );
  }

  private async handleNewToken(tokenData: any) {
    console.log(`New token created: ${tokenData.name} (${tokenData.symbol})`);

    // Send webhook notification
    await fetch("https://your-webhook-url.com/new-token", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(tokenData),
    });
  }

  private async handleTrade(tradeData: any) {
    console.log(`Trade executed on pool ${tradeData.poolId}`);

    // Update local cache, send notifications, etc.
  }
}

// Start monitoring
const monitor = new MemeTradEventMonitor(process.env.BASE_RPC_URL!);
monitor.startMonitoring();

Performance Optimization

Caching Strategy:

import Redis from "ioredis";

class MemeTradCache {
  private redis: Redis;
  private memetrade: MemeTrade;

  constructor() {
    this.redis = new Redis(process.env.REDIS_URL!);
    this.memetrade = new MemeTrade({
      chain: Chain.BASE_SEPOLIA,
      apiKey: process.env.MEMETRADE_API_KEY!,
    });
  }

  async getTokenStats(tokenAddress: string, maxAge = 60) {
    const cacheKey = `token:stats:${tokenAddress}`;

    // Try cache first
    const cached = await this.redis.get(cacheKey);
    if (cached) {
      return JSON.parse(cached);
    }

    // Fetch from API
    const stats = await this.memetrade.tokens.getStats(tokenAddress);

    // Cache with expiration
    await this.redis.setex(cacheKey, maxAge, JSON.stringify(stats));

    return stats;
  }

  async invalidateToken(tokenAddress: string) {
    const keys = await this.redis.keys(`token:*:${tokenAddress}`);
    if (keys.length > 0) {
      await this.redis.del(...keys);
    }
  }
}

Error Handling and Retries

Robust Error Handling

class MemeTradClient {
  private retryDelays = [1000, 2000, 4000, 8000]; // Exponential backoff

  async withRetry<T>(operation: () => Promise<T>, maxRetries = 3): Promise<T> {
    let lastError: Error;

    for (let attempt = 0; attempt <= maxRetries; attempt++) {
      try {
        return await operation();
      } catch (error: any) {
        lastError = error;

        // Don't retry on client errors
        if (error.status >= 400 && error.status < 500) {
          throw error;
        }

        // Don't retry on last attempt
        if (attempt === maxRetries) {
          break;
        }

        // Wait before retry
        await new Promise((resolve) =>
          setTimeout(resolve, this.retryDelays[attempt] || 8000)
        );
      }
    }

    throw lastError!;
  }

  async getTokenSafely(tokenAddress: string) {
    return this.withRetry(async () => {
      const response = await fetch(
        `${BASE_URL}/api/v1/tokens/${tokenAddress}`,
        { headers: this.getHeaders() }
      );

      if (!response.ok) {
        const error = new Error(
          `HTTP ${response.status}: ${response.statusText}`
        );
        (error as any).status = response.status;
        throw error;
      }

      return response.json();
    });
  }
}

Security Best Practices

API Key Management

// Environment-based configuration
const config = {
  apiKey: process.env.MEMETRADE_API_KEY!,
  rpcUrl: process.env.BASE_RPC_URL!,
  privateKey: process.env.PRIVATE_KEY!, // Only for backend services
};

// Validate required environment variables
function validateConfig() {
  const required = ["MEMETRADE_API_KEY", "BASE_RPC_URL"];
  const missing = required.filter((key) => !process.env[key]);

  if (missing.length > 0) {
    throw new Error(
      `Missing required environment variables: ${missing.join(", ")}`
    );
  }
}

// Rate limiting
class RateLimiter {
  private requests: number[] = [];
  private maxRequests: number;
  private windowMs: number;

  constructor(maxRequests = 100, windowMs = 60000) {
    this.maxRequests = maxRequests;
    this.windowMs = windowMs;
  }

  async checkLimit(): Promise<boolean> {
    const now = Date.now();
    this.requests = this.requests.filter((time) => now - time < this.windowMs);

    if (this.requests.length >= this.maxRequests) {
      return false;
    }

    this.requests.push(now);
    return true;
  }
}

Input Validation

import { isAddress } from "ethers/lib/utils";

function validateTokenAddress(address: string): string {
  if (!address || typeof address !== "string") {
    throw new Error("Token address is required");
  }

  if (!isAddress(address)) {
    throw new Error("Invalid token address format");
  }

  return address.toLowerCase();
}

function validateAmount(amount: string | number): string {
  const amountStr = amount.toString();
  const amountNum = parseFloat(amountStr);

  if (isNaN(amountNum) || amountNum <= 0) {
    throw new Error("Amount must be a positive number");
  }

  if (amountNum > 1000000) {
    throw new Error("Amount too large");
  }

  return amountStr;
}

Testing Integration

See the Testing Guide for comprehensive testing strategies and examples.

Support and Resources

Developer Support

Documentation:

Community:

  • Discord: #developer-support channel

  • GitHub: Issues and feature requests

Rate Limits:

  • REST API: 1000 requests/minute per API key

  • WebSocket: 10 subscriptions per connection

  • Testnet: Unlimited (fair use)

Example Projects

GitHub Repositories:

https://github.com/memetrade/sdk-examples
├── trading-bot/          # Automated trading example
├── portfolio-tracker/    # Portfolio monitoring dashboard
├── price-alerts/         # Real-time price notification service
├── liquidity-optimizer/  # LP position management
└── mobile-dapp/         # Mobile web3 integration

Changelog and Updates

API Versioning:

  • Current version: v1

  • Breaking changes will introduce new versions

  • Deprecated versions supported for 6 months

SDK Updates:

# Stay updated with latest SDK
npm update @memetrade/sdk

# Check for breaking changes
npx @memetrade/sdk@latest migrate

Ready to start building? Choose your integration method and dive into the code examples above. Join our Discord for developer support and community collaboration.

Next Steps:

Last updated