Smart Contract

Smart Contract

Definition: Self-executing code deployed on a blockchain that automatically runs when its conditions are met, with no intermediary needed to enforce it.

How It Works

  • Written in a language like Solidity (or Vyper, Rust for non-EVM chains) and compiled down to bytecode that gets deployed permanently on the blockchain
  • Once deployed, its code generally can’t be changed (immutable), and it executes exactly as written whenever called, no exceptions made for good intentions
  • Every function call is a transaction, it costs Gas Fees, since every operation consumes network computation that validators have to perform and verify
  • A contract has its own address, its own persistent storage, and can hold its own balance of the chain’s native asset, functioning like an autonomous account
  • Execution happens inside a deterministic virtual machine, most commonly the Ethereum Virtual Machine (EVM), so every honest node that re-executes the same call reaches exactly the same result
  • Contracts can call other contracts, this composability is what lets DeFi protocols plug into each other, but it also means one contract’s bug can cascade into everything built on top of it
  • Read-only calls (view/pure functions) don’t modify state and cost no gas when called externally off-chain, only state-changing calls submitted as transactions cost gas
  • State changes made by a successful call are permanently recorded, and contracts typically emit events, log entries that off-chain applications and block explorers use to track what happened without re-reading full contract state

Contract Lifecycle

  1. Write the contract’s logic in a high-level language
  2. Compile it to bytecode plus an ABI (Application Binary Interface) describing its callable functions
  3. Deploy the bytecode via a transaction, this both creates the contract’s address and runs its constructor once
  4. Users and other contracts call its functions via transactions (state-changing) or free read-only calls
  5. If the contract includes an upgrade pattern (a proxy), governance or an admin key can later point it at new logic

Common Design Patterns

  • Proxy/upgradeable pattern: a lightweight proxy contract holds the storage and forwards calls to a separate, replaceable logic contract, working around normal immutability
  • Access control: functions restricted to specific addresses (an owner, a role) using modifiers that check msg.sender before allowing execution
  • Pull-over-push payments: instead of a contract sending funds out automatically, it lets recipients withdraw their own balance, reducing exposure to certain attacks
  • Circuit breaker/pause: an emergency switch that lets an admin halt sensitive functions if a bug or exploit is discovered mid-incident
  • Factory pattern: one deployed contract that creates new instances of another contract on demand, used to spin up many identical, independent contracts cheaply
  • Timelock: delays execution of a sensitive action (an upgrade, a large withdrawal) for a fixed period, giving users time to react before it takes effect

Testing and Auditing

  • Unit tests simulate calls against the contract logic before deployment, catching obvious logic errors early
  • Testnets let a contract be deployed and used with fake, valueless tokens under conditions matching the real network
  • A third-party security audit reviews code for known vulnerability classes before mainnet deployment, reducing but not eliminating risk
  • Bug bounty programs pay independent researchers to responsibly report vulnerabilities in exchange for a reward, often sized well below what an exploit could steal
  • Formal verification mathematically proves a contract satisfies specific properties, more rigorous than testing but far more expensive and typically reserved for high-value, security-critical contracts

Under the Hood

Worked example: gas cost of a contract call

  • Given: calling a DeFi protocol’s deposit() function costs roughly 120,000 gas, base fee is 30 gwei, tip 2 gwei
  • Step: total fee per gas = 32 gwei, total gas cost = 120,000 x 32 = 3,840,000 gwei = 0.00384 ETH
  • Answer: at 3,000/ETH,thatcallcostsabout3,000/ETH, that call costs about 11.52, purely in gas, before any amount actually being deposited

