08 — Smart Contracts

Programas que executam em blockchain sob regras determinísticas. EVM domina; Move (Aptos/Sui), Cairo (StarkNet), CosmWasm, Solana eBPF crescem.


1. Definição e propriedades

Smart contract: código executado em blockchain VM, com:

  • Determinismo: mesma input → mesma output em qualquer node.
  • Sandbox: sem acesso a I/O externo (filesystem, network).
  • Persistência: storage on-chain entre invocações.
  • Pagar pra rodar: gas/fees.
  • Imutabilidade após deploy (com excepções: proxies, upgradeable patterns).
  • Composability: contracts chamam contracts.

Termo cunhado por Nick Szabo em 1994 ("Smart Contracts: Building Blocks for Digital Free Markets"). Implementação real só com Ethereum (2015).


2. Linguagens por VM

VM Linguagens primárias Outras
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 qualquer linguagem que compile para RISC-V
SP1 (Succinct) Rust qualquer RISC-V

3. Solidity

Christian Reitwiessner + ConsenSys 2014. Inspirada por 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);
    }
}

Versões marcantes

  • 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-presente): default checked arithmetic (no SafeMath needed). Era atual; ~0.8.24-0.8.27 em 2026.

Features modernas

  • Custom errors (0.8.4): error InsufficientBalance(uint256 available, uint256 required); cheaper que require("string").
  • User-defined value types (0.8.8).
  • Function pointers.
  • Try/catch em 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 em slot, items em \(H(\text{slot})\) + index.
  • Inheritance: linearized C3.

Visibility

  • public: external + internal callable. Auto-getter for state vars.
  • external: only external (this.f() works mas pago).
  • internal: this contract + derived.
  • private: only this contract (mas state ainda público on-chain).

Patterns canônicos

  • Checks-Effects-Interactions (CEI): valida → muda state → external call. Anti-reentrancy.
  • Pull payments: receivers withdraw em vez de 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() em vez de constructor.

4. Vyper

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

Filosofia

  • Removidas features perigosas: inheritance, function overloading, modifiers, infinite loops, recursion.
  • Bounded loops only.
  • Decimal type built-in.
  • Easier auditing.

Adoção

Usada por Curve Finance principalmente. Vyper compiler bug 2023 afetou Curve pools (CRV/ETH, alETH, msETH, pETH) — US$ 73M perdidos. Reincided que linguagem secundária pode ter bugs piores que mainstream (Solidity).

Status 2026

Vyper 0.4.x maduro. Auditorias mais frequentes pós-2023. ~5% market share contracts deployed.


5. EVM intricacies

Calldata vs memory vs storage

Local Custo Uso
Calldata quase grátis Read-only function args
Memory barato (linear+) Local vars dentro função
Storage caro (20k SSTORE first) Persistent state
Transient (0.8.24) barato Intra-tx ephemeral

Gas optimization tips

  • Use uint256 (native word) — packing menor às vezes pior se ler junto.
  • Custom errors > revert strings.
  • external cheaper que public quando só external called.
  • Cache storage → memory dentro da função.
  • Bit packing structs.
  • Use unchecked em loops com bounds garantidos.
  • Foundry --gas-report pra benchmarks.

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

Refactor of 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 é referência standard Solidity.

Contratos canônicos

  • 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 — monitoramento, automation, multisig, upgrade workflow.


7. Foundry

Paradigm 2022. Toolkit Rust para Solidity. Padrão moderno 2024+.

Componentes

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

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 contra mainnet state
}

Forge Std

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

Vantagens vs Hardhat

  • Tests em Solidity (mesma linguagem que contracts).
  • Performance: 10×+ rápido (Rust).
  • Native fuzzing + invariant testing.
  • Built-in fork mode.
  • Stack traces melhores.

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: ainda popular legacy + ecosystem JS. Foundry domina greenfield.


9. Move

Diem (Facebook) 2019 original; herdado por Aptos + Sui (não-100% compatíveis).

Características

  • Resource type: linear types — assets não podem ser duplicated, só moved/transferred. Compile-time enforcement.
  • Bytecode verifier: garante invariants antes de execução.
  • Modules + scripts: módulo = code; script = transação que invoca.
  • 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 sob account.

Sui Move

Object-centric: tudo é objeto com owner ou 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;
    }
}

Object IDs unique. Parallel execution natural.


10. Solana programs

Não "smart contracts" — chamados programs. Stateless: state armazenado em accounts separados que program lê/escreve.

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 / segundo (Sealevel parallel).
  • Compute budget: 200k CU default per tx, ajustável.

Frameworks alternativos

  • Native Solana SDK (sem Anchor, mais boilerplate).
  • Seahorse (Python-like, abandoned).

11. Cairo (StarkNet)

ZK-friendly language. Compiles to AIR (Algebraic Intermediate Representation) provable em 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+) maduro.


12. CosmWasm

WASM smart contracts em 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 com sandbox WASM. Strict resource limits.


13. Vulnerabilidades comuns (SWC)

SWC Registry (swcregistry.io): catálogo de Smart Contract Weakness Classification.

SWC ID Bug Exemplo histórico
SWC-107 Reentrancy The DAO 2016 (US$ 60M)
SWC-101 Integer overflow/underflow BeautyChain 2018 (resolvido por 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 idem
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" só blockchain-level

Bugs categories

  • Reentrancy: external call retorna controle antes de state mudado. Classic + read-only reentrancy variations.
  • Access control: missing onlyOwner/onlyRole checks.
  • Oracle manipulation: usa Uniswap spot price → flash loan attack.
  • Flash loan attacks: arbitrar low-liquidity oracle.
  • Front-running / MEV: unprotected price-sensitive ops.
  • Signature replay: missing nonce ou domain separation.
  • Math errors: precisão (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. Auditoria

Empresas tier-1

  • 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 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

Provar matematicamente que contract atende spec.

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

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

Custo: 5-10× audit normal. Justificável em protocols high-TVL.


16. Account Abstraction (ERC-4337)

Cobertura em 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. Padrões de upgradeability

Padrão Mecânica Trade-off
Transparent Proxy (OpenZeppelin) Proxy delegates; admin separate slot Simple, gas heavier
UUPS (EIP-1822) Upgrade logic em implementation Lighter, risk if upgrade in impl missed
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, audit hard

Não-upgradeable: ideal pra trustless. Upgradeable: backdoor risk (admin can replace logic).


18. Frameworks dev experience

Framework Lang Foco
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 e querying

Smart contract events emitidos on-chain; impractical query directly.

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

20. Stats e tendências

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

21. Referência cruzada

  • VMs em chains: 04-l1-bitcoin.md, 05-l1-ethereum.md, 06-l1-alt.md.
  • L2 onde contracts deployam: 07-l2-scaling.md.
  • DeFi contracts construídos: 09-defi.md.
  • Hacks de smart contract: 14-incidentes.md.
  • Account Abstraction: 05-l1-ethereum.md §6.
  • Cripto formal verification: ../cryptography/02-fundamentos.md §11.