TokenSwap
Advanced token exchange interface with real-time pricing, slippage protection, and multi-DEX routing.
The TokenSwap component provides a complete token exchange interface with intelligent routing, real-time pricing, and built-in protection mechanisms. It aggregates liquidity across multiple DEXs to ensure the best possible prices.
Features
- Multi-DEX Routing: Automatically routes through Uniswap, SushiSwap, 1inch, and others
- Real-time Pricing: Live price feeds with automatic updates
- Slippage Protection: Configurable slippage tolerance with warnings
- Price Impact Display: Clear price impact calculations and warnings
- Gas Optimization: Intelligent gas estimation and optimization
- Token Search: Built-in token selector with search and favorites
Basic Usage
Swap
Balance: 0
≈ $0.00
Balance: 0
≈ $0.00
<template>
<div class="max-w-md mx-auto">
<TokenSwap
:from-token="fromToken"
:to-token="toToken"
@swap="handleSwap"
@preview="handlePreview"
/>
</div>
</template>
<script setup>
const fromToken = ref({
symbol: 'ETH',
address: '0x0000000000000000000000000000000000000000',
decimals: 18,
balance: 2.5,
logoUri: '/tokens/eth.png'
})
const toToken = ref({
symbol: 'USDC',
address: '0xA0b86a33E6441A8A2d5B0a1a6a6b6b6b6b6b6b6b',
decimals: 6,
balance: 0,
logoUri: '/tokens/usdc.png'
})
const handleSwap = async (swapData) => {
console.log('Executing swap:', swapData)
// swapData: { fromAmount, toAmount, route, gasEstimate, slippage }
}
const handlePreview = (preview) => {
console.log('Swap preview:', preview)
// preview: { rate, priceImpact, minReceived, route }
}
</script>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
fromToken | Token | null | Source token object |
toToken | Token | null | Destination token object |
slippage | number | 0.5 | Slippage tolerance percentage |
variant | 'default' | 'compact' | 'minimal' | 'default' | Component style variant |
showRoute | boolean | true | Display routing information |
showPriceImpact | boolean | true | Show price impact warnings |
enableMultiHop | boolean | true | Allow multi-hop routing |
maxHops | number | 3 | Maximum routing hops |
refreshInterval | number | 10000 | Price refresh interval (ms) |
Events
| Event | Payload | Description |
|---|---|---|
@swap | SwapData | Fired when user confirms swap |
@preview | SwapPreview | Fired when swap preview updates |
@token-select | { token: Token, position: string } | Fired when token is selected |
@slippage-change | number | Fired when slippage tolerance changes |
@error | Error | Fired when swap encounters an error |
Token Object
interface Token {
symbol: string
address: string
decimals: number
balance?: number
logoUri?: string
name?: string
chainId?: number
}
Advanced Usage
Custom Slippage Settings
Swap
Balance: 10.5
≈ $0.00
Balance: 1000
≈ $0.00
<template>
<TokenSwap
:slippage="customSlippage"
:slippage-options="[0.1, 0.5, 1.0, 2.0]"
@slippage-change="handleSlippageChange"
/>
</template>
<script setup>
const customSlippage = ref(1.0)
const handleSlippageChange = (newSlippage) => {
customSlippage.value = newSlippage
console.log('Slippage updated:', newSlippage)
}
</script>
Compact Variant
Swap
Balance: 10.5
≈ $0.00
Balance: 1000
≈ $0.00
<template>
<TokenSwap
variant="compact"
:from-token="fromToken"
:to-token="toToken"
:show-route="false"
class="max-w-sm"
/>
</template>
With Custom Token List
Swap
Balance: 10.5
≈ $0.00
Balance: 1000
≈ $0.00
<template>
<TokenSwap
:token-list="customTokens"
:default-tokens="popularTokens"
@token-select="handleTokenSelect"
/>
</template>
<script setup>
const customTokens = ref([
// Custom token list
])
const popularTokens = ref([
'ETH', 'USDC', 'USDT', 'WBTC', 'DAI'
])
const handleTokenSelect = ({ token, position }) => {
console.log(`Selected ${token.symbol} for ${position}`)
}
</script>
Routing & Pricing
Multi-DEX Aggregation
The component automatically routes through multiple DEXs to find the best price:
- Uniswap V2/V3: Primary AMM with multiple fee tiers
- SushiSwap: Alternative routing for better prices
- 1inch: Meta-aggregator for complex routes
- Curve: Optimized for stablecoin swaps
- Balancer: Weighted pool routing
Price Impact Warnings
Swap
Balance: 10.5
≈ $0.00
Balance: 1000
≈ $0.00
<template>
<TokenSwap
:price-impact-threshold="2.0"
:high-impact-threshold="5.0"
@high-impact="handleHighImpact"
/>
</template>
<script setup>
const handleHighImpact = (impact) => {
if (impact > 10) {
// Show strong warning for very high impact
alert(`Warning: ${impact}% price impact!`)
}
}
</script>
Gas Optimization
Gas Price Settings
<TokenSwap
:gas-price="gasPrice"
:gas-options="gasOptions"
show-gas-estimate
@gas-change="handleGasChange"
/>
MEV Protection
<TokenSwap
mev-protection
:flashbots-enabled="true"
:private-mempool="true"
/>
Error Handling
Common error scenarios and handling:
<template>
<TokenSwap
@error="handleSwapError"
:loading="swapping"
/>
</template>
<script setup>
const swapping = ref(false)
const handleSwapError = (error) => {
switch (error.code) {
case 'INSUFFICIENT_BALANCE':
toast.error('Insufficient token balance')
break
case 'SLIPPAGE_EXCEEDED':
toast.error('Price moved beyond slippage tolerance')
break
case 'GAS_ESTIMATION_FAILED':
toast.error('Unable to estimate gas costs')
break
default:
toast.error('Swap failed: ' + error.message)
}
}
</script>
Styling & Customization
Custom Theme
<TokenSwap
class="swap-dark-theme"
:ui="{
background: 'bg-gray-900',
border: 'border-gray-700',
text: 'text-white'
}"
/>
CSS Variables
.token-swap {
--swap-primary: #8b5cf6;
--swap-secondary: #06b6d4;
--swap-success: #10b981;
--swap-warning: #f59e0b;
--swap-error: #ef4444;
}
Integration Examples
DeFi Dashboard Integration
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-2">
<TokenSwap variant="default" />
</div>
<div>
<SwapHistory :recent-swaps="recentSwaps" />
</div>
</div>
Mobile-Optimized Layout
<TokenSwap
variant="compact"
class="w-full max-w-none"
:show-advanced="false"
/>
Related Components
- TokenSelector - Standalone token selection
- PriceChart - Token price visualization
- SwapHistory - Transaction history