Lesson 3 of 4 Ethereum Fundamentals

The Ethereum Virtual Machine

Smart contracts run as bytecode in the Ethereum Virtual Machine. This lesson explains how the EVM executes code, where it keeps data, how contracts call each other and why the EVM's design explains many Solidity rules and gas costs.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain why the EVM must be deterministic.
  • Distinguish the stack, memory, calldata, storage, transient storage and logs.
  • Describe how message calls change msg.sender.
  • Explain why contracts need oracles for external data.

A deterministic, stack-based machine

The EVM is a virtual machine that every Ethereum node runs. Its job is to apply a transaction to the current state and produce the new state. It must be deterministic: given the same state and transaction, every node must reach exactly the same result, or the network could not agree. For this reason contracts cannot read files, call web APIs, use the system clock or generate true random numbers.

The EVM is a stack machine with 256-bit words. Bytecode is a sequence of opcodes, such as PUSH1, ADD, SLOAD, SSTORE, CALL and REVERT, that push and pop values on a stack of up to 1,024 items. Each opcode has a gas cost, and execution stops if gas runs out. The 256-bit word size is why uint256 and bytes32 are the natural Solidity types.

Sort into groups

Can a contract do this?

Exam skills 7.1.1

Decide whether a contract can perform each action, given that every node must reach the same result.

Log in to try this activity Interactive activities are free with an account.

Where the EVM keeps data

During execution, a contract can use several data areas. They differ in lifetime and cost, as the following comparison shows; the Solidity data locations of later modules map onto them.

AreaLifetimeCostUsed for
StackOne execution frameCheapestLocal value-type variables and intermediate results
MemoryOne callCheap, grows quadraticallyTemporary arrays, strings and structs
CalldataOne call, read-onlyCheap to readFunction arguments
StoragePermanentMost expensiveState variables, kept in 32-byte slots
Transient storageOne transactionCheap (100 gas)Values shared across calls within a transaction, such as reentrancy locks
LogsPermanent, not readable by contractsModerateEvents for off-chain applications

Contract storage is a key-value store of 2256 slots of 32 bytes each, all initially zero. Because writing storage changes the state that every node must keep forever, it is priced far higher than computation.

The following diagram orders the data areas by lifetime and cost.

Where the EVM keeps data, from shortest-lived to permanent. The stack lasts one execution frame and is the cheapest. Memory and calldata last one call; calldata is read-only. Transient storage lasts one transaction. Storage is permanent, kept in 32-byte slots by every node, and is the most expensive. Logs are permanent but cannot be read by contracts; they are for off-chain applications.
Permanent storage is priced far above computation.
Match the pairs

EVM data areas

Exam skills 7.1.1

Match each EVM data area with what it is used for.

Log in to try this activity Interactive activities are free with an account.

Messages between contracts

When a contract calls another contract, the EVM creates a new message call with its own execution frame, memory and gas allowance. Inside the callee, msg.sender is the calling contract, not the original user. Calls nest up to a depth of 1,024, and a callee can receive at most 63/64 of the caller's remaining gas.

If a callee reverts, its state changes are undone. A high-level Solidity call then reverts the caller too, while a low-level call returns false and lets the caller decide. Two variants change the context: STATICCALL forbids state changes and DELEGATECALL runs the callee's code against the caller's storage, which is how proxies and libraries work.

Scenario questions

Calls between contracts

Exam skills 7.1.1

Predict how the EVM behaves when one contract calls another.

Log in to try this activity Interactive activities are free with an account.

Gas as the EVM's meter

Because the EVM is Turing-complete, a contract could loop forever. Gas solves this: every opcode consumes gas from the transaction's limit, and execution halts when the limit is reached. The sender pays for all gas consumed, so attacks that consume resources are expensive to the attacker. The gas module covers the costs in detail.

EVM compatibility

The EVM is not unique to Ethereum. Layer 2 rollups and many other blockchains run EVM-compatible machines, so Solidity contracts and tools such as Hardhat and web3.js work on them with small configuration changes.

Worked example

Why can't a contract fetch a price?

A developer wants a contract to call a public web API to get the current ETH to USD price. Why is this impossible, and what is the alternative?

Every node executes the contract independently, and the API could return different values to different nodes at different times, or be unavailable. Nodes would then compute different states and could not agree. External data must be brought on chain in a transaction, by an oracle such as Chainlink, whose contracts store prices that other contracts read. The contract then depends on the oracle's reliability, which is a design and security decision.

Worked example

Memory or storage?

A function builds a temporary list of 50 addresses to compute a total, and the list is not needed afterwards. A colleague stores it in a state variable array. What is the problem?

Writing 50 new storage slots costs about 50 × 22,100 = 1,105,000 gas, and the data stays in state permanently. A memory array exists only during the call and costs a small fraction of that. Data that is not needed after the call belongs in memory; only data that must persist between transactions belongs in storage.

Check yourself

User U calls contract A, which calls contract B. What is msg.sender inside B, and what is tx.origin?

Show answer

msg.sender inside B is contract A, the immediate caller. tx.origin is U, the externally owned account that signed the transaction.

Exam Tips

Remember for the exam

  • The EVM is deterministic, so contracts cannot access external data, clocks or real randomness.
  • Storage is permanent and expensive; memory and calldata last for one call; logs are for off-chain readers.
  • In a called contract, msg.sender is the calling contract.
  • Oracles bring external data on chain through transactions.