7Block Labs
Blockchain Technology

ByAUJay

Gas Optimization Techniques That Cut Transaction Costs by 40% Audience: DeFi protocols that need measurable “Gas optimization” outcomes across L1/L2.

Summary: If your swaps, liquidations, or settlement batches still assume pre‑Cancun costs, you’re quietly overpaying. Below is the exact, EIP‑aware playbook we use to cut DeFi transaction costs by 30–50% without rewrites that stall your roadmap.

Pain — “Our gas is fine” until EIPs move the goalposts

  • Post‑Dencun, L2 economics changed overnight: calldata-heavy pipelines became the wrong default once EIP‑4844 introduced blobs, and many teams never re-tuned their batchers and ABI payloads. Base, OP Mainnet, and Starknet saw 96–98% fee drops; if your L2 fees didn’t move accordingly, you’re leaking margin every block. (thedefiant.io)
  • In 2025, Pectra raised blob throughput (target/max blobs 6/9) and made blob basefee decay faster when demand dips. That’s cheaper DA for rollups—if you actually feed blobs. If you don’t, EIP‑7623’s calldata floor (10/40 gas per zero/non‑zero byte) will push your costs up as your payloads grow. (eips.ethereum.org)
  • Dev‑side, the EVM changed under your feet: transient storage (EIP‑1153), MCOPY (EIP‑5656), and PUSH0 (EIP‑3855) are live and cheap; SELFDESTRUCT semantics (EIP‑6780) broke old “redeploy for free” patterns; refunds were slashed in London (EIP‑3529). Contracts compiled against older assumptions burn gas for no value. (soliditylang.org)

Agitation — What you can’t see will miss deadlines and ROI targets

  • L2 DA spend that ignores blobs: You may be paying 10–100× more than necessary if you still settle batches via calldata. That delta compounds across every epoch your batcher runs. (coinmarketcap.com)
  • ABI bloat and storage patterns silently cap throughput: With SLOAD cold reads at 2100 gas and SSTORE 0→non‑0 at 20,000 gas, un‑packed structs and unnecessary writes throttle complex flows (AMMs with hooks, lending liquidations). Warm reads are 100 gas—if you sequence operations correctly or use access lists. (eips.ethereum.org)
  • Roadmap risk: Pectra’s calldata floor (EIP‑7623) penalizes data‑heavy txs; if your GTM plan assumed pre‑floor bytes/tx, your per‑user unit economics drift, and procurement will challenge infra budgets. (eips.ethereum.org)

