Bird
Raised Fist0
Blockchain / Solidityprogramming~10 mins

Gas optimization for L2 in Blockchain / Solidity - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Gas optimization for L2
Start Transaction
Check L2 Gas Costs
Apply Optimizations?
NoPay Full Gas
Yes
Use Batch Calls
Compress Data
Minimize Storage Writes
Calculate Reduced Gas
Submit Transaction
End
The flow shows starting a transaction on L2, checking gas costs, applying optimizations like batching and compression, then submitting with reduced gas.
Execution Sample
Blockchain / Solidity
function sendBatchTx(transactions) {
  let gasUsed = 0;
  for (let tx of transactions) {
    gasUsed += estimateGas(tx) * 0.8; // 20% optimization
  }
  return gasUsed;
}
This code estimates gas for a batch of transactions applying a 20% gas saving per transaction.
Execution Table
IterationTransactionEstimated GasOptimized Gas (80%)Running Total Gas
1tx1210001680016800
2tx2300002400040800
3tx3150001200052800
Exit---All transactions processed, total gas 52800
💡 All transactions processed with 20% gas optimization applied per transaction.
Variable Tracker
VariableStartAfter 1After 2After 3Final
gasUsed016800408005280052800
Key Moments - 2 Insights
Why do we multiply estimated gas by 0.8 in each iteration?
Multiplying by 0.8 applies a 20% gas saving per transaction, as shown in the 'Optimized Gas (80%)' column in the execution_table.
What happens if we don't batch transactions?
Without batching, each transaction pays full gas separately, increasing total gas cost. The execution_table shows savings by batching.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the running total gas after processing the second transaction?
A40800
B24000
C16800
D52800
💡 Hint
Check the 'Running Total Gas' column at iteration 2 in the execution_table.
At which iteration does the total gas used reach 52800?
AAfter 1
BAfter 2
CAfter 3
DExit
💡 Hint
Look at the 'Running Total Gas' column and find when it reaches 52800.
If the optimization factor changed from 0.8 to 0.9, how would the total gas after 3 transactions change?
AIt would decrease
BIt would increase
CIt would stay the same
DIt would be zero
💡 Hint
Higher factor means less gas saving, so total gas increases; check how 'Optimized Gas' is calculated in execution_table.
Concept Snapshot
Gas optimization on L2 reduces transaction costs by batching calls, compressing data, and minimizing storage writes.
Estimate gas per transaction, apply optimization factor (e.g., 0.8 for 20% savings), sum optimized gas.
Batching multiple transactions reduces overhead.
Compression lowers calldata size, saving gas.
Minimize storage writes as they are costly.
Submit optimized transaction to save gas fees.
Full Transcript
This visual execution traces gas optimization for Layer 2 blockchain transactions. Starting with zero gas used, each transaction's estimated gas is multiplied by 0.8 to apply a 20% saving. The running total gas accumulates these optimized values. After processing three transactions, total gas used is 52800, less than full cost without optimization. Key points include why the 0.8 factor applies savings, the benefit of batching transactions, and how changing optimization affects total gas. This helps beginners see step-by-step how gas optimization reduces costs on L2.

Practice

(1/5)
1. Which of the following is a common method to reduce gas costs on Layer 2 blockchains?
easy
A. Using loops with many iterations
B. Increasing the block size limit
C. Adding more storage variables to the contract
D. Using calldata instead of memory for function inputs

Solution

  1. Step 1: Understand calldata vs memory

    Calldata is cheaper than memory because it is read-only and does not require copying data.
  2. Step 2: Identify gas saving method

    Using calldata for function inputs reduces gas compared to memory or storage.
  3. Final Answer:

    Using calldata instead of memory for function inputs -> Option D
  4. Quick Check:

    Calldata is cheaper than memory [OK]
Hint: Choose calldata for inputs to save gas on L2 [OK]
Common Mistakes:
  • Thinking increasing block size reduces gas
  • Assuming more storage variables save gas
  • Using loops without optimization
2. Which Solidity syntax correctly declares a function parameter to use calldata for gas optimization on L2?
easy
A. function foo(string memory data) external {}
B. function foo(string calldata data) external {}
C. function foo(string storage data) external {}
D. function foo(string data) external {}

Solution

  1. Step 1: Recall parameter data location keywords

    Solidity allows memory, storage, or calldata for reference types in parameters.
  2. Step 2: Identify calldata usage

    Calldata is specified explicitly as string calldata for external functions to save gas.
  3. Final Answer:

    function foo(string calldata data) external {} -> Option B
  4. Quick Check:

    Calldata keyword used correctly [OK]
Hint: Use 'calldata' keyword for external function parameters [OK]
Common Mistakes:
  • Using memory instead of calldata for external inputs
  • Omitting data location keyword
  • Using storage incorrectly in parameters
3. What will be the gas cost difference when using unchecked math in Solidity on L2 compared to normal math?
medium
A. Gas cost decreases because overflow checks are skipped
B. Gas cost increases due to extra checks
C. Gas cost stays the same
D. Gas cost is unpredictable

Solution

  1. Step 1: Understand unchecked math

    Unchecked math skips overflow and underflow checks, saving gas.
  2. Step 2: Compare gas costs

    Skipping checks reduces gas cost compared to normal safe math operations.
  3. Final Answer:

    Gas cost decreases because overflow checks are skipped -> Option A
  4. Quick Check:

    Unchecked math saves gas by skipping checks [OK]
Hint: Unchecked math skips checks, lowering gas [OK]
Common Mistakes:
  • Assuming unchecked math adds overhead
  • Believing gas cost is unchanged
  • Ignoring overflow risks
4. Given this Solidity snippet on L2, what is the main issue causing higher gas usage?
uint256 public count;
function increment() external {
  count = count + 1;
}
medium
A. Missing unchecked block for increment
B. Using public variable instead of private
C. Function should be view instead of external
D. No issue, code is optimal

Solution

  1. Step 1: Identify gas cost in arithmetic

    Normal addition includes overflow checks increasing gas.
  2. Step 2: Suggest unchecked usage

    Wrapping increment in unchecked { count += 1; } saves gas by skipping checks.
  3. Final Answer:

    Missing unchecked block for increment -> Option A
  4. Quick Check:

    Unchecked block reduces gas for safe increments [OK]
Hint: Use unchecked for simple increments to save gas [OK]
Common Mistakes:
  • Thinking public visibility affects gas here
  • Confusing external with view function
  • Assuming code is already optimized
5. You want to optimize a Layer 2 contract that stores multiple small variables. Which approach best reduces gas usage?
hard
A. Use dynamic arrays for all variables
B. Store each variable in separate storage slots for clarity
C. Pack multiple uint8 variables into a single uint256 storage slot
D. Avoid using calldata and always copy to memory

Solution

  1. Step 1: Understand storage slot packing

    Multiple small variables like uint8 can fit into one 256-bit slot, saving gas.
  2. Step 2: Compare storage strategies

    Separating variables wastes slots; dynamic arrays add overhead; calldata usage unrelated here.
  3. Final Answer:

    Pack multiple uint8 variables into a single uint256 storage slot -> Option C
  4. Quick Check:

    Storage packing reduces gas by slot sharing [OK]
Hint: Pack small vars into one slot to save gas [OK]
Common Mistakes:
  • Using separate slots wastes gas
  • Overusing dynamic arrays increases cost
  • Ignoring calldata benefits in storage