How to Write and Deploy a Solidity Smart Contract in 2026

A Solidity smart contract is a program that lives on the Ethereum blockchain and runs exactly as written, with no server owned by anyone. You write it in Solidity, compile it to bytecode, and deploy it in a single transaction. After that, anyone can call it, and nobody can quietly change the rules.

This guide walks the whole path of building a Solidity smart contract. It starts with what a contract is and who uses one, then builds a working example, deploys it to a test network, and finishes with the security mistakes that cost real money. The code was compiled with Solidity 0.8.30 and 0.8.37 before publishing.

Why Do Developers Write Contracts Instead of Regular Backends?

A Solidity smart contract removes the need to trust the operator. In a normal app, the company running the server can change rules, freeze accounts, or go offline. On-chain, the rules are public and execution is verified by the whole network.

That trade has a price. Every operation costs gas, deployed code is hard to change, and a bug is public the moment you deploy. For logic that must be neutral and auditable, such as holding funds or recording ownership, a Solidity smart contract is worth the trade. For everything else, a database is cheaper.

Who Uses Solidity Contracts, and for What?

Every Solidity smart contract serves some purpose, and most of what people do on Ethereum and EVM-compatible chains is built from them. The common cases are listed below.

  • Tokens. ERC-20 tokens and stablecoins are contracts that track balances.
  • NFTs. ERC-721 and ERC-1155 contracts record who owns which item.
  • DeFi. Lending markets, exchanges, and vaults are sets of contracts that hold and move funds.
  • DAOs. Voting and treasury rules are enforced by code instead of by an administrator.
  • Escrow and payments. Funds release only when defined conditions are met.

The same code usually runs on Layer-2 networks and other EVM chains with only a change of network settings. Our guide to building a dapp on Ethereum shows how a contract fits into a full application.

What Are the Building Blocks of Solidity Code?

Every contract is made from a few parts. Learn these and you can read almost any Solidity smart contract you find on a block explorer. The table maps each part to its job.

ElementWhat it doesExample
PragmaLocks the compiler version rangepragma solidity ^0.8.30;
State variableData stored permanently on-chainstring public greeting;
ConstructorRuns once, at deploymentconstructor(string memory g)
FunctionLogic that reads or changes statefunction setGreeting(...)
ModifierReusable check run before a functionmodifier onlyOwner()
EventA log entry apps can listen toevent GreetingChanged(...)
Custom errorA cheap, named revert reasonerror NotOwner();

Function visibility matters too. public and external functions can be called from outside, internal ones only from the contract and its children, and private ones only from the contract itself. Functions marked view read state without changing it, and pure functions do not touch state at all.

Where data lives is the other concept to grasp early. Storage persists and costs the most gas, while memory is temporary and calldata is read-only input.

We compare all three in storage vs. memory vs. calldata in Solidity.

What Do You Need Before You Start?

You need three things to build a Solidity smart contract: a wallet, test funds, and a place to write code. Everything else is optional at the beginning.

  1. A wallet. MetaMask or any browser wallet that can sign transactions. Use a fresh account for development, never one that holds real funds.
  2. Test ETH. Free coins from a faucet pay gas on a test network. Our Sepolia faucet guide lists current options.
  3. A development environment. For a first contract, the browser is enough.

Three tools cover the usual choices. Pick by project size, not by fashion.

ToolWhere it runsBest forTrade-off
Remix IDEBrowserFirst contracts, quick experimentsWeak for multi-file projects
HardhatLocal, JavaScript or TypeScriptScripted deployments and testsMore setup
FoundryLocal, tests written in SolidityFast test suites, larger codebasesSteeper learning curve

How to Write Your First Contract in Solidity

Start small, with a Solidity smart contract that stores a greeting and lets only its owner change it. It is short enough to read in a minute and still uses an access check, an event, and a custom error. Save the code below as Greeter.sol.

solidity

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

contract Greeter {
    address public owner;
    string public greeting;

    event GreetingChanged(address indexed by, string newGreeting);

    error NotOwner();

    constructor(string memory initialGreeting) {
        owner = msg.sender;
        greeting = initialGreeting;
    }

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    function setGreeting(string calldata newGreeting) external onlyOwner {
        greeting = newGreeting;
        emit GreetingChanged(msg.sender, newGreeting);
    }
}

The first line is a license identifier, which the compiler warns about if it is missing. The pragma line says the file needs compiler 0.8.30 or a newer 0.8.x release. Solidity 0.8 also reverts on arithmetic overflow by default, so you no longer need a SafeMath library for basic math.

The constructor stores the deployer as owner. The onlyOwner modifier rejects any other caller, and msg.sender is the address that made the current call. Because greeting and owner are public, the compiler generates read functions for them automatically.

How to Compile and Deploy the Contract Step by Step

Deploying a Solidity smart contract is a transaction that carries the compiled bytecode and creates a new address. The steps below use Remix, so nothing needs to be installed on your machine.

  1. Open Remix, create a file named Greeter.sol, and paste the code.
  2. Open the Solidity Compiler tab, pick a compiler version that matches your pragma, and click Compile. A green check means the bytecode built.
  3. Install a wallet and switch it to Sepolia. Claim test ETH from a faucet.
  4. Open Deploy & Run Transactions and set the environment to Injected Provider. Remix now uses your wallet’s connection to the network.
  5. Enter a greeting in the constructor field, such as Hello, and click Deploy.
  6. Confirm the transaction in your wallet. It normally lands within a block, about 12 seconds on Ethereum.
  7. Expand the deployed contract in Remix and call greeting. It should return your text. Then call setGreeting from the same account, and from a second account to see the NotOwner error.

