Smart Contracts & How They Work

The Ethereum Virtual Machine, gas mechanics, ERC-20 and ERC-721 standards, DeFi use cases, and the major smart contract vulnerability classes — reentrancy, oracle manipulation, flash loans — with risk implications for DeFi traders.

Course 55: Smart Contracts & How They Work

Blockchain & Mining Track · 28 min read · Intermediate

In June 2016, an attacker drained approximately $60 million worth of ETH from a decentralised investment fund called The DAO using a technique that had been publicly discussed for weeks in the smart contract developer community — a reentrancy attack on poorly structured withdrawal logic. The incident resulted in a contentious hard fork of Ethereum (producing Ethereum Classic), crystallised the maxim "code is law," and established smart contract security as a discipline in its own right. That single exploit remains, eight years later, the clearest demonstration of what smart contracts are, what makes them powerful, and what makes them dangerous. This course covers the mechanics of smart contracts from first principles, the Ethereum Virtual Machine (EVM) execution environment, the major vulnerability classes that have cost DeFi protocols billions of dollars, and the practical risk management implications for traders who hold positions in smart-contract-dependent protocols. It extends the blockchain foundation of Course 51 and the consensus architecture of Course 54 into the application layer that makes DeFi, NFTs, and DAOs possible.

What Is a Smart Contract?

The term "smart contract" was coined by cryptographer Nick Szabo in 1994, more than a decade before Bitcoin. Szabo defined a smart contract as a computerised transaction protocol that executes the terms of a contract automatically, self-enforcing the conditions without requiring trusted intermediaries. His canonical analogy was the vending machine: you insert money, select a product, and the machine mechanically enforces the transaction — dispensing the product and returning change — without a human clerk to validate or authorise the exchange. The machine's logic is the contract.

In the context of modern blockchains, a smart contract is a programme stored on a blockchain that runs automatically when specific conditions are met. Key characteristics:

  • Deterministic: given the same inputs and starting state, every node executing the contract produces the same output. There is no ambiguity, no judicial interpretation, no negotiation.
  • Immutable (by default): once deployed to the blockchain, the contract code cannot be altered. Every interaction is permanently recorded. Bugs are permanently deployed unless the contract includes an upgrade mechanism (which introduces its own trust assumptions).
  • Trustless: neither counterparty needs to trust the other. The code enforces the terms. This is the foundational property that makes decentralised exchanges, lending protocols, and stablecoins possible without a bank or broker.
  • Transparent: the contract's bytecode (and usually its source code, verified on Etherscan) is publicly visible to anyone. Security by obscurity is not available.

The Ethereum Virtual Machine (EVM)

Smart contracts on Ethereum run inside the Ethereum Virtual Machine (EVM) — a stack-based, sandboxed computation environment that is identical on every Ethereum node worldwide. This universality is what makes deterministic execution possible: regardless of whether a node runs on a Linux server in Singapore or a laptop in New York, the same contract code produces the same result.

The EVM processes transactions by executing contract bytecode instruction by instruction. Each instruction (opcode) has an associated gas cost — a unit of computational work. Simple operations (arithmetic, comparisons) cost single-digit gas amounts; expensive operations (writing to storage, deploying new contracts, cryptographic operations) cost hundreds to thousands of gas units. A gas limit is specified by the transaction sender; if execution would exceed this limit, the transaction reverts (all state changes are rolled back) but the gas already consumed is still charged. This metering system prevents infinite loops and denial-of-service attacks on the network by making computational abuse economically expensive.

The gas price (denominated in Gwei, where 1 Gwei = 10−9 ETH) is what users pay per unit of gas. Since EIP-1559 (August 2021), gas pricing uses a base fee (algorithmically set by the network, burned) plus an optional priority fee (tip to the validator). During periods of high demand — NFT mints, DeFi liquidation cascades, token launches — the base fee can spike by 10× within minutes. Understanding gas dynamics is essential for timing on-chain interactions and for properly estimating the cost of entering or exiting DeFi positions, which the DennTech free crypto tools help model.

