Abstract
This article summarizes the author’s practical engineering insights and architectural lessons derived from achieving a top-3 leaderboard finish in BuidlGuidl’s recent high-level ETH Techtree Solidity programming competition. It systematically explores four battle-tested runtime gas optimization techniques tailored for decentralized finance (DeFi) smart contracts: Lazy Accounting & Accumulator Patterns, Storage Slot Packing & Bitmasking, Batching & Execution Amortization, and Lightweight Temporal State Machines.
In addition, the article examines the foundational mechanics of EVM gas metering, the critical architectural drivers behind gas reduction, and why gas optimization serves as an indispensable competency for mid-to-senior Web3 developers. By conducting a rigorous analysis of low-level EVM opcode costs, state storage behavior (SLOAD/SSTORE), and memory manipulation dynamics, this work provides clear, actionable solutions to critical and pressing real-world engineering challenges—such as high user transaction fees, execution bottlenecks during peak mainnet congestion, protocol liquidity friction, and gas-driven security vulnerabilities in production smart contracts.
Introduction
In July 2026, the renowned cryptocurrency contract developer collective BuidlGuidl [1] launched a novel Solidity coding competition titled ETH Techtree [2]. As an official member of BuidlGuidl’s 23rd cohort, I was invited early to participate and quickly became engrossed in its innovative challenge design, rigorous scoring system, and fully open-source codebase. Through intense problem-solving and optimization, I grasped the core architecture required and ultimately achieved 3rd place on the global leaderboard (Fig 1).
While navigating the competition brought its share of trial and error, it yielded invaluable practical insights. This article serves to share those hard-earned learnings, converting competitive experience into generalized, on-chain gas optimization theory for DeFi developers.

A critical metric determining leaderboard rankings in this competition is runtime gas consumption—where every saved unit of gas directly improves an entry’s score. Novice developers often wonder why decentralized programs differ from traditional ones by incurring execution costs for every call.
This gas mechanism stems directly from the EVM’s Turing-complete architecture [3], designed to solve the Halting Problem and prevent infinite loops by forcing transactions to halt when gas runs out.
Every execution consumes gas based on specific opcode costs across three primary EVM resource layers (Fig 2): volatile Memory for temporary byte manipulation, read-only Calldata for input parameters, and persistent Storage, where state mutations via SLOAD (reading) and SSTORE (writing) incur the heaviest gas penalties.

