Gas Optimization The $86 Swap That Became $0.39 In January 2025, a simple Uniswap token swap cost $86 in gas fees during peak congestion. Today, February Gas Optimization The $86 Swap That Became $0.39 In January 2025, a simple Uniswap token swap cost $86 in gas fees during peak congestion. Today, February

Gas Optimization Strategies: Why Your Contract Costs More (And How to Fix It)

2026/02/02 19:10
14 min read

Gas Optimization

The $86 Swap That Became $0.39

In January 2025, a simple Uniswap token swap cost $86 in gas fees during peak congestion. Today, February 1, 2026, that same swap costs $0.39.

Ethereum gas fees have dropped 95% following the Dencun upgrade and mass Layer 2 adoption. Average gas prices hover around 0.08–1.17 gwei, down from 4.99 gwei a year ago. On January 17, 2026, Ethereum processed a record 2.6 million transactions without congestion.

So why does gas optimization still matter?

Because when the next DeFi summer hits and gas spikes back to 50+ gwei, your inefficient contract will cost $50 per transaction while optimized competitors charge $5. Users will abandon your dApp faster than they left during the 2021 NFT mania when gas hit 500 gwei.

This is Day 36 of the 60-Day Web3 journey, still in Phase 3: Development. Yesterday we covered the deployment checklist including gas testing. Today we go deeper: understanding why certain patterns cost more and how to architect for efficiency from the start.

Come hang out in Web3ForHumans on Telegram.
Follow me on
Medium | TwitterFuture

Gas optimization isn’t just about saving money. It’s about user retention, protocol sustainability, and building for scale.

Why Gas Fees Are Low Right Now (And Why That Won’t Last)

2026 reality:

  • Dencun upgrade reduced Layer 2 costs by 90%+
  • Layer 2 adoption exploded (Arbitrum, Optimism, Base processing millions of daily transactions)
  • Ethereum mainnet congestion dropped as activity moved to L2s
  • Current gas: 0.08–1.17 gwei (January 2026 average)

But history repeats:

  • 2021 NFT boom: Gas spiked to 500+ gwei
  • 2022 bear market: Gas dropped to 10–15 gwei
  • 2024 inscriptions craze: Brief spike to 100+ gwei
  • 2026: Currently calm, but the next cycle will bring congestion

The pattern: Every bull run brings congestion. Every new use case (DeFi, NFTs, inscriptions, AI agents) floods the network. If your contract isn’t optimized, users will pay the price.

How the EVM Charges for Operations

Understanding gas costs requires understanding how Ethereum Virtual Machine (EVM) works.

Gas cost hierarchy (from cheap to expensive):

  1. Reading from memory (3 gas) — Cheapest
  2. Simple arithmetic (3–5 gas) — Very cheap
  3. Reading from calldata (16–68 gas) — Cheap
  4. Reading from storage (SLOAD) (2,100 gas) — Expensive
  5. Writing to storage (SSTORE) (20,000 gas for new, 5,000 for update) — Very expensive
  6. Creating new contracts (32,000+ gas) — Most expensive

Why storage is expensive:

  • Every node in the network must store your data forever
  • Storage writes are permanent (can’t be “deleted”, only zeroed for partial refund)
  • Reading requires disk access across thousands of nodes

The golden rule: Minimize storage operations. Everything else is relatively cheap.

Storage Optimization: The Biggest Gas Saver

1. Variable Packing

Solidity stores variables in 32-byte (256-bit) slots. If you’re smart, you can pack multiple variables into one slot.

Bad (uses 3 storage slots):

contract Inefficient {
uint256 public a = 1; // Slot 0
uint256 public b = 2; // Slot 1
uint256 public c = 3; // Slot 2
}
// Cost: 3 SSTORE operations = 60,000 gas

Good (uses 1 storage slot):

contract Efficient {
uint128 public a = 1; // Slot 0 (first 128 bits)
uint64 public b = 2; // Slot 0 (next 64 bits)
uint64 public c = 3; // Slot 0 (final 64 bits)
}
// Cost: 1 SSTORE operation = 20,000 gas
// Savings: 40,000 gas (67% reduction)

