🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Ethereum Development with Hardhat: Gas, EVM, and dApps

EthereumđŸŸĸ Free Lesson
Ethereum

The one-line mental model

Every Ethereum transaction is a small paid program run against replicated state: your job as a developer is to keep that program's storage writes few, its external calls safe, and your deployment keys out of the repository.

Prerequisites

  • !Solidity basics: contracts, functions, and modifiers
  • !JavaScript module syntax and async/await

What You'll Learn

  • 1Scaffold a Hardhat project with deterministic config and environment-driven secrets
  • 2Explain the difference between calldata, memory, storage, and stack in execution cost terms
  • 3Apply three concrete gas optimizations and measure them with the built-in tracer
  • 4Deploy to a testnet, verify source, and connect a browser wallet to the result

Scaffolding a workspace that will not embarrass you

The toolchain around Solidity is larger than the language itself, and a clean setup saves days later. npm init plus Hardhat gives you a compiler, a local chain, a deploy runner, and a test harness in one project:

npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox dotenv
npx hardhat init          # choose "Create a JavaScript project"
mkdir -p contracts scripts test

cat > .env <<'EOF'
SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/your-key
PRIVATE_KEY=0xYOUR_DEPLOYER_KEY
ETHERSCAN_API_KEY=your-etherscan-key
EOF

echo ".env" >> .gitignore
echo "artifacts/" >> .gitignore
echo "cache/" >> .gitignore

Keep three directories in mind: contracts/ holds Solidity sources, scripts/ holds deployment transactions, and test/ holds your suite. Everything under artifacts/ and cache/ is generated and should never be committed, because stale artifacts are the classic cause of "it works locally, the deployment is wrong on chain."

Configuration you will not regret changing

Configuration is where environment separation lives. Pin the compiler, enable the optimizer deliberately, and read secrets from the environment:

javascript
// hardhat.config.js
require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config();

const accounts = process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [];

module.exports = {
  solidity: {
    version: "0.8.24",
    settings: {
      optimizer: { enabled: true, runs: 500 },
      viaIR: false,
    },
  },
  networks: {
    hardhat: { chainId: 31337 },
    sepolia: {
      url: process.env.SEPOLIA_RPC_URL,
      accounts,
      chainId: 11155111,
    },
  },
  etherscan: { apiKey: process.env.ETHERSCAN_API_KEY },
};

optimizer.runs trades deploy cost against call cost: a high value tunes the bytecode for frequent calls and deploys a larger contract. A value near 500 is a sensible default for contracts that will be called thousands of times; a one-shot factory wants a much smaller number. Never inline a private key, not even in a local config, because repos leak through forks, screenshots, and CI logs.

Inside the EVM: where the gas goes

The EVM executes bytecode against four data areas, and each one is priced differently. Understanding those four areas eliminates most gas surprises:

AreaLifetimeCost profileTypical use
StackPer operation, 1024 slots deepCheapestLocal arithmetic and arguments
MemoryPer call frame, expanded in 32-byte wordsCheap, resets each callLoops, ABI decoding, temporary structs
StoragePermanent per contractVery expensive on writesBalances, ownership, configuration
CalldataRead-only input to the callCheapest readsFunction arguments, batch payloads
contract DataAreaDemo {
    mapping(address => uint256) public scores;   // storage: 20,000 gas to create
    uint256[] public history;                    // storage: grows with each push

    // memory: cheap, discarded when the call ends
    function median(uint256[] calldata samples) external view returns (uint256) {
        uint256[] memory sorted = new uint256[](samples.length);
        for (uint256 i = 0; i < samples.length; i++) {
            sorted[i] = samples[i];              // calldata read: ~3 gas
        }
        // insertion sort kept short to avoid O(n squared) surprises
        for (uint256 i = 1; i < sorted.length; i++) {
            uint256 key = sorted[i];
            uint256 j = i;
            while (j > 0 && sorted[j - 1] > key) {
                sorted[j] = sorted[j - 1];
                j--;
            }
            sorted[j] = key;
        }
        return sorted[sorted.length / 2];
    }

    function record(uint256 score) external {
        scores[msg.sender] = score;              // one write
        history.push(score);                     // second write, unavoidable here
    }
}

Gas optimizations that survive review

Cuts that show up repeatedly in audited code: cache repeated storage reads in a local variable, pack adjacent small variables into one slot, prefer calldata over memory for read-only parameters, and short-circuit loops before they touch storage.

contract BeforeAfter {
    struct Config { uint64 deadline; uint64 cooldown; address recipient; }
    Config public config;                        // fits in two slots when packed

    function setDeadline(uint64 newDeadline) external {
        config.deadline = newDeadline;           // write once, no full-struct copy
    }

    // Bad: three storage reads of the same slot
    function slow() external view returns (uint256) {
        return uint256(config.deadline) + uint256(config.cooldown);
    }

    // Good: one storage read into memory, two stack additions
    function fast() external view returns (uint256) {
        Config memory c = config;
        return uint256(c.deadline) + uint256(c.cooldown);
    }
}

Measure instead of guessing. npx hardhat test --gas-report prints per-function averages, and the tracer in the Hardhat toolbox can show exactly which opcode consumed a spike. A change that removes one storage write typically saves more than a dozen clever micro-optimizations combined.

Connecting a frontend without leaking control

A dApp is just a browser application that reads chain state and proposes transactions. The wallet signs on the user's behalf, so your frontend never needs a private key of its own:

javascript
import { BrowserProvider, Contract } from "ethers";
import ABI from "./artifacts/contracts/TokenVault.sol/TokenVault.json";

const CONTRACT = "0x5FbDB2315678afecb367f032d93F642f64180aa3";

export async function deposit(amount) {
  if (!window.ethereum) throw new Error("No wallet detected");
  const provider = new BrowserProvider(window.ethereum);
  const signer = await provider.getSigner();
  const vault = new Contract(CONTRACT, ABI.abi, signer);

  const network = await provider.getNetwork();
  if (network.chainId !== 11155111n) throw new Error("Switch to Sepolia");

  const tx = await vault.deposit({ value: amount });
  const receipt = await tx.wait(1);
  return receipt.hash;
}

Two habits matter here. Check the chain ID before prompting a signature, so users on the wrong network get a clear message instead of a reverted transaction. And surface the transaction hash immediately, then poll for confirmations, because wallets resolve their promise as soon as the transaction is broadcast — not when it lands.

There is a second class of reads you should design for: the ones that never become transactions. Reading contract.balanceOf(address) through a provider is an HTTP call to a node and costs nothing but latency, which means features like position previews, health factors, and historical event queries can be built entirely with free calls. Budget your engineering time around that distinction — expensive on-chain reads should be rare and deliberate, while everything the user merely wants to look at belongs in ordinary RPC queries or a cached indexer.

Networks, faucets, and the meaning of confirmation

Ethereum's environments form a ladder you climb in one direction. The in-process Hardhat network exists only while your process runs and resets on every restart, which makes it perfect for unit tests and useless for demos. A local fork of mainnet gives you live protocol state with free ether, so your integration tests against Uniswap or Aave run offline and deterministically. Testnets such as Sepolia add real block times, real mempool behavior, and the awkwardness of public faucets, and they are where you practice the exact deploy-and-verify flow you will repeat on mainnet.

EnvironmentChain IDStateEther costBest used for
Hardhat in-process31337Fresh per test runFreeUnit and integration tests
Local mainnet fork31337Snapshot of mainnetFreeComposability testing
Sepolia11155111Public, resets neverFaucet dropsDeploy, verify, demo
Mainnet1PermanentReal moneyProduction only

Confirmation semantics also differ by environment. On a local chain a single block is instant and final; on a public network a transaction is pending until a builder includes it, confirmed once, and practically irreversible after a handful of blocks. Your application code should treat those as distinct states rather than a single boolean, and it should surface the state to the user, because the gap between broadcast and confirmation is exactly where users click the button twice.

