Fatskills
Practice. Master. Repeat.
Study Guide: Blockchain and Web3 Development: Layer 2 and Scalability Layer 2 Solutions Optimistic Rollups ZKRollups Sidechains
Source: https://www.fatskills.com/cryptocurrency-bitcoin-blockchain-and-more/chapter/blockchain-and-web3-development-blockchain-and-web3-development-layer-2-and-scalability-layer-2-solutions-optimistic-rollups-zkrollups-sidechains

Blockchain and Web3 Development: Layer 2 and Scalability Layer 2 Solutions Optimistic Rollups ZKRollups Sidechains

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~6 min read

What This Is

Layer 2 solutions are protocols that sit on top of the Ethereum base layer (L1) to move most of the work off‑chain while still inheriting its security guarantees. By batching many transactions into a single proof or by posting them to a separate chain, they cut fees dramatically and boost throughput, making everyday DeFi actions—like a Uniswap swap, an NFT mint, or a DAO vote—feel instant and cheap.


Key Terms & Code Snippets

  • Optimistic Rollup: A scaling method that assumes transactions are valid (“optimistic”) and only runs a fraud‑proof if someone challenges the batch. Example: Arbitrum’s L2_Sequencer contract posts calldata to L1.
  • ZK‑Rollup: A scaling method that generates a succinct zero‑knowledge proof (SNARK/STARK) for each batch, proving correctness without revealing data. Example: zkSync’s BatchVerifier contract verifies a proof on L1.
  • Sidechain: An independent blockchain that uses its own validator set and consensus, but periodically bridges assets to Ethereum (e.g., Polygon’s PoS chain).
  • Fraud Proof: A dispute‑resolution game where a challenger submits evidence that a rollup batch is invalid; the challenger is rewarded if correct.
  • Validity Proof: The cryptographic proof (SNARK/STARK) that a batch of transactions is correct; it is submitted to L1 and verified by a verifier contract.
  • Data Availability (DA): Guarantees that all transaction data needed to reconstruct state is published on‑chain (or via a DA service) so anyone can challenge or replay.
  • Bridge Contract (Solidity): A minimal contract that locks ERC‑20 tokens on L1 and emits an event for the L2 to mint a corresponding token.

```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.24;

contract L1Bridge {
event Locked(address indexed token, address indexed sender, uint256 amount, bytes32 indexed l2Recipient);
function lock(address token, uint256 amount, bytes32 l2Recipient) external {
IERC20(token).transferFrom(msg.sender, address(this), amount);
emit Locked(token, msg.sender, amount, l2Recipient);
} } ```


  • EVM Compatibility Layer: A piece of software (e.g., OP‑Stack, zkEVM) that lets existing Solidity contracts run unchanged on a rollup, preserving the same bytecode semantics.
  • Batch Submitter (JS/Hardhat): A script that gathers signed L2 txs, creates a rollup batch, and posts it to the L1 verifier.

js // hardhat script – submit a batch to Optimism’s L1 contract const { ethers } = require("hardhat"); async function main() {
const batch = ethers.utils.defaultAbiCoder.encode(
["bytes[]"], [signedTxs]
);
const verifier = await ethers.getContractAt("OptimismVerifier", L1_VERIFIER);
const tx = await verifier.submitBatch(batch);
await tx.wait();
console.log("Batch submitted, hash:", tx.hash); } main();


  • Gas‑Price Oracle (L2): A contract that publishes the current L2 gas price so wallets can estimate fees; often derived from the L1 base fee plus a scaling factor.


Step‑by‑Step / Process Flow

  1. Write the L2‑ready contract – keep it pure Solidity (no selfdestruct, no blockhash reliance). Test locally with an EVM‑compatible rollup emulator (e.g., @eth-optimism/plugins or zksync-dev).
  2. Compile with Hardhat – set solidity: { version: "0.8.24", settings: { optimizer: { enabled: true, runs: 200 }}}.
  3. Deploy to the L2 testnet – use the rollup’s RPC endpoint (https://goerli.optimism.io or https://testnet.zksync.io). Example with Ethers.js:

js
const provider = new ethers.JsonRpcProvider(L2_RPC);
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);
const factory = new ethers.ContractFactory(abi, bytecode, wallet);
const l2Contract = await factory.deploy();
await l2Contract.waitForDeployment();
console.log("Deployed to L2 at", await l2Contract.getAddress());


  1. Bridge assets – lock ERC‑20 on L1 via the bridge contract, then call the L2 counterpart’s mint (or rely on the rollup’s automatic token bridge).
  2. Interact from the dApp – use wagmi/ethers with the L2 provider; the UI shows “≈ 0.001 ETH” fee instead of “≈ 0.03 ETH”.
  3. Monitor fraud/validity proofs – subscribe to the L1 verifier’s BatchSubmitted and ChallengeResolved events to ensure your batch is accepted.

