# Slippage & Fees Understand how slippage protection and fee deduction work in Vybe swaps. Proper slippage settings prevent failed transactions when prices move, while intelligent fee deduction ensures fees are always taken from liquid tokens—never from illiquid memecoins. ## Understanding Slippage Slippage is the difference between the expected price (at quote time) and the actual execution price. Prices can change between when you request a quote and when the transaction confirms due to: * Other trades executing before yours * Network latency * MEV bots (sandwich attacks) * General market volatility **Slippage tolerance** is your maximum acceptable price difference. If the actual price would be worse than your tolerance, the transaction fails instead of executing at a bad rate. *** ## How Slippage Works ``` Quote: You'll receive 100 USDC for 1 SOL Slippage: 2% Minimum output: 98 USDC Scenarios: ✅ Actual output: 99.5 USDC → Transaction succeeds ✅ Actual output: 98.0 USDC → Transaction succeeds (at minimum) ❌ Actual output: 97.5 USDC → Transaction FAILS (protects you) ``` The transaction failing is actually **protecting you** from a worse-than-expected trade. *** ## Setting Slippage Pass slippage as a percentage (not decimal): ```json { "slippage": 2, // 2% slippage tolerance "..." } ``` | Value | Meaning | | ----- | -------------- | | `0.5` | 0.5% tolerance | | `1` | 1% tolerance | | `5` | 5% tolerance | | `10` | 10% tolerance | *** ## Recommended Slippage by Token Type | Token Type | Recommended | Why | | --------------------------------- | ----------- | ---------------------------------- | | **SOL, USDC, USDT** | 0.5% | Deep liquidity, stable prices | | **Major tokens** (JUP, BONK, WIF) | 1-2% | Good liquidity, some volatility | | **Mid-cap tokens** | 2-3% | Moderate liquidity | | **Small-cap tokens** | 5-10% | Lower liquidity, higher volatility | | **New launches / memecoins** | 15-30% | Extreme volatility, thin liquidity | ### Slippage Too Low? If you set slippage too low for a volatile token, transactions will fail frequently. The token price moves faster than your tolerance allows. **Symptoms:** Repeated "Slippage exceeded" errors **Solution:** Increase slippage tolerance ### Slippage Too High? High slippage leaves you vulnerable to sandwich attacks and bad execution. **Symptoms:** Getting significantly less than quoted **Solution:** Lower slippage, but accept some failed transactions *** ## Slippage Calculation (Technical) Internally, slippage is converted to basis points (BPS): ```javascript // User passes percentage (e.g., 2.5 for 2.5%) const slippagePercent = 2.5; const slippageBps = Math.floor(slippagePercent * 100); // 250 BPS // Calculate bounds const minOutput = quoteOutput * (10000 - slippageBps) / 10000; // For sells const maxInput = quoteInput * (10000 + slippageBps) / 10000; // For buys ``` *** ## Fee Deduction Logic Vybe fees are deducted intelligently from the **most liquid token** in your swap flow. Unlike aggregators that create temporary fee accounts (costing ~0.002 SOL each in unrecoverable rent), Vybe extracts fees directly from your swap tokens. ### The Key Innovation **Fee comes FROM the swap amount itself, not from a separate wallet balance.** When you swap 0.1 SOL → BONK with a 1% fee: * ❌ **Wrong:** Build swap for 0.1 SOL, then check wallet for fee → "Insufficient SOL" * ✅ **Correct:** Deduct fee first, then swap the remainder ``` Example: 0.1 SOL → BONK with 1% fee Step 1: Calculate fee = 0.1 × 1% = 0.001 SOL Step 2: Swap amount = 0.1 - 0.001 = 0.099 SOL Step 3: Build swap for 0.099 SOL Step 4: Add fee transfer (0.001 SOL) at beginning of transaction ``` ### Fee Priority Options (A/B/C/D) | Option | Condition | Fee Source | Timing | | ------ | ------------------------------------------------- | ------------------------------ | ------------ | | **A** | Input is vetted (SOL/WSOL/USDC/USDT) | From swap input | BEFORE swap | | **B** | Input & output NOT vetted, intermediate IS vetted | From intermediate token | BETWEEN hops | | **C** | Output is vetted, input is NOT | From swap output | AFTER swap | | **D** | None vetted | Fallback to wallet SOL or skip | Before swap | ### Vetted Tokens These tokens are considered "vetted" for fee deduction: * SOL / WSOL * USDC * USDT * USD1 * PYUSD * Other major stablecoins ### Why This Matters 1. **No "Insufficient SOL" errors** when swapping SOL → anything 2. **No separate balance check** for fees 3. **Fee included in transaction** atomically 4. **No rent overhead** (unlike aggregator fee accounts) *** ## Fee Examples ### Example 1: SOL → BONK (Option A - Input Vetted) ``` User wants to swap: 0.1 SOL → BONK Fee: 1% ┌─────────────────────────────────────────────────────┐ │ BEFORE (broken approach): │ │ - Build swap for 0.1 SOL │ │ - Check wallet for 0.001 SOL fee │ │ - ERROR: "Insufficient SOL (0 SOL)" ❌ │ │ │ │ AFTER (Vybe approach): │ │ - Fee = 0.1 × 1% = 0.001 SOL │ │ - Swap amount = 0.1 - 0.001 = 0.099 SOL │ │ - Build swap for 0.099 SOL ✅ │ │ - Add fee transfer (0.001 SOL) at start ✅ │ └─────────────────────────────────────────────────────┘ Result: Fee vault receives: 0.001 SOL User receives: BONK worth 0.099 SOL ``` ### Example 2: BONK → SOL (Option C - Output Vetted) ``` User wants to swap: 1,000,000 BONK → SOL Fee: 1% Quote says: 1,000,000 BONK = 0.5 SOL ┌─────────────────────────────────────────────────────┐ │ Flow: │ │ 1. Swap 1,000,000 BONK → 0.5 SOL │ │ 2. Fee = 0.5 × 1% = 0.005 SOL (from output) │ │ 3. User receives: 0.495 SOL │ │ 4. Fee vault receives: 0.005 SOL │ └─────────────────────────────────────────────────────┘ ``` ### Example 3: BONK → WIF (Option D - Neither Vetted) ``` User wants to swap: BONK → WIF Fee: 1% ┌─────────────────────────────────────────────────────┐ │ Flow: │ │ - Input (BONK): NOT vetted │ │ - Output (WIF): NOT vetted │ │ - Fallback: Check wallet for SOL │ │ - If wallet has SOL → Fee from wallet │ │ - If no SOL → Fee skipped │ └─────────────────────────────────────────────────────┘ ``` ### Example 4: Multi-hop with Intermediate (Option B) ``` User wants to swap: BONK → WIF (via SOL) Fee: 1% ┌─────────────────────────────────────────────────────┐ │ Flow: │ │ 1. BONK → SOL (hop 1) │ │ 2. Fee taken from SOL (intermediate is vetted) │ │ 3. SOL → WIF (hop 2) │ └─────────────────────────────────────────────────────┘ ``` *** ## Setting Fees The `fee` parameter is for service providers who want to charge users: ```json { "fee": 1, // 1% service fee "..." } ``` **Note:** This is your application's fee, not Vybe's fee. Set to `0` if you don't want to charge users. *** ## Dynamic Slippage For bots and applications, calculate slippage dynamically based on token characteristics: ```javascript function calculateSlippage(token, amount, liquidity) { // Base slippage by token type let baseSlippage = 1; // 1% default // Adjust for token volatility if (token.isMemecoin) baseSlippage = 10; else if (token.isNewLaunch) baseSlippage = 20; else if (token.isStablecoin) baseSlippage = 0.3; // Adjust for trade size vs liquidity const sizeImpact = (amount / liquidity) * 100; if (sizeImpact > 5) baseSlippage *= 1.5; if (sizeImpact > 10) baseSlippage *= 2; // Cap at reasonable maximum return Math.min(baseSlippage, 30); } ``` *** ## Slippage Protection Best Practices ### For Trading Bots ```javascript async function swapWithAdaptiveSlippage(params, initialSlippage = 2) { let slippage = initialSlippage; const maxSlippage = 15; const maxRetries = 3; for (let i = 0; i < maxRetries; i++) { try { const result = await executeSwap({ ...params, slippage }); return result; } catch (error) { if (error.message.includes('Slippage') && slippage < maxSlippage) { slippage = Math.min(slippage * 2, maxSlippage); console.log(`Increasing slippage to ${slippage}%`); continue; } throw error; } } } ``` ### For User-Facing Apps ```javascript function SlippageSelector({ value, onChange }) { const presets = [ { label: 'Low (0.5%)', value: 0.5, desc: 'May fail on volatile tokens' }, { label: 'Standard (1%)', value: 1, desc: 'Good for most trades' }, { label: 'High (5%)', value: 5, desc: 'For volatile tokens' }, { label: 'Custom', value: 'custom', desc: 'Set your own' } ]; return (