0Pricing
Blockchain Smart Contracts with Solidity · Aula

Modificadores e o Padrão Verificações-Efeitos-Interações

Use modificadores de função para impor pré-condições de forma clara e aplique o padrão verificações-efeitos-interações para escrever contratos mais seguros.

Modificadores e o Padrão Verificações-Efeitos-Interações é uma aula grátis de Blockchain Smart Contracts with Solidity no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Blockchain Smart Contracts with Solidity, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

What Are Modifiers?

A modifier is reusable code that runs before (or around) a function body. It is ideal for enforcing preconditions like access control without repeating the same checks everywhere.

Declaring a Modifier

The special _; placeholder marks where the function body executes. Code before it runs first; code after runs when the function returns.

modifier onlyOwner() {
    require(msg.sender == owner, "Not owner");
    _;
}

Applying a Modifier

Attach a modifier to a function declaration. The check runs automatically on every call, keeping the function body focused on logic.

function withdraw() public onlyOwner {
    payable(owner).transfer(address(this).balance);
}

Modifiers with Parameters

Modifiers can take arguments, making them flexible for validating dynamic conditions such as minimum values.

modifier costs(uint price) {
    require(msg.value >= price, "Not enough");
    _;
}

Stacking Multiple Modifiers

You can apply several modifiers to one function; they run left to right. Keep them small and single-purpose so combinations stay predictable.

function buy() public payable onlyWhenOpen costs(1 ether) {
    // ...
}

The Reentrancy Danger

When a contract calls out to an external address, that address can call back into your contract before the first call finishes. This reentrancy can drain funds if state is updated too late.

Checks-Effects-Interactions

The checks-effects-interactions pattern orders your function in three phases: validate inputs (checks), update state (effects), then call external contracts (interactions). External calls come last.

A Vulnerable Withdraw

This sends ETH before zeroing the balance, leaving a reentrancy window.

// VULNERABLE
function withdraw() public {
    uint amt = balances[msg.sender];
    payable(msg.sender).call{value: amt}("");
    balances[msg.sender] = 0; // too late!
}

The Safe Version

Update state before the external call so a reentrant call sees a zero balance.

// SAFE
function withdraw() public {
    uint amt = balances[msg.sender];
    balances[msg.sender] = 0;   // effects first
    payable(msg.sender).call{value: amt}(""); // interaction last
}

Reentrancy Guards

For extra safety, add a reentrancy guard modifier that sets a lock flag during execution, rejecting nested calls. Libraries like OpenZeppelin provide nonReentrant.

Combining the Patterns

Use modifiers for the checks phase (access and validation), structure the body as effects-then-interactions, and add a guard on functions that move value. Together they form a strong defensive baseline.

Quick Check

Check your knowledge of safe contract patterns.

Recap

You learned defensive Solidity patterns:

  • Modifiers centralize preconditions like access control
  • They can take parameters and be stacked
  • Checks-effects-interactions orders functions to prevent reentrancy
  • Add a reentrancy guard on value-moving functions

These patterns are foundational to writing secure contracts.

Perguntas Frequentes

A aula “Modificadores e o Padrão Verificações-Efeitos-Interações” é grátis?

Sim — o texto completo de “Modificadores e o Padrão Verificações-Efeitos-Interações” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Blockchain Smart Contracts with Solidity, atualize para CoddyKit PRO. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.

O que vou aprender em “Modificadores e o Padrão Verificações-Efeitos-Interações”?

Use modificadores de função para impor pré-condições de forma clara e aplique o padrão verificações-efeitos-interações para escrever contratos mais seguros. Você pratica Blockchain Smart Contracts with Solidity com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Blockchain Smart Contracts with Solidity?

Nenhuma experiência prévia é necessária. Blockchain Smart Contracts with Solidity no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Modificadores e o Padrão Verificações-Efeitos-Interações”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Blockchain Smart Contracts with Solidity?

Sim. Cada aula de Blockchain Smart Contracts with Solidity inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Herança e interfaces
  2. Bibliotecas e contratos abstratos
  3. Tratamento de erros com Revert/Require
  4. Modificadores e o Padrão Verificações-Efeitos-Interações
← Voltar para Blockchain Smart Contracts with Solidity