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

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.

Sorumluluk Reddi: Bu sitede yeniden yayınlanan makaleler, halka açık platformlardan alınmıştır ve yalnızca bilgilendirme amaçlıdır. MEXC'nin görüşlerini yansıtmayabilir. Tüm hakları telif sahiplerine aittir. Herhangi bir içeriğin üçüncü taraf haklarını ihlal ettiğini düşünüyorsanız, kaldırılması için lütfen service@support.mexc.com ile iletişime geçin. MEXC, içeriğin doğruluğu, eksiksizliği veya güncelliği konusunda hiçbir garanti vermez ve sağlanan bilgilere dayalı olarak alınan herhangi bir eylemden sorumlu değildir. İçerik, finansal, yasal veya diğer profesyonel tavsiye niteliğinde değildir ve MEXC tarafından bir tavsiye veya onay olarak değerlendirilmemelidir.

Ayrıca Şunları da Beğenebilirsiniz

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…
Paylaş
BitcoinEthereumNews2025/09/18 00:09
Ethereum Price Prediction: ETH Targets $10,000 In 2026 But Layer Brett Could Reach $1 From $0.0058

Ethereum Price Prediction: ETH Targets $10,000 In 2026 But Layer Brett Could Reach $1 From $0.0058

Ethereum price predictions are turning heads, with analysts suggesting ETH could climb to $10,000 by 2026 as institutional demand and network upgrades drive growth. While Ethereum remains a blue-chip asset, investors looking for sharper multiples are eyeing Layer Brett (LBRETT). Currently in presale at just $0.0058, the Ethereum Layer 2 meme coin is drawing huge [...] The post Ethereum Price Prediction: ETH Targets $10,000 In 2026 But Layer Brett Could Reach $1 From $0.0058 appeared first on Blockonomi.
Paylaş
Blockonomi2025/09/17 23:45
IP Hits $11.75, HYPE Climbs to $55, BlockDAG Surpasses Both with $407M Presale Surge!

IP Hits $11.75, HYPE Climbs to $55, BlockDAG Surpasses Both with $407M Presale Surge!

The post IP Hits $11.75, HYPE Climbs to $55, BlockDAG Surpasses Both with $407M Presale Surge! appeared on BitcoinEthereumNews.com. Crypto News 17 September 2025 | 18:00 Discover why BlockDAG’s upcoming Awakening Testnet launch makes it the best crypto to buy today as Story (IP) price jumps to $11.75 and Hyperliquid hits new highs. Recent crypto market numbers show strength but also some limits. The Story (IP) price jump has been sharp, fueled by big buybacks and speculation, yet critics point out that revenue still lags far behind its valuation. The Hyperliquid (HYPE) price looks solid around the mid-$50s after a new all-time high, but questions remain about sustainability once the hype around USDH proposals cools down. So the obvious question is: why chase coins that are either stretched thin or at risk of retracing when you could back a network that’s already proving itself on the ground? That’s where BlockDAG comes in. While other chains are stuck dealing with validator congestion or outages, BlockDAG’s upcoming Awakening Testnet will be stress-testing its EVM-compatible smart chain with real miners before listing. For anyone looking for the best crypto coin to buy, the choice between waiting on fixes or joining live progress feels like an easy one. BlockDAG: Smart Chain Running Before Launch Ethereum continues to wrestle with gas congestion, and Solana is still known for network freezes, yet BlockDAG is already showing a different picture. Its upcoming Awakening Testnet, set to launch on September 25, isn’t just a demo; it’s a live rollout where the chain’s base protocols are being stress-tested with miners connected globally. EVM compatibility is active, account abstraction is built in, and tools like updated vesting contracts and Stratum integration are already functional. Instead of waiting for fixes like other networks, BlockDAG is proving its infrastructure in real time. What makes this even more important is that the technology is operational before the coin even hits exchanges. That…
Paylaş
BitcoinEthereumNews2025/09/18 00:32