0Pricing
Blockchain Smart Contracts with Solidity · 강의

라이브러리와 추상 계약

순수하고 재사용 가능한 함수를 위한 라이브러리와 기본 기능을 정의하는 추상 계약의 사용법을 살펴봅니다.

라이브러리와 추상 계약은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.

“라이브러리와 추상 계약”에서 뭘 배우나요?

순수하고 재사용 가능한 함수를 위한 라이브러리와 기본 기능을 정의하는 추상 계약의 사용법을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“라이브러리와 추상 계약” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 상속과 인터페이스
  2. 라이브러리와 추상 계약
  3. Revert/Require를 활용한 오류 처리
  4. 수정자와 검사-효과-상호 작용 패턴
← Blockchain Smart Contracts with Solidity(으)로 돌아가기