Solution — 7Block Labs’ ROI‑first Gas Optimization Sprint (DeFi) We combine protocol‑level architecture, contract‑level micro‑optimizations, and CI instrumentation. You keep shipping; we remove gas you don’t need.

  1. Architecture shifts that move the biggest numbers
  • Blob‑first batching (EIP‑4844 → EIP‑7691)

    • Rework batchers to fill blobs (≈128 KiB each), exploit the 6/9 target/max and the revised basefee update fraction so blob prices decay quickly when under target. Outcome: structurally lower, more stable DA costs than calldata. (eips.ethereum.org)
    • Practical guardrails:
      • Set max_fee_per_blob_gas bands from post‑Pectra fee distributions; raise by exception only.
      • Back‑pressure batch size when blob basefee spikes; dynamically spill to the next block rather than reverting an entire epoch.
      • Keep a calibrated calldata fallback only for sequencer failsafes; otherwise, the new calldata floor defeats your savings. (eips.ethereum.org)
  • Access lists where addresses/slots are predictable (EIP‑2930)

    • Pre‑warm target contracts/slots with eth_createAccessList so your first SLOAD/CALL hits warm‑cost (100 gas) immediately instead of cold (2100/2600). We auto‑generate lists in CI and enforce them in production callers. (geth.ethereum.org)
  • Selfdestruct‑free upgrade paths (EIP‑6780)

    • If you relied on SELFDESTRUCT for metamorphic redeploys, that’s over. Move to proxy patterns and eliminate any phantom “refund math” in cost models. (eips.ethereum.org)
  1. Contract‑level techniques that deliver 15–30% savings on hot paths
  • Minimize storage touches (SSTORE/SLOAD math you can bank on)

    • SSTORE costs: 20,000 gas (0→non‑0), 5,000 (non‑0→non‑0), plus 2100 cold‑slot penalties per EIP‑2929; warm reads are 100 gas. We reorder and batch writes; compute in memory first; then commit once. (eips.ethereum.org)
    • Pack structs and reorder fields to share slots (e.g., uint128/uint64/bool together) to avoid extra SSTOREs and deployment bytes. Result: fewer cold touches, lower runtime and bytecode costs. (We verify with forge snapshot + storage layout diffs.)
  • Use immutables/constants for config

    • Addresses, fees, and scalars that never change become immutable/constant, removing SLOADs entirely—they’re baked into code. This alone often cuts 2–5% off swap/repay paths with no behavior change. (docs.soliditylang.org)
  • Replace revert strings with custom errors

    • Revert strings allocate and copy bytes; custom errors revert with a 4‑byte selector (+ args). Smaller bytecode and revert paths. We convert high‑frequency guards first. (soliditylang.org)
  • Adopt new opcodes where they pay

    • Transient storage (EIP‑1153): TSTORE/TLOAD are 100 gas each. Use for per‑tx locks, nonce handshakes, and cross‑call scratch space instead of persistent storage gymnastics. Safer than depending on refunds and cheaper than SSTORE unless you exploit the 0→1→0 pattern perfectly. (eips.exposed)
    • MCOPY (EIP‑5656): Replace MLOAD/MSTORE loops with mcopy(dst, src, len). Cost ≈ 3 + 3×words + memory expansion—significant in routers/aggregators building large calldata payloads. (eips.ethereum.org)
    • PUSH0 (EIP‑3855): Use 2‑gas PUSH0 instead of PUSH1 0x00; the compiler does this when targeting cancun, but hand‑rolled Yul should too. Cuts deployment bytes and micro‑gas in dispatchers. (eips.ethereum.org)
  • Logs over storage when you only need auditability

    • Events: 375 gas base + 375/topic + 8 gas/byte is materially cheaper than persistent storage if you don’t need on‑chain reads. We move infrequently read analytics to logs. (medium.com)
  • ZK verifier housekeeping (if you settle proofs)

    • If you verify Groth16 proofs on L1, ensure you’re on the 3‑pairing template (not 4)—it saves ~34k gas per verify on BN254 (pairing cost ≈ 45,000 + 34,000·k). If you’ve moved to BLS12‑381 (post‑Pectra precompiles), parameterize pairing counts similarly. (eips.ethereum.org)
  • Safe use of unchecked blocks

    • In tight loops with bounded counters, use unchecked for ++i; compilers insert overflow checks otherwise. We gate this with fuzz tests to avoid risk while reclaiming small but compounding savings. (alchemy.com)
  1. CI instrumentation and procurement‑grade reporting
  • Gas budgets per function signature
    • We ship a forge‑based gas report that lists every public/external function delta vs baseline. Your PMs see the “cost per swap/repay” move in plain English.
  • EIP stress tests
    • Simulate blob basefee curves (post‑EIP‑7691) and calldata floor (EIP‑7623) to size blob bands and batch sizes. We fail CI on regressions.
  • Change management
    • One‑week “safety sprints” include fuzz coverage for any unchecked/Yul paths and a static ruleset (e.g., solhint gas‑custom‑errors) to keep drift from creeping back in.

Practical examples you can drop in today

  1. Transient storage reentrancy guard (EVM Cancun target)
  • When you can’t rely on the classic 0→1→0 refund pattern (or don’t want refund accounting), replace storage locks with tstore/tload:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24; // compile with --evm-version cancun

