0Pricing
Blockchain Smart Contracts with Solidity · レッスン

Revert/Requireによるエラー処理

`require()`、`revert()`、`assert()`を使った効果的なエラー処理戦略を実装し、堅牢なコントラクト実行を実現します。

「Revert/Requireによるエラー処理」はCoddyKit上の無料Blockchain Smart Contracts with Solidityレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはBlockchain Smart Contracts with Solidity学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Blockchain Smart Contracts with Solidityコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Robust Contracts: Error Handling

Welcome to error handling in Solidity! Writing smart contracts requires extreme care, as they often manage valuable assets and are immutable once deployed.

Effective error handling is crucial for creating robust and secure decentralized applications (dApps). It helps prevent unexpected behavior and protects users.

`require()`: Validating Inputs

The require() function is your primary tool for validating conditions that must be true before a function executes.

  • It checks pre-conditions and user inputs.
  • If the condition is false, it reverts all state changes made in the current transaction.
  • It refunds any remaining gas to the caller, effectively canceling the transaction.

Use require() for external conditions and user-provided data checks.

`require()` in Action

Let's see require() in a simple contract. This function only allows users older than 18 to register.

pragma solidity ^0.8.0;

contract UserRegistration {
    uint public minAge = 18;
    address[] public registeredUsers;

    function registerUser(uint _age) public {
        // Validate user input: age must be at least minAge
        require(_age >= minAge, "Must be 18 or older to register.");
        registeredUsers.push(msg.sender);
    }
}

`revert()`: Flexible Error Handling

The revert() statement offers more flexibility than require(), especially when you need to handle complex error logic or integrate with custom error types.

  • Like require(), it reverts all state changes and refunds gas.
  • It's often used inside if statements for more intricate conditional checks.
  • It can be called directly or with a string message, similar to require().

Custom Errors with `revert()`

Solidity 0.8.4+ introduced Custom Errors. These are more gas-efficient than string messages and provide better clarity for off-chain applications.

You define custom errors at the contract or file level, then use them with revert(). They help reduce transaction costs and improve contract readability.

Custom Error Demo

Here's how to define and use a custom error with revert(). Notice the error keyword.

pragma solidity ^0.8.4;

contract Wallet {
    address public owner;
    uint public balance;

    // Define a custom error
    error InsufficientFunds(uint requested, uint available);

    constructor() {
        owner = msg.sender;
    }

    function deposit() public payable {
        balance += msg.value;
    }

    function withdraw(uint _amount) public {
        require(msg.sender == owner, "Only owner can withdraw.");

        // Use revert() with the custom error
        if (_amount > balance) {
            revert InsufficientFunds(_amount, balance);
        }
        balance -= _amount;
        payable(owner).transfer(_amount);
    }
}

`assert()`: Internal Invariants

The assert() function is used for a very specific purpose: checking internal invariants.

  • It verifies conditions that should never be false if your code is working correctly.
  • If an assert() fails, it indicates a bug in your contract logic.
  • Crucially, a failed assert() consumes all remaining gas, unlike require() and revert() which refund gas.

Use assert() for post-conditions or internal consistency checks, not for user input validation.

When to Use Which?

Choosing the right error handler is key:

  • require(): For validating user inputs, external conditions, or state changes before execution. Refunds gas.
  • revert(): For more complex error logic, often with custom errors. Also refunds gas.
  • assert(): For internal consistency checks and invariants. Indicates a bug if it fails and consumes all gas.

Prioritize require() and revert() for expected errors, and reserve assert() for unexpected, internal errors.

Error Handling Check

You're building a function that transfers tokens. Before sending, you need to ensure the sender has enough balance. If not, the transaction should fail and refund any unused gas.

Recap: Error Handling

You've learned how to make your Solidity contracts robust with proper error handling:

  • require() is for validating external conditions and user inputs.
  • revert() offers flexibility, often used with gas-efficient custom errors.
  • assert() is for internal invariants, signaling a bug if it fails.

Mastering these ensures your smart contracts are secure and predictable. Great job!

よくある質問

「Revert/Requireによるエラー処理」レッスンは無料ですか?

はい。「Revert/Requireによるエラー処理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Blockchain Smart Contracts with Solidityコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Blockchain Smart Contracts with Solidityコースには全4レッスンが含まれています。

「Revert/Requireによるエラー処理」で何を学びますか?

`require()`、`revert()`、`assert()`を使った効果的なエラー処理戦略を実装し、堅牢なコントラクト実行を実現します。 ブラウザで直接実行するハンズオンコードでBlockchain Smart Contracts with Solidityを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Blockchain Smart Contracts with Solidityを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのBlockchain Smart Contracts with Solidityは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「Revert/Requireによるエラー処理」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このBlockchain Smart Contracts with Solidityレッスンでコードを書いて実行できますか?

はい。すべてのBlockchain Smart Contracts with Solidityレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 継承とインターフェース
  2. ライブラリと抽象コントラクト
  3. Revert/Requireによるエラー処理
  4. 修飾子とChecks-Effects-Interactionsパターン
← Blockchain Smart Contracts with Solidityに戻る