EVM Smart Contract Execution FlowUser Transactiondata + gas limit + tipEVM Executorbytecode + stack + memoryGas Meterdeduct per opcode; revert if OOGState Updateor REVERTEVM State: World State (all accounts) + Contract Storage + Transaction ContextAccount Types:EOA (externally owned)Contract (code + storage)Gas Opcode Costs (examples):ADD: 3 gas | SSTORE (new): 20,000 gasCALL: 700 gas | CREATE: 32,000 gasEIP-1559 Fee:Base fee (burned) +Priority fee (to validator)
Fig 1 — EVM execution flow. A user transaction triggers bytecode execution in the EVM. Each opcode deducts gas; an out-of-gas (OOG) condition reverts all state changes. Successful execution updates the world state; EIP-1559 burns the base fee and pays the priority fee to the proposing validator.

Token Standards: ERC-20 and ERC-721

The vast majority of assets in DeFi exist as smart contracts implementing standardised interfaces. Two standards dominate:

  • ERC-20 (fungible tokens): the token standard for interchangeable assets. Every ERC-20 implements six mandatory functions: totalSupply(), balanceOf(address), transfer(to, amount), transferFrom(from, to, amount), approve(spender, amount), and allowance(owner, spender). Any exchange, wallet, or protocol that knows the ERC-20 interface can interact with any ERC-20 token without special integration. USDC, LINK, UNI, AAVE, and thousands of other tokens are ERC-20 contracts. The approval mechanism is a frequent source of phishing attacks: malicious contracts request unlimited approval, then drain the approved amount later.
  • ERC-721 (non-fungible tokens): the NFT standard. Each token has a unique tokenId. The standard implements ownership tracking, transfer logic, and approval — but no two ERC-721 tokens in a collection are interchangeable. CryptoPunks, Bored Ape Yacht Club, and most profile picture NFT collections are ERC-721 contracts. ERC-1155 extends this to semi-fungible tokens (multiple quantities of the same unique item) and is widely used in gaming.

The token approval risk is practically significant for active DeFi traders: every time you approve a protocol to spend your tokens, you create an open allowance that persists until explicitly revoked. Compromised protocols, malicious upgrades, and phishing contracts all exploit existing approvals. Regularly auditing and revoking unnecessary token approvals is a baseline operational security practice, covered in the security principles of Course 52.

DeFi: What Smart Contracts Enable

The combination of ERC-20 tokens, AMM liquidity pools, lending protocols, and smart contract composability created Decentralised Finance (DeFi) — a financial system where users can lend, borrow, trade, and earn yield without custodial intermediaries. The key primitives:

  • Decentralised exchanges (DEXs): Uniswap, Curve, and Balancer use Automated Market Maker (AMM) logic. Liquidity providers deposit token pairs into a smart contract pool; the pool's price function (typically x × y = k for Uniswap v2) determines trade execution automatically. No order book, no counterparty matching — all governed by contract logic.
  • Lending protocols: Aave, Compound, and Morpho allow users to deposit collateral and borrow other assets, with interest rates determined algorithmically by utilisation ratios. Collateral liquidations are automated by smart contracts when positions fall below their minimum collateral ratio — a key source of on-chain volatility cascade.
  • Stablecoins: DAI (MakerDAO), FRAX, and similar crypto-collateralised stablecoins are maintained entirely by smart contract logic — liquidating under-collateralised vaults to maintain the peg. Algorithmic stablecoins like the former LUNA/UST system used smart contract mint/burn mechanics to maintain peg — and failed catastrophically when that logic interacted with a bank-run dynamic in May 2022.
  • Yield aggregators and vaults: Yearn Finance and similar protocols use smart contracts to automatically allocate capital to the highest-yielding strategies across multiple protocols — compounding gains and rebalancing without manual intervention.

Smart Contract Vulnerabilities

