0
0
Blockchain / Solidityprogramming~5 mins

Library contracts in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Library contracts help you reuse code in blockchain programs. They save space and make your code easier to manage.

When you want to share common functions between multiple smart contracts.
When you want to save gas by avoiding duplicate code in your contracts.
When you want to organize your code better by separating reusable parts.
When you want to update logic in one place and have all contracts use it.
When you want to keep your main contract simple and clean.
Syntax
Blockchain / Solidity
library LibraryName {
    function functionName(params) internal pure returns (returnType) {
        // function code
    }
}

contract MyContract {
    using LibraryName for Type;

    function myFunction() public {
        // call library functions
    }
}

Library contracts cannot have state variables or receive Ether.

Functions in libraries are usually marked internal or public.

Examples
This example shows a simple library with an add function used inside a contract.
Blockchain / Solidity
library MathLib {
    function add(uint a, uint b) internal pure returns (uint) {
        return a + b;
    }
}

contract Calculator {
    function sum(uint x, uint y) public pure returns (uint) {
        return MathLib.add(x, y);
    }
}
This example shows how to attach library functions to a type using using for.
Blockchain / Solidity
library StringUtils {
    function toUpper(string memory str) internal pure returns (string memory) {
        // code to convert string to uppercase
    }
}

contract TextProcessor {
    using StringUtils for string;

    function shout(string memory text) public pure returns (string memory) {
        return text.toUpper();
    }
}
Sample Program

This program defines a library with a multiply function. The contract uses it to double a number.

Blockchain / Solidity
pragma solidity ^0.8.0;

library Math {
    function multiply(uint a, uint b) internal pure returns (uint) {
        return a * b;
    }
}

contract Test {
    function double(uint x) public pure returns (uint) {
        return Math.multiply(x, 2);
    }
}
OutputSuccess
Important Notes

Library contracts help reduce gas costs by avoiding code duplication.

Libraries cannot hold state or receive Ether, so they are safe helpers.

Use using LibraryName for Type; to add library functions to types.

Summary

Library contracts let you reuse code in smart contracts.

They help save gas and keep code organized.

Use library keyword and call functions from your contracts.