DEV Community

Cover image for 8 Ways to Optimize Gas Fees on Token Swaps
Moon Soon
Moon Soon

Posted on • Originally published at swapapi.dev

8 Ways to Optimize Gas Fees on Token Swaps

Gas fees are the hidden tax on every token swap. A simple ETH-to-USDC trade on Ethereum mainnet can cost $5-50 in gas depending on network congestion, while the same swap on an L2 like Arbitrum or Base costs under $0.10. For developers building trading bots, DCA tools, or wallet backends, unoptimized gas spending erodes user value on every single transaction. Across the EVM ecosystem, users paid over $1.5 billion in gas fees in 2025 on Ethereum alone. This guide covers 8 practical strategies to reduce gas costs on token swaps, with code examples using real chain data and token addresses.

1. Use L2 and Low-Fee Chains

The single biggest gas optimization is choosing the right chain. Ethereum L1 gas costs are 50-100x higher than L2 rollups for the same swap operation. A token swap that consumes ~150,000 gas units costs dramatically different amounts depending on the network.

Chain Chain ID Avg Gas Price Swap Cost (USD)
Ethereum 1 15-30 gwei $5.00 - $15.00
Polygon 137 30-80 gwei $0.01 - $0.03
Arbitrum 42161 0.1 gwei $0.03 - $0.10
Base 8453 0.005 gwei $0.01 - $0.05
Optimism 10 0.004 gwei $0.01 - $0.05
BSC 56 1-3 gwei $0.05 - $0.15
Avalanche 43114 25 nAVAX $0.02 - $0.08

If your application supports multiple chains, default users to the cheapest one where the token pair has adequate liquidity. With an API that covers 46 chains, you can query the same endpoint across all networks and let the user choose:

curl "https://api.swapapi.dev/v1/swap/8453?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913&amount=1000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
Enter fullscreen mode Exit fullscreen mode

That request swaps 1 ETH for USDC on Base (chain 8453) for a fraction of a cent in gas. The same swap on Ethereum mainnet would cost 100x more.

2. Estimate Gas Before Submitting

Never submit a swap transaction without estimating gas first. The eth_estimateGas RPC call tells you exactly how much gas the transaction will consume before you spend anything. This prevents two costly scenarios: overpaying by setting an arbitrarily high gas limit, and losing gas entirely when a transaction reverts.

The swap API returns a gasPrice field and recommended RPCs. Use them to estimate and add a 20% buffer for complex multi-hop routes:

const quote = await fetch("https://api.swapapi.dev/v1/swap/42161?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0xaf88d065e77c8cC2239327C5EDb3A432268e5831&amount=1000000000000000000&sender=0xYOUR_ADDRESS").then(r => r.json());

const gasEstimate = await provider.estimateGas(quote.data.tx);
const gasLimit = Math.ceil(Number(gasEstimate) * 1.2);
Enter fullscreen mode Exit fullscreen mode

If eth_estimateGas fails, the transaction would revert on-chain. Do not submit it. This single check saves users from burning gas on doomed transactions, which is the most wasteful type of gas spending.

3. Use Aggregators for Optimal Routing

DEX aggregators find the best route across hundreds of liquidity pools, often splitting a trade across multiple sources to minimize price impact and total cost. A direct swap on a single pool might execute at a worse price, meaning you need a larger input amount (and more gas) to get the same output.

Aggregator routing also affects gas efficiency directly. A well-optimized route through a single concentrated liquidity pool uses ~150,000 gas, while a poorly routed multi-hop swap through three pools can use 400,000+ gas. The aggregator balances price improvement against gas cost to find the optimal path.

curl "https://api.swapapi.dev/v1/swap/137?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359&amount=500000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
Enter fullscreen mode Exit fullscreen mode

This queries an aggregated swap of 500 POL to USDC on Polygon. The response includes priceImpact so you can verify the routing quality. Reject swaps with priceImpact below -0.05 (-5%) to avoid excessive slippage on low-liquidity pairs.

4. Use EIP-1559 Fee Mechanics

EIP-1559 replaced the blind gas price auction with a base fee plus priority tip model. On EIP-1559 chains (Ethereum, Arbitrum, Base, Optimism, Polygon, and most modern EVMs), using maxFeePerGas and maxPriorityFeePerGas instead of a flat gasPrice prevents overpaying during fee spikes.

The swap API returns a gasPrice field as a legacy gas price suggestion. On EIP-1559 chains, most wallet libraries (ethers.js, viem, web3.py) automatically convert to EIP-1559 parameters when you omit gasPrice from the transaction:

const tx = quote.data.tx;
await wallet.sendTransaction({ to: tx.to, data: tx.data, value: tx.value, gasLimit });
Enter fullscreen mode Exit fullscreen mode

By omitting gasPrice and letting the library handle EIP-1559 fee estimation, you pay only the current base fee plus a small priority tip instead of a potentially inflated legacy gas price. During periods of high congestion followed by a sudden drop, this can save 20-40% on gas.

5. Time Your Swaps for Low Congestion

Gas prices on Ethereum and other EVM chains fluctuate significantly throughout the day. On Ethereum mainnet, gas prices during off-peak hours (weekends, early UTC mornings) can be 2-5x lower than during peak trading activity. L2s show less variation, but L1 data posting costs still fluctuate.

For non-urgent swaps in DCA bots or portfolio rebalancers, implement a gas price threshold. Fetch a quote, check the returned gasPrice, and only execute if it falls below your target:

const quote = await fetch("https://api.swapapi.dev/v1/swap/1?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&amount=1000000000000000000&sender=0xYOUR_ADDRESS").then(r => r.json());

const gasPriceGwei = Number(quote.data.tx.gasPrice) / 1e9;
if (gasPriceGwei > 25) return;
Enter fullscreen mode Exit fullscreen mode

For Ethereum mainnet swaps, targeting gas prices below 15 gwei (common on weekends and late-night UTC) can cut costs by 50% compared to executing during weekday peak hours.

6. Batch Transactions Where Possible

Every Ethereum transaction has a base overhead of 21,000 gas, regardless of what the transaction does. If your application executes multiple swaps in sequence (e.g., rebalancing a portfolio across several tokens), each swap pays that overhead separately.

Batching strategies that reduce per-swap overhead include:

  • Approval + swap in one flow: Check token allowance before fetching the swap quote. If approval is needed, submit it first and wait for confirmation, then fetch a fresh quote. The swap API calldata is time-sensitive (30-second deadline), so always re-fetch after the approval confirms rather than reusing a stale quote.

  • Multi-chain parallelism: If rebalancing across chains, fire swap quotes on all chains simultaneously. Each chain's transaction is independent, so submit them in parallel instead of sequentially. The API supports 46 chains from the same endpoint.

  • Smart contract batching: For advanced use cases, a custom contract can execute multiple swaps atomically in a single transaction, paying the 21,000 gas overhead only once. This is particularly effective on L2s where the per-transaction overhead is a larger percentage of total cost.

7. Avoid Fee-on-Transfer (Tax) Tokens

Tax tokens (tokens with built-in transfer fees of 1-10%) create hidden gas costs beyond the tax itself. The transfer fee mechanism adds extra storage writes and event emissions to every transfer, increasing gas consumption by 30-80% compared to standard ERC-20 tokens.

Additionally, the swap API cannot account for the transfer tax in expectedAmountOut. The actual received amount will be lower than quoted. This means you may need to set higher maxSlippage to prevent reverts, which further exposes you to unfavorable execution.

When working with tax tokens, set maxSlippage higher to accommodate the fee:

curl "https://api.swapapi.dev/v1/swap/1?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&amount=1000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045&maxSlippage=0.1"
Enter fullscreen mode Exit fullscreen mode

Where possible, swap through standard ERC-20 tokens (USDC, USDT, DAI, WETH) as intermediaries to avoid tax token overhead on the routing path.

8. Choose the Right Chain for Each Token Pair

Not all chains price the same token pair equally. Liquidity depth, gas cost, and token decimals all vary by chain. A critical example: USDC and USDT use 6 decimals on most chains but 18 decimals on BSC. Sending the wrong amount value wastes gas on a transaction that either reverts or swaps a dust amount.

Here are the correct stablecoin addresses and decimals across major chains:

Chain USDC Decimals USDT Decimals Native Token
Ethereum (1) 6 6 ETH
Arbitrum (42161) 6 6 ETH
Base (8453) 6 6 ETH
Polygon (137) 6 6 POL
BSC (56) 18 18 BNB
Optimism (10) 6 6 ETH
Avalanche (43114) 6 6 AVAX

Swapping 100 USDC on BSC requires amount=100000000000000000000 (100 * 10^18), while on Ethereum it is amount=100000000 (100 * 10^6). Getting this wrong is a common and costly mistake.

Compare costs across chains before committing to a swap:

curl "https://api.swapapi.dev/v1/swap/56?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0x55d398326f99059fF775485246999027B3197955&amount=1000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
Enter fullscreen mode Exit fullscreen mode

Frequently Asked Questions

How much can L2s save on gas compared to Ethereum?

L2 rollups like Arbitrum, Base, and Optimism typically reduce swap gas costs by 50-100x compared to Ethereum mainnet. A swap that costs $10 on Ethereum costs $0.05-0.10 on most L2s.

Does using an aggregator cost more gas than a direct DEX swap?

Aggregator contracts have slightly higher base gas overhead than a direct Uniswap-style router call. However, the price improvement from better routing typically more than compensates. For large trades, aggregator routing can save 1-3% on price impact, which far outweighs the extra 20,000-30,000 gas units.

How do I simulate a swap without spending gas?

Use eth_call with the transaction object returned by the API. This executes the swap against the current chain state without submitting a real transaction. If it reverts, the swap would fail on-chain. This is free and is the safest pre-flight check before committing gas.

Why does my swap revert even after gas estimation succeeds?

Swap calldata includes a deadline (typically 30 seconds). If you wait too long between fetching the quote and submitting the transaction, the deadline expires and the transaction reverts. Always re-fetch a fresh quote if more than 30 seconds have passed.

What gas buffer should I add to the estimate?

A 20% buffer (multiply eth_estimateGas result by 1.2) is recommended. Complex multi-hop routes can have variable gas consumption depending on pool state changes between estimation and execution. Unused gas is refunded, so a buffer costs nothing extra.

Get Started

Swap API is free with no API key required. It supports 46 EVM chains from a single endpoint. Fetch a quote, estimate gas, simulate with eth_call, and submit. Every strategy in this guide works with a single GET request:

GET https://api.swapapi.dev/v1/swap/{chainId}?tokenIn={address}&tokenOut={address}&amount={rawAmount}&sender={address}
Enter fullscreen mode Exit fullscreen mode

Read the full API documentation to start integrating gas-optimized swaps into your application.

Top comments (0)