Libraries are similar to contracts, but their purpose is that they are deployed only once at a specific address and their code is reused by various contracts. This means that if library functions are called, their code is executed in the context of the calling contract; that is, this points to the calling contract, and especially, the storage from the calling contract can be accessed. As a library is an isolated piece of source code, it can only access state variables of the calling contract if they are explicitly supplied (it would have no way to name them otherwise).
Libraries cannot have state variables; they don't support inheritance and they cannot receive Ether. Libraries can contain structs and enums.
Once a Solidity library is deployed to the blockchain, it can be used by anyone, assuming you know its address and have the source code (with only prototypes or complete implementation). The source code is required by the Solidity compiler so that it can make sure that the methods you are trying to access actually exist in the library.
Let's take a look at an example:
library math
{
function addInt(int a, int b) returns (int c)
{
return a + b;
}
}
contract sample
{
function data() returns (int d)
{
return math.addInt(1, 2);
}
}
We cannot add the address of the library in the contract source code; instead, we need to provide the library address during compilation to the compiler.
Libraries have many use cases. The two major use cases of libraries are as follows:
- If you have many contracts that have some common code, then you can deploy that common code as a library. This will save gas as gas depends on the size of the contract too. Therefore, we can think of a library as a base contract of the contract that uses it. Using a base contract instead of a library to split the common code won't save gas because in Solidity, inheritance works by copying code. Due to the reason that libraries are thought of as base contracts, functions with the internal visibility in a library are copied to the contract that uses it; otherwise, functions with the internal visibility of a library cannot be called by the contract that uses the library, as an external call would be required and functions with the internal visibility cannot be invoked using the external call. Also, structs and enums in a library are copied to the contract that uses the library.
- Libraries can be used to add member functions to data types.