Crypto exchange swaps let users trade one token for another without placing limit or market orders. Instead of managing order book positions, the platform calculates a quote, locks it for a brief window, and executes the trade at that rate. This article examines how centralized and decentralized exchanges implement swaps, the technical choices that affect price discovery and execution risk, and the operational details practitioners need to audit or integrate these systems.
Centralized Exchange Swap Models
Centralized exchanges typically offer swaps through two mechanisms: internal liquidity routing and external aggregation.
Internal routing uses the exchange’s existing order books. When a user requests a swap from ETH to USDC, the platform queries its spot market depth, calculates a synthetic quote based on current bids and offers, and executes the trade as two or more sequential fills. The exchange absorbs the spread and often charges a flat fee or percentage markup. The user sees a single quote and final balance update. No partial fills or order management UI.
Aggregated routing queries multiple internal markets or external liquidity sources. If the platform supports ETH, BTC, and USDC, a direct ETH to obscure token swap might route through ETH → BTC → target token if that path offers better pricing than ETH → USDC → target. The routing algorithm weighs market depth, fees, and slippage. Some exchanges expose the routing path in the quote response. Others present only the final rate.
The technical constraint in both models is quote validity. Centralized swaps usually guarantee the quoted rate for 5 to 30 seconds. If the user confirms within that window, the exchange executes at the locked price regardless of market movement. If the window expires, the quote refreshes. This shifts execution risk from the user to the exchange’s market making or hedging operations.
Decentralized Exchange Swap Primitives
Decentralized swaps rely on onchain liquidity pools or aggregators that query multiple protocols.
Automated market maker (AMM) pools calculate swap rates algorithmically. The constant product formula (x × y = k) means depositing token A into a pool automatically adjusts the ratio and returns token B. Slippage increases nonlinearly with trade size relative to pool depth. Users specify a maximum slippage tolerance. If the onchain execution exceeds that threshold, the transaction reverts.
The critical implementation detail is price impact calculation. Frontend interfaces estimate impact by simulating the trade against current pool reserves. Actual execution happens in a separate transaction that might land several blocks later. If another trade executes first and shifts the pool ratio, your transaction either completes at a worse rate (within your slippage bound) or reverts. Mempool monitoring services can frontrun large swaps to extract value from the predictable price movement.
Onchain aggregators split a single swap across multiple liquidity sources. A tool might route 60% through Uniswap, 30% through Curve, and 10% through Balancer to minimize total slippage. The aggregator contract must hold approvals for each underlying protocol, execute the splits in a single atomic transaction, and return the combined output to the user. Gas costs rise with the number of hops. Complex routes may cost 300,000 to 600,000 gas compared to 150,000 for a direct AMM swap.
Quote Staleness and Execution Guarantees
The gap between quote generation and execution creates distinct failure modes.
In centralized systems, the exchange updates internal order books continuously. The swap quote reflects a snapshot. Market volatility during the validity window affects the exchange’s hedging cost but not the user’s executed rate. Some platforms widen spreads or reduce validity windows during high volatility to limit their exposure.
In decentralized systems, no counterparty guarantees the quote. The user signs a transaction with a minimum output amount derived from the quoted rate and slippage tolerance. Miners or validators include the transaction in a block when it becomes profitable or meets priority fee thresholds. Block inclusion can lag by seconds or minutes during congestion. Price movements between signing and execution either stay within tolerance or trigger a revert.
Aggregators and advanced AMMs use deadline parameters. The transaction includes a UNIX timestamp. If the block timestamp exceeds the deadline when the transaction executes, it reverts regardless of price. This prevents stale transactions from executing hours later under completely different market conditions.
Fee Structures and Hidden Costs
Centralized swap fees typically appear as a percentage markup on the quoted rate or a flat service fee. The actual cost includes this explicit fee plus the bid ask spread the platform absorbs. Comparing the swap rate to the midpoint of the spot order book reveals the implicit cost. During low liquidity periods, this spread can exceed the stated fee.
Decentralized swaps charge protocol fees (set by governance or fixed in the contract) plus network gas. Protocol fees usually range from 0.05% to 1% depending on the pool. Gas costs vary by network congestion and transaction complexity. A simple Uniswap V2 swap might cost $2 in gas at 20 gwei on Ethereum mainnet. The same swap during congestion can exceed $50. Aggregated routes multiply this cost.
Some AMMs implement dynamic fees that adjust based on recent volatility or pool utilization. The quoted fee at the time you generate the estimate may differ from the fee applied when your transaction executes if volatility spikes between those events.
Worked Example: Aggregated DEX Swap Execution
A user wants to swap 10 ETH for USDC on Ethereum mainnet. They query a DEX aggregator API.
The aggregator simulates the swap across Uniswap V3, Curve, and Balancer. Uniswap quotes 18,520 USDC for 10 ETH (effective rate 1,852 USDC per ETH). Curve quotes 18,480 USDC. Balancer quotes 18,500 USDC. The aggregator also simulates split routes: 5 ETH through Uniswap + 5 ETH through Balancer yields 18,540 USDC total.
The user sets 0.5% slippage tolerance. Minimum acceptable output: 18,540 × 0.995 = 18,447 USDC. The aggregator constructs a transaction that calls Uniswap with 5 ETH, calls Balancer with 5 ETH, and transfers the combined USDC output to the user’s address. The transaction includes a 10 minute deadline (current time + 600 seconds).
The user signs and broadcasts. A frontrunning bot detects the pending transaction and submits a higher priority fee transaction that swaps 3 ETH through the same pools, shifting the price. The user’s transaction executes two blocks later. Uniswap now returns 9,240 USDC for 5 ETH. Balancer returns 9,230 USDC for 5 ETH. Total: 18,470 USDC. This exceeds the 18,447 minimum, so the transaction completes.
The user receives 70 USDC less than quoted but stays within their stated tolerance. Gas cost: 0.018 ETH (approximately $33 at the prevailing rate). Effective rate after gas and frontrunning: 1,845 USDC per ETH instead of the quoted 1,854.
Common Mistakes and Misconfigurations
- Setting slippage too tight on volatile pairs. A 0.1% tolerance on a token with 2% minute-to-minute swings causes frequent reverts and wasted gas.
- Ignoring deadline parameters. Transactions without deadlines can execute hours later if they remain in the mempool, locking in obsolete rates.
- Assuming aggregator quotes include gas. Most APIs return the token output only. Users must separately estimate and fund gas.
- Overlooking token approval transactions. First time swaps require an approval transaction before the swap transaction. Double the gas cost and wait time.
- Trusting centralized swap quotes during halted markets. Some exchanges disable or delay quote updates when they pause spot trading. The swap quote may not reflect the actual unavailability of liquidity.
- Executing large swaps as single transactions on shallow pools. Splitting a 100 ETH swap into 10 smaller sequential swaps often reduces total slippage despite higher cumulative gas costs.
What to Verify Before You Rely on This
- Current slippage tolerance defaults in the interface or API you are using. Some tools set 3% or higher, which can cost significantly on stable pairs.
- Gas price estimates and whether the aggregator or interface updates them dynamically. Stale gas estimates cause transactions to pend indefinitely.
- Protocol fee schedules for each liquidity source in your route. Governance votes can change these without notice.
- Token contract implementations for transfer fees or rebasing mechanics. Some tokens charge fees on every transfer, which breaks standard swap math.
- Whether the exchange or protocol has paused swaps for specific pairs. Emergency pauses can last hours or days.
- API rate limits if you are integrating swaps programmatically. Exceeding limits can block quote requests or cause temporary bans.
- Whether quoted rates include all fees or if some are applied post execution. Read the API documentation or test with a small amount.
- Frontrunning protections offered by the platform. Some aggregators use private mempools or MEV protection services. Others expose all transactions publicly.
- Network congestion and average block times. Quotes generated during 15 second block times may be stale by the time they execute if congestion extends block intervals.
- Jurisdiction specific restrictions. Some platforms block swaps for certain tokens or user locations based on compliance policies.
Next Steps
- Test swap execution with small amounts on a testnet or with minimal mainnet funds to observe actual gas costs, slippage, and execution times for your typical trade sizes and pairs.
- Compare effective rates across multiple aggregators and direct AMM interfaces using the same input amount and slippage settings to identify which routing consistently delivers better execution.
- Monitor mempool activity or use MEV protection services if you regularly execute swaps large enough to be profitable frontrunning targets.
Category: Crypto Trading