Given that gas consumption is an inherent trade-off of EVM design, why is optimizing its footprint a non-negotiable skill for crypto contract engineers? Unchecked execution costs severely degrade on-chain performance and user experience across three critical vectors.
First, for User Experience, high gas creates direct financial friction that disincentivizes retail interactions.
Second, regarding Protocol Competitiveness, high-frequency DeFi operations like MEV arbitrage and liquidations rely on automated searcher bots [4]; unoptimized logic increases dynamic costs, causing liquidators to deprioritize the contracts and creating insolvency risks.
Finally, Ethereum imposes a strict Block Gas Limit (the maximum gas allocated per block), meaning inefficient functions risk hitting execution ceilings, stalling critical transactions, or getting priced out during severe network congestion.
This explains why elite engineering competitions like ETH Techtree use runtime gas efficiency as a core benchmark for senior on-chain developers. Apart from cost reduction, mastering EVM gas dynamics provides a vital defense against severe security vulnerabilities—such as unbounded loops triggering Out-of-Gas DoS attacks [5] that permanently stall crypto contract execution. Furthermore, gas optimization is not micro-tuning at all costs; it requires developers to strike a deliberate balance between low-level opcode efficiency and code maintainability, readability, and auditability.
Runtime Gas vs. Deployment Gas
Before diving into architectural optimizations, a critical distinction must be drawn between Deployment Gas and Runtime Gas. The former represents the one-time cost of deploying contract bytecode onto the blockchain—a metric largely determined by compiled bytecode size and basic compiler configurations.
In contrast, the latter one quantifies the dynamic execution cost generated every time a user invokes an on-chain function, driven by opcode execution paths and state mutations (SLOAD/SSTORE). This article—and top-tier engineering competitions like ETH Techtree—focuses exclusively on Runtime Gas. Optimizing Runtime Gas demands far deeper engineering expertise than bytecode reduction: it forces developers to confront the physical realities of the EVM execution pipeline, where every single opcode dictates deterministic execution throughput under stress.
Lazy Accumulator Accounting
In traditional staking, yield distribution, and token streaming systems, early architectures often relied on active, push-based loops. Under this paradigm, global updates—such as fee distributions—attempt to iterate over an array of all active user addresses to update balances individually. This naive approach creates severe scalability bottlenecks, driving gas consumption up linearly at $O(N)$ relative to the participant count $N$.
As user bases grow, executing a single update requires sweeping through hundreds of storage slots via repetitive SLOAD and SSTORE operations [6]. This active iteration rapidly inflates costs, pricing out users and ultimately triggering transaction reverts by exceeding the Block Gas Limit.
To eliminate $O(N)$ execution bottlenecks, high-performance structure pivots to a pull-based, lazy accounting framework using a precision-scaled accumulator [7]. Instead of actively pushing updates to individual accounts, the contract tracks a single global state variable—typically representing cumulative rewards or fees accumulated per staked unit. This global accumulator scales by a high-precision factor (such as $1text{e}18$) to prevent integer truncation errors during division.
When a distribution event occurs, the global accumulator updates in a single $O(1)$ operation. Individual user balance adjustments remain deferred until the user explicitly interacts with the contract—such as depositing, withdrawing, or claiming rewards.
During these user-initiated state changes, the system calculates pending entitlements lazily by comparing the current global accumulator against the user’s stored entry snapshot (“reward debt”) (Snippet 1). This approach decouples state updates from participant scale, transforming linear storage writes into deterministic, low-cost $O(1)$ calculations.
// Snippet 1
// Global accumulator update: O(1) execution cost
accRewardPerShare += (newRewards * 1e18) / totalStaked;
// Lazy user settlement upon interaction: O(1) execution cost
pendingReward = (userStaked * accRewardPerShare / 1e18) - userRewardDebt;
userRewardDebt = (userStaked * accRewardPerShare / 1e18);
Implementing this technique requires strict arithmetic discipline. Developers must order operations strictly—executing multiplications before divisions—to eliminate precision loss from integer rounding. From a gas perspective, this pattern replaces unbounded $O(N)$ execution loops with isolated, single-slot Storage writes. In large-scale distributors, updating reward states across thousands of users formerly required millions of gas units, frequently hitting block gas ceilings.
Under lazy accounting, global state transitions consume a flat cost of roughly 2,100 to 5,000 gas per distribution event, irrespective of the user base increasing [8]. By shifting computational burdens to individual claims, this structural optimization provides deterministic execution overhead, guaranteeing both system efficiency and transaction predictability even during intense network congestion.
Bitwise Storage Packing
The EVM operates on a 256-bit (32-byte) word structure, reading and writing storage in uniform slots. When state variables are defined without explicit layout planning, Solidity assigns each variable to a dedicated slot, incurring a severe “Cold Slot Tax”—where each fresh storage write (SSTORE) consumes up to 20,000 gas.
To eliminate this memory bloat, high-efficiency architecture employs a dual-tier packing strategy. The first tier leverages compiler-level struct alignment [9], ordering variables smaller than 32 bytes sequentially so Solidity automatically packs them into a single 256-bit word (e.g., combining an address with a uint96).
The second tier bypasses compiler boundaries through manual bitwise encoding; developers manipulate bitwise operators (<<, >>, &, |) to embed custom bit-fields or boolean bitmasks within a single uint256 [10]. By tightly compressing operational data—such as packing user balance, timestamp, and authorization flags into one slot—the on-chain program collapses multiple high-cost storage allocations into a single atomic word mutation (Fig 3).

