Sub topic 6
Ethereum: Accounts, the EVM, and Smart Contracts
This chapter assumes you know what a blockchain ledger is, how public and private keys sign messages, how proof of stake orders blocks, and how Bitcoin's UTXO model works. You should also be able to read short Python snippets. Gas pricing and fee burning have their own chapters, so they appear here only where needed.
From coins to a shared state machine
Bitcoin's ledger records which coin outputs are unspent. Ethereum's ledger records a world state: a mapping from every address to an account with its current data. A block is a batch of transactions that moves this state from one version to the next. Every node applies the same transactions in the same order and must reach the same result. Ethereum is therefore described as a replicated state machine.
The aim is different from Bitcoin's. Bitcoin is built around a narrow job: transfer value with a small, conservative scripting language. Ethereum is built to run general programs whose results all nodes can verify.
The account model
Ethereum has two kinds of accounts. Both are identified by a 20-byte address, and both have the same four fields.
| Field | Meaning |
|---|---|
| nonce | For an externally owned account, the number of transactions it has sent. For a contract, the number of contracts it has created. |
| balance | Amount of ether held, in wei (1 ether = 10^18 wei). |
| storageRoot | Root hash of the account's persistent key-value storage. It is empty for plain user accounts. |
| codeHash | Hash of the account's code. It is the hash of empty data for plain user accounts. |
- An externally owned account (EOA) is controlled by a private key. It has no code, and only it can start a transaction.
- A contract account is controlled by its code. It has no private key. It acts only when a transaction or another contract calls it.
The world state is stored in a Merkle Patricia trie, a tree keyed by address. Each block header commits to the state root, so a single hash summarizes every balance and every storage slot.
Nonces
Each transaction carries the sender's current nonce, and it is valid only if that number matches the account's nonce. This has two effects:
- A signed transaction cannot be replayed, because the nonce moves on after it runs.
- A sender's transactions execute in strict order. A transaction with nonce 5 waits until nonce 4 has been included.
UTXO compared with accounts
| Aspect | Bitcoin UTXO | Ethereum account |
|---|---|---|
| What is stored | Unspent outputs | Balances and storage per address |
| Spending | Consume whole outputs, create new ones | Subtract from one balance, add to another |
| Replay protection | An output can be spent once | Per-account nonce |
| Programs | Small locking scripts, no persistent state | Contracts with persistent storage |
| Parallel validation | Easy, since outputs are independent | Harder, since transactions can touch shared state |
| Balance lookup | Sum your outputs | Read one field |
The account model makes stateful programs natural, because a contract needs a place to keep data between calls. The price is shared mutable state, which makes ordering matter and creates new bug classes, described below.
Transactions
A transaction is a message signed by an EOA. Its main fields are:
nonce: the sender's current counter.to: the recipient address. An emptytomeans "create a contract."value: wei to transfer.data: input for the recipient's code, or the new contract's code when creating one.- gas fields: a gas limit and fee settings, covered in the gas chapter.
- a signature, from which nodes recover the sender's address.
There are three common cases:
- Plain transfer.
tois an EOA anddatais empty. - Contract call.
tois a contract anddataselects a function and its arguments. - Contract creation.
tois empty anddataholds the initialization code. The new address is derived from the sender's address and nonce, or by theCREATE2rule from a salt and the code hash.
The Ethereum Virtual Machine
The Ethereum Virtual Machine (EVM) is the runtime every node uses to execute contract code. Developers usually write in a high-level language such as Solidity or Vyper, and a compiler produces bytecode, a sequence of single-byte opcodes.
The EVM has these parts:
- A stack of 256-bit words, with a maximum depth of 1024. Opcodes pop their operands from it and push results.
- Memory, a byte array that exists only for the current call.
- Storage, a persistent key-value store of 256-bit slots owned by the contract. Writing to it is among the most expensive operations.
- Calldata, the read-only input sent with the call.
- Context opcodes that expose the caller, the value sent, the block number, and similar values.
The EVM is deterministic. A contract cannot read a clock, a random source, a web page, or a file. If it could, nodes would disagree and consensus would break. To use outside data, contracts rely on oracles, which are other contracts that transactions fill with data. Oracles add a trust assumption.
Execution is also metered. Every opcode costs gas, and a transaction brings a gas limit. If the limit runs out, execution halts and the call's state changes are undone. The sender still pays for the work done. This is why an infinite loop cannot freeze the network.
A contract can call another contract. The main call types are CALL, STATICCALL (which forbids state changes), and DELEGATECALL (which runs another contract's code against the caller's own storage). Delegated calls are what upgradeable proxy contracts are built on.
Smart contracts
A smart contract is code stored at a contract address, together with its storage. Once deployed, its code does not change. "Upgradeable" contracts are an indirection pattern: a fixed proxy forwards calls to a logic contract whose address an admin can change. That admin power is a trust assumption you should look for.
Contracts are a good fit for rules that several parties need to trust without a middleman, such as token balances, escrow, auctions, and automated exchanges. Token standards like ERC-20 are simply contracts that keep a table of balances. The next chapters build on this.
Two properties shape how contracts are written:
- Atomicity. A transaction either completes in full or has no effect on state. A contract can use this by reverting when a condition fails.
- Transparency. Contract code and storage are public. Anyone can read them and check what a contract will do before sending it funds.
A smart contract is not "smart" in any other sense, and it is not automatically a legal contract. It does exactly what its code says, including when the code has a bug.
A runnable toy model
This Python model captures the account rules above: nonce checking, value transfer, a contract with storage, and atomic revert. It is not the real EVM. It has no gas, no bytecode, and no signatures.
import copy
from dataclasses import dataclass, field
class Revert(Exception):
pass
@dataclass
class Account:
balance: int = 0
nonce: int = 0
code: object = None
storage: dict = field(default_factory=dict)
class World:
def __init__(self):
self.accounts = {}
def get(self, addr):
return self.accounts.setdefault(addr, Account())
def transact(self, sender, nonce, to, value=0):
acct = self.get(sender)
if nonce != acct.nonce:
raise ValueError(f"bad nonce: expected {acct.nonce}, got {nonce}")
if acct.balance < value:
raise ValueError("insufficient balance")
acct.nonce += 1 # survives a revert, as on Ethereum
snapshot = copy.deepcopy(self.accounts)
try:
acct.balance -= value
target = self.get(to)
target.balance += value
if target.code is not None:
target.code(self, to, sender, value)
return "success"
except Revert as err:
self.accounts = snapshot
return f"reverted: {err}"
def guestbook(world, addr, sender, value):
if value < 10:
raise Revert("minimum deposit is 10")
store = world.accounts[addr].storage
store[sender] = store.get(sender, 0) + value
world = World()
world.get("alice").balance = 100
world.accounts["guestbook"] = Account(code=guestbook)
print(world.transact("alice", 0, "guestbook", 25))
print(world.transact("alice", 1, "guestbook", 5))
try:
world.transact("alice", 0, "guestbook", 25)
except ValueError as err:
print("rejected:", err)
alice = world.accounts["alice"]
book = world.accounts["guestbook"]
print(alice.balance, alice.nonce)
print(book.balance, book.storage)The output is:
success
reverted: minimum deposit is 10
rejected: bad nonce: expected 2, got 0
75 2
25 {'alice': 25}The second transaction reverts, so Alice keeps her 5 units and the contract storage is unchanged. Her nonce still advances to 2, so the reused nonce 0 is rejected. This is the replay protection described earlier.
Common errors and gotchas
- Treating a revert as "nothing happened." The state is rolled back, but the sender's nonce increases and gas is still paid.
- Reentrancy. When a contract sends ether or calls an unknown contract before updating its own records, the callee can call back in and act on stale data. The standard defenses are to update storage first and then make external calls (the checks-effects-interactions pattern), or to use a reentrancy guard. The 2016 DAO attack was a reentrancy exploit.
- Assuming code is final. Check whether a contract is behind a proxy and who holds the upgrade key.
- Confusing account types. Only EOAs start transactions. A contract cannot act on a schedule without someone sending a transaction to it, which is why keeper services exist.
- Assuming off-chain data is free. Oracle inputs are only as trustworthy as their source.
- Key risk is unchanged. An EOA is controlled by one private key. An upgrade in 2025 (EIP-7702) lets an EOA delegate to contract code, but the key still controls the account.
Why this design matters for comparison
The account model and EVM give Ethereum its flexibility. They also give it a larger attack surface and heavier validation than Bitcoin's design, and these costs feed into the scalability and risk chapters. When you compare cryptocurrencies later, ask what each chain's state model lets programs do, and what that costs in complexity and trust.
Exercise
A user signs a transaction with nonce 7 to a contract. The contract's code hits a failed check and reverts. Describe the state afterward: what happens to the transferred value, the user's nonce, and the contract's storage? Then say whether the same signed transaction can be replayed.
Show answer
The transferred value returns to the sender, because the whole state change is rolled back, and the contract's storage is unchanged. The sender's nonce still increases to 8, and the sender still pays for the gas used before the revert. The signed transaction cannot be replayed, because it carries nonce 7 and the account now expects nonce 8.
Exercise
Why can an EVM contract not fetch the current price of an asset from a website directly? Name the usual workaround and the trust cost it adds.
Show answer
Every node must execute the contract and reach the same result, so the EVM allows no nondeterministic inputs such as web requests. The usual workaround is an oracle, a contract that trusted parties update with off-chain data through transactions. The cost is that the contract now trusts the oracle's operators and data source.
Exercise
Give two reasons Ethereum's account model suits stateful contracts better than Bitcoin's UTXO model, and one downside.
Show answer
Contracts need persistent storage, and an account holds a storage root, while UTXOs carry only a value and a locking script. A balance is a single field that code can read and update, instead of a set of outputs to gather. The downside is shared mutable state, so transaction ordering matters and bugs such as reentrancy appear.