Library
Libraries in Solidity smart contracts are blocks of reusable code. Libraries also help you to save gas by using the existing code that is already available on the Blockchain instead of writing the code again.
For example, I want to create various methods related to Array which can help to manipulate the data according to your need like reverse method, get the index of the specific array element, etc. It is just like python or javascript methods like sort, reverse, index, etc, you don’t write your own functionality when it is natively available in python/JS or if someone has already created a library for it. You will straight away use them instead of creating your own methods from scratch.
Similarly, It will make more sense to use these methods if someone has already deployed them on the Blockchain instead of writing your methods from scratch.
you can create a library with the library keyword followed by the library Name. In the below example, when you deploy the codiesAlert contract REMIX IDE will automatically deploy the library first and then link this library with the codiesAlert contract and deploy it on Blockchain. Since library and contracts are deployed separately so they will have a different address. If you want to know how to use the existing library that is already deployed by someone then check this post.
There are two ways to access library functions inside the contract.
- The first way is by using the library name ArrayLib dot followed by the method name. ArrayLib.reverse(arr)
- The second way is by using the using keyword.using ArrayLib for unit[];This will make all the methods available for type uint[] inside the codiesAlert contract and then you can access this like arr.reverse() and this will do the exact same this. The second way is much better to use.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ArrayLib {
function reverse(uint[] storage arr) external view returns(uint[] memory) {
uint[] memory reverseArr = new uint[](arr.length);
uint count = 1;
for(uint i ; i < arr.length; i++) {
reverseArr[arr.length - count] = arr[i];
count +=1;
}
return reverseArr;
}
}
contract CodiesAlert {
uint[] public arr = [1,2,3,4];
function reverse() public view returns(uint[] memory) {
return ArrayLib.reverse(arr);
}
}
Libraries are a special form of contracts that:
- Cannot have any storage or state variables that change
- Cannot have fallback functions
- Have no event logs
- Do not hold Ether
- Are stateless
- Cannot use destroy
- Cannot inherit or be inherited