The monetary impact of bitwise storage packing manifests primarily in state mutations. Consolidating four independent variables into a single 256-bit slot converts four cold SSTORE allocations (totaling up to 80,000 gas) into a single cold write followed by warm updates, capturing a net saving exceeding 70% in storage execution overhead.
However, this optimization introduces a subtle engineering trade-off: bitwise packing is an explicit exchange of CPU execution for state storage. Retrieving a packed field requires the EVM to execute additional bitwise operations—such as bitwise right shift (SHR) and bitmask AND (AND)—to extract and clean the target variable during execution.
While these computational opcodes carry nominal costs (3 gas each), aggressive bitwise packing in read-heavy access patterns can introduce cumulative overhead. Senior contract architects must evaluate access frequency: in write-heavy workflows like high-frequency order books or deposit registries, storage savings far outweigh throughput loss; conversely, for read-heavy governance or oracle querying contracts, over-packing can degrade read efficiency.
Calldata Assembly Optimization
EVM memory is linear and volatile, governed by a non-linear memory expansion gas cost that scales quadratically beyond 320 bytes allocated within an execution context. When complex data types—such as dynamic arrays, nested structs, or bytes—are passed into a function as memory, the EVM forcefully executes a CALLDATACOPY opcode to duplicate the payload into active memory.
This extra step triggers severe computational drag and memory expansion fees. High-performance contracts eliminate this friction by declaring read-only function parameters as calldata. Operating as an immutable, read-only slice of the transaction input, calldata enables zero-copy execution: opcodes like CALLDATALOAD or CALLDATACOPY [11] can read input values directly from the incoming transaction payload without instantiating memory slots.
For high-throughput endpoints processing bulk signature arrays or batch order updates, shifting from memory to calldata completely neutralizes memory allocation costs, cutting input processing gas by over 60% while preserving a zero-allocation runtime footprint across deep call stacks.
Beyond memory management, optimizing runtime opcodes requires bypassing the safety overhead built into high-level Solidity abstractions. Starting with version 0.8.0, Solidity automatically injects implicit overflow checks and array bounds validation into every iteration step, triggering a repetitive opcode penalty inside tight loops. Using inline assembly, developers can replace high-level array-indexed lookups with raw pointer arithmetic, with calldataload and add instructions to directly read parameter offsets without inducing compiler-generated branch checks (Snippet 2).
Complementing pointer manipulation, high-efficiency contracts replace legacy string-based assertions (require(condition, “error string”)) with Custom Errors (error CustomError()). In execution reverts, Custom Errors truncate the dynamic memory copy and ABI string encoding overhead down to a static 4-byte function selector [12]. This combined lower-level approach strip-mines redundant branch instructions and error-path allocations, maximizing throughput during both normal execution frames and revert branches.
// Snippet 2
// High-level array read (Includes implicit bounds/overflow checks)
uint256 val = dataArray[i];
// Yul raw pointer arithmetic (Zero bounds checks, minimal opcode friction)
assembly {
let offset := add(dataArray.offset, mul(i, 0x20))
val := calldataload(offset)
}
Transient Storage Flash Accounting
The introduction of EIP-1153 (Transient Storage) [13] via the Cancun upgrade established a third data location within the EVM, fundamentally altering the economics of inter-frame execution state. Traditional storage opcodes (SSTORE and SLOAD) read and modify the persistent Merkle Patricia Trie, triggering disk I/O operations and inducing costs ranging from 2,100 gas for warm slots up to 20,000 gas for cold allocations.
In contrast, transient storage operates on a temporary memory space that exists strictly within the context of a single transaction frame.
Controlled by two distinct EVM opcodes—TSTORE and TLOAD—it bypasses disk persistence entirely, pricing both reads and writes at a flat, nominal cost of 100 gas. Upon transaction completion, the transient state is automatically purged without writing to the global blockchain state, eliminating cold slot expansion penalties and storage refunds. By leveraging TSTORE to manage intermediate execution flags and temporary balances, contract architectures could reduce the heavy gas friction historically required to persist intra-transaction data across deeply nested call stacks.
This physical 100-gas mechanism serves as the foundation for Flash Accounting—a paradigm pioneered by protocols like Uniswap v4 that collapses multi-step transaction clearings into a single net settlement.
Under traditional settlements, executing complex multi-pool swaps or multi-hop liquidity routings forces immediate ERC-20 token transfers (transfer/transferFrom) at each intermediate hop. Each transfer invokes external contract calls and state writes, accumulating immense storage burden. This technique replaces real-time token movements with transient balance tracking. As operations execute, contracts record token credits and debits as transient deltas via TSTORE.
Only at transaction termination does the protocol verify that all transient deltas net to zero, performing a single, consolidated token transfer for the remaining net balance (Fig 4). By deferring physical asset movement to the final execution boundary, Flash Accounting truncates redundant inter-contract token transfers. Complex multi-hop trades that previously triggered thousands of gas in repeated state updates now run with flat memory-speed bookkeeping, achieving over 40% reduction in total transaction costs.

In addition to balance settlement, transient storage fundamentally upgrades contract security primitives—most notably reentrancy guards. Standard reentrancy locks depend on persistent storage mutations (SSTORE), executing expensive state updates solely to block reentrant entry points. Reimplementing this pattern with transient flags converts reentrancy validation into an ephemeral, in-memory check that automatically vanishes when the execution context resolves.
However, integrating EIP-1153 introduces critical threat vectors around context boundaries. Because transient storage persists across internal delegatecall invocations and nested external calls within the same transaction frame, an uncleared transient flag can inadvertently bleed into subsequent execution steps, causing unintended authorization locks or silent logic overrides.
To prevent cross-call state contamination, we must establish strict zero-state invariants in finally blocks or post-execution hooks that guarantee the storage is sanitized even when internal sub-calls revert or fail prematurely.
Bridging Optimization and Security
After discussing these four core optimization paradigms, I believe high-performance engineering requires looking beyond code efficiency and evaluating its broader operational impact. In my daily practice, contract security and systemic resilience have become essential competencies that every engineer must master.
This led me to reflect on a crucial question: how do these low-level gas optimization theories inspire and intersect with blockchain security?
Far from being mere tricks for contest leaderboard scoring, I have found that gas optimization techniques directly empower contract auditors to eliminate economic attack vectors. Minimizing runtime gas inherently mitigates Denial of Service risks [14].
By writing loops with lazy accumulators or EIP-1153 transient storage, we can neutralize SWC-128 vulnerabilities that lead to protocol fund freezing via block gas limit exhaustion. Furthermore, understanding the precise EVM gas dynamics of warm versus cold storage slots enables security researchers to evaluate protocol resistance against griefing attacks during peak network traffic.
On the flip side, when reviewing hyper-optimized codebases, I focus my auditing on the fragile state boundaries created by aggressive byte-level shortcuts. Bypassing compiler checks through assembly requires verifying that strict execution invariants remain intact. In memory-optimized functions, security analysis must confirm that scratch space writes preserve 0x40 memory pointer alignment, preventing subtle struct overwrites downstream.
When evaluating transient storage implementations, we should inspect teardown paths to ensure TSTORE flags clear deterministically before frame exit, blocking residual state leakage into sibling delegatecalls. Finally, assessing execution asymmetry during market volatility reveals whether high runtime overhead forces bots to abandon liquidation routines, resulting in bad debt. Every gas optimization must be paired with explicit safety checks, proving that runtime efficiency never sacrifices protocol invariants.
Conclusion
Mastering EVM gas dynamics is ultimately an exercise in structural balance. Through my research, security auditing, and practical application—such as securing third place on the ETH Tech Tree leaderboard—I have come to view runtime optimization not as a collection of isolated assembly tricks, but as a holistic discipline where low-level execution mechanics, economic design, and security invariants intersect.
As the EVM’s essence continues to evolve—from storage layout paradigms to transient frames—striking the right balance between gas efficiency and contract robustness remains critical. Achieving true runtime performance requires developer discipline: optimizing execution paths without sacrificing maintainability or safety. When approached with engineering rigor, gas-conscious design inherently yields cleaner code, lower transaction friction, and more sustainable architectures.
Reference
[2] https://www.ethtechtree.com
[3] https://ethereum.github.io/yellowpaper/paper.pdf
[4] https://docs.flashbots.net
[5] https://swcregistry.io/docs/SWC-128
[7] https://batog.info/papers/scalable-reward-distribution.pdf
[8] https://eips.ethereum.org/EIPS/eip-2200
[9] https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html
[10] https://docs.openzeppelin.com/contracts/4.x/api/utils#BitMaps
[11] https://docs.soliditylang.org/en/latest/assembly.html
[12] https://soliditylang.org/blog/2021/04/21/custom-errors/
[13] https://eips.ethereum.org/EIPS/eip-1153
[14] https://consensys.github.io/smart-contract-best-practices/attacks/denial-of-service/