08 smart contracts

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

*mart contract* código executado em blockchain VM, com:

  • *eterminismo* mesma input → mesma output em qualquer node.
  • *andbox* sem acesso a I/O externo (filesystem, network).
  • *ersistência* storage on-chain entre invocações.
  • *agar pra rodar* gas/fees.
  • *mutabilidade após deploy*(com excepções: proxies, upgradeable patterns).
  • *omposability* contracts chamam contracts.

Termo cunhado por *ick 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
*VM* Solidity, Vyper Yul, Huff, Fe
*oveVM (Aptos)* Aptos Move
*oveVM (Sui)* Sui Move
*olana SVM (eBPF)* Rust (Anchor framework), C, C++
*airoVM (StarkNet)* Cairo 1.0
*ASM (CosmWasm, ICP, Polkadot)* Rust, AssemblyScript Go (TinyGo)
*lutus Core (Cardano)* Plutus (Haskell), Marlowe, Aiken
*ON VM* FunC, Tact, Tolk
*ichelson (Tezos)* SmartPy, LIGO, Archetype
*VM (Algorand)* TEAL, PyTeal, Reach
*tylus (Arbitrum)* Rust, C, C++ via WASM EVM-compatible bridge
*ISC Zero zkVM* Rust qualquer linguagem que compile para RISC-V
*P1 (Succinct)* Rust qualquer RISC-V

3. Solidity

*hristian 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

  • *.4.x*(2017): legacy era. ICO boom contracts.
  • *.5.x*(2018): explicit visibility + storage location.
  • *.6.x*(2019): try/catch, abstract contracts.
  • *.7.x*(2020): SPDX, transitional.
  • *.8.x*(2020presente): *efault checked arithmetic*(no SafeMath needed). Era atual; ~0.8.240.8.27 em 2026.

Features modernas

  • *ustom errors*(0.8.4): error InsufficientBalance(uint256 available, uint256 required); cheaper que require("string").
  • *ser-defined value types*(0.8.8).
  • *unction pointers*
  • *ry/catch*em external calls.
  • *unchecked { ... }`*for explicit overflow allow.
  • *ransient storage*(0.8.24, EIP1153): cheap intratx storage.

Storage layout

  • 256bit slots, 0indexed.
  • 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

  • *hecksEffectsInteractions*(CEI): valida → muda state → external call. Anti-reentrancy.
  • *ull payments* receivers withdraw em vez de push. Anti-locking.
  • *eentrancy guards* nonReentrant modifier (OpenZeppelin).
  • *ccess control* Ownable, AccessControl (RBAC), Pausable.
  • *roxy upgradeability* Transparent (OZ), UUPS, Diamond (EIP-2535), Beacon.
  • *nitializer pattern*(proxies): initialize() em vez de constructor.

4. Vyper

*italik + Vlad Zamfir 2017+* Pythonlike, securityfirst.

Filosofia

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

Adoção

Usada por *urve Finance*principalmente. *yper 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

  • *RC20, ERC721, ERC1155*(mintable, burnable, pausable variants).
  • *ccessControl*(RBAC).
  • *wnable, Ownable2Step*
  • *overnor*(DAO governance reference).
  • *imelockController*
  • *ransparentUpgradeableProxy, UUPSUpgradeable, BeaconProxy*
  • *CDSA, EIP712, MessageHashUtils*
  • *afeERC20*(handles non-standard ERC20).
  • *erkleProof, MerkleTree*
  • *eentrancyGuard*

Defender (cloud product)

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


7. Foundry

*aradigm 2022* Toolkit Rust para Solidity. *adrão moderno*2024+.

Componentes

  • *orge* build + test (Solidity-native tests).
  • *ast* CLI para interagir com chains.
  • *nvil* local devnet (replaces Hardhat node).
  • *hisel* 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

*omic 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.

*tatus 2026* ainda popular legacy + ecosystem JS. Foundry domina greenfield.


9. Move

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

Características

  • *esource type* linear types — assets não podem ser duplicated, só moved/transferred. Compile-time enforcement.
  • *ytecode verifier* garante invariants antes de execução.
  • *odules + scripts* módulo = code; script = transação que invoca.
  • *enerics*
  • *ormal 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 *rograms* Stateless: state armazenado em *ccounts*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

  • *ative Solana SDK*(sem Anchor, mais boilerplate).
  • *eahorse*(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)

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

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

Bugs categories

  • *eentrancy* external call retorna controle antes de state mudado. Classic + read-only reentrancy variations.
  • *ccess control* missing onlyOwner/onlyRole checks.
  • *racle manipulation* usa Uniswap spot price → flash loan attack.
  • *lash loan attacks* arbitrar low-liquidity oracle.
  • *rontrunning / MEV* unprotected pricesensitive ops.
  • *ignature replay* missing nonce ou domain separation.
  • *ath errors* precisão (FP not native), overflow (pre-0.8), rounding.
  • *ogic bugs* protocol design flaws (Compound DAI/USDC reward bug 2021 — US$80M).
  • *omposability bugs* contract A interacts unexpectedly with B.

14. Auditoria

Empresas tier-1

  • *penZeppelin*(security focus).
  • *rail of Bits*(Manticore, Slither, Echidna).
  • *onsenSys Diligence*(MythX, Mythril).
  • *ertora*(formal verification).
  • *ode4rena*(crowdsourced contests).
  • *herlock*(insurance + audit).
  • *antina*(formerly Spearbit).
  • *ellic, Halborn, NCC Group, Quantstamp, Hacken*

Tools

  • *lither*(Trail of Bits): static analyzer Python.
  • *ythril* symbolic execution.
  • *chidna* property-based fuzzer.
  • *oundry invariant testing*
  • *almos*(a16z): symbolic execution Foundry-compatible.
  • *ertora Prover* SMT-based formal verification.
  • *anticore* symbolic execution.
  • *ythX*(deprecated 2023).

Bug bounties

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

15. Formal verification

Provar matematicamente que contract atende spec.

  • *ertora* K-spec language + SMT.
  • *almos* symbolic execution.
  • *ove Prover* built-in Move language.
  • *-Framework* formal semantics of EVM (KEVM).
  • ** / Liquidity Haskell* research.

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

Custo: 510× audit normal. Justificável em protocols highTVL.


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
*ransparent Proxy*(OpenZeppelin) Proxy delegates; admin separate slot Simple, gas heavier
*UPS*(EIP-1822) Upgrade logic em implementation Lighter, risk if upgrade in impl missed
*eacon* Multiple proxies → 1 beacon → 1 impl Mass upgrade
*iamond*(EIP-2535) Multifacet, functionlevel routing Complex, very flexible
*etamorphic*(CREATE2 + selfdestruct) Same address, redeploy Risky, audit hard

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


18. Frameworks dev experience

Framework Lang Foco
*oundry* Rust+Solidity EVM (preferred 2026)
*ardhat* TS/JS EVM (legacy, popular)
*nchor* Rust Solana
*ruffle* JS EVM (sunset 2023)
*rownie* Python EVM (declining)
*peworx* Python EVM (modern Python)
*caffold-ETH 2* Next.js + Foundry/Hardhat Full-stack starter
*ake* Python EVM auditing

19. Indexers e querying

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

  • *he Graph*(decentralized indexing protocol).
  • *oldsky*(managed).
  • *ubsquid*(modular).
  • *lchemy Subgraphs*
  • *onder*(TypeScript framework, modern).
  • *nvio*(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.
  • ZKVMs (RISC Zero, SP1, Jolt) for generalpurpose 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.

Source: ../home/koder/dev/koder/meta/docs/blockchain/compendium/08-smart-contracts.md