Worked example: a reentrancy attack, step by step

  • Given: a vulnerable contract’s withdraw() function sends ETH to the caller before updating the caller’s recorded balance to zero
  • Step: an attacker’s malicious contract calls withdraw(), which sends ETH and, in the process of sending, triggers the attacker contract’s fallback function
  • Step: that fallback function immediately calls withdraw() again, before the original call has updated the balance, so the check still sees the original (unreduced) balance
  • Step: this repeats in a loop, draining funds far beyond the attacker’s actual balance, each recursive call passing the same stale balance check
  • Answer: the fix is the “checks-effects-interactions” pattern, update the recorded balance to zero before sending funds, so a reentrant call sees the balance already at zero and fails the check; this exact bug caused the 2016 DAO hack, which drained roughly 3.6 million ETH before a contentious hard fork reversed it

Why It Matters

  • Enables trustless agreements, two parties who don’t trust each other can still transact safely because the contract’s logic is enforced by the network, not a middleman
  • Removes the need for manual enforcement, a contract that says “release funds when condition X is met” actually does it automatically the moment X becomes true on-chain
  • Provides a public, auditable record of exactly what logic governs an agreement, unlike a private legal contract whose terms aren’t independently verifiable by outsiders
  • Forms the base layer nearly everything else in this glossary section runs on, DeFi, NFTs, and DAOs are all just smart contracts with specific logic
  • Lets developers build permissionlessly on top of existing contracts, a new protocol can integrate a widely-used lending or exchange contract the same day it launches, without needing anyone’s approval

Common Pitfalls

  • Bugs in deployed smart contract code often can’t be patched, since the code is immutable by default, security review before deployment is far more critical than in typical software
  • Underestimating how public smart contract code is, any vulnerability can be found and exploited by anyone reading the deployed bytecode, security through obscurity doesn’t work here
  • Reentrancy: calling out to an untrusted external contract before finishing your own state updates, letting that external call loop back in and exploit stale state
  • Integer overflow/underflow: arithmetic that wraps around instead of erroring, largely mitigated in modern Solidity versions (0.8+) by default, but still a real risk in older code or low-level assembly
  • Weak access control: forgetting a permission check on a sensitive function, letting any address call something that should be admin-only
  • Trusting an unverified or unaudited contract because its interface “looks normal,” the UI a user interacts with says nothing about what the underlying bytecode actually does
  • Relying on a manipulable on-chain value (like a spot price from a single low-liquidity pool) as a source of truth, instead of a proper oracle
  • Assuming a proxy/upgradeable contract is automatically safer, an upgradeable contract also means a hidden central point of control, whoever holds the upgrade key can change the rules later

Comparison

Smart contractTraditional legal contractTraditional backend software
EnforcementAutomatic, by the networkCourts, if a party breachesWhoever operates the server
Modifiable after deploymentNo, by defaultYes, by amendmentYes, anytime
TransparencyFully public bytecodePrivate unless disclosedPrivate, closed source typical
Failure recourseLittle to noneLegal systemCompany support, refunds
Execution costGas fee per operationLegal/administrative feesServer hosting costs
Who can verify behaviorAnyone, by reading bytecodeLawyers, courtsOnly the operator

Example

A smart contract can hold funds in escrow and automatically release them to a seller only once a buyer confirms delivery, with no bank or escrow agent involved, both parties can read the exact contract code beforehand and know precisely how it will behave.

FAQ

Can a smart contract be deleted? Only if it was explicitly written with a self-destruct function, which is deprecated behavior on Ethereum as of the Cancun upgrade, most contracts are permanent once deployed.

Who pays gas when a contract calls another contract? The original transaction’s sender ultimately pays for the entire call chain’s gas, spread across every nested contract call it triggers.

Can a smart contract hold cryptocurrency? Yes, a contract has its own address and balance just like a wallet, and can send or receive funds as part of its logic.

Is a smart contract legally binding? It depends on jurisdiction, some legal systems recognize on-chain execution as binding, others still require a traditional contract layered alongside it.

What language are most smart contracts written in? Solidity dominates on Ethereum and other EVM-compatible chains, other ecosystems use Rust (Solana), Move (Aptos/Sui), or other chain-specific languages.

Dig deeper