FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Ethereum EVM: Opcode Execution, Storage, and Gas

Trace EVM calldata, stack, memory, and storage operations to understand gas charges, reverts, and the state changes committed by a transaction.

Freshness: current•10 min read•Distributed AI Platforms
Full Technical Reference Document

Mental model

The Ethereum Virtual Machine is a deterministic stack machine: it decodes transaction calldata, executes bytecode instruction by instruction, and charges gas before an operation can consume unbounded work. Each frame has a bounded 1024-item stack and expands linear memory as needed; persistent account storage lives in a trie, so memory disappears after the call while committed storage changes update world state.

Theory

From calldata to an execution frame

For a contract call, the transaction's data bytes are supplied to the EVM as calldata. Under the Solidity ABI, the first four bytes are the selector derived from the Keccak-256 hash of the canonical function signature; the remaining bytes encode arguments. Static values occupy 32-byte words. Dynamic values such as strings and arrays use offset words that point to length-and-data regions, so a decoder must validate offsets and lengths before using them.

The EVM begins a message call with a program counter, a 256-bit word stack, linear memory, a gas allowance, and access to the current state. Opcodes pop and push words: CALLDATALOAD reads a 32-byte window from calldata, PUSH places a constant on the stack, ADD consumes operands and pushes a result, and JUMPI changes control flow when its condition is nonzero. A stack can contain at most 1024 words. An underflow, invalid jump destination, invalid opcode, or out-of-gas condition halts the frame exceptionally.

Memory is a byte-addressed scratch area that starts empty and grows when an instruction touches a higher offset. It is not the same as Solidity's persistent storage: memory is local to a call frame, while a storage write changes an account's key/value state and is reflected in the post-transaction state root if the frame succeeds. calldata is read-only input and avoids copying dynamic arguments unless the program needs a mutable memory representation. Solidity's source types are hints; compiler output determines which actual operations execute.

Memory expansion and worked calculation

Let ww be the highest memory size reached, rounded up to 32-byte words. The EVM's memory expansion schedule is quadratic at large sizes:

Cmem(w)=3w+⌊w2512⌋,ΔC=Cmem(wnew)−Cmem(wold)C_{\text{mem}}(w)=3w+\left\lfloor\frac{w^2}{512}\right\rfloor,\qquad \Delta C=C_{\text{mem}}(w_{\text{new}})-C_{\text{mem}}(w_{\text{old}})

Here, CmemC_{\text{mem}} and ΔC\Delta C are gas units, and ww is a count of 32-byte words. If a copy first writes 64 bytes at offset zero, memory grows from zero to two words: Cmem(2)=6C_{\text{mem}}(2)=6 gas. A later write through byte 95 expands it to three words: Cmem(3)=9C_{\text{mem}}(3)=9, so that second expansion adds 3 gas. These figures count memory expansion only. The copy opcode's own base and per-word charge, calldata access, stack work, and any storage operations add more.

This schedule explains why a small offset mistake can be expensive when it pushes the end of a copy into a new word. At larger allocations, the quadratic term raises the marginal cost; at 256 words, expansion totals 3(256)+⌊2562/512⌋=8963(256)+\lfloor 256^2/512\rfloor=896 gas. Gas is an execution budget, not a CPU-time estimate: the protocol assigns charges to operations so that block execution is bounded across clients.

Persistent storage and gas accounting

Solidity lays out storage slots deterministically from the contract's declarations. A mapping value is not stored in a packed array: its slot is derived by hashing the padded key together with the mapping's declared slot. The EVM loads and stores 32-byte words at that derived location. The price of a storage operation depends on the fork's gas schedule and the slot's access and original/current/new values, so measuring one test state does not predict every transaction. Repeated reads in one transaction may be warm after the first access, while the first access is charged differently.

Gas is charged per opcode, with additional charges for memory expansion, hashing, logs, and external calls. If an instruction exceeds the remaining budget, the frame fails; an included top-level transaction can still consume the supplied execution gas and advance its sender nonce even though its call-level state changes are reverted. eth_estimateGas simulates against a particular node state and block context. It is a sizing hint, not a fixed price or a proof that the same call will succeed when included.

Decode ABI selector and arguments
Load words onto the EVM stack
Expand memory for copied bytes
Read or write persistent storage
Commit gas use and successful state changes
Conceptual teaching model synthesized from:ethereum-yellow-paper,ethereum-execution-specs,ethereum-dev-docs

Implementation example

This small Solidity contract has one pure calldata loop and one persistent mapping update. Compile it with a pinned solc version and inspect the generated opcodes: the compiler can change instruction selection across versions even when the source-level result stays the same.

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
​
contract GasTraceLedger {
mapping(address => uint256) public credits;
​
error ZeroAccount();
error BatchTooLarge();
​
function sum(uint256[] calldata values) external pure returns (uint256 total) {
if (values.length > 64) revert BatchTooLarge();
for (uint256 i; i < values.length; ++i) {
total += values[i];
}
}
​
function addCredit(address account, uint96 amount) external {
if (account == address(0)) revert ZeroAccount();
credits[account] += amount;
}
}

Failure modes and misconceptions

An eth_call that succeeds does not reserve state or gas for a later transaction. Between simulation and inclusion, a mapping value may change, a different branch may execute, or another transaction may consume the sender's nonce. Re-run the call against recent state, set a bounded gas limit with headroom, and verify the receipt and resulting state after inclusion.

Do not add opcodes' published gas figures as if they were a complete quote. Memory expansion is incremental; storage costs depend on the access pattern and values; nested calls have forwarding rules; and the transaction has intrinsic costs before contract bytecode starts. A revert rolls back state for the failed call but does not make the transaction free. A source-level loop can also become unbounded if its input length is not limited, eventually making a method unusable within a block's gas capacity.

Trade-offs

Keeping arrays in calldata avoids an initial memory copy and makes input immutable, but repeated access or a library interface may require an explicit copy. Batching amortizes transaction overhead and can process related state together, while increasing worst-case gas and making one failure revert the whole batch. Smaller batches improve per-call reliability but may expose intermediate state or require idempotent continuation keys.

Assembly can reduce overhead in a measured hot path, but it bypasses Solidity's type and bounds checks and makes storage-slot reasoning harder. Prefer the compiler's clear representation until a pinned compiler build and representative traces show a material cost; then test the change against invariants, boundary inputs, and reverts.

Decision scenario

A payout contract estimates 1.8 million gas for a batch of 90 recipients, close to the product's per-transaction safety budget. Increasing the limit could fit on today's chain but would make the call sensitive to state-dependent storage costs and leave little room for future schedule changes. First measure cold and warm storage cases with the pinned compiler, then choose a smaller bounded batch or a resumable process with an explicit cursor and duplicate protection. Do not silently split an atomic payout if partial completion changes the business invariant.

Learning outcomes

  • Trace calldata and ABI offsets into EVM stack, memory, and storage operations.
  • Calculate the memory expansion component for a concrete byte range and distinguish it from full opcode gas.
  • Explain why storage access cost depends on state and transaction history.
  • Use compiler output, estimates, receipts, and post-state checks to review a gas-sensitive contract.
Reflect before revealing the guide

Prerequisites & Related Concepts (1)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-502Blockchain & Decentralized AI Systems Engineer

Master blockchain execution, consensus, smart contract security, rollups, zkML verification, and safe on-chain AI agent protocols.

10 concepts~24h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next