Which test network you choose matters, and the picture is shifting. According to ethereum.org, updated in September 2026, Sepolia is the recommended default testnet for application development, and Hoodi is meant for validator and protocol testing. The Ethereum Foundation’s 2025 plan had set Sepolia’s end of support for September 30, 2026, yet Sepolia is still scheduled to host the Glamsterdam upgrade test on October 6, 2026. Check the ethereum.org page before you hardcode a chain ID, and see our Sepolia guide for the retirement timeline.

How Do Scripts Reach the Network Without Remix?

Scripts that deploy a Solidity smart contract, such as Hardhat, Foundry, or ethers.js setups, do not use your wallet’s built-in connection. They send signed transactions to an API endpoint, which relays them to the network and returns results. You can run that software yourself, but syncing and maintaining it is a job in its own right.

For a script, a hosted Ethereum API endpoint is usually simpler. NOWNodes offers both mainnet and Sepolia access, and its Start plan includes 100,000 requests for one month, which is plenty for repeated test deployments. Developers who use AI coding assistants can also connect them to documented methods through the NOWNodes MCP Server. Switching from Sepolia to mainnet then comes down to changing one URL in your config.

What Does It Cost to Deploy a Contract?

The cost of a Solidity smart contract depends on bytecode size and on how many storage slots the constructor writes. Every transaction starts at a flat 21,000 gas, contract creation adds more, and each byte of deployed code and each new storage slot is charged on top. Writing to a fresh storage slot is one of the priciest operations, which is why the Greeter above is cheap but a contract with a large initial state is not.

Before mainnet, estimate the gas in your tool and compare it with the current gas price. Test deployments cost nothing, so use them to measure. Shorter code, fewer storage writes, and custom errors instead of long revert strings all reduce the bill.

Which Security Mistakes Cost the Most?

Access control is the most expensive weakness in any Solidity smart contract, by a wide margin. The OWASP Smart Contract Top 10 ranks improper access control first, based on 149 incidents in 2024 that together caused over $1.42 billion in losses. Dedaub’s analysis of that dataset attributes $953.2 million of the total to this one class.

The pattern is usually boring. In a vulnerable Solidity smart contract, a privileged function, such as changing an admin or withdrawing funds, is left callable by anyone, or an initializer can be run twice. The onlyOwner check in the Greeter is a small version of the fix.

Watch for these once you move past the first example. Each one has drained real contracts.

  • Use msg.sender for permission checks, not tx.origin. A malicious intermediary contract can pass a tx.origin check.
  • Update state before external calls. This blocks reentrancy, where a called contract re-enters yours before the balance changes.
  • Do not build on selfdestruct. It has been deprecated since Solidity 0.8.18, following EIP-6049.
  • Reuse audited code. OpenZeppelin Contracts covers tokens, roles, and pausing, and its Wizard generates a starting point.
  • Pin and update the compiler on purpose. The Solidity team ships bug notices with releases. Version 0.8.37, published on September 10, 2026, fixes three bugs and adds support for the SLOTNUM opcode of the Amsterdam EVM version.

Static analysis tools such as Slither catch known patterns, but they cannot replace review of business logic. For anything that will hold user funds, budget for an independent audit.

How Do You Verify and Test the Deployed Contract?

Verifying a Solidity smart contract publishes your source so anyone can compare it with the on-chain bytecode. Block explorers such as Etherscan accept the source file, compiler version, and optimizer settings. Wallets and integrators tend to treat unverified contracts as a warning sign.

Tests for a Solidity smart contract belong before deployment, not after. Hardhat and Foundry both run unit tests against a local chain in seconds. Write a test for every rule you care about, including the failing case: a second account calling setGreeting must revert.

Conclusion

A working Solidity smart contract needs surprisingly little code: state, a constructor, a guarded function, and an event. The hard part of any Solidity smart contract is the decisions made around it, such as who can call what, which network to test on, and how much review the code gets before real money touches it.

Start with a small Solidity smart contract in Remix, move to Hardhat or Foundry once a project has more than a couple of files, and always deploy to a test network first. Keep the compiler current, and lean on audited libraries instead of writing token logic by hand.

FAQ

Can a Deployed Contract Be Changed?

Not directly. A deployed Solidity smart contract is immutable, so a fix means deploying a new contract and moving users over. Teams that need upgrades use a proxy pattern, which adds complexity and its own attack surface.

Which Language Should I Learn Besides Solidity?

Vyper is the main alternative on the EVM, with a smaller syntax that some teams prefer for auditing. Rust is the standard for Solana programs, which follow a different model entirely. A Solidity smart contract runs on Ethereum and most EVM chains.

Do I Need to Pay to Practice?

No. Remix is free, and faucets supply test ETH. Real costs only start on mainnet.

What Is the Difference Between Compiling and Deploying?

Compiling turns source code into bytecode and an ABI on your machine. Deploying sends that bytecode in a transaction, which creates the contract at a new address and costs gas.

What Is an ABI?

The Application Binary Interface is a JSON description of a contract’s functions and events. Wallets, scripts, and front ends use it to encode calls and decode results.