--- name: lifi-dev description: > Comprehensive development support for LI.FI DEX aggregator including SDK, Widget, and API integration for cross-chain swaps and bridging. Use when building applications with LI.FI for - (1) Cross-chain token swaps and bridges, (2) Multi-chain liquidity aggregation, (3) Trading widget integration, (4) Custom DEX aggregation UI, (5) Gas subsidy implementation, (6) Revenue monetization with integrator fees, (7) Route optimization across 60+ chains, (8) Intent-based trading systems. Covers SDK usage (TypeScript/JavaScript), Widget customization (React/Vue/Svelte), API integration (REST), and LI.FI-specific features like cross-chain routing, gas subsidies (LI.Fuel), and multi-protocol aggregation across Uniswap, 1inch, Stargate, Across, and 800+ protocols. --- # LI.FI Development Support Comprehensive toolkit for building cross-chain swap and bridge applications with LI.FI - the leading DEX and bridge aggregation protocol supporting 60+ chains and 800+ protocols. ## Quick Start ### Product Selection LI.FI offers three integration methods. Choose based on your use case: **Quick Decision**: - Ready-made UI component → **Widget** (5 min integration, highly customizable) - Full control over UX → **SDK** (TypeScript/JavaScript, frontend & backend) - Direct API access → **REST API** (language-agnostic, maximum flexibility) - Existing widget + custom logic → **Widget + SDK combo** (best of both worlds) **Integration Complexity**: - Widget: ⭐ (Easiest - drop-in component) - SDK: ⭐⭐ (Moderate - programmatic control) - API: ⭐⭐⭐ (Advanced - full customization) ### Common Tasks **1. Add swap widget to your app**: - Review [widget_integration.tsx](scripts/widget_integration.tsx) for React integration - Key points: theme customization, chain filtering, event handling - Production-ready in under 5 minutes - See [widget-guide.md](references/widget-guide.md) for advanced customization **2. Execute cross-chain swap programmatically**: - Use [sdk_swap_example.ts](scripts/sdk_swap_example.ts) for SDK implementation - Key points: route optimization, gas estimation, slippage protection - See [sdk-guide.md](references/sdk-guide.md) for comprehensive SDK patterns **3. Get best swap route via API**: - Use [api_routes_example.ts](scripts/api_routes_example.ts) for direct API calls - Key points: rate limiting, error handling, route comparison - See [api-reference.md](references/api-reference.md) for complete endpoint documentation **4. Implement gas subsidy (LI.Fuel)**: - Use [gas_subsidy_example.ts](scripts/gas_subsidy_example.ts) for LI.Fuel integration - Solve cold-start problem on new chains - See [gas-subsidy-guide.md](references/gas-subsidy-guide.md) for implementation details **5. Monetize with integrator fees**: - Configure fees in [LI.FI Portal](https://portal.li.fi) - See [monetization-guide.md](references/monetization-guide.md) for fee structure and withdrawal ## Core Workflows ### Widget Integration **React/Next.js Integration**: ```typescript import { LiFiWidget, WidgetConfig } from '@lifi/widget'; // 1. Configure widget const widgetConfig: WidgetConfig = { integrator: 'your-app-name', // Required for analytics and fees // Appearance variant: 'expandable', // 'default' | 'wide' | 'drawer' | 'expandable' theme: { palette: { primary: { main: '#3f51b5' }, secondary: { main: '#f50057' } }, shape: { borderRadius: 12 } }, // Chain & token filtering fromChain: 1, // Ethereum toChain: 137, // Polygon fromToken: '0x...', // Specific token address (optional) // Advanced configuration fee: 0.03, // 0.03% integrator fee slippage: 0.005, // 0.5% max slippage // Event handlers onRouteExecutionStarted: (route) => { console.log('Swap started:', route); }, onRouteExecutionCompleted: (route) => { console.log('Swap completed:', route); } }; // 2. Render widget function App() { return (
); } ``` **Vue.js Integration**: ```vue ``` **Vanilla JavaScript**: ```html
``` See [widget_integration.tsx](scripts/widget_integration.tsx) for complete examples. ### SDK Integration **Installation**: ```bash npm install @lifi/sdk # or yarn add @lifi/sdk # or pnpm add @lifi/sdk ``` **Basic Swap Flow**: ```typescript import { LIFI } from '@lifi/sdk'; import { createWalletClient, http } from 'viem'; import { mainnet } from 'viem/chains'; // 1. Initialize SDK const lifi = new LIFI({ integrator: 'your-app-name', // Required apiKey: process.env.LIFI_API_KEY // Optional - higher rate limits }); // 2. Get available chains and tokens const chains = await lifi.getChains(); const tokens = await lifi.getTokens({ chains: [1, 137] }); // Ethereum & Polygon // 3. Get best route for swap const routeRequest = { fromChainId: 1, // Ethereum fromTokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC fromAmount: '1000000000', // 1000 USDC (6 decimals) toChainId: 137, // Polygon toTokenAddress: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', // USDC on Polygon fromAddress: '0x...', // User wallet address // Optional optimizations options: { slippage: 0.005, // 0.5% order: 'RECOMMENDED', // or 'FASTEST', 'CHEAPEST', 'SAFEST' allowSwitchChain: true } }; const routes = await lifi.getRoutes(routeRequest); const bestRoute = routes.routes[0]; // Pre-sorted by 'order' parameter // 4. Check route details console.log('Estimated time:', bestRoute.steps.reduce((t, s) => t + s.estimate.executionDuration, 0), 'seconds'); console.log('Gas cost:', bestRoute.gasCostUSD); console.log('Output amount:', bestRoute.toAmountMin); // Minimum guaranteed // 5. Execute route const wallet = createWalletClient({ chain: mainnet, transport: http() }); // Approve token spending if needed if (bestRoute.steps[0].action.fromToken.address !== '0x0000000000000000000000000000000000000000') { const approvalTx = await lifi.approveToken({ walletClient: wallet, token: bestRoute.steps[0].action.fromToken, amount: bestRoute.steps[0].action.fromAmount, spender: bestRoute.steps[0].estimate.approvalAddress }); await approvalTx.wait(); } // Execute swap const execution = await lifi.executeRoute({ route: bestRoute, walletClient: wallet, // Event callbacks updateRouteHook: (updatedRoute) => { console.log('Route updated:', updatedRoute.status); }, switchChainHook: async (requiredChainId) => { // Handle chain switch in your UI await wallet.switchChain({ id: requiredChainId }); }, acceptExchangeRateUpdateHook: (oldRate, newRate) => { // Return true to accept rate changes return confirm(`Rate changed from ${oldRate} to ${newRate}. Continue?`); } }); console.log('Swap completed!', execution); ``` **Advanced Route Filtering**: ```typescript // Filter by specific bridges and exchanges const routes = await lifi.getRoutes({ ...routeRequest, options: { bridges: { allow: ['stargate', 'across', 'hop'] }, exchanges: { allow: ['uniswap', '1inch'] }, // Exclude specific protocols // bridges: { deny: ['multichain'] }, // Fee configuration integrator: 'your-app', fee: 0.03 // 0.03% fee on fromAmount } }); ``` See [sdk_swap_example.ts](scripts/sdk_swap_example.ts) for production-ready implementation. ### API Integration **Base URL**: `https://li.quest/v1` **Authentication** (Optional): ```bash # Higher rate limits with API key curl -H "x-lifi-api-key: YOUR_API_KEY" https://li.quest/v1/... ``` **Get Route Quote**: ```typescript // GET /quote const response = await fetch( 'https://li.quest/v1/quote?' + new URLSearchParams({ fromChain: '1', toChain: '137', fromToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC toToken: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', // USDC on Polygon fromAmount: '1000000000', // 1000 USDC fromAddress: '0x...', // Optional integrator: 'your-app-name', fee: '0.03', // 3% integrator fee (decimal format: 0.03 = 3%) slippage: '0.005', // 0.5% order: 'RECOMMENDED' }), { headers: { 'x-lifi-api-key': process.env.LIFI_API_KEY // Optional } } ); const quote = await response.json(); // Quote contains single optimized route console.log('Estimated output:', quote.estimate.toAmount); console.log('Execution time:', quote.estimate.executionDuration, 'seconds'); console.log('Gas cost:', quote.estimate.gasCosts); ``` **Get Multiple Routes**: ```typescript // GET /advanced/routes - Returns multiple route options const response = await fetch( 'https://li.quest/v1/advanced/routes?' + new URLSearchParams({ fromChainId: '1', toChainId: '137', fromTokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', toTokenAddress: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', fromAmount: '1000000000', fromAddress: '0x...' }) ); const { routes } = await response.json(); // Compare multiple routes routes.forEach((route, i) => { console.log(`Route ${i + 1}:`); console.log(' Steps:', route.steps.length); console.log(' Time:', route.steps.reduce((t, s) => t + s.estimate.executionDuration, 0)); console.log(' Output:', route.toAmount); }); ``` **Get Supported Chains**: ```typescript // GET /chains const response = await fetch('https://li.quest/v1/chains'); const chains = await response.json(); chains.forEach(chain => { console.log(`${chain.name} (${chain.id}): ${chain.nativeToken.symbol}`); }); ``` **Get Supported Tokens**: ```typescript // GET /tokens const response = await fetch( 'https://li.quest/v1/tokens?' + new URLSearchParams({ chains: '1,137,42161' // Ethereum, Polygon, Arbitrum }) ); const { tokens } = await response.json(); // Returns: { [chainId]: Token[] } ``` **Check Route Status**: ```typescript // GET /status const response = await fetch( 'https://li.quest/v1/status?' + new URLSearchParams({ txHash: '0x...', bridge: 'stargate', // Optional - speeds up lookup fromChain: '1', toChain: '137' }) ); const status = await response.json(); console.log('Status:', status.status); // 'DONE' | 'PENDING' | 'FAILED' console.log('Destination tx:', status.receiving?.txHash); ``` See [api_routes_example.ts](scripts/api_routes_example.ts) and [api-reference.md](references/api-reference.md). ### Gas Subsidy Implementation (LI.Fuel) **Problem**: Users bridging to a new chain lack native gas tokens. **Solution**: LI.Fuel converts a portion of bridged assets to destination chain's native token. ```typescript import { LIFI } from '@lifi/sdk'; const lifi = new LIFI({ integrator: 'your-app' }); // Request route with gas subsidy const routes = await lifi.getRoutes({ fromChainId: 1, // Ethereum fromTokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC fromAmount: '1000000000', // 1000 USDC toChainId: 137, // Polygon toTokenAddress: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', // USDC on Polygon fromAddress: userAddress, // Enable gas subsidy fromAmountForGas: '50000000' // Convert 50 USDC to MATIC on Polygon }); // Route automatically includes gas conversion step const route = routes.routes[0]; // Verify gas subsidy is included const gasStep = route.steps.find(step => step.type === 'lifi'); if (gasStep?.includedSteps?.some(s => s.type === 'swap' && s.action.toToken.address === '0x0000000000000000000000000000000000000000')) { console.log('Gas subsidy enabled: User will receive native tokens'); } ``` **API Version**: ```typescript const response = await fetch( 'https://li.quest/v1/quote?' + new URLSearchParams({ fromChain: '1', toChain: '137', fromToken: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', toToken: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', fromAmount: '1000000000', fromAddress: userAddress, // Add gas subsidy parameter fromAmountForGas: '50000000' // 50 USDC → MATIC }) ); ``` **Limitations**: - ❌ Not supported with `/contractCalls` endpoint - ❌ Not supported via Composer (multi-action transactions) - ✅ Supported via `/quote` and `/routes` endpoints - ✅ Works with SDK's `getRoutes()` method See [gas_subsidy_example.ts](scripts/gas_subsidy_example.ts) and [gas-subsidy-guide.md](references/gas-subsidy-guide.md). ### Fee Monetization **Earn revenue by adding integrator fees to swaps**: ```typescript // 1. Register at https://portal.li.fi to get your integrator account // 2. Add fee parameter to SDK/API calls const routes = await lifi.getRoutes({ ...routeRequest, integrator: 'your-app-name', // Required fee: 0.03 // 3% fee (decimal: 0.03 = 3%, 0.001 = 0.1%) }); // Fee is deducted from fromAmount automatically // Example: User sends 1000 USDC // → 30 USDC goes to you (3%) // → 970 USDC is swapped/bridged ``` **Fee Collection**: ```typescript // Via API const response = await fetch('https://li.quest/v1/integrators/fees', { headers: { 'Authorization': 'Bearer YOUR_API_TOKEN', 'x-lifi-api-key': 'YOUR_API_KEY' } }); const { fees } = await response.json(); console.log('Collected fees:', fees); // Withdraw via Portal or API await fetch('https://li.quest/v1/integrators/fees/withdraw', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_TOKEN', 'x-lifi-api-key': 'YOUR_API_KEY' }, body: JSON.stringify({ token: '0x...', // Token to withdraw amount: '1000000000' // Amount }) }); ``` **Base Fee Structure**: - LI.FI base fee: 0.25% on all transactions - Your integrator fee: Configurable (typically 0.1% - 1%) - User pays: LI.FI fee + your fee + protocol fees (DEX/bridge) **Volume Discounts**: - High-volume integrators can negotiate reduced LI.FI base fees - Contact LI.FI team for enterprise pricing **Important**: - ⚠️ Must withdraw fees from the same wallet used during integration - ⚠️ Switching wallets will lock previous fee claims - ✅ Can set up automatic consolidation and conversion to stablecoins See [monetization-guide.md](references/monetization-guide.md) for complete setup guide. ## Critical Security Requirements **Never deploy without**: 1. **Slippage Protection**: Always set `slippage` parameter (default 0.5% = 0.005) 2. **Amount Validation**: Verify `toAmountMin` in routes before execution 3. **Token Approval Limits**: Approve exact amounts, not unlimited allowances 4. **Rate Limiting**: Implement client-side rate limiting for API calls 5. **Error Handling**: Handle network errors, route failures, and bridge delays 6. **Chain Verification**: Verify user is on correct chain before execution 7. **Transaction Monitoring**: Track transaction status across chains 8. **API Key Protection**: Never expose API keys in frontend code (use backend proxy) 9. **User Confirmation**: Show final amounts, fees, and execution time before swap 10. **Bridge Risk Disclosure**: Inform users about bridge security and delays **Widget Security**: ```typescript const widgetConfig = { integrator: 'your-app', // Prevent unlimited approvals (recommended) infiniteApproval: false, // Set maximum slippage slippage: 0.005, // 0.5% // Disable risky bridges (optional) bridges: { deny: ['bridge-with-issues'] }, // Add transaction confirmation onRouteExecutionStarted: (route) => { // Log for monitoring analytics.track('swap_started', { fromChain: route.fromChainId, toChain: route.toChainId, amount: route.fromAmount }); } }; ``` **SDK Security**: ```typescript // ✅ GOOD: Exact approval await lifi.approveToken({ token: route.steps[0].action.fromToken, amount: route.steps[0].action.fromAmount, // Exact amount spender: route.steps[0].estimate.approvalAddress }); // ❌ BAD: Unlimited approval await lifi.approveToken({ token: route.steps[0].action.fromToken, amount: ethers.MaxUint256, // Dangerous! spender: route.steps[0].estimate.approvalAddress }); // ✅ GOOD: Rate limiting const rateLimit = { maxRequests: 10, perSeconds: 60 }; // ✅ GOOD: Timeout handling const routePromise = lifi.getRoutes(request); const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Route timeout')), 30000) ); try { const routes = await Promise.race([routePromise, timeoutPromise]); } catch (error) { // Handle timeout or error } ``` See [security.md](references/security.md) for complete security checklist. ## Architecture Patterns ### LI.FI Aggregation Architecture ``` ┌─────────────────────────────────────────────┐ │ Your Application (dApp) │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ Widget │ │ SDK │ │ API │ │ │ └────┬────┘ └────┬────┘ └────┬────┘ │ └───────┼───────────┼────────────┼───────────┘ │ │ │ └───────────┴────────────┘ │ ┌───────────▼────────────┐ │ LI.FI Smart Router │ │ (Route Optimization) │ └───────────┬────────────┘ │ ┌───────────────┼───────────────┐ │ │ │ ┌───▼────┐ ┌────▼─────┐ ┌────▼────┐ │ Bridges│ │ DEX Agg │ │ Solvers │ │ │ │ │ │ │ │Stargate│ │ Uniswap │ │ 1inch │ │ Across │ │ Sushiswap│ │ 0x │ │ Hop │ │ Curve │ │ Kyber │ │Connext │ │ Balancer │ │ ParaSwap│ └────────┘ └──────────┘ └─────────┘ │ │ │ └──────────────┴──────────────┘ │ ┌────────▼─────────┐ │ 60+ Blockchains │ │ 800+ Protocols │ └──────────────────┘ ``` ### Integration Decision Tree ``` Start: Need cross-chain swap/bridge functionality │ ├─ Need UI component? │ │ │ ├─ Yes → Use Widget │ │ │ │ │ ├─ Basic theme customization → Widget default config │ │ ├─ Advanced customization → Widget + custom theme │ │ └─ Need custom logic → Widget + SDK hooks │ │ │ └─ No → Need programmatic control? │ │ │ ├─ TypeScript/JavaScript → Use SDK │ │ │ │ │ ├─ Frontend → SDK + wallet provider │ │ └─ Backend → SDK + private key signer │ │ │ └─ Other language/platform → Use REST API │ │ │ ├─ Python/Go/Ruby → Direct HTTP │ └─ Mobile native → HTTP client ``` ### Multi-Step Route Flow ``` User Swap: 1000 USDC (Ethereum) → USDT (Arbitrum) │ ├─ Step 1 (SWAP on Ethereum): │ └─ 1000 USDC → 1000 USDT via Uniswap V3 │ ├─ Step 2 (BRIDGE): │ └─ 1000 USDT (Ethereum) → 998 USDT (Arbitrum) via Stargate │ (2 USDT bridge fee) │ └─ Result: 998 USDT on Arbitrum Optional: Gas Subsidy (LI.Fuel) │ ├─ Step 2a (before bridge): │ └─ 50 USDT → 0.05 ETH (for gas on Ethereum) │ └─ Step 2b (on destination): └─ Bridge converts 50 USDT → ~40 ARB native tokens └─ User receives: 948 USDT + 40 ARB (for gas) ``` ### Rate Limiting Architecture ``` Without API Key (per IP): ├─ /quote, /routes: 10 requests/minute ├─ /chains, /tokens: 20 requests/minute └─ /status: 30 requests/minute With API Key (per key): ├─ /quote, /routes: 100 requests/minute ├─ /chains, /tokens: 200 requests/minute └─ /status: 300 requests/minute Enterprise (contact LI.FI): └─ Custom limits + dedicated infrastructure ``` ## Development Setup ### Dependencies **Widget Installation**: ```bash # React npm install @lifi/widget # Includes all peer dependencies # Vue npm install @lifi/widget vue # Svelte npm install @lifi/widget svelte # Vanilla JS (via CDN) # No installation needed - use