Open In App

Solidity – Libraries

Improve
Improve
Like Article
Like
Save
Share
Report

Libraries in solidity are similar to contracts that contain reusable codes. A library has functions that can be called by other contracts. Deploying a common code by creating a library reduces the gas cost. Functions of the library can be called directly when they do not modify the state variables i.e. only pure and view functions can be called from outside of the library. It cannot be destroyed because it is assumed as stateless. The library does not have state variables, it cannot inherit any element and cannot be inherited.

Creating Library

A library contract is defined by using the library keyword instead of a general contract. Libraries do not have any storage thus it cannot hold state variables, fallback or payable functions also cannot be created inside the library as it cannot store ethers. Libraries are not for changing the state of the contract, it can only be used for performing basic operations based on inputs and outputs. However it can implement some data types like struct and enums which are user-defined, and constant variables that are stored in a stack of Ethereum, not in storage. 

Syntax:

library <libraryName> {
    // block of code
}

Example: In the below example, the library libraryExample is created to demonstrate the procedure to create a library.

Solidity

// Solidity program to demonstrate 
// how to create a library
pragma solidity ^0.5.0;

// Library Definition
library libraryExample {
    
    // Defining structure
    struct Constants {

        // Declaring variables
        uint Pi;             
        uint EulerNb;        
        uint PythagoraConst; 
        uint TheodorusConst; 
    }
    
}

Deploying Library Using ‘For’ Keyword

A library can be defined on the same contract as well as it can be imported from outside by using the import statements. 

Example:

import <libraryName> from “./library-file.sol”;

A single file can contain multiple libraries that can be specified using curly braces in the import statement separated by a comma. A library can be accessed within the smart contract by using ‘for’ keyword. 

Syntax:

<libraryName> for <dataType>    

The above statement can be used to attach library functions to any type. libraryName is the name of the desired library to import, dataType is the variable type for which we want to access the library. All members of the library can also be used by the wildcard operator(*).

Example: In the below example, the contract libraryExample is created to demonstrate how to deploy a library using the ‘For’ keyword.

Solidity

// Solidity program to demonstrate 
// how to deploy a library
pragma solidity ^0.5.0;

// Defining Library
library LibExample {

    // Function to power of 
    // an unsigned integer
    function pow(
      uint a, uint b) public view returns (
      uint, address) {
        return (a ** b, address(this));
    }
}

// Defining calling contract
contract LibraryExample {
    
    // Deploying library using 
    // "for" keyword
    using LibExample for uint;
    address owner = address(this);
    
    // Calling function pow to 
    // calculate power 
    function getPow(
      uint num1, uint num2) public view returns (
      uint, address) {
        return num1.pow(num2);
    }
}

Output : 
 

Deploying Library

Deploying Library Without using For Keyword 

Example: In the below example, the contract libExample is created to demonstrate how to deploy a library without using the ‘For’ keyword.

Solidity

// Solidity program to demonstrate 
// how to deploy library 
// without using for keyword
pragma solidity ^0.5.0;

// Defining library
library libraryExample {

         // Defining structure
         struct strings {

              // Declaring variables
               string str1 ;
               string str2 ;
               string str3 ;
      }
       
     // function to concatenate 
    // 2 strings 
      function concatenate(
       string memory _In1, string memory _In2) 
                              public view returns(
       string memory){
           return string(
           abi.encodePacked(_In1, _In2));
           }
 }

// Defining calling contract
contract libExample{

         // Deploying the library 
         // without using "for" keyword
        libraryExample.strings data 
          = libraryExample.strings("Geeks", "For", "Geeks");

        // Function to calculate and display 
        // the result of string concatenation
          function getResult(
         ) public view returns(string memory){
          string memory result 
           = libraryExample.concatenate(data.str1, data.str2);
          result = libraryExample.concatenate(result, data.str3);
          return result;
     }
}

Output: 
 

Deploying Library without using For Keyword

Inbuilt libraries

Solidity has some inbuilt libraries for the ease of the users. Some of the libraries are listed below : 

  1. Modular network: This includes many modular libraries that are very useful for implementation like ArrayUtils, Token, CrowdSale, Vesting, StringUtils, LinkedList, Wallet, etc.
  2. OpenZeppelin: other supporting libraries are Roles, MerkleProof, ECDSA, Math, Address, SafeERC20, ERC165Checker, SafeMath, Arrays, etc which protects from overflow.
  3. Dapp-bin: Created by Ethereum includes interesting and useful libraries like DoublyLinkedList, StringUtils, IterableMapping, etc.

Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads