Module 1 – Foundations of Smart Contracts & Execution Environments
This module develops a rigorous understanding of smart contracts as programmable state machines on decentralised ledgers. We examine their conceptual origins, execution environments, account models, and transaction-driven lifecycle, with an emphasis on the engineering constraints that shape real-world decentralised applications.
1. Conceptual Origins of Smart Contracts
The notion of a “smart contract” predates blockchains. In the 1990s, Nick Szabo described smart contracts as computable specifications of contractual clauses embedded in the infrastructure that executes them. The key idea is that many forms of economic and legal relationships can be expressed as conditional logic:
- “If payment is received, then transfer access rights.”
- “If collateral remains above a threshold, keep the position open; otherwise liquidate.”
- “If a majority votes for a proposal, then enact the state change.”
Prior to blockchains, implementing such logic required trusted intermediaries—banks, clearing houses, registries, or platforms. Blockchains introduced an execution substrate where this logic could be deployed globally, executed deterministically, and verified independently by any network participant.
In this module, we treat a smart contract as:
A replicated, deterministic state machine whose state transitions are authorised by digital signatures and recorded on a consensus-driven ledger.
2. Accounts and State: EOAs vs Contract Accounts
In smart-contract platforms such as Ethereum, the global state is organised around accounts. Each account has:
- An address (a globally unique identifier).
- A balance (usually denominated in the native currency, e.g., ETH).
- A nonce (for replay protection and ordering).
- Optional code and persistent storage (for contract accounts).
2.1 Externally Owned Accounts (EOAs)
EOAs are controlled by private keys. Humans or off-chain systems initiate transactions by signing messages with their private keys. EOAs:
- Do not contain code.
- Cannot autonomously initiate transactions (they must be triggered off-chain).
- Pay transaction fees (gas) when sending transactions.
2.2 Contract Accounts
Contract accounts are controlled by code, not by private keys. They:
- Contain bytecode that defines their behaviour.
- Have persistent storage (key–value mappings) maintained on-chain.
- Only execute when invoked by a transaction or by other contracts.
The separation between EOAs and contract accounts clarifies an important point: Only EOAs originate transactions; contracts merely react to them.
3. The Execution Environment (EVM and Beyond)
Smart contracts execute within specialised virtual machines that enforce determinism, resource metering, and sandboxing. The most prominent example is the Ethereum Virtual Machine (EVM).
3.1 Deterministic Execution
Every node in the network must be able to replay contract code and arrive at the same result, given the same input and prior state. This precludes:
- Non-deterministic system calls (e.g., local time, random OS data).
- Unbounded loops without cost (they must incur gas costs).
- External network calls to arbitrary APIs during execution.
3.2 Sandboxing
The virtual machine restricts access to the underlying host environment. Contracts cannot:
- Write to disk on validating nodes.
- Open arbitrary network sockets.
- Modify state outside their defined storage and allowed interfaces.
3.3 Gas as a Resource Meter
To prevent denial-of-service attacks and unbounded computation, every instruction in the virtual machine is assigned a gas cost. The transaction sender specifies:
- A gas limit (maximum computational budget).
- A gas price (or fee parameter) indicating willingness to pay.
If execution consumes all available gas, it halts and reverts state changes, but the gas spent up to that point is still charged to the sender.
4. Transactions as State Transition Triggers
Smart contracts never “wake up” spontaneously. Instead, they are driven by transactions originating from EOAs. Each transaction defines:
- The sender (an EOA).
- The target (an EOA or contract address, or empty for contract creation).
- The value (amount of native currency to transfer).
- Input data (encoded function calls and parameters).
- Gas limit and fee parameters.
- A nonce (for ordering and replay protection).
4.1 Transaction Lifecycle Overview
- Construction: The wallet constructs a transaction with the desired parameters.
- Signing: The private key of the EOA signs the transaction.
- Broadcast: The transaction is propagated to the peer-to-peer network.
- Inclusion: A validator/miner includes it in a block.
- Execution: All nodes execute the transaction, updating state accordingly.
- Finality: After sufficient confirmations, the state change is considered stable.
From the contract’s perspective, a transaction is simply an input event that drives its state machine from one configuration to another.
5. Contract State, Storage and Logs
The global blockchain state consists of all account balances and contract storage. For contracts, we distinguish between:
- Storage: Persistent key–value mappings that survive across transactions.
- Memory: Temporary data structures used only during execution.
- Stack: The VM’s transient operand stack for computation.
5.1 Storage Layout
High-level languages like Solidity compile into storage operations (e.g., SSTORE, SLOAD).
Underneath:
- State variables map to specific storage slots (256-bit keys).
- Mappings and dynamic arrays are implemented via hashed keys.
- Each storage write is relatively expensive in gas terms.
5.2 Logs and Events
Contracts cannot push data directly to external systems, but they can emit events (logs) that:
- Are stored in a separate log structure indexed by topics.
- Do not affect contract state.
- Can be efficiently queried by off-chain applications and analytics tools.
In practical DApps, events become the primary communication channel from on-chain logic to off-chain user interfaces and services.
6. Execution Semantics: Call Graphs and Re-entrancy
Smart contract execution is not always linear. A single transaction may invoke multiple contracts, forming a call graph:
- EOA transaction → Contract A → Contract B → Contract C …
- Internal calls may be message calls or delegate calls.
6.1 Synchronous Execution
All contract calls are executed synchronously within a single transaction context. Either the entire call graph succeeds (commits) or fails (reverts).
6.2 Re-entrancy
Re-entrancy occurs when a contract:
- Calls out to another contract (or externally-owned account).
- That external code then calls back into the original contract before the first invocation has finished updating its state.
This can be dangerous if the contract’s logic assumes that certain invariants hold between these calls. A classic mitigation strategy is:
- Update internal state before making external calls.
- Use re-entrancy guards (e.g., “checks-effects-interactions” pattern).
7. Gas, Cost Models and Engineering Constraints
Every operation in a smart contract has an associated gas cost. From an engineering perspective, this implies that:
- Data structures should be chosen with write costs in mind.
- On-chain loops over large datasets are discouraged.
- Complex business logic may need to be partially offloaded to off-chain computation.
7.1 Examples of Expensive Operations
- Writing to storage for the first time (initial allocation).
- Expanding dynamic arrays or mappings with new keys.
- Creating new contracts.
7.2 Design Implications
Instead of on-chain iteration, systems often:
- Store minimal state and reconstruct views off-chain.
- Use events as append-only logs for indexing.
- Design interactions as small, atomic operations rather than monolithic functions.
8. Platform Variants: EVM, WASM, and Alternative Runtimes
While Ethereum popularised the EVM, modern smart-contract platforms use different execution environments:
- EVM-compatible chains: Share bytecode-level compatibility (e.g., many L2 rollups).
- WASM-based runtimes: Use WebAssembly to support multiple languages (e.g., Rust, AssemblyScript).
- Custom VMs: Purpose-built virtual machines optimised for specific workloads.
Despite these differences, all production platforms must satisfy:
- Determinism across nodes.
- Clear resource accounting.
- Isolation from the host environment.
For this course, we focus on EVM semantics conceptually, as they generalise to many other systems and provide a widely used reference model.
9. A Minimal Smart Contract: Escrow Concept
To ground these concepts, consider a simplified escrow contract. The idea: a buyer deposits funds; a seller ships goods; a third-party arbitrator or timeout condition releases funds.
In high-level pseudocode (Solidity-like syntax):
// NOTE: Illustrative pseudocode only
contract SimpleEscrow {
address public buyer;
address public seller;
uint256 public amount;
bool public funded;
bool public released;
constructor(address _seller) payable {
buyer = msg.sender;
seller = _seller;
amount = msg.value;
funded = true;
}
function release() public {
require(msg.sender == buyer, "Only buyer can release");
require(funded && !released, "Invalid state");
released = true;
payable(seller).transfer(amount);
}
}
Conceptually, this contract defines:
- State variables to track the parties, amount, and status.
- A constructor that initialises state when deployed.
- A
releasefunction that enforces preconditions and triggers a state transition.
Every call to release is a transaction-driven state transition that nodes
validate deterministically.
10. Limitations and Design Trade-offs
Smart contracts are powerful but constrained. Effective design requires acknowledging and working within these constraints:
- No native privacy: Contract state and code are typically public.
- Irreversibility: Bugs in deployed contracts can be difficult or impossible to fix.
- Cost-sensitivity: Overly complex logic may be uneconomical to execute on-chain.
- Latency: Interaction depends on block times and network conditions.
These limitations motivate patterns such as:
- Using upgradeable proxy architectures (covered in later modules).
- Off-chain computation with on-chain settlement.
- Formal verification and rigorous auditing before deployment.
11. Smart Contracts vs Traditional Web Services
At a high level, both smart contracts and web services implement business logic. However, their trust, deployment, and execution models differ fundamentally.
11.1 Traditional Web Service
- Runs on servers controlled by a single operator or organisation.
- Users must trust the operator not to modify logic or data arbitrarily.
- State is mutable off-chain and can be changed without global consensus.
11.2 Smart Contract
- Runs on many independent nodes simultaneously.
- Code and state transitions are transparent and verifiable.
- Upgrades require predefined mechanisms and consensus logic.
This shift from “trusting institutions” to “verifying code and consensus” is the central conceptual difference in decentralised application design.
12. Module Summary
In this module, we have:
- Traced the conceptual origin of smart contracts as programmable agreements.
- Differentiated externally owned accounts from contract accounts.
- Examined the properties of virtual machines such as the EVM.
- Analysed how transactions drive contract execution and state transitions.
- Introduced storage, logs, call graphs, re-entrancy, and gas cost models.
- Outlined core limitations and their architectural implications.
This foundation prepares us to proceed in Module 2 to the language-level view of smart contracts: Solidity syntax and semantics, core patterns, and how high-level constructs compile down to the low-level execution model studied here.