The immutability and transparency of smart contracts creates a unique security environment: bugs are publicly visible and permanently exploitable. The major vulnerability classes:

  • Reentrancy: the vulnerability that drained The DAO. A reentrancy attack occurs when a smart contract calls an external contract before completing its own state update. If the external contract calls back into the original contract (re-enters it), it can exploit the un-updated state. In The DAO's case: the withdraw() function sent ETH before marking the balance as zero. An attacker's malicious contract repeatedly called withdraw() in its receive() function before the first call completed, recursively draining funds. The fix: always update state before making external calls (the "Checks-Effects-Interactions" pattern) and/or use reentrancy guards.
  • Integer overflow/underflow: before Solidity 0.8.0, arithmetic operations could silently wrap around (a uint8 at 255 incremented by 1 would become 0). This was exploited in several token contracts. Solidity 0.8.0 added automatic overflow checks; older contracts or those using unchecked blocks remain vulnerable.
  • Oracle manipulation: smart contracts often need real-world price data (e.g., "what is ETH/USD right now?"). On-chain oracle solutions (Chainlink, Pyth) are the standard, but many protocols have used single on-chain liquidity pool spot prices as oracles. These can be manipulated within a single transaction using flash loans (borrow huge amounts without collateral, manipulate the price, exploit the oracle-dependent contract, repay — all within one atomic transaction). The bZx, Harvest Finance, and Cheese Bank exploits all exploited oracle manipulation via flash loans.
  • Access control failures: missing or incorrect onlyOwner or role-based modifiers that allow arbitrary users to call privileged functions. The Ronin Bridge hack ($625M, 2022) resulted from compromised private keys of validator nodes, not a contract bug per se — but the access control model concentrated too much signing authority in too few keys.
  • Upgradeable proxy misuse: many protocols use upgradeable proxy patterns (the implementation contract can be replaced). If the upgrade mechanism has insufficient access controls or the new implementation has bugs, the entire protocol's funds are at risk. The Wormhole bridge exploit ($320M, 2022) involved a logic error in the verification function of a new implementation.
Reentrancy Attack — The DAO PatternAttacker Contract1. call withdraw(100 ETH)4. receive() → call withdraw again!repeat until pool drainedVictim DAO Contract2. send(100 ETH) ← FIRST3. balance[attacker] -= 100 ← SECONDbalance not updated before send!FIX: Checks-Effects-Interactions Pattern1. Check: require(balance[msg.sender] >= amount)2. Effect: balance[msg.sender] -= amount ← update state FIRST3. Interaction: msg.sender.transfer(amount) ← external call LAST
Fig 2 — Reentrancy attack pattern. The victim contract sends ETH before updating the attacker's balance. The attacker's receive() function re-enters withdraw() while the balance still shows the original amount. The fix (Checks-Effects-Interactions) updates state before making any external call.

Flash Loans: Capital Without Collateral

Flash loans are an innovation unique to smart contract platforms with no analogue in traditional finance. In a flash loan, a user borrows any amount of tokens from a lending protocol — potentially hundreds of millions of dollars — with no collateral requirement, on the condition that the borrowed amount (plus a small fee) is repaid within the same transaction. If the loan is not repaid within the transaction, the entire transaction reverts as if nothing happened. The protocol faces no credit risk.

Flash loans are legitimately useful for: arbitrage between DEXs (buy low on Uniswap, sell high on Curve, repay loan, pocket the spread — all atomically); liquidating under-collateralised positions with borrowed capital; collateral swaps in lending protocols. They are also the key enabler of many oracle manipulation attacks: an attacker can temporarily distort a DEX pool's price using a flash loan, exploit a protocol that reads that pool as its price oracle, then repay the loan — all in one transaction. The ability to temporarily move billions of dollars through the system in one atomic block is a structural fact of DeFi that has no precedent and no equivalent risk management framework from traditional finance.

Smart Contract Audits and Formal Verification

