Smart Contracts Explained: What They Are & How They Work

A smart contract is a program deployed on a blockchain that executes automatically when its conditions are met — no lawyers, no banks, no middlemen. Every DeFi protocol, NFT collection, and DAO is built from smart contracts. Understanding how they work — and how they fail — is the foundation for evaluating any crypto project.

What a smart contract is (the simple version)

Imagine a vending machine. You insert the right amount of money, press the button for your item, and the machine automatically dispenses it — no cashier required, no possibility of the machine deciding to keep your money arbitrarily. The rules are mechanical and enforced by the machine itself.

A smart contract is the blockchain equivalent. You interact with it by sending a transaction. If the conditions in the code are met (you sent enough ETH, you hold the right tokens, the required time has elapsed), the contract executes its programmed action. No company processes your request. No human approves the transaction. The code runs.

Nick Szabo described the concept in 1994 — long before blockchains existed — as a "computerized transaction protocol that executes the terms of a contract." Ethereum made it practical in 2015 by providing a global, permissionless computer that any smart contract can run on.

How the EVM executes smart contracts

Smart contracts on Ethereum are written in Solidity (or occasionally Vyper or other languages), compiled into EVM bytecode — a low-level instruction set — and deployed to the blockchain at a unique address. From that point, anyone can call the contract's functions by sending a transaction to its address.

The Ethereum Virtual Machine (EVM) is a stack-based virtual machine that every Ethereum node runs. When a transaction calls a smart contract, every node independently executes the same bytecode with the same inputs and reaches the same state transition. The result is recorded in the next block. This is why smart contracts are called trustless: you do not need to trust any single party to execute the code correctly — the entire network of validators enforces it identically.

Layer 2 networks like Polygon run compatible EVM implementations but process transactions off the main Ethereum chain, settling proofs or summaries to Ethereum periodically. Smart contracts deployed on Layer 2s are largely identical to Ethereum contracts but execute at a fraction of the gas cost.

Gas: the cost of execution

Every EVM operation has a gas cost measured in units. Simple operations (reading storage, arithmetic) cost less gas; complex operations (writing to storage, calling other contracts) cost more. The total gas consumed by a transaction is the sum of all its operations.

Users set a gas price — the amount of ETH (in gwei: 1 gwei = 0.000000001 ETH) they are willing to pay per unit of gas. The total transaction fee is gas used multiplied by gas price. During periods of high network demand, users compete on gas price to get their transactions included in the next block.

If a transaction runs out of gas mid-execution (because the user set too low a gas limit), it reverts — all state changes are rolled back — but the gas is still consumed by the validators who did the work. Efficient smart contract code minimizes gas usage because every operation costs real money at scale.

What smart contracts enable

The programmability of smart contracts makes complex financial and organizational coordination possible without trusted intermediaries:

  • Lending and borrowingAave's entire lending market is a set of smart contracts that accept deposits, track balances, maintain collateral ratios, and trigger liquidations automatically
  • Token trading — a DEX is a smart contract holding token reserves and pricing trades algorithmically, executing swaps without any order book or human market maker
  • NFT ownership — an NFT is a smart contract mapping unique token IDs to wallet addresses, enforcing one owner per token
  • Governance — a DAO uses smart contracts to record votes, queue proposals in timelocks, and execute approved changes automatically
  • Oracle data feeds Chainlink's oracle contracts feed real-world price data into DeFi lending contracts so they know when to trigger liquidations

Common smart contract vulnerabilities

Reentrancy attacks

A reentrancy attack exploits a contract that sends ETH (or calls another contract) before updating its internal state. The attacker deploys a receiving contract that calls back into the victim before the state update completes, allowing repeated withdrawals in a loop that drains the balance.

The 2016 DAO hack used reentrancy to drain approximately 3.6 million ETH (worth ~$60M at the time) from an early Ethereum investment fund. The community's decision to hard-fork and reverse the theft caused the Ethereum/Ethereum Classic split. The standard mitigation is the Checks-Effects-Interactions pattern: check conditions, update state, then make external calls — never the reverse order.

Oracle manipulation

DeFi lending protocols need price feeds to know the current value of collateral. If an attacker can manipulate the price feed — for example, by using a flash loan to temporarily distort a DEX price that the protocol uses as its oracle — they can trick the protocol into releasing more funds than the collateral is worth.

The standard defense is using decentralized oracle networks like Chainlink, which aggregate price data from many independent sources and use time-weighted average prices (TWAPs) that are resistant to single-block manipulation. Protocols that rely on single on-chain sources or spot prices are significantly more vulnerable.

Access control flaws

Smart contracts must carefully restrict which addresses can call privileged functions (minting tokens, pausing the protocol, withdrawing fees). Improperly implemented access control — for example, a function marked public that should be admin-only — allows attackers to perform operations the contract author intended to be restricted. The 2022 Nomad bridge hack ($190M) exploited an initialization bug that effectively turned the bridge into an open vault anyone could drain.