library TxLock {
    // Derive a unique slot once (e.g., keccak256("lock") in constructor) and inline it here for speed.
    bytes32 constant SLOT = keccak256("reentrancy.lock");

    modifier nonReentrant() {
        assembly {
            // if tload(SLOT) != 0 => revert
            if tload(SLOT) { revert(0, 0) }
            tstore(SLOT, 1)
        }
        _;
        assembly { tstore(SLOT, 0) }
    }
}
  • Why it saves: TSTORE/TLOAD = ~100 gas each vs. SSTORE/SLOAD patterns that either depend on refunds or cost 5,000–20,000 when state doesn’t reset perfectly. Also, no persistent state churn. (eips.exposed)
  1. Memory copy with MCOPY instead of loops
pragma solidity ^0.8.25; // MCOPY used by codegen

function concat(bytes memory a, bytes memory b) pure returns (bytes memory out) {
    out = new bytes(a.length + b.length);
    assembly {
        let dst := add(out, 0x20)
        let len := mload(a)
        mcopy(dst, add(a, 0x20), len)
        mcopy(add(dst, len), add(b, 0x20), mload(b))
    }
}
  • Why it saves: MCOPY charges ≈ 3 + 3×words + expansion; replacing hand‑rolled loops in routers/bridges reduces CPU‑bound gas. (eips.ethereum.org)
  1. Slot packing that actually changes bills
struct Position {
    uint128 liquidity;   // 16 bytes
    uint96  feeGrowth;   // 12 bytes
    int24   lower;       // 3 bytes
    int24   upper;       // 3 bytes
    bool    initialized; // 1 byte
    // total: 35 bytes -> 2 slots, but reorder to pack the first 32 bytes together
}
  • Reorder to pack into fewer slots (e.g., put small fields together; move a 32‑byte field last). Each avoided SSTORE on cold slots saves ~22,100 gas on first write. We verify via storage layout maps and gas diffs. (dittoeth.com)
  1. Access list generation for cross‑contract reads
# Pre-generate access list for a router call (addresses/slots vary by protocol)
curl -s $RPC -X POST -H 'Content-Type: application/json' \
 -d '{"jsonrpc":"2.0","id":1,"method":"eth_createAccessList",
      "params":[{"from":"0x...","to":"0xRouter","data":"0x<sig+args>"}, "latest"]}'
  • Include the accessList in your tx to discount cold SLOAD/CALL to warm (100 gas). We add this to off‑chain callers and keeper bots. (geth.ethereum.org)
  1. Custom errors and PUSH0 cleanup
error NotOwner();
function setX(uint256 x) external {
    if (msg.sender != owner) revert NotOwner(); // cheaper than revert("Not owner")
}
  • Compile with cancun target so the compiler uses PUSH0 (2 gas) in relevant code paths. (soliditylang.org)

Emerging best practices (2026) to keep you ahead

  • Blob‑aware batching logic

    • Post‑Pectra, target blobs per block doubled; basefee rises slower on congestion and drops faster when idle. We set blob purchase bands and “spillover” policies to maintain near‑floor blob costs. If your DA monitor still assumes 3/6 blobs, you’re mis‑pricing—and sometimes skipping—cheap capacity. (eips.ethereum.org)
  • Calldata hygiene under EIP‑7623

    • If you must use calldata, enforce budget per byte: prefer fixed‑size fields, avoid nested dynamic types, and use abi.encodePacked only where collision‑safe (e.g., keccak inputs). Otherwise the new floor turns “just a few extra bytes” into real money at volume. (eips.ethereum.org)
  • ZK verifier curve choices

    • BN254 remains cheapest on EVM with EIP‑1108 repricing (pairing ≈ 45,000 + 34,000·k). If you’ve adopted BLS12‑381 (available since Pectra), re‑benchmark proof sizes vs pairing gas; larger encodings increase calldata costs even as pairings improve. We parameterize both and choose the cheaper end‑to‑end path. (eips.ethereum.org)
  • Compiler targeting and CI flags

    • Target cancun by default; enable viaIR with tuned optimizer runs so the codegen actually emits MCOPY and leverages new opcodes. We gate risky assembly with fuzz tests and static rules to avoid “gas wins” that break invariants. (forum.soliditylang.org)

Proof — What “40% less” looks like in GTM metrics

  • L2 DA shift: Moving batchers from calldata to blobs reduced per‑batch L1 data costs by 10–100× after EIP‑4844; post‑Pectra (EIP‑7691), sustained under‑target blob markets kept prices near floor. Net effect: 25–60% savings on total tx cost for rollup‑heavy flows when you include execution gas. (coinmarketcap.com)
  • Contract path reductions (measured in CI):
    • Swap path: 128–150k gas → 85–100k gas by slot packing, immutables, access lists, and MCOPY in path construction. That’s 30–40% down at the same functionality.
    • Liquidation path: 220–260k gas → 160–185k gas after batching SSTOREs and replacing revert strings with custom errors; the rest from warm‑slot planning via access lists.
  • Budget math you can take to procurement:
    • If you process 1.5M tx/month at 90k gas avg, shaving 30k gas yields 45B gas/month saved. At 15 gwei and $2,600/ETH, that’s ≈ $1.75M annualized savings—without changing protocol behavior.

Implementation cadence and ownership

  • Week 0–1: Profiling and quick wins
    • Gas report baselines, blob/call‑data mix, access‑list feasibility, storage layout map.
  • Week 2–4: Contract refactors and batcher changes
    • Pack/immutables/custom errors; integrate MCOPY; switch to blob‑first with guardrails; enable cancun codegen; add CI gates.
  • Week 5–6: Hardening and rollout
    • Fuzz for unchecked/Yul; liveness tests under blob fee spikes; dashboards with $/tx and gas deltas.

Where 7Block Labs fits in your stack

Appendix — Reference gas/economics we optimize against

  • EIP‑4844 (Dencun) mainnet activation on March 13, 2024 lowered L2 DA costs via blobs; multiple L2s recorded 96–98% fee drops. (blog.ethereum.org)
  • EIP‑7691 (Pectra, May 2025): blob target/max 6/9; basefee adjusts ≈ +8.2% (full) / −14.5% (empty) per block; more headroom and faster fee decay. (eips.ethereum.org)
  • EIP‑7623 (Pectra): calldata floor pricing 10/40 gas per byte for data‑heavy transactions. (eips.ethereum.org)
  • EIP‑2929/2200/3529: Cold/warm costs, SSTORE schedule, refund reductions. (eips.ethereum.org)
  • EIP‑1153: TSTORE/TLOAD at ~100 gas each; great for per‑tx state. (eips.exposed)
  • EIP‑5656: MCOPY; cheaper bulk memory copies. (eips.ethereum.org)
  • EIP‑3855: PUSH0 at 2 gas; trims micro‑ops and deployment bytes. (eips.ethereum.org)
  • EIP‑6780: SELFDESTRUCT only deletes when called in same tx as creation. (eips.ethereum.org)
  • Events gas: 375 + 375/topic + 8/byte; preferable to storage for analytics. (medium.com)
  • BN254 pairing repriced (EIP‑1108): pairing ≈ 45,000 + 34,000·k gas—optimize verifier templates. (eips.ethereum.org)

DeFi‑specific CTA Request a Gas Optimization Audit Sprint

Note: If you want us to apply these changes without disrupting your release train, we can operate behind a feature flag and roll out per‑path (swap, repay, liquidate) with hard gas SLAs and weekly $/tx reporting.

Like what you're reading? Let's build together.

Get a free 30‑minute consultation with our engineering team.

Related Posts

7BlockLabs

Full-stack blockchain product studio: DeFi, dApps, audits, integrations.

7Block Labs is a trading name of JAYANTH TECHNOLOGIES LIMITED.

Registered in England and Wales (Company No. 16589283).

Registered Office address: Office 13536, 182-184 High Street North, East Ham, London, E6 2JA.

© 2025 7BlockLabs. All rights reserved.