Common Mistakes

  • Mistake: Assuming L2 gas costs are the same as L1.
    Correction: Always query the L2 gas‑price oracle; L2 gas is cheaper per unit but the total cost depends on batch size and proof verification.

  • Mistake: Hard‑coding block.timestamp for time‑sensitive logic.
    Correction: Rollups may reorder batches, so use block.number or a deterministic epoch supplied by the rollup’s L2Block contract.

  • Mistake: Forgetting to enable data availability when using a sidechain.
    Correction: Choose a sidechain that publishes calldata on L1 (e.g., Polygon’s PoS bridge) or run a DA service like Celestia; otherwise users cannot challenge fraudulent state.

  • Mistake: Deploying a contract that relies on tx.origin for auth.
    Correction: Use msg.sender and role‑based access (OpenZeppelin AccessControl) because rollup batches can be relayed by a sequencer, breaking tx.origin expectations.

  • Mistake: Ignoring the challenge window (e.g., 7 days on Optimism).
    Correction: Build UI alerts that warn users when a batch is still under dispute; premature withdrawals can be reverted by a successful fraud proof.


Blockchain Developer Interview / Practical Insights

  1. Optimistic vs. ZK Rollup: Interviewers love to ask you to compare the two. Emphasize that Optimistic rollups rely on fraud proofs and have a challenge period, while ZK rollups provide instant finality via validity proofs but require heavy off‑chain proving.
  2. call vs. delegatecall: Explain that delegatecall runs the callee’s code in the caller’s storage context—critical when building proxy patterns on L2 where upgradeability must preserve state.
  3. ERC‑20 vs. ERC‑777 on L2: Show you know that ERC‑777’s hooks increase gas usage; on a rollup you might prefer the simpler ERC‑20 to keep batch size low.
  4. Bridge Security: Auditors will ask you to walk through the lock‑mint‑burn flow and identify the “single‑point‑of‑failure” (the L1 bridge contract). Demonstrate knowledge of “canonical token” patterns and how to mitigate replay attacks with a unique nonce.

Quick Check Questions

  1. Scenario: A user submits a transaction to an Optimistic rollup, but the sequencer is offline for 2 days. What happens to the user’s transaction?
    Answer: It stays in the mempool until the sequencer resumes; the rollup’s challenge window only starts after the batch is posted, so the user’s tx isn’t at risk of being censored permanently.

  2. Scenario: Your L2 contract uses block.timestamp to enforce a 24‑hour voting period. A batch is delayed by 6 hours. Does the voting period extend automatically?
    Answer: No. block.timestamp reflects the block’s time, not real‑world elapsed time; delayed batches shorten the effective voting window, so you should base periods on batch numbers or a rollup‑provided epoch.

  3. Scenario: You lock 100 USDC on L1 and receive 100 USDC on a ZK‑Rollup, but later the proof verification fails. What is the state of the L1 lock?
    Answer: The L1 lock remains unreleased (still held by the bridge) because the rollup batch was rejected; users can retry the bridge after the issue is resolved.


Last‑Minute Cram Sheet (10 one‑liners)

  1. ⚠️ Never trust tx.origin for auth—sequencers can forward calls, breaking the origin chain.
  2. Optimistic rollups have a challenge window (usually 7 days) before finality; ZK rollups are final instantly.
  3. Validity proofs are verified by a single on‑chain verifier contract; keep its bytecode minimal to reduce gas.
  4. Data availability is the Achilles’ heel of sidechains; always confirm calldata is posted on L1.
  5. Gas‑optimizing tip: Use unchecked {} for simple loops when you know overflow is impossible (Solidity 0.8+).
  6. Compiler version: Most rollup SDKs target Solidity 0.8.24; avoid older versions because they lack built‑in overflow checks.
  7. ERC‑20 vs. ERC‑777: ERC‑777 adds hooks → higher calldata size → larger rollup batches → higher fees.
  8. Bridge pattern: lock → emit event → L2 listener → mint; always include a nonce to prevent replay.
  9. EVM compatibility: zkEVMs aim for 1:1 bytecode equivalence; however, some opcodes (e.g., SELFDESTRUCT) are disabled.
  10. Fraud‑proof incentive: Challenger must post a bond; if they win they claim the bond plus a reward, which discourages frivolous disputes.


ADVERTISEMENT