Integer overflow and underflow

In older Solidity versions (pre-0.8.0), integer arithmetic did not automatically check for overflow (a number exceeding its maximum value wraps around to zero or below). An attacker could craft transactions to cause overflow and manipulate balances. Solidity 0.8.0 introduced built-in overflow checking; older contracts relied on SafeMath libraries.

Logic errors

Some of the largest exploits have stemmed not from cryptographic weaknesses but from errors in the business logic of the contract itself — conditions that the developers did not anticipate being met in combination. These are the hardest vulnerability class to eliminate through automated tools and require deep, adversarial code review.

The audit ecosystem

Security audits are the primary quality gate before smart contract deployment. Major audit firms include Trail of Bits, OpenZeppelin, Certik, Spearbit, Halborn, and Peckshield. The audit process typically involves:

  1. Static analysis — automated tools checking for known vulnerability patterns
  2. Manual review — experienced auditors reading every line of code
  3. Test suite review — assessing whether the existing tests cover critical paths
  4. Report publication — findings categorized by severity (critical, high, medium, low)

Audit reports should be publicly available. When evaluating a project's whitepaper, always check:

  • Which firms audited the contracts, and when?
  • Have all critical and high-severity findings been resolved?
  • Is there an active bug bounty program, and what is its maximum payout?
  • Are new contract versions audited before deployment, or only the initial version?

Audits are necessary but not sufficient. Multiple high-profile exploits — Euler Finance ($197M, 2023), Beanstalk ($182M, 2022) — occurred in audited protocols. An audit is a snapshot review of code at a specific point in time; subsequent changes or unforeseen interaction effects between protocols can introduce new risks. Formal verification (mathematically proving that code satisfies its specification) is the highest assurance level and is used for the most critical code paths in protocols like Aave and MakerDAO.

Upgradeability: the flexibility-trust tradeoff

Immutability is a feature — until there is a bug that needs fixing. Most major protocols use upgradeable smart contract patterns (proxy contracts) that allow the underlying logic to be replaced without changing the contract address. The security question is: who controls the upgrade key?

A protocol where a single admin address can upgrade contracts unilaterally is not meaningfully trustless — the admin is a single point of failure and trust. Well-designed protocols route upgrade authority through a DAO governance vote with a timelock, giving token holders control and users advance notice of any change to the contracts they are using.

Smart contract projects on ChainClarity

  • Ethereum — the dominant smart contract platform; home to the EVM and most DeFi activity
  • Aave — audited DeFi lending smart contracts; multiple versions with published audit reports
  • Polygon — EVM-compatible smart contracts at dramatically lower gas cost on a Layer 2 network
  • Chainlink — oracle smart contracts powering price feeds, VRF, and automation for the DeFi ecosystem

Frequently asked questions

What is a smart contract?

A smart contract is a program stored on a blockchain that executes automatically when predetermined conditions are met — no intermediary required. On Ethereum, smart contracts are written in Solidity, compiled to bytecode, and deployed to a specific blockchain address. Every node in the network executes them identically, producing the same output from the same input, with results recorded permanently on-chain.

How are smart contracts different from regular software?

Regular software runs on servers controlled by a company that can modify or shut it down. A deployed smart contract is immutable — the code cannot be changed without deploying a new contract — and runs on a decentralized network that no single party controls. The immutability is both the main advantage (censorship resistance, trustless operation) and the main risk: bugs are also permanent.

What is a reentrancy attack?

A reentrancy attack exploits a contract that sends ETH before updating its internal state. The receiving contract calls back into the sender before the state update completes, allowing it to drain funds in a loop. The 2016 DAO hack used reentrancy to drain $60M from an Ethereum fund — and caused the Ethereum/Ethereum Classic split when the community hard-forked to reverse the theft. The fix is the Checks-Effects-Interactions pattern: always update state before making external calls.

What is gas and why does it matter?

Gas is the unit measuring the computational work required to execute a smart contract operation on Ethereum. Every EVM opcode has a gas cost; complex contracts cost more gas. Users set a gas price (in gwei — billionths of ETH) that they are willing to pay per unit of gas. Gas total cost = gas used × gas price. Layer 2 networks like Polygon reduce gas costs dramatically by batching execution off-chain and settling proofs to Ethereum.

Do smart contracts need to be audited?

Yes, for any contract holding significant value. Security audits by independent firms (Trail of Bits, OpenZeppelin, Certik, Spearbit, and others) systematically review code for known vulnerability classes. Audits reduce risk but do not eliminate it — the Euler Finance hack in March 2023 drained $197M from a protocol that had been audited multiple times. Bug bounty programs complement audits by incentivizing ongoing researcher review after deployment.

New whitepapers explained, weekly

Plain-English breakdowns of new crypto projects, delivered when they drop. No price predictions, no hype — just clear analysis you can actually use.

First look

Each whitepaper we add to the library lands in your inbox before it goes live.

Reader picks

See which projects the ChainClarity community is reading and discussing each week.