Back to Blog

What Is a Smart Contract and How It Works: A Beginner's Guide

Onchain 101Web3

Learn what smart contracts are, how they execute code on blockchains like Ethereum and Base, and why they power tokens, DeFi, and NFTs.

Summarize this post with

Smart Contracts, Simply Explained

A smart contract is a program stored on a blockchain that automatically executes when specific conditions are met. Think of it as a vending machine for digital agreements: you input the right combination of actions (inserting coins, selecting a product), and the machine delivers exactly what you requested, every time, without requiring a cashier to oversee the transaction.

Smart contracts live at unique addresses on blockchains like Ethereum and Base, just like your wallet does. But instead of holding only funds, these addresses contain executable code combined with persistent data (called "state"). When you interact with a decentralized app—swapping tokens, minting an NFT, or voting in a DAO—you're calling functions in smart contracts that run automatically according to their programmed rules.

The name "contract" comes from their ability to enforce agreements without intermediaries. Traditional contracts require lawyers, banks, or escrow agents to verify compliance. Smart contracts replace this manual oversight with code: if you pay 1 ETH and the seller confirms delivery, the contract automatically releases funds. No disputes, no delays, no trust required in any single party.

This matters because smart contracts enable what many call "programmable money." Instead of money sitting idle in accounts waiting for humans to move it, onchain assets flow through code-defined rules that execute 24/7 across thousands of nodes, creating applications impossible in traditional finance.

Why Smart Contracts Matter: Trustless Apps and Automated Rules

The core promise of smart contracts is removing trust from transactions. In traditional systems, you trust banks to maintain balances, payment processors to complete transfers, or platforms to apply rules fairly. Smart contracts flip this model: you trust auditable code running on a decentralized network where no single entity controls execution.

This enables three fundamental shifts:

Programmatic money means assets move according to logic, not manual approval. A lending protocol can automatically liquidate undercollateralized positions. A streaming payment contract can release salary every second. A crowdfund can refund contributors if the goal isn't met—all without human operators making judgment calls.

Open access breaks down financial gatekeeping. Anyone with an internet connection and wallet can interact with Ethereum contracts offering services like trading, lending, or insurance. No credit checks, no citizenship requirements, no business hours. Over 5 million contracts deployed on Ethereum since 2015 serve users globally, with Base hosting 500,000+ contracts processing 20 million transactions daily as of 2025.

Composability turns every smart contract into a building block others can use. A token contract (like USDC) can be called by lending protocols, decentralized exchanges, and NFT marketplaces simultaneously. Developers combine existing contracts like Lego bricks instead of rebuilding from scratch. This is why DeFi grew to $120 billion in total value locked—applications stack on top of each other, compounding utility.

The result: financial infrastructure that's transparent (code is auditable), permissionless (no approval needed to use), and censorship-resistant (no single point of shutdown). These properties power everything from stablecoins serving the unbanked to DAOs coordinating global communities.

How Smart Contracts Work Under the Hood (Without the Jargon)

At their core, smart contracts combine three elements at a unique blockchain address: executable code, mutable state (data storage), and deterministic execution rules.

When you write a smart contract in languages like Solidity, you define functions (like transfer or mint) and storage variables (like token balances). A compiler converts this human-readable code into bytecode—machine instructions the Ethereum Virtual Machine (EVM) understands. This bytecode gets deployed to the blockchain via a transaction, creating a permanent contract address.

Once deployed, the contract waits for transactions that trigger its functions. Every operation—reading a balance, updating ownership, calculating interest—executes inside the EVM, a sandboxed runtime that runs identically across thousands of nodes. This determinism is crucial: given the same inputs and blockchain state, every node must reach the same outputs, ensuring consensus without central coordination.

State lives in storage slots at the contract address. An ERC-20 token stores a mapping of addresses to balances. An NFT contract stores owner IDs. When functions execute, they read current state, apply logic, and write updates. For example, calling transfer(recipient, 100) reads your balance (500), subtracts 100, adds 100 to the recipient's balance, and saves both changes—all atomically in one transaction.

Gas fuels this execution. Every bytecode instruction has a cost—adding two numbers might cost 3 gas, storing data 20,000 gas. You set a gas limit (max units to spend) and gas price when submitting transactions. If execution exceeds your limit, the transaction reverts, ensuring no infinite loops can halt the network. Miners or validators collect gas fees as payment for computational resources.

This architecture creates predictable, verifiable programs that execute exactly as written, viewable by anyone on block explorers like Etherscan or BaseScan.

From Idea to Onchain: The Smart Contract Lifecycle

Smart contracts progress through four stages before users can interact with them:

Write and Compile
Developers write logic in Solidity or Vyper, defining functions like deposit() or withdraw() and storage variables. A compiler (like solc) converts source code into EVM bytecode—the actual instructions nodes execute. Compilation also generates an Application Binary Interface (ABI), a JSON file describing function names, parameters, and return types that front-ends use to communicate with the contract.

Deploy
Deployment is a special transaction with no recipient address—just bytecode and constructor arguments in the data field. When miners include this transaction in a block, the EVM creates a new contract account at a deterministic address, initializes state (like setting the deployer as owner), and stores the bytecode permanently. From this moment, the contract can't be deleted, though it can be rendered unusable if designed with a selfdestruct function (deprecated in recent upgrades).

Verify
Deployed bytecode is machine-readable but opaque to humans. Verification means uploading the original source code to block explorers like Etherscan or BaseScan, which re-compile it and confirm the bytecode matches. This crucial step lets anyone read the actual logic, audit for vulnerabilities, and trust what the contract does. Verified contracts display a green checkmark and human-readable code on explorer pages.

Interact
After deployment, users and other contracts call functions via transactions. Your wallet crafts a transaction specifying the contract address, encoded function call (via ABI), gas parameters, and your signature. If execution succeeds, state updates persist onchain and events get logged for indexers to track. If logic conditions aren't met (like insufficient balance), the transaction reverts, rolling back all changes while still consuming gas for attempted computation.

This lifecycle ensures contracts are transparent, auditable, and immutable by default—you deploy once, verify for trust, and interact forever under known rules.

Interacting With a Smart Contract: What Your Wallet Actually Does

When you click "Swap" on Uniswap or "Mint" on an NFT site, your wallet performs several steps to communicate with smart contracts:

Function Selection via ABI
The front-end application references the contract's ABI to find the correct function. If you're transferring tokens, it looks for transfer(address recipient, uint256 amount) and prepares the inputs you specified—recipient address and token quantity. The ABI acts as a translation guide between user-friendly interfaces and the bytecode the EVM understands.

Transaction Construction
Your wallet builds a transaction containing:

  • To address: The smart contract address
  • Data: ABI-encoded function call (e.g., function selector + encoded parameters)
  • Value: ETH amount to send (if function is payable)
  • Gas limit: Maximum computation units authorized
  • Gas price/priority fee: Your bid for inclusion speed
  • Nonce: Transaction sequence number preventing replay attacks

Signing and Broadcasting
You review the transaction details and sign with your private key, generating a cryptographic signature proving authorization. The wallet broadcasts this signed package to the mempool, where validators pick it up for inclusion in the next block. Once mined, the EVM executes your function call.

Execution and State Changes
The contract function runs with your inputs. It might check balances, update mappings, calculate prices, or call other contracts. If all conditions pass, changes commit to state and events emit. If any check fails (like require(balance >= amount)), execution reverts, refunding unused gas but keeping the base fee for attempted computation.

Approval Transactions
Many DeFi interactions require two steps. First, you approve(spenderAddress, amount) on a token contract, granting permission for another contract (like a DEX) to move your tokens. This updates an allowance mapping. Later, when you swap, the DEX calls transferFrom(yourAddress, recipient, amount), using the allowance you pre-authorized. This pattern protects users—contracts only move tokens you've explicitly permitted, and you can revoke unused approvals anytime via tools like Revoke.cash.

Understanding this flow helps you recognize what transactions actually do: each signature authorizes specific contract code to execute specific logic with your assets.

Core Building Blocks: ABIs, Events, Logs, and Storage

Smart contracts expose several mechanisms for interaction and transparency:

Application Binary Interfaces (ABIs)
ABIs define the contract's public API—every function name, input type, output type, and whether functions modify state. When a front-end wants to call balanceOf(address) on a token contract, it uses the ABI to encode this call into bytecode and decode the returned uint256 balance. Without ABIs, wallets couldn't communicate with contracts in a standardized way.

Events and Logs
Contracts can't naturally "push" data to external systems, but they can emit events—indexed announcements stored in transaction receipts. When you transfer tokens, the contract emits Transfer(from, to, amount), logging the action onchain. Front-ends and indexers listen for these events to update balances instantly without repeatedly polling storage. Events are cheaper than storage updates, making them ideal for historical records.

For example, a swap on an AMM emits a Swap event containing input/output amounts and user address. Websites subscribe to these events via JSON-RPC to display real-time activity. Block explorers aggregate logs to show contract history.

Storage and State
State variables (like mappings and arrays) persist between function calls in contract storage slots. Reading storage is relatively cheap; writing is expensive (20,000 gas to store 32 bytes vs 3 gas to add two numbers). Developers optimize by minimizing storage writes, using memory for temporary data during execution.

Each contract's storage is isolated—one contract can't directly read another's storage. Interaction happens through function calls. This isolation is critical for security but requires intentional design for composability.

Reading vs Writing
Functions marked view or pure only read state or compute locally—calling them doesn't require transactions or gas fees. You can query balanceOf(myAddress) instantly via RPC. Functions that modify state require transactions, consume gas, and wait for block confirmation. This distinction lets users inspect contract state freely while paying only for changes.

These building blocks enable the rich interaction layer—wallets encode calls via ABIs, users monitor activity through events, and applications read state to display interfaces, all without trusting centralized backends.

Common Smart Contract Use Cases (With Real-World Examples)

Smart contracts power the applications transforming how we interact with money and digital assets:

ERC-20 Tokens
The ERC-20 standard defines fungible tokens like USDC or DAI. These contracts maintain balance mappings and implement transfer(), approve(), and transferFrom() functions. Over 80% of tokens follow ERC-20, enabling seamless integration across wallets, exchanges, and DeFi protocols. On Base, USDC at address 0x833... (simplified) processes millions of stablecoin transfers daily at under $0.01 per transaction.

Automated Market Makers (AMMs)
AMM contracts like Uniswap hold liquidity pools and execute swaps via mathematical formulas. When you swap ETH for USDC, the contract calculates output amounts using its reserves, updates balances, collects fees for liquidity providers, and emits a Swap event—all atomically in one transaction. Aerodrome Finance on Base demonstrates how Layer 2 scaling makes frequent swaps economically viable.

NFTs (ERC-721/ERC-1155)
Non-fungible token contracts assign unique IDs to digital items. ERC-721 (one item per ID) powers collectibles; ERC-1155 (multiple copies per ID) powers gaming items. Zora's creator contracts on Base let artists deploy minting contracts with custom rules—price, supply limits, royalty percentages—that execute trustlessly. Buyers call mint(), triggering ownership transfers recorded in Transfer events.

Escrow and Crowdfunding
Simple escrow contracts hold funds until conditions satisfy both parties. A buyer deposits payment; the contract releases to the seller when the buyer confirms delivery, or refunds after a timeout. Crowdfunding contracts collect contributions, checking if a goal is met by a deadline—if yes, funds go to the project; if no, contributors withdraw refunds. These "if/then" rules eliminate intermediary trust.

Stablecoins and Overcollateralization
MakerDAO's DAI uses contracts that lock ETH as collateral, minting stablecoins against it. If collateral value drops (tracked via Chainlink oracles), liquidation functions automatically execute, selling collateral to maintain stability. This programmatic risk management runs 24/7 without human intervention.

Decentralized Autonomous Organizations (DAOs)
DAO contracts hold treasury funds and execute proposals voted on by token holders. Members submit actions (like "send 10 ETH to developer"), vote onchain, and if the proposal passes, the contract automatically executes the transfer. Governance becomes transparent and programmable.

These examples share common patterns: codified rules replace manual enforcement, state updates reflect real ownership, and composability lets contracts build on each other's functionality.

Reading a Contract on a Block Explorer (Etherscan/BaseScan Walkthrough)

Block explorers like Etherscan and BaseScan let you inspect any contract's activity and code:

Finding a Contract
Search by address, transaction hash, or token name. The contract page displays its balance, transaction count, creation date, and whether source code is verified (green checkmark). Verified contracts show the original Solidity code alongside the compiled bytecode.

Read Contract Tab
View-only functions appear here. You can query balances, check allowances, or read configuration without connecting a wallet or paying gas. For example, calling balanceOf(0xYourAddress) on USDC instantly returns your token balance. This tab uses read-only RPC calls to fetch current state.

Write Contract Tab
State-changing functions require wallet connection. Click "Connect to Web3" to link MetaMask or another wallet, then interact with functions like approve() or transfer(). The explorer builds the transaction for you—fill parameters, confirm in your wallet, and the transaction submits onchain.

Internal Transactions
When a contract calls other contracts mid-execution, these appear as internal transactions. A swap might show external transaction (your wallet to DEX) plus internals (DEX to token contracts for transfers). This reveals the full execution flow.

Events Logs
The "Logs" tab shows all events emitted—Transfer, Approval, Swap, etc. Each entry includes indexed parameters (like sender address) and data (like amounts). Front-ends and analytics tools parse these logs to reconstruct activity history.

Verified Source Code
Scroll down to see the actual Solidity code if verified. You can audit logic for vulnerabilities, confirm what approvals allow, or understand fee structures. Compare multiple contracts to spot standardization (all ERC-20s have similar structures).

Key Indicators to Check:

  • Contract age (older generally means more tested)
  • Transaction volume (high activity suggests legitimacy)
  • Verification status (unverified code is a red flag)
  • Presence of admin functions like pause() or upgradeTo()

Explorers turn opaque bytecode into readable histories, making onchain activity transparent for anyone willing to look.

Safety, Upgrades, and Limitations: What Contracts Can and Can't Do

Smart contracts have powerful capabilities but fundamental constraints:

Immutability by Default
Deployed contracts can't be altered. If you find a bug post-launch, you can't patch the code at that address. This permanence is a feature—users trust rules won't change—but requires thorough auditing before deployment. The DAO hack in 2016 exploited a reentrancy bug that drained $60 million precisely because the vulnerable contract couldn't be updated.

Upgradeable Contracts via Proxies
Proxy patterns work around immutability by separating logic from data. A proxy contract (unchanging address users interact with) delegates calls to an implementation contract (changeable via admin function). Projects can fix bugs or add features by pointing the proxy to new logic. However, this introduces centralization—whoever controls the upgrade function can alter behavior, potentially maliciously.

Admin Keys and Trust
Many contracts include privileged roles—admins who can pause trading, mint tokens, or upgrade logic. While useful for emergency responses, these keys centralize control. Users must trust admins won't abuse power. Check for functions like onlyOwner modifiers and understand who holds these keys before interacting.

Oracle Dependence
Smart contracts can't fetch data from the internet—they operate in deterministic sandboxes. To access prices, weather data, or sports scores, they rely on oracles like Chainlink that push external data onchain. This creates a trust dependency: if oracle data is manipulated, contract execution reflects false information. DeFi protocols carefully select audited oracles to minimize this risk.

Reentrancy and Attack Vectors
Certain coding patterns enable exploits. Reentrancy occurs when a contract calls external code that calls back into the original contract before the first call finishes, potentially draining funds. Modern contracts use checks-effects-interactions patterns and reentrancy guards to prevent this. Audits from firms like Trail of Bits or OpenZeppelin catch these vulnerabilities.

What Contracts Can't Do:

  • Access HTTP APIs directly (need oracles)
  • Generate true randomness (need verifiable random functions)
  • Execute conditionally based on future time (need keeper networks like Gelato)
  • Operate offchain (computations happen on EVM)

Understanding these limitations helps evaluate project architecture—is data sourcing trustworthy? Are admin keys decentralized? Is the code audited?

Costs and Performance: Gas, Complexity, and Why Layer 2 Helps

Every smart contract operation consumes computational resources measured in gas:

Gas Mechanics
Simple operations cost little—adding two numbers uses 3 gas, reading storage 200 gas. Expensive operations include writing storage (20,000 gas per 32-byte slot) and deploying contracts (hundreds of thousands). When you submit a transaction, you specify a gas limit (maximum units you'll pay) and a gas price (in gwei per unit).

Total cost = gas used × gas price. A token transfer on Ethereum mainnet might use 65,000 gas. At 50 gwei price and $3,000 ETH, that's 65,000 × 50 × 10⁻⁹ × $3,000 = $9.75. Complex DeFi interactions (swaps with multiple pool hops) can exceed 200,000 gas, costing $30+ at peak times.

Code Complexity Impacts Fees
Inefficient contracts burn more gas. Loops over large arrays, unnecessary storage writes, or redundant checks inflate costs. Developers optimize by:

  • Using mappings instead of arrays for lookups
  • Batching operations (one transaction updating multiple balances)
  • Storing minimal data (using events for history instead of storage)
  • Leveraging assembly for critical paths

Why Layer 2 Solutions Like Base Help
Base (an Optimism rollup) executes transactions offchain, batching and posting compressed data to Ethereum for security. This reduces gas costs 99%—swaps costing $30 on mainnet drop to $0.30 on Base. Same EVM compatibility, same contracts, dramatically lower fees.

For users, this means:

  • Minting NFTs for cents instead of dollars
  • Frequent swaps become economically viable
  • Microtransactions (tipping, gaming) are practical

Over 500,000 Base contracts demonstrate how L2 scaling unlocks use cases prohibitively expensive on mainnet while maintaining Ethereum security guarantees.

Gas isn't a bug—it prevents denial-of-service attacks by making spam costly. But L2s prove execution can be affordable without sacrificing decentralization.

Composability and Standards: Why ERC-20/721/1155 Matter

Smart contracts become exponentially more powerful when they follow common standards:

ERC-20: Fungible Token Standard
Every ERC-20 contract implements the same core functions: balanceOf(), transfer(), approve(), transferFrom(), totalSupply(), and two events (Transfer, Approval). This consistency means wallets display any ERC-20 balance identically, DEXs can swap any pair, and lending protocols accept any compliant collateral—all without custom integration per token.

80% of tokens follow ERC-20, creating a unified layer for value transfer. When you approve Uniswap to spend your DAI, the DEX calls DAI's transferFrom() knowing exactly how it behaves.

ERC-721: Non-Fungible Token Standard
NFT contracts implement ownerOf(tokenId), transferFrom(), and approve() for unique items. Marketplaces like OpenSea integrate any ERC-721 collection automatically—they query metadata, display images, and enable transfers using standardized functions. 90% of NFT projects use ERC-721, making digital ownership interoperable.

ERC-1155: Multi-Token Standard
Gaming and virtual worlds need both fungible (gold coins) and non-fungible (swords) items in one contract. ERC-1155 supports batch operations—transfer 100 gold and 3 swords in one transaction—reducing gas. Standards let game items move between applications seamlessly.

Contract Composability in Practice
A yield aggregator contract calls:

  1. An ERC-20 token's approve() to authorize spending
  2. A lending protocol's deposit() to supply liquidity
  3. A staking contract's stake() to earn rewards
  4. An AMM's swap() to rebalance assets

All atomically in one transaction. If any step fails, everything reverts. This composability—contracts calling contracts—enables complex strategies built from simple primitives.

Standards are "interfaces" that make contracts plug-and-play. Without them, every integration would require custom code, fragmenting liquidity and limiting innovation. Shared standards create network effects where each new compliant contract increases value for all existing ones.

Practical Tips: Interacting Safely and Confidently

Protect yourself when using smart contracts:

Simulate Transactions
Tools like Tenderly or wallet simulation features let you preview transaction outcomes before signing. You see exact state changes—how much you'll pay, what you'll receive, which approvals update. If simulation shows unexpected results (like receiving 0 tokens), don't proceed.

Verify Contracts on Explorers
Always check verification status on Etherscan or BaseScan. Unverified contracts hide their code—you're trusting bytecode you can't read. Verified contracts display source code you can audit or have experts review. Look for:

  • Recent audits from reputable firms
  • Active development (recent transactions)
  • Clear documentation

Manage Token Approvals
Many DeFi hacks exploit unlimited approvals. When you approve a DEX, you often grant permission to spend your entire token balance. If that contract gets compromised, attackers can drain approved tokens. Use tools like Revoke.cash to:

  • Review all active approvals
  • Revoke unused permissions
  • Set limited approvals (approve exact amounts, not max uint256)

Recognize Red Flags
Be cautious of contracts with:

  • Unverified source code
  • High admin privileges (pause, mint, upgrade functions)
  • No audit history
  • Extremely high APYs (usually unsustainable)
  • Concentration of tokens in few wallets

Start Small
Test new protocols with minimal amounts first. If you want to try a new DEX, swap $10 before moving $10,000. Understand how gas fees work so you're not surprised by costs.

Use Layer 2 for Learning
Base's low fees make it ideal for experimenting. You can mint NFTs, swap tokens, and interact with DeFi for cents per transaction, building familiarity without financial risk.

Understand What You're Signing
Wallets show transaction details before signing—contract address, function name, parameters, gas cost. Don't blindly approve. If you don't understand what a transaction does, don't sign it. Phishing attacks trick users into signing malicious transactions disguised as legitimate ones.

Smart contracts are tools—powerful when used correctly, risky when misunderstood. Take time to learn, verify what you interact with, and build confidence gradually.

FAQs: Quick Answers to the Most Common Smart Contract Questions

Can smart contracts be changed after deployment?
No, by default deployed contracts are immutable. However, upgradeable proxy patterns allow updates by changing the implementation contract the proxy points to. Check if admin keys can upgrade logic.

Can smart contracts hold funds?
Yes, contract addresses can receive and store ETH and tokens just like wallet addresses. DeFi protocols hold billions in smart contracts, secured by code logic rather than private keys.

Why did my transaction fail?
Transactions revert if conditions aren't met—insufficient balance, failed slippage checks, or require statements failing. You still pay gas for attempted computation. Check the error message on the block explorer for specifics.

Do all blockchains use smart contracts the same way?
Most EVM chains (Ethereum, Base, Polygon, Arbitrum) run smart contracts identically. Non-EVM chains like Solana or Cardano use different virtual machines with distinct programming models but similar concepts.

What's the difference between reading and writing?
Reading contract state (view functions) is free and instant—no transaction needed. Writing state requires signed transactions, gas fees, and block confirmation time.

Are smart contracts secure?
Security depends on code quality. Audited contracts from established projects are generally safe, but bugs exist. The DAO hack, various reentrancy exploits, and oracle manipulations show smart contracts aren't automatically secure—careful design and auditing are essential.

How do I know if a contract is legitimate?
Check verification on block explorers, review audit reports, examine transaction history, and research the team. Legitimate projects provide documentation and transparent code.

Key Takeaways: What to Remember Before Your Next Onchain Action

Smart contracts are programs at blockchain addresses that execute deterministically when conditions are met, replacing intermediaries with transparent, auditable code. They power tokens, DeFi, NFTs, and DAOs by automating agreements without requiring trust in any single party.

When you interact with onchain apps, you're calling contract functions via ABI-encoded transactions your wallet signs. Understanding how wallets work helps you recognize what each signature authorizes. Contracts update state, emit events for indexers to track, and either complete successfully or revert atomically.

Key mechanisms to understand:

  • ABIs translate between user interfaces and contract bytecode
  • Events announce state changes for front-ends to monitor
  • Token approvals grant spending permissions that should be managed carefully
  • Gas pays for computation, with L2s like Base reducing costs 99%
  • Standards like ERC-20 enable composability where contracts build on each other

Safety practices matter:

  • Verify contracts on explorers before interacting
  • Simulate transactions to preview outcomes
  • Revoke unused token approvals regularly
  • Start with small amounts on new protocols
  • Use Layer 2 networks for affordable experimentation

Smart contracts aren't perfect—they can't access external data without oracles, bugs can't be patched without proxy patterns, and admin keys introduce centralization risks. But when designed well and audited thoroughly, they create trustless infrastructure enabling financial applications accessible to anyone with internet access.

The next time you swap tokens, mint an NFT, or vote in a DAO, you'll understand the contract mechanics underneath: your wallet encoding function calls, the EVM executing logic across thousands of nodes, state updates persisting onchain, and events logging activity for all to see. This transparency is what makes Web3 different—every transaction, every balance, every rule visible and verifiable by anyone who cares to look.