Information Technology is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Smart contracts

Concise study notes on smart contracts: what they are, how they run on blockchains (EVM model), key Solidity patterns and vulnerabilities, and exam-style worked examples students must know.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Smart contracts let engineers encode rules that execute automatically on a blockchain. You will use them to build decentralized applications such as tokens, automated exchanges, supply-chain logic and access control — where correctness, cost (gas) and security are critical.

Key ideas

  • State machine model (exact statement): Let S be the set of all possible global states. A blockchain is a deterministic state machine with a transition function T such that for any state s ∈ S and transaction tx, the next state s' = T(s, tx). Assumptions: T is deterministic, all nodes run the same T, and transactions are applied in the same order produced by consensus.

  • Transaction — a signed message that requests a state transition (contract creation, function call or value transfer). A transaction includes: sender, signature, nonce, to (address or empty for creation), data (input), value (in wei), gas limit and fee parameters (EIP-1559: maxFeePerGas, maxPriorityFeePerGas), and the chain ID (for replay protection).

  • Ethereum Virtual Machine (EVM) — the deterministic execution environment that runs smart contract bytecode. Define: EVM executes opcodes with a stack, memory, and storage. Each opcode consumes gas (a measure of compute and storage cost).

  • Gas — the unit that measures the computational cost of executing EVM instructions. Gas protects the network from infinite loops. Since EIP-1559, each block has a base fee (burned) and a priority fee (tip) paid to the block producer (validator). The sender specifies a gas limit and fee caps (maxFeePerGas, maxPriorityFeePerGas); unspent gas is not charged and the corresponding ETH is returned. Separate “gas refunds” may apply for clearing storage.

  • Solidity — a high-level contract-oriented language compiled to EVM bytecode. Common terms and syntax to know are given in Formulas.

  • Storage vs memory — storage is persistent contract state (written to blockchain, expensive). Memory is a temporary byte-array for a single call (cleared after execution, cheaper). Always be explicit which you use in Solidity function signatures. Also know calldata: a non-modifiable, non-persistent area holding function arguments for external calls; cheaper than memory for parameters.

  • msg.sender and msg.value — special variables inside contract execution. msg.sender is the immediate caller address; msg.value is the Ether (in wei) sent with the call.

  • ABI (Application Binary Interface) — the encoding rules used to call contract functions and decode return values between off-chain clients and on-chain contracts.

  • Event — a log entry emitted by contracts. Events are stored in transaction logs (not in storage) and are cheaper to record; they can have indexed parameters (stored in topics) for efficient filtering, and are used by off-chain applications.

  • Fallback/receive — special functions in Solidity. receive() is executed on plain Ether transfers when msg.data is empty (if defined); otherwise, if no function matches the selector or calldata is non-empty and no receive exists, fallback() executes. Only payable versions can accept Ether.

  • Call vs Delegatecall (exact definitions):

    • call: executes another contract’s code in the context of the callee; in the callee, msg.sender is the immediate caller (the calling contract or EOA); storage used is the callee's storage.
    • delegatecall: executes the callee’s code but in the context of the caller; msg.sender is preserved from the caller’s context; storage used is the caller's storage. Assumption: used for proxy patterns and upgrades; misuse can lead to storage layout vulnerabilities.
  • Reentrancy (definition) — when a contract calls an external contract which then calls back into the original contract before the first call finishes, possibly manipulating state assumptions. Classic cause of fund theft if checks and state updates are ordered incorrectly.

  • Checks-Effects-Interactions pattern (definition) — a defensive programming pattern: first check inputs and access rights, then update state (effects), and only then interact with external contracts (interactions). This ordering prevents many reentrancy bugs.

  • CREATE2 (definition and exact address formula) — an opcode that creates a contract at an address computed deterministically from sender, a salt and the init code, enabling precomputed addresses for factory patterns. Address computation: keccak256(0xff ++ senderAddress ++ salt ++ keccak256(init_code)) and take the last 20 bytes. Assumptions: keccak256 is the hash function used; ++ denotes byte concatenation; salt is 32 bytes.

  • Oracle — an off-chain service that supplies external data (price feeds, weather) to smart contracts. Oracles are not trustless by themselves; design must consider trust or decentralised oracles.

  • Upgradeability — patterns (proxy, unstructured storage) used to allow changing contract behaviour post-deployment because deployed code is otherwise immutable.

Diagrams to draw (exam guidance):

  • Draw a blockchain timeline: boxes for blocks linked by hashes; in a block draw transactions; highlight a contract-creation tx and a function call tx. Label sender, nonce, value, data.
  • Draw EVM call frame stack: show caller -> CALL -> callee frame with storage/memory and return value; annotate msg.sender and msg.value changes.

Formulas

state' = T(state, tx) — state transition: state (S) to new state (S') by applying transaction tx through transition function T. Applies in any deterministic blockchain VM.

CREATE2_address = last20bytes(keccak256(0xff ++ senderAddress ++ salt ++ keccak256(init_code))) — compute contract address for CREATE2. 0xff is one byte; salt is 32 bytes; init_code is the contract creation bytecode.

msg.sender — address of the immediate caller (type: address)

msg.value — amount of Ether denominated in wei sent with the call (type: uint256; 1 ETH = 10^18 wei, i.e., 1 wei = 10^-18 ETH)

Solidity syntax to remember (examples): contract C { constructor() { } function f(uint x) public payable returns (uint) { ... } event E(address indexed who); mapping(address => uint) public balance; }

address.call{value: v, gas: g}(data) — low-level call returning (bool, bytes) and forwarding control/gas.

require(condition, "error") — revert if condition false, refund unused gas.

revert() — revert execution and state changes, consume gas used so far but refund unused gas.

Worked examples

Example 1 — Reentrancy vulnerability and fix (exam-style model answer) Problem: A naive withdraw contract. Solidity-like pseudo-code:

contract Vulnerable { mapping(address=>uint) balance;
 function deposit() public payable { balance[msg.sender] += msg.value; }
 function withdraw(uint amt) public {
   require(balance[msg.sender] >= amt);
   (bool ok,) = msg.sender.call{value:amt}("");
   require(ok);
   balance[msg.sender] -= amt;
 }
}

Trace of attack (steps):

  1. Attacker deposits 1 ETH: balance[attacker]=1.
  2. Attacker calls withdraw(1). Contract checks balance>=1 (true).
  3. Contract performs external call to attacker fallback BEFORE updating balance.
  4. Attacker fallback calls withdraw(1) again. Because balance not yet decreased, check passes again.
  5. Repeat until gas exhausted; attacker drains more than 1 ETH. Fix using Checks-Effects-Interactions:
function withdraw(uint amt) public {
  require(balance[msg.sender] >= amt);
  balance[msg.sender] -= amt;               // effect first
  (bool ok,) = msg.sender.call{value:amt}("");
  require(ok);
}

Or use a reentrancy guard (mutex) or pull-payments pattern. What to write in exam: show the order of operations, show how call enables reentrancy, then show corrected code and why it stops the attack.

Example 2 — CREATE2 address derivation (explain, no numeric hash) Question: How can a factory precompute where a deployed contract will live? Answer: use CREATE2. Steps to show:

  1. Given factory address F, salt S, init_code C, compute h = keccak256(C).
  2. Compute H = keccak256(0xff ++ F ++ S ++ h).
  3. The new contract address is last 20 bytes of H. Draw the concatenation bytes when answering. Write: This allows the factory to publish an address before funding it, useful for counterfactual interactions.

Common mistakes

  • Updating state after making external calls (causes reentrancy). Forgetting Checks-Effects-Interactions.
  • Not distinguishing storage and memory leading to unexpected overwrites and gas costs.
  • Misunderstanding delegatecall: forgetting that it uses caller storage layout and can corrupt state if storage slots mismatch.
  • Assuming events are part of contract storage (they are logs; cheaper but not accessible by on-chain code).
  • Using transfer or send as security silver bullets; gas stipend semantics changed with EIP-1884 and may break assumptions. Prefer patterns that handle failure explicitly.

For your exam

Kinds of questions:

  • Definitions and short notes: define smart contract, EVM, gas, reentrancy, CREATE2, ABI.
  • Derivations: show state transition model and explain deterministic execution; derive CREATE2 address formula and describe inputs.
  • Programs: read small Solidity snippets and identify vulnerabilities; write corrected code (Checks-Effects-Interactions, reentrancy guard).
  • Diagrams: draw call stack frames, show msg.sender changes for CALL vs DELEGATECALL, or draw block/tx/contract creation flow.
  • Long answers: explain upgradeability patterns and security trade-offs, or model answer explaining how oracles introduce trust.

What a full-marks answer includes:

  • Clear definitions with bold term names, assumptions stated (e.g., determinism, consensus), step-by-step derivations for formulas, labelled diagrams drawn as requested, and corrected code where required with explanation of why it fixes the bug.

Quick check

  1. What variable gives the immediate caller address inside a contract?
  2. Name the pattern that prevents reentrancy by ordering operations.
  3. Give the high-level formula used to compute a CREATE2 address (conceptual, not hash bytes).

Answers: 1. msg.sender. 2. Checks-Effects-Interactions (or reentrancy guard). 3. last20bytes(keccak256(0xff ++ sender ++ salt ++ keccak256(init_code))).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?