08 — Smart Contracts

Programs that execute on a blockchain under deterministic rules. EVM dominates; Move (Aptos/Sui), Cairo (StarkNet), CosmWasm, Solana eBPF are growing.


1. Definition and properties

Smart contract: code executed on a blockchain VM, with:

  • Determinism: same input → same output on any node.
  • Sandbox: no access to external I/O (filesystem, network).
  • Persistence: on-chain storage between invocations.
  • Pay to run: gas/fees.
  • Immutability after deploy (with exceptions: proxies, upgradeable patterns).
  • Composability: contracts call contracts.

Term coined by Nick Szabo in 1994 ("Smart Contracts: Building Blocks for Digital Free Markets"). Real implementation only with Ethereum (2015).


2. Languages by VM

VM Primary languages Others
EVM Solidity, Vyper Yul, Huff, Fe
MoveVM (Aptos) Aptos Move
MoveVM (Sui) Sui Move
Solana SVM (eBPF) Rust (Anchor framework), C, C++
CairoVM (StarkNet) Cairo 1.0
WASM (CosmWasm, ICP, Polkadot) Rust, AssemblyScript Go (TinyGo)
Plutus Core (Cardano) Plutus (Haskell), Marlowe, Aiken
TON VM FunC, Tact, Tolk
Michelson (Tezos) SmartPy, LIGO, Archetype
AVM (Algorand) TEAL, PyTeal, Reach
Stylus (Arbitrum) Rust, C, C++ via WASM EVM-compatible bridge
RISC Zero zkVM Rust any language that compiles to RISC-V
SP1 (Succinct) Rust any RISC-V

3. Solidity

Christian Reitwiessner + ConsenSys 2014. Inspired by JavaScript, C++, Python.

Hello world

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Counter {
    uint256 public count;

    event Incremented(uint256 newValue);

    function increment() external {
        count += 1;
        emit Incremented(count);
    }
}

Notable versions

  • 0.4.x (2017): legacy era. ICO boom contracts.
  • 0.5.x (2018): explicit visibility + storage location.
  • 0.6.x (2019): try/catch, abstract contracts.
  • 0.7.x (2020): SPDX, transitional.
  • 0.8.x (2020-present): default checked arithmetic (no SafeMath needed). Current era; ~0.8.24-0.8.27 in 2026.

Modern features

  • Custom errors (0.8.4): error InsufficientBalance(uint256 available, uint256 required); cheaper than require("string").
  • User-defined value types (0.8.8).
  • Function pointers.
  • Try/catch on external calls.
  • unchecked { ... } for explicit overflow allow.
  • Transient storage (0.8.24, EIP-1153): cheap intra-tx storage.

Storage layout

  • 256-bit slots, 0-indexed.
  • Mappings: \(H(\text{key} \\\| \text{slot})\).
  • Dynamic arrays: length in slot, items at \(H(\text{slot})\) + index.
  • Inheritance: linearized C3.

Visibility

  • public: external + internal callable. Auto-getter for state vars.
  • external: external only (this.f() works but paid).
  • internal: this contract + derived.
  • private: only this contract (but state is still public on-chain).

Canonical patterns

  • Checks-Effects-Interactions (CEI): validate → change state → external call. Anti-reentrancy.
  • Pull payments: receivers withdraw instead of push. Anti-locking.
  • Reentrancy guards: nonReentrant modifier (OpenZeppelin).
  • Access control: Ownable, AccessControl (RBAC), Pausable.
  • Proxy upgradeability: Transparent (OZ), UUPS, Diamond (EIP-2535), Beacon.
  • Initializer pattern (proxies): initialize() instead of constructor.

4. Vyper

Vitalik + Vlad Zamfir 2017+. Python-like, security-first.

Philosophy

  • Dangerous features removed: inheritance, function overloading, modifiers, infinite loops, recursion.
  • Bounded loops only.
  • Built-in decimal type.
  • Easier auditing.

Adoption

Used mainly by Curve Finance. The Vyper compiler bug 2023 affected Curve pools (CRV/ETH, alETH, msETH, pETH) — US$ 73M lost. Reinforced that a secondary language can have worse bugs than the mainstream one (Solidity).

Status 2026

Vyper 0.4.x is mature. More frequent audits post-2023. ~5% market share of deployed contracts.


5. EVM intricacies

Calldata vs memory vs storage

Location Cost Use
Calldata nearly free Read-only function args
Memory cheap (linear+) Local vars inside a function
Storage expensive (20k SSTORE first) Persistent state
Transient (0.8.24) cheap Intra-tx ephemeral

Gas optimization tips

  • Use uint256 (native word) — smaller packing is sometimes worse if read together.
  • Custom errors > revert strings.
  • external cheaper than public when only externally called.
  • Cache storage → memory inside the function.
  • Bit packing structs.
  • Use unchecked in loops with guaranteed bounds.
  • Foundry --gas-report for benchmarks.

EOF (Ethereum Object Format, EIP-7692, future Pectra+)

Refactor of the bytecode format:

  • Headers, sections, validation upfront.
  • Disable some legacy opcodes (CALLCODE, SELFDESTRUCT semantics).
  • New opcodes (RJUMP, EOFCREATE, RETURNCONTRACT).
  • Easier static analysis, prep for ZK-EVMs.

6. OpenZeppelin

openzeppelin-contracts is the standard Solidity reference.

Canonical contracts

  • ERC20, ERC721, ERC1155 (mintable, burnable, pausable variants).
  • AccessControl (RBAC).
  • Ownable, Ownable2Step.
  • Governor (DAO governance reference).
  • TimelockController.
  • TransparentUpgradeableProxy, UUPSUpgradeable, BeaconProxy.
  • ECDSA, EIP712, MessageHashUtils.
  • SafeERC20 (handles non-standard ERC20).
  • MerkleProof, MerkleTree.
  • ReentrancyGuard.

Defender (cloud product)

OpenZeppelin Defender — monitoring, automation, multisig, upgrade workflow.


7. Foundry

Paradigm 2022. Rust toolkit for Solidity. The modern standard 2024+.

Components

  • Forge: build + test (Solidity-native tests).
  • Cast: CLI to interact with chains.
  • Anvil: local devnet (replaces Hardhat node).
  • Chisel: Solidity REPL.

Testing

function testIncrement() public {
    counter.increment();
    assertEq(counter.count(), 1);
}

function testFuzz_Increment(uint256 n) public {
    vm.assume(n < 1000);
    for (uint i; i < n; i++) counter.increment();
    assertEq(counter.count(), n);
}

function testFork() public {
    vm.createSelectFork("https://eth-mainnet.g.alchemy.com/v2/...");
    // test against mainnet state
}

Forge Std

Helpers: cheatcodes (vm.warp, vm.prank, vm.expectRevert), assertions, fuzz/invariant testing.

Advantages vs Hardhat

  • Tests in Solidity (same language as the contracts).
  • Performance: 10×+ faster (Rust).
  • Native fuzzing + invariant testing.
  • Built-in fork mode.
  • Better stack traces.

8. Hardhat

Nomic Foundation 2018. JavaScript/TypeScript-based.

const { ethers } = require("hardhat");

it("increments", async () => {
  const counter = await ethers.deployContract("Counter");
  await counter.increment();
  expect(await counter.count()).to.equal(1);
});

Plugins: hardhat-ethers, hardhat-waffle, hardhat-deploy, hardhat-gas-reporter, hardhat-verify.

Status 2026: still popular as legacy + JS ecosystem. Foundry dominates greenfield.


9. Move

Diem (Facebook) 2019 originally; inherited by Aptos + Sui (not 100% compatible).

Characteristics

  • Resource type: linear types — assets cannot be duplicated, only moved/transferred. Compile-time enforcement.
  • Bytecode verifier: ensures invariants before execution.
  • Modules + scripts: module = code; script = transaction that invokes.
  • Generics.
  • Formal verification: Move Prover.

Aptos Move

module my_addr::counter {
    struct Counter has key {
        value: u64,
    }

    public entry fun increment(account: &signer) acquires Counter {
        let c = borrow_global_mut<Counter>(signer::address_of(account));
        c.value = c.value + 1;
    }
}

Account-centric. Resources stored under an account.

Sui Move

Object-centric: everything is an object with an owner or shared.

module example::counter {
    use sui::object::{Self, UID};
    use sui::transfer;
    use sui::tx_context::{Self, TxContext};

    struct Counter has key {
        id: UID,
        value: u64,
    }

    public fun new(ctx: &mut TxContext) {
        transfer::share_object(Counter { id: object::new(ctx), value: 0 });
    }

    public fun increment(c: &mut Counter) {
        c.value = c.value + 1;
    }
}

Unique object IDs. Natural parallel execution.


10. Solana programs

Not "smart contracts" — called programs. Stateless: state stored in separate accounts that the program reads/writes.

Anchor framework

use anchor_lang::prelude::*;

declare_id!("...");

#[program]
pub mod counter {
    use super::*;

    pub fn increment(ctx: Context<Increment>) -> Result<()> {
        ctx.accounts.counter.value += 1;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Increment<'info> {
    #[account(mut)]
    pub counter: Account<'info, Counter>,
}

#[account]
pub struct Counter {
    pub value: u64,
}

Performance

  • ~50k programs callable / second (Sealevel parallel).
  • Compute budget: 200k CU default per tx, adjustable.

Alternative frameworks

  • Native Solana SDK (without Anchor, more boilerplate).
  • Seahorse (Python-like, abandoned).

11. Cairo (StarkNet)

ZK-friendly language. Compiles to AIR (Algebraic Intermediate Representation) provable in STARK.

#[starknet::contract]
mod Counter {
    #[storage]
    struct Storage {
        count: u64,
    }

    #[external(v0)]
    fn increment(ref self: ContractState) {
        let current = self.count.read();
        self.count.write(current + 1);
    }
}

Cairo 1.0 (2023): Rust-inspired syntax. Cairo 2.x (2024+) mature.


12. CosmWasm

WASM smart contracts on Cosmos SDK chains. Adoption: Osmosis, Injective, Stargaze, Juno, Sei.

#[entry_point]
pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> Result<Response, ContractError> {
    match msg {
        ExecuteMsg::Increment {} => execute_increment(deps),
    }
}

Rust with WASM sandbox. Strict resource limits.


13. Common vulnerabilities (SWC)

SWC Registry (swcregistry.io): catalog of the Smart Contract Weakness Classification.

SWC ID Bug Historical example
SWC-107 Reentrancy The DAO 2016 (US$ 60M)
SWC-101 Integer overflow/underflow BeautyChain 2018 (solved by Solidity 0.8 default checked)
SWC-104 Unchecked call return TheRunOnEarth 2018
SWC-105 Unprotected ether withdrawal Parity Wallet 2017 (US$ 280M frozen)
SWC-106 Unprotected SELFDESTRUCT Parity 2017
SWC-114 Tx.origin auth phishing
SWC-115 Authorization via tx.origin same
SWC-118 Incorrect constructor name pre-0.4.22 typos
SWC-128 DoS by gas limit unbounded loops
SWC-132 Race conditions front-running, MEV
SWC-133 Hash collisions Solidity packed encoding
SWC-136 Unencrypted private data "private" is only blockchain-level

Bug categories

  • Reentrancy: external call returns control before state is changed. Classic + read-only reentrancy variations.
  • Access control: missing onlyOwner/onlyRole checks.
  • Oracle manipulation: uses Uniswap spot price → flash loan attack.
  • Flash loan attacks: arbitrage a low-liquidity oracle.
  • Front-running / MEV: unprotected price-sensitive ops.
  • Signature replay: missing nonce or domain separation.
  • Math errors: precision (FP not native), overflow (pre-0.8), rounding.
  • Logic bugs: protocol design flaws (Compound DAI/USDC reward bug 2021 — US$80M).
  • Composability bugs: contract A interacts unexpectedly with B.

14. Auditing

Tier-1 firms

  • OpenZeppelin (security focus).
  • Trail of Bits (Manticore, Slither, Echidna).
  • ConsenSys Diligence (MythX, Mythril).
  • Certora (formal verification).
  • Code4rena (crowdsourced contests).
  • Sherlock (insurance + audit).
  • Cantina (formerly Spearbit).
  • Zellic, Halborn, NCC Group, Quantstamp, Hacken.

Tools

  • Slither (Trail of Bits): static analyzer in Python.
  • Mythril: symbolic execution.
  • Echidna: property-based fuzzer.
  • Foundry invariant testing.
  • Halmos (a16z): symbolic execution, Foundry-compatible.
  • Certora Prover: SMT-based formal verification.
  • Manticore: symbolic execution.
  • MythX (deprecated 2023).

Bug bounties

  • Immunefi (immunefi.com): largest bounty platform. US$ 100k–10M+ payouts.
  • HackerOne (some chains).
  • Internal bounties (Coinbase, Aave, Compound).

15. Formal verification

Mathematically prove that a contract meets its spec.

  • Certora: K-spec language + SMT.
  • Halmos: symbolic execution.
  • Move Prover: built into the Move language.
  • K-Framework: formal semantics of the EVM (KEVM).
  • F* / Liquidity Haskell: research.

Adoption: Aave, Compound, MakerDAO, Curve use Certora.

Cost: 5-10× a normal audit. Justifiable on high-TVL protocols.


16. Account Abstraction (ERC-4337)

Coverage in 05-l1-ethereum.md §AA.

Smart wallets are smart contracts. Dev considerations:

  • Implement validateUserOp(UserOperation, hash, missingFunds) → validationData.
  • Custom signature schemes (multisig, ECDSA, EdDSA, BLS, WebAuthn passkey, post-quantum).
  • Paymaster integration.
  • Session keys.
  • Nonce management (sequential or batched).

17. Upgradeability patterns

Pattern Mechanics Trade-off
Transparent Proxy (OpenZeppelin) Proxy delegates; admin in separate slot Simple, gas heavier
UUPS (EIP-1822) Upgrade logic in implementation Lighter, risk if upgrade missed in impl
Beacon Multiple proxies → 1 beacon → 1 impl Mass upgrade
Diamond (EIP-2535) Multi-facet, function-level routing Complex, very flexible
Metamorphic (CREATE2 + selfdestruct) Same address, redeploy Risky, hard to audit

Non-upgradeable: ideal for trustlessness. Upgradeable: backdoor risk (admin can replace logic).


18. Dev experience frameworks

Framework Lang Focus
Foundry Rust+Solidity EVM (preferred 2026)
Hardhat TS/JS EVM (legacy, popular)
Anchor Rust Solana
Truffle JS EVM (sunset 2023)
Brownie Python EVM (declining)
Apeworx Python EVM (modern Python)
Scaffold-ETH 2 Next.js + Foundry/Hardhat Full-stack starter
Wake Python EVM auditing

19. Indexers and querying

Smart contract events are emitted on-chain; impractical to query directly.

  • The Graph (decentralized indexing protocol).
  • Goldsky (managed).
  • Subsquid (modular).
  • Alchemy Subgraphs.
  • Ponder (TypeScript framework, modern).
  • Envio (high-perf indexing).

  • ~80M unique contracts deployed on Ethereum + L2s combined.
  • ~5k auditing firms / individual auditors active.
  • ~$100M+ paid in bug bounties via Immunefi cumulatively.
  • Foundry surpassed Hardhat in new project starts ~2024.
  • Move + Cairo gaining traction outside the EVM.
  • ZK-VMs (RISC Zero, SP1, Jolt) for general-purpose verifiable compute.

21. Cross-reference

  • VMs on chains: 04-l1-bitcoin.md, 05-l1-ethereum.md, 06-l1-alt.md.
  • L2s where contracts deploy: 07-l2-scaling.md.
  • DeFi contracts built: 09-defi.md.
  • Smart contract hacks: 14-incidents.md.
  • Account Abstraction: 05-l1-ethereum.md §6.
  • Crypto formal verification: ../cryptography/02-fundamentos.md §11.