Advanced Functions

Libraries

Beginner Level

Libraries are reusable pieces of code that can be called from multiple contracts.

  • Cannot hold state variables or inherit / be inherited.
  • Can be internal (code is embedded in the calling contract) or external (deployed once, referenced by contracts).

1) Internal library

  • Functions are copied into the calling contract during compilation.

Example:


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

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

contract UseMath {
    function sum(uint256 a, uint256 b) public pure returns (uint256) {
        return MathLib.add(a, b);
    }
}

2) External library

  • Deployed once on the blockchain, multiple contracts can reference it.
  • Saves deployment gas.

Example:


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

library StringUtils {
    function length(string memory str) external pure returns (uint256) {
        return bytes(str).length;
    }
}

contract UseString {
    function getLength(string memory str) public view returns (uint256) {
        return StringUtils.length(str); // Calls external library
    }
}

Summary table

Feature Description
Events & Logging Emit events to log information without using storage
Function Overloading Multiple functions with same name but different parameters
Fallback & Receive Special functions to handle Ether & unknown calls
Call Low-level external function call
Delegatecall Executes external code in the context of calling contract
Libraries Reusable code modules; internal embedded, external deployed once

Continue Learning

Explore more topics in Solidity or browse other tutorials.