Non-FictionInformativeEducational

Advanced Solidity and Gas Optimization eBook

A Coursebook on Advanced Solidity and Gas Optimiza

by Jeffrey Dennise

  • English
  • 91 pages
  • 2026
  • SamEnrico

A Coursebook on Advanced Solidity and Gas Optimization

Formats

Free sample

Chapter 1: The Opcode Mindset...--–- Every Solidity developer remembers the moment of confusion. You write two contracts that seem identical. Both store a number. Both update that number with a function. Both are compiled with the same optimizer settings. Yet when you deploy them, one costs 150,000 gas and the other costs 220,000 gas. The difference is not a bug. It is not a compiler error. It is the EVM revealing its true nature—and most developers are not listening.This chapter is not an introduction. It is a recalibration. If you have written more than ten Solidity contracts, you already know the syntax of mappings, the rules of inheritance, and the shape of a modifier. What you likely do not know is why a seemingly trivial change—reordering two lines of code, swapping a variable’s type, or splitting a function into two—can save 30% of your transaction cost. The answer lies not in Solidity, but in the layer beneath: the Ethereum Virtual Machine and its language of opcodes.The central argument of this book, and the thesis of this opening chapter, is that gas optimization is not about writing clever Solidity. It is about aligning your high-level code with the low-level execution model of the EVM. Every time you write a line of Solidity, the compiler translates it into a sequence of opcodes—tiny operations like SLOAD (storage load), MSTORE (memory store), ADD (addition), and JUMP (control flow). Each opcode has a fixed gas cost, determined by the Ethereum protocol. Some opcodes cost 3 gas. Some cost 2,100 gas. One particular opcode, SLOAD when accessing a cold storage slot, costs 2,100 gas—700 times more than an MLOAD from memory. If you do not know which opcodes your Solidity generates, you cannot possibly predict your gas costs.This chapter strips away the abstractions. You will learn to read the opcode output of the Solidity compiler. You will understand why the 21,000 gas baseline exists and how calldata bytes add to it. You will see the difference between optimizing gas usage (execution units) and optimizing gas price (the fee market under EIP-1559)—a distinction most developers get wrong. And you will be introduced to the Solidity optimizer’s --via-ir flag, a tool that fundamentally changes how your code is compiled. By the end of this chapter, you will never look at a require statement or a loop the same way again.The EVM as a State Machine Before we can optimize gas, we must understand what gas pays for. The Ethereum Virtual Machine is a quasi-Turing-complete state machine. "Quasi-Turing-complete" means that while it can perform any computable operation in theory, it has a practical limitation: every operation costs gas, and if you run out of gas, execution halts. This design prevents infinite loops and denial-of-service attacks.The EVM’s state consists of several components:Storage: A persistent key-value store mapping 32-byte keys to 32-byte values. Storage is the only data that persists between transactions. It is also, by far, the most expensive resource.Memory: A byte-addressable, linear array that is wiped clean at the start of each transaction. Memory is cheap but has an expansion cost that grows quadratically beyond 724 bytes.Calldata: The read-only data sent with a transaction. Calldata is cheaper than memory and cannot be modified.The Stack: A last-in-first-out (LIFO) data structure limited to 1024 elements. Most arithmetic operations pop from and push to the stack.When you write uint256 public balance; in Solidity, you are instructing the compiler to reserve a 32-byte slot in storage. When you write balance += amount;, the compiler generates a sequence of opcodes that load the current value from storage (SLOAD), add the new amount (ADD), and store the result back (SSTORE). Each of these opcodes has a gas cost. The cost of SLOAD depends on whether the storage slot has been accessed before in the same transaction (warm vs. cold). The cost of SSTORE depends on whether the value is changing from zero to non-zero, non-zero to non-zero, or non-zero to zero.This is not trivia. These distinctions are the difference between a transaction that costs 50,000 gas and one that costs 200,000 gas.Opcodes and Their True Cost The foundation of gas optimization is knowing the cost of individual opcodes. Table 1.1 shows the most important opcodes for Solidity developers, with their gas costs after the London fork (EIP-1559) and the Berlin fork (EIP-2929), which introduced the warm/cold distinction.Table 1.1: Critical Opcode Costs Opcode Operation Gas Cost (Warm)Gas Cost (Cold)MLOADLoad from memory3N/AMSTOREStore to memory3N/ASLOADLoad from storage1002,100SSTOREStore to storage (non-zero to non-zero)10020,100SSTOREStore to storage (zero to non-zero)22,10022,100ADD/SUB/MULArithmetic5N/ADIV/SDIVDivision5N/AKECCAK256Hash computation30 + 6 per word N/ACALLExternal call700 + (additional costs)2,600DELEGATECALLDelegate call700 + (additional costs)2,600JUMPUnconditional jump8N/AJUMPIConditional jump10N/AThe warm/cold distinction is critical. When you first access a storage slot in a transaction, it is "cold" and costs 2,100 gas for SLOAD or 20,100 gas for SSTORE (if changing a non-zero to another non-zero). Subsequent accesses to the same slot in the same transaction are "warm" and cost only 100 gas for SLOAD or 100 gas for SSTORE. This means that reading the same storage variable twice in a function is dramatically cheaper than reading two different variables once each—if the second read of the same variable is warm.Consider this example:solidity Copy Download// Expensive: two cold reads

uint256 a = balance Of[user1]; uint256 b = balance Of[user2];

// Cheaper: one cold read, one warm read uint256 a = balance Of[user1]; uint256 b = balance Of[user1];The first version pays 2,100 + 2,100 = 4,200 gas for the two SLOADs. The second version pays 2,100 + 100 = 2,200 gas. This is not a theoretical curiosity—it is a pattern you will use repeatedly in optimized contracts.The 21,000 Gas Baseline Every transaction that modifies the blockchain pays a baseline cost of 21,000 gas before any opcodes are executed. This baseline covers the cost of signature verification, nonce increment, and the basic overhead of including the transaction in a block. If you send a transaction that does nothing—a simple ETH transfer with an empty payload—you will pay exactly 21,000 gas plus the cost of the calldata.Calldata bytes have their own cost structure:Zero bytes (0x00) cost 4 gas per byte.Non-zero bytes (anything else) cost 16 gas per byte.This asymmetry exists because zero bytes are compressible. The Ethereum protocol can store them more efficiently. Therefore, if you are sending large amounts of calldata, you can save gas by packing your data to include as many zero bytes as possible. For example, encoding a uint256 value of 1 uses 31 zero bytes and 1 non-zero byte, costing (31 × 4) + (1 × 16) = 140 gas for the calldata. Encoding a uint256 value of 2^255 (a number with all bytes non-zero) costs 32 × 16 = 512 gas.This principle extends to function selectors and arguments. The first four bytes of calldata are the function selector, derived from the function signature. Those four bytes are almost never zero, so they cost 64 gas. After that, each argument is padded to 32 bytes. If you can design your functions to accept values that are small and naturally zero-padded, you reduce calldata costs.Gas Usage…

This is the end of the free sample. Get the eBook to keep going. Buy now

About this book

A Coursebook on Advanced Solidity and Gas Optimization

Details

Author
Jeffrey Dennise
Publisher
SamEnrico
Language
English
Genre
Non-Fiction, Informative, Educational
Released
2026-06-02
Pages (approx.)
91
Available as
eBook, Audiobook

Read better in the ZLOADR app

Your eBooks on your phone or tablet. Sign in with your SamEnrico account and start reading.

More by Jeffrey Dennise

See all

You may also like

See all