What is a smart contract? How it works, gas and security
A smart contract is code deployed to a blockchain that runs automatically when its conditions are met. This entry covers how smart contracts work, what they cost in gas, and why their bugs are so expensive.
On this page
A smart contract is program code deployed to a blockchain that runs automatically when its conditions are met. It holds funds, enforces rules, and settles transactions without a middleman. The agreement and its enforcement are the same thing, and once the contract is live, nobody can edit the code at that address.
How smart contracts work
A contract is deployed to an address on a network like Ethereum, as detailed in the Ethereum smart contract documentation. Anyone can call its functions by sending a transaction, usually signed from one of the crypto wallets that hold their keys. Every node on the network runs the same code, agrees on the result, and records the state change on the chain. There's no server you can log into and patch, and no operator who can reverse a call after the fact.
Given the same inputs and on-chain state, the contract produces the same output on every machine, every time. Valid input goes in, a defined output comes out, and there's nobody to appeal to, even when the contract custodies millions of dollars.
What a smart contract can and cannot do
A smart contract can do a lot inside its own world and almost nothing outside it.
- Can: move tokens, enforce logic, hold value in escrow, and read other contracts' state on the same chain.
- It can't reach out to a bank API, check today's weather, or pull a stock price by itself. Blockchains are deliberately isolated.
To bring in outside data, a contract depends on an oracle, a service that feeds off-chain facts on-chain. That dependency is convenient and, as you'll see below, one of the sharper edges in the whole model. A contract also can't run on a schedule by itself. Something external has to poke it with a transaction before any code executes.
What smart contracts enable
Most smart contract examples you'll meet fall into a few groups.
- Token standards carry fungible and non-fungible assets, the ERC-20 and ERC-721 building blocks behind most tokens and NFTs, commonly implemented using audited libraries from the OpenZeppelin Contracts documentation.
- DeFi protocols run lending markets, swaps, and staking with no bank in the loop.
- Escrow and settlement, such as our Zert smart contract escrow platform, release funds only when verifiable conditions are met.
- On-chain governance lets token holders vote on proposals and treasury rules.
What these share is that no trusted operator sits in the middle of the transaction. That's useful, but it doesn't remove trust entirely. You're now trusting whoever wrote the code.
Gas and the cost of execution
Running a smart contract isn't free. Every operation consumes gas, a unit that measures computational work, and you pay for the gas your transaction uses. The total fee is roughly gas used times gas price, with prices quoted in gwei (one gwei is a billionth of an ETH).
Since the EIP-1559 upgrade, an Ethereum fee splits into a base fee that gets burned and an optional priority tip that goes to validators for faster inclusion. Costs swing with congestion, so an identical transaction can be cheap at 3am and painful during a busy mint. That makes gas efficiency a real engineering concern: a wasteful loop costs every user who touches the contract, on every call.
Layer-2 rollups cut these costs sharply. Since EIP-4844 introduced a separate blob-gas market in March 2024, rollups post their data far more cheaply, which is a big part of why L2 fees now sit well below mainnet for most everyday activity.
Common smart contract vulnerabilities
Two properties make smart contract bugs, cataloged in the OWASP Smart Contract Top 10, uniquely dangerous. Contracts are immutable once deployed, and they often custody real value. A single flaw can drain a protocol in one transaction, with no undo and no support line to call. Losses run to billions of dollars a year: the OWASP 2025 edition counts about $1.42B lost across 149 incidents in 2024 alone.
Access control flaws top that list by losses. A function meant for the owner or an admin role ships without the check, or a privileged key is poorly guarded, and an attacker simply calls it.
Reentrancy is the classic. If a contract sends funds before it updates its own balance, an attacker's contract can call back in and withdraw again, and again, before the books are settled. This is the bug behind the 2016 DAO hack, which drained roughly $60M in ETH at the time. The standard defense is the checks-effects-interactions pattern (update your state before you call any other contract) plus a reentrancy guard.
Oracle manipulation is a common modern attack. Because contracts trust the
price data an oracle feeds them, an attacker can use a flash loan to yank a
market price for a single block, trick a lending protocol into mispricing
collateral, and walk away with the difference. Reading prices from a
well-distributed, decentralized oracle network like Chainlink instead of a single
thin market is the usual mitigation. Older contracts also suffered from integer overflow, but
Solidity 0.8 and later check arithmetic by default unless you opt out with an
unchecked block.
The audit and testing lifecycle
Before a contract holds a cent, it goes through a lifecycle that assumes something is broken until proven otherwise.
- Test hard. Cover the logic with unit and property tests, then run fuzzing to throw millions of random inputs at it and see what breaks.
- Deploy to a testnet. Rehearse the real thing on a network like Sepolia, where mistakes cost nothing.
- Get an independent audit. A specialist firm reviews the code for the vulnerability classes above and the ones you haven't thought of, following a structured smart contract audit guide.
- Consider formal verification. For contracts guarding large sums, prove mathematically that specific properties always hold.
An audit covers the code as it stood on the day of review. It lowers your risk without removing it, and any upgrade after the audit reopens the question. Read the report for what it checked and what it didn't.
Chains and languages
Smart contracts aren't an Ethereum-only idea, though Ethereum set the template.
Solidity is the dominant language, and it compiles to bytecode for the Ethereum Virtual Machine (EVM). Because so many networks are EVM-compatible, one body of Solidity knowledge travels a long way. Vyper is a smaller, deliberately simpler EVM language some teams prefer for its narrower surface area. Move was built around safe handling of digital assets. Your chain choice decides the language, the tooling, and much of the security model you'll live with, so make it first.
Smart contracts are the machinery under most of web3 and blockchain development, from the base chain up through DeFi protocols. If you're building one, our guide to DeFi smart contract development covers the engineering side in more depth.
Frequently asked questions
It's a small program stored on a blockchain that carries out an agreement by itself. When the agreed conditions are met, the code moves the money or tokens, and nobody in the middle has to approve it.
Not automatically. A smart contract executing on-chain is code, not a court-recognized agreement on its own. Enforceability still depends on ordinary contract law, offer, acceptance, consideration, and jurisdiction. Some US states, including Arizona and Tennessee, explicitly recognize smart contracts and blockchain signatures within their electronic-transaction statutes, but parties must still meet standard legal requirements.
The deployed bytecode is immutable, so you cannot edit the code at that address. Teams that need to ship fixes use a proxy pattern, where a fixed proxy address delegates calls to a separate logic contract you can swap out. That buys upgradeability, but it also hands whoever controls the upgrade key real power, which is its own risk.
It depends on the chain. Ethereum and other EVM networks mostly use Solidity, Solana mostly uses Rust, and Aptos and Sui use Move.
There's no fixed price. Deployment burns gas in proportion to contract size and network congestion, so the same contract can cost anywhere from a few dollars to several hundred on Ethereum mainnet, depending on gas prices and the ETH rate. Layer-2 networks are usually cheaper by an order of magnitude. Gas is rarely the biggest line, though. For anything holding real value, a professional audit often costs far more than deployment itself.
Keep exploring
What is blockchain? How it works, explained
A blockchain is a shared, append-only ledger replicated across many computers that agree on its contents through consensus. Here is how blocks, hashing, and consensus work, plus the trade-offs it forces.
7 min readDeFiDecentralized finance (DeFi), explained
DeFi rebuilds financial services (lending, trading, saving, yield) as smart contracts anyone can use without a bank or broker. Here's how the core building blocks work, how DeFi compares with CeFi, and where the risk actually lives.
6 min readBlockchain & Web3Crypto wallet: what it is and how it works
A crypto wallet stores the private keys that prove you own on-chain assets. It never holds the coins. How keys and seed phrases work, and how custodial, non-custodial, hot, cold, MPC and smart contract wallets compare.
6 min read