Real-world example from Uniswap V3:

struct Slot0 {
uint160 sqrtPriceX96; // 160 bits
int24 tick; // 24 bits
uint16 observationIndex; // 16 bits
uint16 observationCardinality; // 16 bits
uint16 observationCardinalityNext; // 16 bits
uint8 feeProtocol; // 8 bits
bool unlocked; // 8 bits
}
// All 7 variables packed into ONE 256-bit slot!

Packing rules:

  • Order variables by size (largest to smallest)
  • Group variables that are accessed together
  • Use uint8, uint16, uint32, uint64, uint128 instead of always using uint256

2. Use immutable and constant

Variables declared as constant or immutable are not stored in storage. They're compiled directly into the bytecode.

Expensive:

contract Expensive {
address public owner; // SLOAD cost: 2,100 gas per read
uint256 public maxSupply; // SLOAD cost: 2,100 gas per read

constructor() {
owner = msg.sender;
maxSupply = 1000000;
}
}

Cheap:

contract Cheap {
address public immutable owner; // No SLOAD, direct bytecode access
uint256 public constant MAX_SUPPLY = 1000000; // No SLOAD

constructor() {
owner = msg.sender;
}
}
// Savings: 2,100 gas per read (100% reduction for that operation)

When to use:

  • constant: Value known at compile time (e.g., MAX_SUPPLY, DECIMALS)
  • immutable: Value set in constructor and never changes (e.g., owner, token address)

3. Cache Storage Reads in Memory

Every SLOAD costs 2,100 gas. If you read the same storage variable multiple times, cache it in memory.

Expensive:

function badTransfer(address to, uint256 amount) public {
require(balances[msg.sender] >= amount); // SLOAD #1
balances[msg.sender] -= amount; // SLOAD #2
balances[to] += amount;
emit Transfer(msg.sender, to, amount);
}
// Cost: 2 SLOADs = 4,200 gas just for reading

Cheap:

function goodTransfer(address to, uint256 amount) public {
uint256 senderBalance = balances[msg.sender]; // SLOAD #1 (cache in memory)
require(senderBalance >= amount); // Memory read (3 gas)
balances[msg.sender] = senderBalance - amount; // SSTORE
balances[to] += amount;
emit Transfer(msg.sender, to, amount);
}
// Cost: 1 SLOAD = 2,100 gas
// Savings: 2,100 gas (50% reduction for that operation)

4. Use mapping Instead of array for Lookups

Arrays require iterating (expensive). Mappings are direct lookups (cheap).

Expensive:

contract ExpensiveWhitelist {
address[] public whitelist;

function isWhitelisted(address user) public view returns (bool) {
for (uint i = 0; i < whitelist.length; i++) { // O(n) complexity
if (whitelist[i] == user) return true;
}
return false;
}
}
// Cost with 100 users: ~210,000+ gas (grows linearly)

Cheap:

contract CheapWhitelist {
mapping(address => bool) public whitelist;

function isWhitelisted(address user) public view returns (bool) {
return whitelist[user]; // O(1) complexity
}
}
// Cost: 2,100 gas (constant, regardless of size)
// Savings: 99% reduction for large lists

Function Optimization

1. Use external Instead of public for External-Only Functions

public functions can be called both internally and externally, requiring more gas. If a function is only called externally, mark it external.

Expensive:

function publicFunction(uint256[] memory data) public {
// Function body
}
// Cost: Copies array from calldata to memory (expensive)

Cheap:

function externalFunction(uint256[] calldata data) external {
// Function body
}
// Cost: Reads directly from calldata (cheap)
// Savings: ~1,000-5,000 gas depending on array size

2. Use view and pure Functions

Functions that don’t modify state should be marked view or pure. They're free when called externally (off-chain).

function getBalance(address user) public view returns (uint256) {
return balances[user];
}
// Cost when called externally: 0 gas (read-only RPC call)
// Cost when called internally: 2,100 gas (SLOAD)