Debugging a failed transaction without an IDE

When a transaction reverts, the RPC error tells you the transaction hash, and the trace tells you everything else. Fetch the receipt, replay the call with a trace-enabled provider, and read the revert reason. In Hardhat, await expect(tx).to.be.revertedWith("over allowance") does this for you during tests; against a live network, the explorer's trace tab or a local replay against a fork shows the same information.

The four failure modes you will see most often are insufficient gas, an explicit require failing, an arithmetic underflow or overflow reverting in Solidity 0.8 and later, and an out-of-gas error caused by an unbounded loop over a growing array. The fourth one is the most instructive, because it is not a bug in the logic — it is a design that assumed a data set would stay small. Replace unbounded loops with pull patterns, pagination, or commit schemes that let users process one item per transaction.

Deploy, verify, and repeat safely

A deploy script is a file you will run many times, so make it idempotent and loud:

javascript
// scripts/deploy.js
const hre = require("hardhat");

async function main() {
  const [deployer] = await hre.ethers.getSigners();
  console.log("deploying with", deployer.address);

  const factory = await hre.ethers.getContractFactory("DataAreaDemo");
  const contract = await factory.deploy();
  await contract.waitForDeployment();

  const address = await contract.getAddress();
  console.log("deployed to", address);

  if (hre.network.name === "sepolia") {
    console.log("waiting for verifications...");
    await hre.run("verify:verify", { address, constructorArguments: [] });
  }
}

main().catch((e) => { console.error(e); process.exitCode = 1; });

Run npx hardhat run scripts/deploy.js --network sepolia, copy the printed address into your frontend constant, verify the source on the block explorer, and only then point testers at it. Keeping the address in one exported constant — rather than scattered through components — turns an upgrade into a single-file change.

âš ī¸Testnets still cost real money

Sepolia ETH has no value, but habits do. Always confirm the chain badge in your wallet, keep a dedicated deployer address separate from your treasury, and never reuse a key that ever held mainnet funds on a testnet deployment.

Common Mistakes

Committing .env files or hardcoding private keys in config

Fix: Load secrets from environment variables, gitignore the env file, and rotate any key that was ever committed

Optimizing bytecode before profiling

Fix: Run the gas report first; the top two or three lines almost always reveal a storage write you can batch or eliminate

Assuming a broadcast transaction is a confirmed transaction

Fix: Await tx.wait with a confirmation count before updating UI state or crediting a user

Scattering the contract address across dozens of components

Fix: Export one addresses module per network and import it everywhere so redeployments are a one-line change

Best Practices

  • Pin compiler versions and optimizer settings so bytecode is reproducible between machines
  • Separate deployer, admin, and user-facing addresses so one leaked key cannot compromise everything
  • Verify contracts on the explorer immediately after deployment to make the source auditable
  • Keep local fork tests against mainnet state when your contract integrates with live protocols

Interview Questions

Q1: Why can two contracts with identical source deploy different bytecode?

Optimizer settings, compiler version, constructor arguments, and metadata hash all feed into the deployed bytes. Pinning the version and optimizer runs makes a build reproducible, which is what verification depends on.

Q2: What is the practical difference between calldata and memory for an array parameter?

Calldata is read-only and never copied, so it costs far less for large inputs. Memory is writable and implies a full copy into working memory, which you pay for in gas and in the O(n) copy time.

Q3: How does a frontend authenticate a user without a server?

It does not authenticate in the classical sense: a signed message proves control of a private key, and the contract address plus chain ID define which application is being addressed. Authorization inside the contract is then checked per function.

Key Takeaways

  • Hardhat bundles compilation, a local chain, deployment, testing, and verification into one project layout
  • The EVM prices stack, memory, storage, and calldata very differently; storage writes dominate every gas bill
  • Batch storage writes, pack variables, and prefer calldata for read-only inputs before reaching for clever tricks
  • Frontends hold no private keys: the wallet signs, your code verifies chain ID and waits for confirmations
  • Reproducible builds and gitignored secrets are the difference between a demo and a deployable project
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement