How to Create a Smart Contract: Step-by-Step Tutorial

How to Create a Smart Contract: Step-by-Step Tutorial

By Marcus Williams, Blockchain & DeFi Editorial Desk · January 1, 2026 · Updated November 20, 2026 · 1 min read

Updated November 20, 2026: Updated the setup, test and deploy steps for Hardhat 3 (version 3.22.0, checked 20 November 2026): npx hardhat --init, Node.js 22.13 or later, hardhat.config.ts, node:test with viem, and Hardhat Ignition deployment to Sepolia.

Quick Answer

To create a smart contract, write it in Solidity, test it locally with Hardhat and deploy it to an Ethereum testnet such as Sepolia before mainnet. This tutorial sets up the environment with Node.js and Hardhat, writes a SimpleStorage contract that stores and returns a value, then covers testing and testnet deployment.

Introduction to Smart Contracts

Smart contracts are self-executing programs stored on a blockchain that run when predetermined conditions are met.

What Do You Need Before You Start?

  • Node.js 22.13.0 or later installed (the minimum Hardhat 3 requires)
  • Basic JavaScript knowledge
  • Understanding of blockchain concepts
  • MetaMask wallet

Step 1: Set Up Your Environment

bash
mkdir my-smart-contract
cd my-smart-contract
npm init -y
npm install --save-dev hardhat
npx hardhat --init

This tutorial uses Hardhat 3 (version 3.22.0 was current on 20 November 2026). When the wizard asks which project type to create, choose the Node.js Test Runner with viem template (node-test-runner-viem), accept the defaults and let it install the dependencies. You can also skip the prompts with npx hardhat --init --template node-test-runner-viem. Run npx hardhat --help to confirm the install.

The generated project contains hardhat.config.ts (TypeScript, with the Solidity version, networks and plugins), contracts/ for Solidity files, test/ for tests and ignition/modules/ for deployment modules. It includes a sample Counter contract, its tests and a Counter deployment module; delete those four files (contracts/Counter.sol, contracts/Counter.t.sol, test/Counter.ts and ignition/modules/Counter.ts) before adding your own.

Step 2: Write Your First Contract

Save this as contracts/SimpleStorage.sol. The Hardhat 3 template compiles with Solidity 0.8.34, and the ^0.8.28 pragma accepts it.

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

contract SimpleStorage {
    uint256 private value;

    event ValueChanged(uint256 newValue);

    function setValue(uint256 _value) public {
        value = _value;
        emit ValueChanged(_value);
    }

    function getValue() public view returns (uint256) {
        return value;
    }
}

What Is Solidity, and What Does Hardhat Do?

Before running more commands, it helps to know what each tool is for. Solidity is an object-oriented, high-level language for implementing smart contracts, and the SimpleStorage example above is written in it. The Solidity documentation defines a contract as a collection of code and data that resides at a specific address on the Ethereum blockchain. In SimpleStorage, the code is the setValue and getValue functions, and the data is the value variable they read and write.

Hardhat is the project tooling around that code. Its documentation describes it as a flexible and extensible development environment for Ethereum software. When you initialise a project, Hardhat generates a folder layout that separates contracts, tests and deployment. Deployment is handled by Hardhat Ignition, and the project documentation notes that its deployment modules describe how to deploy your contracts. Writing the deployment as a module, rather than as a one-off script, makes it easier to repeat the same steps on a local network first and a public testnet afterwards. To connect a contract to a front end, see our Web3 DApp tutorial.

The setup commands above were checked against Hardhat 3.22.0 and its getting-started page on 20 November 2026. Hardhat changes between major versions (Hardhat 2 used npx hardhat init and a hardhat.config.js file), so check the current getting-started page for the initialisation command and the supported Node.js version before you copy commands from any tutorial, this one included. Solidity 0.8.39 was released on 19 November 2026; if you pin a newer compiler in hardhat.config.ts, keep the pragma compatible. This tutorial uses no OpenZeppelin contracts; if you add them later, install the current release (5.6.1 on 20 November 2026) with npm install @openzeppelin/contracts.

Step 3: Test Your Contract

Write tests to ensure your contract works as expected before deployment. Save this as test/SimpleStorage.ts:

ts
import assert from "node:assert/strict";
import { describe, it } from "node:test";

import { network } from "hardhat";

describe("SimpleStorage", async function () {
  const { viem } = await network.create();

  it("returns zero before any write", async function () {
    const simpleStorage = await viem.deployContract("SimpleStorage");
    assert.equal(await simpleStorage.read.getValue(), 0n);
  });

  it("stores the value and emits ValueChanged", async function () {
    const simpleStorage = await viem.deployContract("SimpleStorage");

    await viem.assertions.emitWithArgs(
      simpleStorage.write.setValue([42n]),
      simpleStorage,
      "ValueChanged",
      [42n],
    );

    assert.equal(await simpleStorage.read.getValue(), 42n);
  });
});

Then run the tests:

bash
npx hardhat test

Both tests ran and passed on a fresh Hardhat 3.22.0 project on 20 November 2026.

Step 4: Deploy to Testnet

Use Hardhat Ignition to deploy your contract to a test network like Sepolia. First describe the deployment in ignition/modules/SimpleStorage.ts:

ts
import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";

export default buildModule("SimpleStorageModule", (m) => {
  const simpleStorage = m.contract("SimpleStorage");

  return { simpleStorage };
});

Deploy it to the local simulated network first:

bash
npx hardhat ignition deploy ignition/modules/SimpleStorage.ts

The template's hardhat.config.ts already defines a sepolia network that reads two configuration variables, SEPOLIA_RPC_URL and SEPOLIA_PRIVATE_KEY. Store them in Hardhat's encrypted keystore, then deploy with the --network flag:

bash
npx hardhat keystore set SEPOLIA_RPC_URL
npx hardhat keystore set SEPOLIA_PRIVATE_KEY
npx hardhat ignition deploy ignition/modules/SimpleStorage.ts --network sepolia

Hardhat asks for your keystore password and for confirmation before it deploys.

Choosing a Testnet and Getting Test ETH

A testnet lets you rehearse a deployment without risking real funds. The Ethereum documentation names Sepolia as the recommended default testnet for application development, so it is a sensible first target for a contract like SimpleStorage. Transactions on a testnet still need gas, but the ETH you pay with has no market value. As the networks page explains, most people get testnet ETH for free from faucets, which are web apps where you enter your wallet address and receive a small amount of test ETH.

A typical first deployment follows a short routine. Add a test account to MetaMask, switch the wallet to the Sepolia network, request test ETH from a faucet, then store your Sepolia RPC URL and private key in the Hardhat keystore and run the deployment command above. Keep the private key for that account separate from any wallet that holds real assets, and never commit it to a repository. Once the transaction confirms, you can look up the contract address on a Sepolia block explorer and call getValue to confirm the stored value is what you expect. To interact with a deployed contract from code, see our Python Web3 tutorial.

Why Testing Matters Before You Deploy

The reason tutorials push you toward testnets is permanence. The Ethereum documentation notes that public blockchains like Ethereum are immutable, making it difficult to change a smart contract's code after deployment. If you find a bug after mainnet deployment, you usually cannot patch the contract in place. You deploy a new one and ask users to move, which is awkward at best and costly at worst.

That is why the testing step deserves more than a single line. Start with unit tests, which evaluate contract functions separately and check that each component works correctly. For SimpleStorage, that means checking that getValue returns zero before any write, that setValue stores the number you pass, and that the ValueChanged event is emitted with the new value. When you move on to contracts that hold funds, add tests for the cases you hope never happen, such as calls from the wrong account or unexpected inputs.

Two more ideas are worth carrying into your next contract. First, cost: gas is the unit that measures the computational effort required to execute operations, so every extra storage write or loop makes your contract more expensive to use. Second, visibility: smart contracts are public on Ethereum and can be thought of as open APIs, which means anyone can read and call your deployed contract. Design every public function on the assumption that a stranger will call it with the worst possible input.

Best Practices

  • Always audit your code
  • Use established patterns
  • Optimize for gas efficiency
  • Test edge cases thoroughly

Conclusion

You've created your first smart contract! Continue learning by building more complex applications.

Sources

The primary sources this article cites, checked in November 2026:

Key Takeaways

  • Smart contracts are self-executing programs on blockchain
  • Solidity is the most popular language for Ethereum
  • Always test thoroughly before mainnet deployment
  • Gas optimization is crucial for cost efficiency

Frequently Asked Questions

What programming language do I need to write an Ethereum smart contract?

Solidity, the most popular language for Ethereum smart contracts and the one this tutorial uses. It was designed specifically for the Ethereum Virtual Machine, so most beginner guides, documentation and example code assume it. The tutorial's first contract, SimpleStorage, is written in Solidity and simply stores a value and returns it.

Do I have to spend real money to deploy my first smart contract?

No. You can practice for free by deploying to an Ethereum testnet such as Sepolia before touching mainnet. Testnets mirror the real network but use valueless test tokens, so you can experiment without financial risk. Confirm everything works there before committing real funds and paying real gas fees on mainnet.

Why is it important to test a smart contract before mainnet deployment?

Smart contracts are difficult or impossible to change once deployed to mainnet, so a bug can lock or lose funds permanently. Local testing catches errors while fixes are still free and easy. Write tests that confirm the contract works as expected, cover edge cases thoroughly, and audit your code before any live deployment.

What is Hardhat used for?

Hardhat is a development environment for compiling, testing and deploying smart contracts. It runs your Solidity code on a simulated blockchain on your own machine, so you can verify behavior and debug quickly. In this tutorial you install it with npm, initialize a project with npx hardhat --init, and use it to test and deploy to a testnet.

What does gas optimization mean, and why should beginners care?

Gas optimization means writing contract code that uses less computational effort, which lowers the fees users pay to run it. Every operation on Ethereum costs gas, so inefficient code becomes expensive at scale. Keeping gas in mind from your first contract helps separate practical contracts from ones too costly to use.

About the Author

Marcus Williams avatar

Marcus Williams

Blockchain & DeFi Editorial Desk

Blockchain & DeFi Editorial Desk · Web3AIBlog

Marcus Williams is a pen name for our blockchain and DeFi editorial desk. Posts under this byline are written and reviewed by contributors with backgrounds in protocol engineering, on-chain analysis, smart contract auditing, tokenomics, and decentralized finance. The desk covers consensus mechanisms, liquidity protocols, MEV, on-chain forensics, regulatory frameworks across jurisdictions, and the operational realities of running and using DeFi at scale. Our coverage is an editorial synthesis of protocol documentation, on-chain data, and audited primary sources, with every figure verified against a primary source before publication.