The DeFi ecosystem has developed a cottage industry of smart contract security auditing. Major audit firms (Trail of Bits, OpenZeppelin, Certik, Consensys Diligence, Spearbit, Code4rena) review contract code for known vulnerability patterns, logic errors, and economic exploits. An audit provides reasonable assurance but is not a guarantee: audited contracts have been exploited (Ronin, Euler Finance). An audit confirms the code was reviewed by credentialed researchers at a specific point in time; it does not prevent later upgrades introducing new vulnerabilities, nor does it guarantee all attack vectors were identified.

Formal verification is a higher rigour approach: mathematical proof that contract code satisfies specified properties (e.g., total supply never exceeds cap; no reentrancy possible in the withdraw function). MakerDAO and Uniswap v3 have had components formally verified. It is significantly more expensive and time-consuming than traditional auditing and is not universally applicable to complex contract systems.

For traders, the practical question is: what audit history does a protocol have? Who audited it? How recent was the audit? Has the code been modified since? Bug bounty programmes and total-value-locked (TVL) age are imperfect but useful proxies: protocols with large, longstanding TVL have survived longer periods of adversarial market conditions than freshly deployed protocols.

Implications for Traders

Smart contract risk is a distinct, non-negligible category of risk for any position in DeFi-adjacent assets:

  • Protocol risk sizing: treat DeFi protocol exposure as a distinct risk layer separate from price risk. A 50% drop in token price and a 100% protocol hack are both loss events, but they have different causes and different correlations with market conditions. The crypto risk calculator helps size positions within total portfolio risk budgets that account for this layer.
  • Audit quality is not binary: "audited" is not a binary safety flag. Look for multiple independent audits, public audit reports accessible on the project's GitHub, and active bug bounty programmes. A protocol with a $1M bug bounty is incentivising the white-hat security community to find vulnerabilities before black-hats do.
  • Token approval hygiene: maintain a practice of reviewing and revoking token approvals you no longer need. Tools like Revoke.cash allow you to audit all open approvals across your wallets. An old unlimited approval to a compromised protocol is a live financial exposure.
  • New protocol premiums: freshly deployed protocols with unaudited or lightly audited code typically offer higher yields to attract liquidity precisely because the smart contract risk is higher. This is not free money — it is compensation for bearing a risk that institutional capital avoids. If the yield on a new protocol seems implausibly high compared to audited alternatives, the smart contract risk is the implicit cost you are accepting. Apply the risk/reward analysis frameworks from Course 6 before chasing such yields.
  • Bridge and cross-chain risk: bridges are the highest-risk smart contract category by total dollar value exploited. The Ronin Bridge ($625M), Wormhole ($320M), and Nomad ($190M) exploits represent the three largest DeFi hacks in history, all targeting bridge infrastructure. Cross-chain positions carry bridge smart contract risk in addition to protocol risk and price risk. This is examined further in Course 56: Layer 1 vs Layer 2 Blockchains.

Summary

Smart contracts are deterministic, immutable programmes stored on a blockchain that execute automatically when conditions are met. The Ethereum Virtual Machine provides a sandboxed, gas-metered execution environment that is identical on every node. Token standards (ERC-20, ERC-721) create interoperable building blocks for DeFi, NFTs, and DAOs. The major vulnerability classes — reentrancy, oracle manipulation, integer overflow, access control failures — have collectively cost DeFi billions in exploits, with reentrancy alone enabling the $60M DAO hack that split Ethereum in 2016. Flash loans add a dimension of temporary unlimited capital that enables atomic arbitrage, liquidations, and price manipulation attacks with no precedent in traditional finance. For traders, smart contract risk is a concrete position risk that must be sized, audited, and monitored — separate from price risk, and not compensated by yield alone. The next course, Course 56: Layer 1 vs Layer 2 Blockchains, addresses the scalability challenge that determines when, where, and at what cost you can actually use these smart contracts.

Your Free Crypto Tools for This Course

The concepts introduced in this course connect directly to several of DennTech’s free crypto tools. There is no registration required to use any of them: