What Is a Smart Contract? EVM, Gas, Proxies and Failures
How a smart contract works: bytecode at an address, EVM execution, gas, ABIs, proxies and upgrade keys, plus the failures that drain wallets.
Last verified
Table of contents
- What is a smart contract?
- The EVM: a deterministic state machine
- Storage slots, and why contract state is public
- The ABI, function selectors, and what you are actually signing
- Events and logs
- Calls and transactions: reading versus writing
- Gas: the metering that makes halting safe
- A minimal contract, annotated
- Immutability, and the proxy patterns that work around it
- Upgrade keys are the real trust assumption
- How smart contract platforms compare
- Fees and costs
- What goes wrong
- What an audit buys, and what it does not
- How to read a contract before you sign
- Who needs this, and who can skip it
- The bottom line
Every token you hold, every swap you make, and every lending position you open is a call into a smart contract. The name borrows from law and suggests something that runs itself. What sits onchain is a program that does nothing until a transaction reaches it. This guide takes the mechanism apart: what is actually stored at a contract address, how the Ethereum Virtual Machine executes it, why gas exists, what your wallet is really signing, how immutable code gets upgraded anyway, and the named, documented ways these systems have lost money.
What is a smart contract?
A smart contract is a program compiled to bytecode and stored at an address on a blockchain, with its own balance and its own persistent storage, which executes deterministically whenever a transaction or a call reaches it. That is the whole definition, and each clause matters.
It is a program, so it does exactly what the code says under every input, including inputs the author did not imagine. It lives at an address, so it can hold a balance and receive transfers like any other account. It has persistent storage, so it remembers balances, owners, and parameters between transactions. It is deterministic, so every node that replays the transaction arrives at the same result, which is what lets thousands of strangers agree on the outcome without a referee.
One property people consistently get wrong: a smart contract cannot act on its own. It has no timer and no background thread. A contract that "pays out weekly" is a contract somebody calls weekly, usually a keeper bot paid to do it. If nobody calls it, nothing happens. Liquidations in lending markets work the same way, and that is why a market under stress depends on liquidators showing up and paying gas.
The other property people get wrong is privacy. A contract's storage is readable by anyone with a node, whether or not the code exposes a getter. Marking a variable private in Solidity hides it from other contracts at compile time and hides nothing from the chain. If you are new to the wider system these contracts run on, the Ethereum guide covers the base layer underneath, and the DeFi guide covers what people build with them.
The EVM: a deterministic state machine
The Ethereum Virtual Machine is the runtime every node implements identically. Ethereum's own documentation describes the network as a distributed state machine holding accounts, balances and a machine state that changes block by block according to fixed rules, expressed as a transition function that takes the old valid state plus new transactions and produces a new state.
Mechanically, the EVM is a stack machine with a depth of 1024 items, and each item is a 256-bit word. The 256-bit width was chosen to make the cryptography Ethereum relies on cheap to express. Contracts get three kinds of working space:
- Stack. Where arithmetic happens. Cheap, small, and the reason deeply nested Solidity functions hit "stack too deep" compiler errors.
- Memory. A byte array that exists for the duration of one execution and is wiped afterwards. Function arguments, temporary arrays and return data live here.
- Storage. A persistent key-value map committed into the global state trie. This is the expensive one, because every full node has to keep it forever.
Determinism is enforced by leaving out everything unpredictable. There is no clock beyond the block timestamp, no network access, no random number generator, and no filesystem. A contract that needs a price, a random number, or any fact about the outside world has to be told by a transaction, which is the entire reason oracles exist as a product category and why Chainlink turned a plumbing problem into a business.
Storage slots, and why contract state is public
Contract storage is addressed as slots, each holding one 256-bit word, and the Solidity compiler assigns them in declaration order. Small variables are packed together into a single slot where they fit, which is why the order in which you declare variables changes deployment and usage cost. Mappings and dynamic arrays do not sit inline; their contents are placed at slots derived by hashing the key together with the slot number, so the map can be sparse across an enormous address space without reserving anything.
Two practical consequences follow. First, anyone can read any slot directly with an RPC call, so "private" is a language keyword rather than a privacy feature. Second, storage layout is part of a contract's compatibility surface. When an upgradeable system swaps in new implementation code whose variables are declared in a different order, the new code reads old data through the wrong lens. Storage collisions of this kind are among the more expensive self-inflicted upgrade bugs, and they are why proxy standards reserve their own pseudo-random slots instead of using slot zero.
The ABI, function selectors, and what you are actually signing
A contract does not expose named functions at the protocol level. It exposes one entry point that receives a blob of bytes called calldata, and it is the compiled code's job to work out what you meant.
The convention that makes this usable is the Application Binary Interface. The Solidity ABI specification states that the first four bytes of calldata specify the function to be called, and that those bytes are the first four bytes of the Keccak-256 hash of the function's signature, meaning the name plus its parameter types. From the fifth byte onward the encoded arguments follow, padded to 32-byte words, with dynamic types like strings and arrays placed via offset pointers.
So a transfer request is four bytes identifying transfer(address,uint256) followed by two 32-byte words. That is the entire message. Your wallet reverses the process for display: it takes those four bytes, looks them up against a signature database or the verified source, and renders "Transfer 100 USDC". When the wallet cannot decode the selector, it shows you raw hexadecimal, and that is a moment to slow down rather than click through.
Four bytes is a small space, so two different function signatures can hash to the same selector. Selector clashes are a known hazard in proxy design, which is why OpenZeppelin's transparent proxy answers admin calls at the proxy itself instead of letting them fall through to the implementation where a clash could be exploited. The practical consequence for you is that a decoded, human-readable simulation from your wallet is worth more than a function name.
Events and logs
Contracts cannot push notifications, so they emit events, which are written into the transaction receipt as logs rather than into storage. Logs are much cheaper than storage because contracts cannot read them back; they exist for the outside world. Up to three indexed parameters become searchable topics, so an application can ask a node for every Transfer log involving a given address without replaying the chain.
Every portfolio tracker, block explorer table and subgraph you have used is reading logs. When a protocol's front end shows your position and the chain shows something different, the discrepancy is almost always an indexing lag in that log pipeline rather than a change in the contract's state.
Calls and transactions: reading versus writing
There are two ways to interact with a contract, and confusing them causes real mistakes.
A read-only call (eth_call at the RPC level) runs the code on a single node against current state, returns the result immediately, costs nothing, and discards any state changes. Wallets and front ends fire these constantly to display balances, allowances, quotes and health factors.
A transaction is signed with your private key, broadcast to the mempool, included in a block, and re-executed by every node. It costs gas, it is ordered relative to everyone else's transactions, and its effects persist.
The gap between them is where people get hurt. A simulation succeeding proves the call would have worked against the state the node had at that instant. By the time your transaction lands, a price may have moved, a pool may have been drained, or a searcher may have sandwiched you. Slippage limits exist precisely because the simulated price and the executed price are different numbers, and the MEV guide explains who profits from that gap.
A subtler trap: a simulation that returns success is weaker evidence than it looks. A contract can accept a call, do nothing useful, and return normally. Success means no revert, and it does not mean the state changed the way you assumed.
Gas: the metering that makes halting safe
Running arbitrary code submitted by strangers on a network anyone can join should be impossible. Gas is what makes it merely expensive.
Every EVM instruction carries a gas cost roughly proportional to the burden it puts on nodes. Arithmetic is cheap. Reading storage is far more expensive than reading memory. Writing a storage slot from zero to non-zero is the most expensive routine operation, because it grows the state every node must keep, and clearing a slot back to zero refunds part of the cost. You submit a gas limit, the execution consumes gas as it runs, and you pay for what was used at the prevailing price.
If execution exhausts the limit, the transaction reverts: every state change is rolled back, and you still pay for the work performed, because the nodes did it. That single rule is the practical answer to the halting problem. Nobody needs to prove a contract terminates, because an infinite loop terminates when the money runs out.
Gas costs also shape how contracts are written. Loops over unbounded arrays are dangerous because the array can grow until iterating it exceeds a block's gas limit and the function becomes permanently uncallable. A contract that distributes rewards by looping over every holder is a contract with a built-in expiry date. Experienced authors use pull-based patterns where each user claims their own share, which is cheaper, safer, and incidentally removes a reentrancy surface.
Deployment has its own ceiling. EIP-170 caps deployed contract bytecode at 24,576 bytes (0x6000) on Ethereum mainnet, and creation fails with an out-of-gas error above it, which is why large systems split logic across libraries and facets instead of shipping one enormous contract. Proposals to raise the limit and meter oversized code by gas exist, and as of this writing none has shipped to mainnet.
A minimal contract, annotated
Here is a deliberately small contract that carries most of the concepts above. Read the comments rather than the syntax.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Vault {
// Storage slot 0. Written once at deployment, read on every admin call.
address public owner;
// A mapping. Nothing is stored inline; each balance lives at a slot
// derived by hashing (depositor address, slot number).
mapping(address => uint256) public balanceOf;
// Events are written to logs rather than storage. Indexed parameters
// searchable topics so indexers can filter without replaying the chain.
event Deposited(address indexed who, uint256 amount);
event Withdrawn(address indexed who, uint256 amount);
// Runs once, at deployment. The deployed bytecode does not include it.
constructor() {
owner = msg.sender;
}
// A modifier: reusable precondition. Access control is just a check,
// and a missing check is how most access-control failures happen.
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
// `payable` means this function may receive value. msg.value is the
// amount sent with the call, in wei.
function deposit() external payable {
balanceOf[msg.sender] += msg.value;
emit Deposited(msg.sender, msg.value);
}
function withdraw(uint256 amount) external {
// CHECKS: validate before touching anything.
require(balanceOf[msg.sender] >= amount, "insufficient");
// EFFECTS: update our own bookkeeping BEFORE the external call.
// Reversing these two blocks recreates the reentrancy bug that
// drained The DAO: the callee can re-enter while the old balance
// is still recorded.
balanceOf[msg.sender] -= amount;
// INTERACTIONS: the external call comes last. `call` forwards all
// remaining gas and hands control to arbitrary code at `msg.sender`.
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "transfer failed");
emit Withdrawn(msg.sender, amount);
}
// Anyone can read `owner` and `balanceOf` directly from storage over RPC,
// with or without these getters. `private` would not change that.
function setOwner(address next) external onlyOwner {
owner = next;
}
}
The ordering in withdraw is the checks-effects-interactions pattern, and it is the single most valuable habit in the language. The external call is the moment control leaves your contract and enters somebody else's, and everything you have not yet written down is still stale when it does.
Immutability, and the proxy patterns that work around it
The bytecode at an address is fixed once deployed. There is no edit, and the only removal mechanism the EVM ever offered was selfdestruct, whose behaviour has been deliberately narrowed over successive upgrades.
That immutability is a feature for a token or an AMM whose rules should never move, and it is impractical for a lending market that needs new collateral types and parameter changes. The industry answer is the proxy.
A proxy is a thin contract that holds the balances and the storage, and forwards every call it receives to a separate implementation contract using delegatecall. That opcode runs the implementation's code in the proxy's storage context, so the logic is borrowed while the data stays put. Upgrading means pointing the proxy at a new implementation address. Your address for the protocol never changes, and its behaviour can change completely.
Four shapes cover almost everything you will meet:
| Pattern | Where upgrade logic lives | Main advantage | Main hazard |
|---|---|---|---|
| Transparent proxy | In the proxy, behind an admin address | Simple, widely tooled, the admin cannot accidentally hit user functions | Slightly higher gas per call, admin address must be managed separately |
| UUPS (ERC-1822 style) | In the implementation contract | Cheaper calls, smaller proxy | Shipping an implementation with a broken or missing upgrade function can brick upgrades permanently |
| Diamond (ERC-2535) | In a facet routing table | Routes around the 24,576-byte size limit, modular | Much larger surface, harder to audit and to reason about which facet answered |
| Beacon proxy | In a shared beacon contract | Upgrades many proxies at once | One key change moves every deployment simultaneously |
ERC-1967 standardises the storage slots these patterns use, defining fixed locations for the implementation address, the admin address and the beacon address, which is what allows block explorers to detect a proxy and show you both halves. Each slot is the keccak-256 hash of an identifying string minus one, for example eip1967.proxy.implementation, a value the Solidity compiler will never allocate to an ordinary variable and whose preimage nobody can reach through a mapping key.
Upgrade keys are the real trust assumption
Once you understand proxies, the security question changes shape. Reading the code at an address tells you what it does today. The question that governs your risk is who can replace it tomorrow, and how fast.
In practice the upgrade key is one of four things: a single externally owned account, a multisig such as a Safe, a timelock contract that queues changes for a fixed delay before they can execute, or a token-voting DAO. They are ordered there roughly from worst to best, with one caveat: a DAO with concentrated token ownership is a multisig wearing a costume, and a timelock only helps if somebody is watching the queue.
The questions worth asking before you commit size to any contract:
- Is it a proxy at all? The explorer will usually say.
- Who is the admin, and is that address a multisig or one key?
- What threshold does the multisig require, and are the signers publicly known and independent?
- Is there a timelock, and how long is the delay? A delay is only useful if it is longer than the time you need to exit.
- Can parameters like fees, oracles or collateral factors be changed instantly, separately from a code upgrade?
Malicious and compromised upgrades are one of the recurring ways large sums have left DeFi protocols, and in most of those cases the contract code itself was fine and had been audited. The keys were the weak part. This is the same category of risk that account abstraction is trying to make legible at the wallet level, by turning your account into a contract with explicit, inspectable rules.

How smart contract platforms compare
The EVM dominates, and it is one design among several. The differences show up in how state is modelled and how parallel execution works, which then shows up in what kinds of bugs are common.
| Platform | Language | Execution model | State model | Typical strengths | Where it bites |
|---|---|---|---|---|---|
| Ethereum and EVM chains | Solidity, Vyper | Sequential, single-threaded EVM | Contract owns its own storage | Largest tooling ecosystem, most audited libraries, works across Layer 2s and many L1s | Reentrancy and approval risks are native to the model, and sequential execution limits throughput |
| Solana | Rust, via the Anchor framework | Parallel, transactions declare the accounts they touch | Programs are stateless, data lives in separate accounts | High throughput because non-overlapping transactions run at once | Account validation is the developer's job, and missing checks are the dominant bug class |
| Sui | Move | Parallel for independent objects | Assets are first-class objects with ownership rules | The type system makes it hard to duplicate or accidentally drop an asset | Smaller ecosystem, fewer reusable audited components |
| Cosmos chains | Rust, via CosmWasm | Sequential per chain | Contract-owned key-value store | Contracts sit inside app-specific chains with custom modules | Fragmented liquidity across many sovereign chains |
| Bitcoin | Script | Deliberately limited, no loops | UTXO, no contract storage | Very small attack surface, predictable validation | Cannot express most DeFi logic without layers built on top |
The EVM's share of tooling is the practical argument for it. Battle-tested libraries, static analysers, formal verification tools, and a large pool of reviewers who have seen the same mistakes hundreds of times all concentrate there. Ethereum alone carries several times the DeFi value of most other ecosystems, with chain TVL around $30.54B at the time of writing. That concentration is also why attackers study it hardest.
Fees and costs
Contracts cost money in more places than the gas fee at the top of your wallet screen.
| Cost | Who charges it | Shape | How to reduce it |
|---|---|---|---|
| Execution gas | The network, via block space demand | Scales with how much storage the call reads and writes, so a swap costs multiples of a plain transfer | Transact on an L2 where the same call costs a fraction, or wait for quiet periods on mainnet |
| Approval transaction | The network | A separate transaction before your first interaction with a token and contract pair | Use contracts that support permit-style signed approvals, which fold the approval into the action |
| Failed and reverted transactions | The network | You pay for the work done up to the revert, and receive nothing | Simulate first, set slippage deliberately, avoid racing into congested mints |
| Protocol fee | The contract itself | A percentage of the trade, the yield, or the borrow rate, written into the code and often adjustable by governance | Read the fee parameter and check who can change it before you size a position |
| Slippage and price impact | The liquidity pool | Usually larger than gas on thin pairs, and invisible unless you look | Trade deep pairs on a major DEX, split large orders |
| MEV extraction | Searchers and builders | A sandwich around your trade, paid as a worse execution price | Use private transaction routes where your wallet offers one, keep slippage tight |
| Deployment | The network, once | Proportional to bytecode size, capped at 24,576 bytes | Split logic into libraries, ship less code |
| Audit | The reviewing firm | Priced per engineer-week, so scope and code size dominate | Reduce scope by reusing standard audited components |
Two habits save the most money. Batch your activity so approvals and bridge hops are not repeated, and do the routine work on a low-fee chain, keeping mainnet for the positions that are big enough to justify it. Gas prices move constantly, so treat any figure you read anywhere, including here, as a shape rather than a quote and check your wallet before confirming.
What goes wrong
Every item below has cost real money, and each has a standard fix that was known before the incident.
Reentrancy. A contract sends value or calls an external address before updating its own accounting, and the callee calls straight back in while the stale balance is still recorded. This drained roughly 3.6 million ETH from The DAO in June 2016, about a third of the fund, and the community's response was the hard fork at block 1,920,000 on 20 July 2016 that split the chain and created Ethereum Classic. The fix: checks-effects-interactions ordering, plus a reentrancy guard on any function that makes an external call. Read-only reentrancy, where a view function returns stale data mid-transaction and another protocol trusts it, is the modern variant that still catches people.
Missing or wrong access control. A function that should be restricted is callable by anyone, or the wrong contract is trusted to speak for another. In August 2021 an attacker exploited the relationship between Poly Network's cross-chain contracts to change the keeper public key and then authorise withdrawals, taking about $611 million across Ethereum, BNB Chain and Polygon. The funds were returned over the following two weeks. The fix: explicit role checks on every state-changing function, a written list of which addresses may call what, and tests that assert unauthorised callers revert.
Uninitialised contracts and dangerous opcodes. In November 2017 an unprotected initialiser on a shared Parity wallet library let an outside account take ownership and then call selfdestruct on it. Nothing was stolen, and more than half a million ETH became permanently unreachable because the logic those wallets depended on no longer existed. The fix: initialise implementation contracts at deployment, disable initialisers on the implementation behind a proxy, and treat selfdestruct and delegatecall as requiring a written justification.
Oracle manipulation. A contract prices collateral from a market that is cheap to move. In October 2022 an attacker pushed the MNGO price up on the venues feeding Mango Markets' oracle, borrowed against the inflated collateral, and let the price collapse, taking roughly $110 million. A US jury convicted the trader in April 2024. On 23 May 2025 the trial court entered a judgment of acquittal, vacating the commodities fraud and wire fraud convictions on venue grounds and holding that the wire fraud count also lacked evidence of a false statement, because the protocol imposed no rules on borrowing that could be lied about. The mechanism is the same either way. The fix: use time-weighted or aggregated feeds from multiple independent sources, cap how fast a price can move between updates, and never price a thin asset from its own spot pool.
Economic design that breaks under a flash loan. Code can be correct and the incentives still wrong. In April 2022 an attacker flash-borrowed over a billion dollars, converted it into Beanstalk's whitelisted governance tokens, reached a supermajority of voting weight, and used the protocol's own emergency-execution path to pass and run a malicious proposal, removing about $182 million. The fix: snapshot voting power at a block before the proposal, enforce a real delay between proposal and execution, and assume any capital requirement that can be met within one transaction will be.
Rounding, precision and unchecked arithmetic. Solidity 0.8 made arithmetic revert on overflow and underflow by default, with unchecked blocks restoring the old wrapping behaviour where an author asks for it, and rounding remains a live bug class. Share-based vaults are the classic case: an attacker deposits a tiny amount, donates assets directly to inflate the share price, and later depositors' shares round down to zero. The fix: round in the protocol's favour deliberately, seed vaults with dead shares at deployment, and write property tests that assert an attacker cannot end a sequence richer than they started.
Signatures and approvals granted to the wrong place. A phishing site does not need a bug. It asks you to sign an approval or a permit, and then legitimately spends your tokens. There is no contract flaw to find afterwards, because the contract did what you authorised. The fix: read what your wallet is asking before approving, keep long-term holdings in a wallet that never touches unfamiliar sites, and revoke old allowances periodically. How to spot crypto scams covers the delivery side of this.
What an audit buys, and what it does not
An audit is a time-boxed review of a specific commit by people who have seen a lot of Solidity. Done well, it catches the known bug classes, questions the assumptions in the design, and hands the team a list of findings with severities and suggested fixes.
What it genuinely buys: a sharp reduction in the odds of a familiar mistake reaching production, a second opinion on the threat model, and a public artefact that tells you someone competent looked. Competitive audit platforms and bug-bounty programmes add a different shape of coverage, with many independent reviewers instead of one team.
What it does not buy:
- Coverage of anything deployed after the review. Compare the audited commit hash to what is live.
- Protection from a malicious or careless upgrade. No reviewer can audit code that does not exist yet.
- Key security. Compromised signers defeat perfect code.
- Economic safety. Most audits examine code correctness, and incentive design under adversarial capital is a separate discipline.
- Oracle robustness beyond the integration itself. Whether the upstream feed can be pushed around is often out of scope.
Read the report rather than the badge. The scope section tells you which files were in and which were excluded, the findings list tells you what was found and whether it was fixed, and the acknowledged-risk section is where teams record the things they decided to live with. That last section is usually the most informative page in the document. Our best smart contract auditors guide covers who does this work, and pwnsy's smart contract vulnerabilities breakdown goes deeper into the bug classes themselves.
How to read a contract before you sign
You do not need to read Solidity to do most of this. Ten minutes on a block explorer separates ordinary risk from obvious traps.
- Get the address from the project's own domain or docs, never from a search ad, a DM or a Discord link. Bookmark it. A perfect contract at a fake address takes everything.
- Open the address on a block explorer and check the Contract tab. Verified source means the published code matches the deployed bytecode. Unverified means you are trusting a stranger's description of a black box.
- Check whether it is a proxy. Explorers detect the ERC-1967 slots and offer a "read as proxy" view. If it is one, open the implementation address too, and find the admin.
- Look at age and holdings. A contract deployed three days ago holding almost nothing, asking for an unlimited approval, is a different proposition from one that has held nine figures for two years.
- Read the transaction your wallet is proposing. Three requests behave very differently: a value transfer moves funds once, an approval grants standing permission, and an offchain signature can authorise something later with no transaction trace to warn you.
- Check the allowance amount. If the interface offers a finite approval, take it. If it insists on unlimited, decide whether you trust the contract for years rather than for this trade.
- Test with a small amount. Send a small first transaction, confirm the result on the explorer, then size up. This catches wrong-network and wrong-address errors before they matter.
- Check who can change the rules. Find the owner or admin, see whether it is a multisig or a timelock, and look for a recent upgrade. A contract upgraded yesterday deserves a second look today.
- Review your approvals on a schedule. Set a recurring reminder and clear out allowances you no longer use, particularly on wallets holding size.
Who needs this, and who can skip it
If you hold assets in self-custody and interact with DeFi, the parts that matter to you are approvals, proxies and upgrade keys. Everything else here is useful context, and those three are what decide whether you keep your money. Steps 5, 6 and 9 above are the whole return on this article for most readers.
If you are building, the mechanism sections are the floor. Use audited standard implementations rather than writing your own token or proxy, get a review before you hold other people's funds, and budget for a bug bounty as an ongoing cost.
If you only buy and hold on a regulated exchange, or keep coins on a hardware wallet and never sign anything, you can treat this as background. Your risk lives with the exchange's solvency and your own key handling, and neither is a contract question. The moment you connect a wallet to a protocol, it becomes one.
If you are evaluating a protocol as an investment rather than as a user, the upgrade-key section is the part to read twice. Code risk is one input, and governance concentration tends to be the input that determines what happens on the worst day.
The bottom line
A smart contract is a program at an address that runs when it is called, remembers its state, and does exactly what it says under inputs nobody anticipated. The EVM makes that execution deterministic, gas makes it safe to let strangers run arbitrary code, and the ABI is the four-byte convention that lets your wallet name what you are about to authorise.
The interesting risk sits above the code. Deployed bytecode is immutable, so almost every large protocol you use is a proxy in front of swappable logic, and the key that swaps it is the real counterparty. An audit narrows the space of known bugs in a snapshot of that logic, and it does not cover the upgrade, the keys, the oracle or the permission you granted three years ago and forgot.
Learn to read a contract's proxy status, its admin, and the approval your wallet is requesting. Those three checks take minutes and defend against most of what has actually gone wrong.
Frequently asked questions
What is a smart contract in simple terms?
A smart contract is a program stored on a blockchain at its own address. It holds a balance and its own persistent data, and it runs only when someone sends it a transaction. Every node on the network runs the same code against the same prior state and must reach the same answer, which is what makes the result trustworthy without a referee. The rules are fixed once the code is deployed, so a lending market, a token, or an exchange written this way behaves the same for everyone who calls it.
Are smart contracts legally binding contracts?
Usually not by themselves. A smart contract is software that executes a set of rules automatically, and most deployments have no named parties, no governing law and no dispute process. Some jurisdictions recognise code as evidence of an agreement, and some regulated products deliberately wrap onchain execution in a normal legal agreement. Treat the code as the thing that will actually happen, and treat any legal protection as a separate question you have to answer with paperwork.
Can a smart contract be changed after it is deployed?
The bytecode at a given address cannot be edited. Teams work around that by deploying a thin proxy contract that holds the balances and delegates every call to a separate implementation contract, then pointing the proxy at new implementation code when they want to change behaviour. The transparent proxy, UUPS and diamond patterns are the common shapes. This means the code you reviewed can be replaced by whoever holds the upgrade key, which is a governance trust assumption rather than a code one.
What is gas and why do smart contracts need it?
Gas is the unit that meters computational work. Every EVM instruction has a gas cost, you set a limit for your transaction, and you pay for the gas consumed at the prevailing price. Metering solves the halting problem in practice: an infinite loop stops when it exhausts the gas limit instead of freezing the network. If a transaction runs out of gas it reverts every state change it made, and you still pay for the work the network already performed.
What is a reentrancy attack?
Reentrancy happens when a contract sends value or calls out to another address before it finishes updating its own bookkeeping. The receiving contract can call straight back into the original function while the old balance is still recorded, and repeat that loop to withdraw far more than it deposited. This is the bug that drained roughly 3.6 million ETH from The DAO in June 2016 and led to the hard fork at block 1,920,000 that created Ethereum Classic. The standard defences are the checks-effects-interactions ordering and a reentrancy guard.
Does an audit mean a smart contract is safe?
No. An audit is a time-boxed review of a specific commit by people looking for known bug classes. It reduces the odds of a familiar mistake surviving to production, and it says nothing about code deployed after the review, about a malicious or careless upgrade, about compromised signer keys, about an oracle that can be pushed around, or about economic designs that behave badly under a flash loan. Read the scope, the commit hash and the list of unresolved findings rather than the badge.
How do I check a contract before I sign a transaction?
Open the address on a block explorer and confirm the source code is verified, so the published Solidity actually compiles to the deployed bytecode. Check whether the explorer flags it as a proxy, and if so find the implementation and the admin. Look at how old the contract is and how much it holds. Then read what your wallet is asking for: a token approval, a signature, or a value transfer are very different requests, and an unlimited approval to an unfamiliar address is the single most common way wallets get emptied.
What is the difference between a call and a transaction?
A read-only call is simulated by one node against current state, returns an answer immediately, costs nothing and changes nothing. A transaction is signed, broadcast, included in a block and re-executed by every node, which is why it costs gas and why its effects are permanent. Wallets use calls constantly to show you balances and quotes. The important consequence is that a successful simulation does not prove the same call will succeed as a transaction, because state may have moved in between.
Sources & References
Figures in this guide are cross-referenced against the sources below.
- Ethereum Virtual Machine (EVM) · Ethereum Foundation
- Solidity documentation: contract ABI specification · Solidity
- ERC-1967: Proxy Storage Slots · Ethereum Improvement Proposals
- Smart contracts overview · Ethereum Foundation
- EIP-170: Contract code size limit · Ethereum Improvement Proposals
- Ethereum history: the DAO fork at block 1,920,000 · Ethereum Foundation
- Venue fatal in crypto fraud case: United States v. Eisenberg · Venable LLP
- Smart contract vulnerabilities · pwnsy