How smart contracts work
A smart contract is code deployed to a blockchain that runs automatically when its conditions are met. Here is how they work, what they cost, and why bugs are uniquely expensive.
On this page
A smart contract is program code deployed to a blockchain that runs automatically when its conditions are met. So what is a smart contract in plain terms? It holds funds, enforces rules, and settles transactions without a middleman. The agreement and its enforcement are the same thing, and once it is live, no one can quietly change the terms.
How smart contracts work
A contract is deployed to an address on a network like Ethereum. Anyone can call its functions by sending a transaction. Every node on the network runs the same code, agrees on the result, and records the state change on the chain. There is no server you can log into and patch, and no operator who can reverse a call after the fact.
That determinism is the point. Given the same inputs and on-chain state, the contract produces the same output on every machine, every time. A smart contract behaves less like a web app and more like a vending machine that happens to custody millions of dollars: valid input in, defined output out, no clerk to appeal to.
What a smart contract can and cannot do
Here is the honest boundary. 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.
- Cannot: 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 will see below, one of the sharper edges in the whole model. A contract also cannot run on a schedule by itself. Something external has to poke it with a transaction before any code executes.
What smart contracts enable
Most of what people call web3 is smart contracts wearing different hats.
- Token standards carry fungible and non-fungible assets, the ERC-20 and ERC-721 building blocks behind most tokens and NFTs.
- DeFi protocols run lending markets, swaps, and staking with no bank in the loop.
- Escrow and settlement release funds only when verifiable conditions are met.
- On-chain governance lets token holders vote on proposals and treasury rules.
The common thread is removing a trusted operator from the middle of a transaction. Sometimes that is genuinely useful, and sometimes it just moves the trust to whoever wrote the code.
Gas and the cost of execution
Running a smart contract is not 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. Gas efficiency is a real engineering concern here: a wasteful loop is not just slow, it is a recurring tax on every user who touches the contract.
Layer-2 rollups cut these costs sharply. Since EIP-4844 introduced a separate blob-gas market in 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 vulnerabilities
Two properties make smart-contract bugs 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, and cumulatively such exploits have cost the industry billions of dollars.
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, which is a fancy way of saying: update your state before you talk to anyone else, and add a reentrancy guard.
Oracle manipulation is the modern favorite. 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
Serious projects treat launch as the last step, not the first. 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 have not thought of.
- Consider formal verification. For contracts guarding large sums, prove mathematically that specific properties always hold.
Fair warning: an audit is a snapshot, not a guarantee. It lowers your risk, it does not zero it, and any upgrade after the audit reopens the question. Treat the report as evidence, not a certificate.
Chains and languages
Smart contracts are not 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, including Arbitrum, Base, Polygon, and BNB Smart Chain, 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.
Off the EVM, the picture is more varied. Solana runs programs written in Rust. Aptos and Sui use Move, a language built around safe handling of digital assets. Cosmos chains often use Rust through CosmWasm. The takeaway is simple: pick the chain first, because the chain decides the language, the tooling, and much of the security model you will live with.
Smart contracts are the machinery under most of web3, from the base chain up through DeFi protocols. If you take one thing away, make it this: the code is the contract, so the code has to be right the first time.
Frequently asked questions
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 uses Rust, and Aptos and Sui use Move. Pick the chain first; it decides the language.
There is no fixed price. Deployment burns gas in proportion to contract size and network congestion, so the same contract can cost a few dollars on a quiet day or far more when Ethereum is busy. Layer-2 networks are usually cheaper by an order of magnitude. And the gas is rarely the big number. Budget for a professional audit too, which for anything holding real value often costs far more than deployment itself.
Keep exploring
How blockchain works
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 readDeFiA guide to decentralized finance (DeFi)
DeFi rebuilds financial services (lending, trading, saving, yield) as smart contracts anyone can use without a bank or broker. Here is how the core building blocks work and where the risk actually lives.
6 min readBlockchain & Web3Understanding crypto wallets
A crypto wallet stores the private keys that prove ownership of on-chain assets — it does not hold coins. Here is how keys work and how the main wallet types compare.
6 min read