3. Short-Circuit Evaluation

Order your conditions to fail fast.

Expensive:

require(expensiveCheck() && cheapCheck());
// Runs expensiveCheck() first, even if cheapCheck() would fail

Cheap:

require(cheapCheck() && expensiveCheck());
// Fails on cheapCheck() without running expensiveCheck()
// Savings: Variable, but can be significant

Advanced Optimization Techniques

1. Bitmap Tricks for Boolean Flags

Instead of storing multiple bool variables (each takes a full 256-bit slot), use a single uint256 as a bitmap.

Expensive (8 slots):

contract Flags {
bool flag1;
bool flag2;
bool flag3;
bool flag4;
bool flag5;
bool flag6;
bool flag7;
bool flag8;
}
// Cost: 8 slots = 160,000 gas to initialize

Cheap (1 slot):

contract OptimizedFlags {
uint256 private flags; // Can store 256 boolean flags

function setFlag(uint8 position) internal {
flags |= (1 << position);
}

function clearFlag(uint8 position) internal {
flags &= ~(1 << position);
}

function getFlag(uint8 position) internal view returns (bool) {
return (flags & (1 << position)) != 0;
}
}
// Cost: 1 slot = 20,000 gas
// Savings: 140,000 gas (87.5% reduction)

2. Use Assembly for Critical Paths

Inline assembly gives you low-level control and can be more gas-efficient for specific operations.

Solidity:

function getHash(uint256 a, uint256 b) public pure returns (bytes32) {
return keccak256(abi.encodePacked(a, b));
}
// Cost: ~300 gas

Assembly:

function getHashOptimized(uint256 a, uint256 b) public pure returns (bytes32 result) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
result := keccak256(0x00, 0x40)
}
}
// Cost: ~200 gas
// Savings: ~33% reduction

Warning: Assembly bypasses Solidity’s safety checks. Only use for hot paths after thorough testing.

3. Batch Operations

Process multiple items in one transaction instead of many separate transactions.

Expensive:

// User calls this 10 times
function mint(address to) public {
_mint(to, nextTokenId++);
}
// Cost: 10 transactions × 21,000 base gas = 210,000+ gas

Cheap:

function batchMint(address[] calldata recipients) public {
for (uint i = 0; i < recipients.length; i++) {
_mint(recipients[i], nextTokenId++);
}
}
// Cost: 1 transaction × 21,000 base gas + loop operations
// Savings: ~180,000 gas (86% reduction)

Measuring Gas with Foundry

Use forge snapshot to track gas usage across your test suite.

Step 1: Write gas-focused tests

// test/GasOptimization.t.sol
contract GasOptimizationTest is Test {
function testTransferGas() public {
token.transfer(alice, 100 ether);
}

function testBatchTransferGas() public {
address[] memory recipients = new address[](10);
uint256[] memory amounts = new uint256[](10);
// ... fill arrays
token.batchTransfer(recipients, amounts);
}
}

Step 2: Create baseline snapshot

forge snapshot

Step 3: Optimize your contract

Step 4: Compare gas usage

forge snapshot --diff .gas-snapshot

Output shows exactly how much gas you saved:

testTransferGas() (gas: -2100 (-4.5%))
testBatchTransferGas() (gas: -18000 (-12.3%))

This workflow is how protocols like Aave and Uniswap maintain gas efficiency across updates.

Real-World Example: Uniswap V3 Gas Optimizations

Uniswap V3 is one of the most gas-optimized protocols in DeFi. Here’s what they did:

1. Packed storage (Slot0 struct):

  • 7 variables in 1 storage slot
  • Saved ~120,000 gas on pool initialization

2. Bitmap for tick tracking:

  • Instead of array of active ticks, used bitmap
  • Reduced gas for swaps by 40%

3. Custom math libraries in assembly:

  • sqrt, div, mul operations optimized
  • Saved ~15–20% gas per swap

4. Minimized external calls:

  • Batched token transfers
  • Reduced callback overhead

Result: Uniswap V3 swaps cost 30–40% less gas than V2, despite being more feature-rich.

When NOT to Optimize

Premature optimization is the root of all evil — Donald Knuth

Don’t optimize:

  • Before your contract works correctly
  • Before you have comprehensive tests
  • Functions that are rarely called (admin functions used once a month)
  • Micro-optimizations that save <100 gas but hurt readability
  • Security-critical code where clarity > efficiency

Do optimize:

  • Hot paths (functions called frequently by users)
  • User-facing functions (mint, swap, transfer, approve)
  • Loops that process arrays or mappings
  • Storage-heavy operations
  • After deployment testing from Day 35

The trade-off:

// Readable but expensive
function isWhitelisted(address user) public view returns (bool) {
for (uint i = 0; i < whitelist.length; i++) {
if (whitelist[i] == user) return true;
}
return false;
}

// Optimized but requires more storage management
mapping(address => bool) public whitelist;
function isWhitelisted(address user) public view returns (bool) {
return whitelist[user];
}

For admin-only functions called once a month? The readable version is fine. For user-facing checks called thousands of times daily? Optimize it.

Gas Optimization Checklist

Before deploying to mainnet, run through this checklist:

Storage (Biggest Impact)

  • [ ] Packed variables into 32-byte slots where possible
  • [ ] Used constant for compile-time values
  • [ ] Used immutable for constructor-set values
  • [ ] Cached storage reads in memory for repeated access
  • [ ] Used mapping instead of arrays for lookups
  • [ ] Considered bitmaps for multiple boolean flags

Functions

  • [ ] Marked external-only functions as external (not public)
  • [ ] Used calldata instead of memory for external function parameters
  • [ ] Marked read-only functions as view or pure
  • [ ] Ordered conditionals for short-circuit evaluation (fail fast)
  • [ ] Batched operations where possible

Data Types

  • [ ] Used smallest viable uint size (uint128, uint64, uint32, etc.)
  • [ ] Avoided string storage (used events or IPFS for long strings)
  • [ ] Used bytes32 instead of string for fixed-length strings

Measurements

  • [ ] Ran forge snapshot to establish baseline
  • [ ] Identified most expensive functions
  • [ ] Optimized hot paths
  • [ ] Re-ran snapshot to measure improvements
  • [ ] Tested with realistic gas prices (10–50 gwei scenarios)

2026 Gas Price Context: Why Optimization Still Matters

Current state (February 2026):

  • Average gas: 0.08–1.17 gwei
  • Simple transfer: $0.01–0.05
  • Uniswap swap: $0.39
  • NFT mint: $0.50–1.00

Sounds cheap, right?

But remember:

  • January 2025: Average gas was 4.99 gwei (4x higher)
  • Bull markets bring congestion
  • One viral dApp can spike gas to 50+ gwei overnight
  • Your users will compare your costs to competitors

The math:

Inefficient contract: 150,000 gas
Optimized contract: 50,000 gas

At 1 gwei (today): $0.30 vs $0.10 (nobody cares)
At 50 gwei (next bull run): $15 vs $5 (users abandon the $15 one)
At 500 gwei (2021 NFT mania): $150 vs $50 (only whales use the $150 one)

The protocols that survive bull runs are the ones optimized during bear markets.

Common Gas Optimization Mistakes

Mistake 1: Optimizing the wrong things

// Saved 50 gas on an admin function called once a month
function setOwner(address newOwner) public onlyOwner {
owner = newOwner; // Already optimized enough
}

// Ignored 5,000 gas waste on user function called 1000x/day
function transfer(address to, uint amount) public {
require(balances[msg.sender] >= amount); // Multiple SLOADs!
balances[msg.sender] -= amount;
// ...
}

Focus on user-facing, high-frequency functions first.

Mistake 2: Breaking security for gas savings

// DON'T DO THIS
function unsafeTransfer(address to, uint amount) external {
balances[msg.sender] -= amount; // No checks!
balances[to] += amount;
}

Security > Gas savings. Always.

Mistake 3: Not measuring before optimizing

// Spent 2 hours optimizing this
function complexCalculation() internal pure returns (uint) {
// assembly magic that saved 200 gas
}

// But function is only called once during deployment

Use forge snapshot to identify actual bottlenecks.

Tools for Gas Optimization

1. Foundry’s gas profiling

# Detailed gas report
forge test --gas-report

# Snapshot for tracking changes
forge snapshot

# Compare against baseline
forge snapshot --diff .gas-snapshot

2. Hardhat Gas Reporter (if using Hardhat)

// hardhat.config.js
module.exports = {
gasReporter: {
enabled: true,
currency: 'USD',
gasPrice: 21
}
};

3. Solidity Visual Developer (VSCode extension)

  • Highlights expensive operations
  • Shows storage layout
  • Estimates gas costs inline

4. Tenderly (for deployed contracts)

  • Gas profiling of real transactions
  • Identifies optimization opportunities
  • Simulates gas costs at different prices

Key Takeaway

Gas optimization is about respecting your users’ money.

Today’s $0.39 Uniswap swap is cheap because teams spent years optimizing. When gas was 500 gwei in 2021, unoptimized DEXes died while Uniswap thrived.

The techniques we covered today aren’t theoretical:

  • Storage packing: Uniswap V3 uses this in Slot0 struct
  • Bitmaps: Uniswap V3 tick tracking
  • Immutable variables: Every major DeFi protocol
  • Caching storage reads: Aave, Compound, all lending protocols
  • Assembly optimization: Critical paths in Uniswap, Balancer

You don’t need to optimize on Day 1. But by the time you’re ready for mainnet deployment, gas efficiency should be baked into your architecture.

The 80/20 rule for gas optimization:

  1. Pack storage variables (20% effort, 40% savings)
  2. Use immutable/constant (10% effort, 20% savings)
  3. Cache storage reads (10% effort, 15% savings)
  4. Use external + calldata (5% effort, 10% savings)
  5. Everything else (55% effort, 15% savings)

Start with the easy wins. The advanced techniques (assembly, bitmaps) come later when you’re squeezing the last bits of efficiency.

Think About This

Open your favorite DeFi protocol (Uniswap, Aave, Compound) on Etherscan. Look at their contract source code. Count how many times you see:

  • Variables packed into structs
  • immutable and constant keywords
  • external instead of public
  • Assembly blocks in critical functions

These aren’t accidents. They’re the result of thousands of hours optimizing for user experience.

Now look at a failed DeFi protocol from 2021. Check their gas costs per transaction. See the difference?

Gas optimization isn’t glamorous. But it’s what separates protocols that scale from protocols that die when gas spikes.

Resources

  • Ethereum Gas Tracker (Live Prices) — Real-time gas prices
  • Solidity Gas Optimization Guide — Comprehensive tricks list
  • Alchemy: 12 Solidity Gas Optimization Techniques — Battle-tested methods
  • Foundry Gas Snapshots — Official Foundry documentation
  • Uniswap V3 Core Code — Real-world optimization examples
  • Cyfrin Gas Optimization Tutorial — Advanced techniques
  • OpenZeppelin Contracts — Gas-optimized standard implementations
  • Solmate — Ultra gas-optimized contract library

Come hang out in Web3ForHumans on Telegram.
Follow me on
Medium | TwitterFuture

Read the previous article: Testnet to Mainnet: The Checklist Every Developer Needs Before Deploying Real Money

Want to try this yourself? Take one of your contracts and run forge snapshot. Identify the most expensive function. Apply storage caching or variable packing. Run forge snapshot --diff and see how much gas you saved. Share your results in the Telegram community!


Gas Optimization Strategies: Why Your Contract Costs More (And How to Fix It) was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

The Channel Factories We’ve Been Waiting For

The Channel Factories We’ve Been Waiting For

The post The Channel Factories We’ve Been Waiting For appeared on BitcoinEthereumNews.com. Visions of future technology are often prescient about the broad strokes while flubbing the details. The tablets in “2001: A Space Odyssey” do indeed look like iPads, but you never see the astronauts paying for subscriptions or wasting hours on Candy Crush.  Channel factories are one vision that arose early in the history of the Lightning Network to address some challenges that Lightning has faced from the beginning. Despite having grown to become Bitcoin’s most successful layer-2 scaling solution, with instant and low-fee payments, Lightning’s scale is limited by its reliance on payment channels. Although Lightning shifts most transactions off-chain, each payment channel still requires an on-chain transaction to open and (usually) another to close. As adoption grows, pressure on the blockchain grows with it. The need for a more scalable approach to managing channels is clear. Channel factories were supposed to meet this need, but where are they? In 2025, subnetworks are emerging that revive the impetus of channel factories with some new details that vastly increase their potential. They are natively interoperable with Lightning and achieve greater scale by allowing a group of participants to open a shared multisig UTXO and create multiple bilateral channels, which reduces the number of on-chain transactions and improves capital efficiency. Achieving greater scale by reducing complexity, Ark and Spark perform the same function as traditional channel factories with new designs and additional capabilities based on shared UTXOs.  Channel Factories 101 Channel factories have been around since the inception of Lightning. A factory is a multiparty contract where multiple users (not just two, as in a Dryja-Poon channel) cooperatively lock funds in a single multisig UTXO. They can open, close and update channels off-chain without updating the blockchain for each operation. Only when participants leave or the factory dissolves is an on-chain transaction…
Share
BitcoinEthereumNews2025/09/18 00:09
Markets await Fed’s first 2025 cut, experts bet “this bull market is not even close to over”

Markets await Fed’s first 2025 cut, experts bet “this bull market is not even close to over”

Will the Fed’s first rate cut of 2025 fuel another leg higher for Bitcoin and equities, or does September’s history point to caution? First rate cut of 2025 set against a fragile backdrop The Federal Reserve is widely expected to…
Share
Crypto.news2025/09/18 00:27
Best Crypto to Buy as Saylor & Crypto Execs Meet in US Treasury Council

Best Crypto to Buy as Saylor & Crypto Execs Meet in US Treasury Council

The post Best Crypto to Buy as Saylor & Crypto Execs Meet in US Treasury Council appeared on BitcoinEthereumNews.com. Michael Saylor and a group of crypto executives met in Washington, D.C. yesterday to push for the Strategic Bitcoin Reserve Bill (the BITCOIN Act), which would see the U.S. acquire up to 1M $BTC over five years. With Bitcoin being positioned yet again as a cornerstone of national monetary policy, many investors are turning their eyes to projects that lean into this narrative – altcoins, meme coins, and presales that could ride on the same wave. Read on for three of the best crypto projects that seem especially well‐suited to benefit from this macro shift:  Bitcoin Hyper, Best Wallet Token, and Remittix. These projects stand out for having a strong use case and high adoption potential, especially given the push for a U.S. Bitcoin reserve.   Why the Bitcoin Reserve Bill Matters for Crypto Markets The strategic Bitcoin Reserve Bill could mark a turning point for the U.S. approach to digital assets. The proposal would see America build a long-term Bitcoin reserve by acquiring up to one million $BTC over five years. To make this happen, lawmakers are exploring creative funding methods such as revaluing old gold certificates. The plan also leans on confiscated Bitcoin already held by the government, worth an estimated $15–20B. This isn’t just a headline for policy wonks. It signals that Bitcoin is moving from the margins into the core of financial strategy. Industry figures like Michael Saylor, Senator Cynthia Lummis, and Marathon Digital’s Fred Thiel are all backing the bill. They see Bitcoin not just as an investment, but as a hedge against systemic risks. For the wider crypto market, this opens the door for projects tied to Bitcoin and the infrastructure that supports it. 1. Bitcoin Hyper ($HYPER) – Turning Bitcoin Into More Than Just Digital Gold The U.S. may soon treat Bitcoin as…
Share
BitcoinEthereumNews2025/09/18 00:27