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

ライブラリと抽象コントラクト

純粋で再利用可能な関数にライブラリを、基盤となる機能の定義に抽象コントラクトを使う方法を学びます。

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

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

Module: Code Reusability

Welcome to Libraries and Abstract Contracts! In this lesson, we'll explore two powerful Solidity features that enhance code reusability, modularity, and maintainability.

You'll learn how to build reusable utility functions with libraries and define common interfaces and base functionalities using abstract contracts.

What are Solidity Libraries?

Solidity Libraries are like special contracts that contain reusable code. They are designed for utility functions and cannot have state variables (with rare advanced exceptions) or hold Ether.

  • They are deployed once and their code can be used by many contracts.
  • This promotes code reuse and can be gas-efficient for complex operations.
  • Functions within a library are typically internal or public.

Defining a Utility Library

To create a library, you use the library keyword. Let's define a simple MathUtils library that provides basic arithmetic functions. Notice that library functions are often pure or view as they don't modify state.

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

library MathUtils {
    function add(uint a, uint b) internal pure returns (uint) {
        return a + b;
    }

    function subtract(uint a, uint b) internal pure returns (uint) {
        require(b <= a, "Subtraction overflow");
        return a - b;
    }
}

Integrating a Library

To use our MathUtils library, we link it to a data type within our contract using the using A for B; syntax. This makes the library's functions available on that data type.

Try deploying the SimpleCalculator and calling its functions!

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

library MathUtils {
    function add(uint a, uint b) internal pure returns (uint) {
        return a + b;
    }

    function subtract(uint a, uint b) internal pure returns (uint) {
        require(b <= a, "Subtraction overflow");
        return a - b;
    }
}

contract SimpleCalculator {
    using MathUtils for uint; // Attaches MathUtils functions to uint

    function performAddition(uint x, uint y) public pure returns (uint) {
        return x.add(y); // Using the library's add function
    }

    function performSubtraction(uint x, uint y) public pure returns (uint) {
        return x.subtract(y); // Using the library's subtract function
    }
}

What are Abstract Contracts?

An abstract contract is a contract that cannot be deployed on its own. It's like a blueprint or a partial implementation for other contracts.

  • They define functions without implementing them (abstract functions).
  • They can also have implemented functions and state variables.
  • They serve as a base for other "concrete" contracts to inherit from, ensuring a common structure.

Blueprint with Abstract Contract

An abstract contract is declared using the abstract contract keyword. It must have at least one function declared without an implementation (meaning, without curly braces {}).

These unimplemented functions must be marked virtual in the abstract contract and override in the inheriting concrete contract.

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

abstract contract BaseShape {
    string public name;

    constructor(string memory _name) {
        name = _name;
    }

    // An abstract function - no implementation here
    function getArea() public view virtual returns (uint);

    // Can also have implemented functions
    function getName() public view returns (string memory) {
        return name;
    }
}

Implementing an Abstract Contract

To use an abstract contract, another contract must inherit from it using the is keyword and provide implementations for all its abstract functions.

This ensures that any contract inheriting from BaseShape will have a getArea function, guaranteeing a common interface for all shapes.

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

abstract contract BaseShape {
    string public name;

    constructor(string memory _name) {
        name = _name;
    }

    function getArea() public view virtual returns (uint);

    function getName() public view returns (string memory) {
        return name;
    }
}

contract Circle is BaseShape {
    uint public radius;
    // For simplicity, we'll use radius^2 as area, ignoring Pi.

    constructor(uint _radius) BaseShape("Circle") {
        radius = _radius;
    }

    // Must implement the abstract function from BaseShape
    function getArea() public view override returns (uint) {
        return radius * radius;
    }
}

contract Square is BaseShape {
    uint public side;

    constructor(uint _side) BaseShape("Square") {
        side = _side;
    }

    function getArea() public view override returns (uint) {
        return side * side;
    }
}

Libraries: Key Benefits

Libraries are a great choice when you need:

  • Pure Functions: Operations that don't change state, like complex math, string utilities, or data conversions.
  • Gas Efficiency: For external libraries, the bytecode is deployed once and its functions are called via a low-cost DELEGATECALL.
  • Modularity: Keeps your main contracts cleaner by offloading utility logic.
  • Reusability: Avoids duplicating common code across multiple contracts.

Abstract Contracts: Key Benefits

Abstract contracts are essential for:

  • Interface Enforcement: Guaranteeing that inheriting contracts implement a specific set of functions.
  • Base Functionality: Providing common state variables and implemented functions that all derived contracts will share.
  • Design Patterns: Implementing patterns like 'template method' where a high-level algorithm is defined, but specific steps are left to concrete implementations.
  • Polymorphism: Allowing different concrete implementations to be treated as the same base type.

Check Your Understanding

Which of the following statements about Solidity Libraries and Abstract Contracts are TRUE?

Recap: Libraries & Abstract Contracts

In this lesson, we explored two powerful tools for structuring Solidity code: Libraries and Abstract Contracts.

  • Libraries provide reusable, stateless utility functions, promoting modularity and gas efficiency. They are linked to contracts to extend their functionality.
  • Abstract Contracts act as blueprints, defining common interfaces and base functionalities that concrete contracts must inherit and implement. They enforce structure and promote consistency.

Mastering these patterns helps you write cleaner, more maintainable, and robust smart contracts in Solidity.

よくある質問

「ライブラリと抽象コントラクト」レッスンは無料ですか?

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

「ライブラリと抽象コントラクト」で何を学びますか?

純粋で再利用可能な関数にライブラリを、基盤となる機能の定義に抽象コントラクトを使う方法を学びます。 ブラウザで直接実行するハンズオンコードでBlockchain Smart Contracts with Solidityを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

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

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

「ライブラリと抽象コントラクト」レッスンにはどのくらい時間がかかりますか?

ほとんどの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に戻る