Skip to main content

Command Palette

Search for a command to run...

Libraries

Published
2 min readView as Markdown
Libraries

Libraries

  1. In Solidity, a library is a collection of functions that can be reused across multiple contracts. Libraries are similar to contracts, but they are not meant to be deployed on the blockchain and do not have their own storage. Instead, the functions in a library can be called by other contracts and the library code is executed in the context of the calling contract.

  2. Libraries can be used to improve code organization and reduce code duplication. By putting commonly used functions in a library, multiple contracts can call those functions without needing to duplicate the code in each contract.

Here's an example of a library:

pragma solidity ^0.8.0;

library Math {
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "Math: addition overflow");
        return c;
    }
}
  1. In this example, we define a library named Math that contains a single function called add. The add function takes two uint256 values as input and returns their sum. The internal visibility modifier means that the function can only be called from within the same contract or from contracts that inherit from the same contract.

  2. To use the Math library in a contract, we need to import the library and then call the functions using the library name. Here's an example:

pragma solidity ^0.8.0;

import "./Math.sol";

contract MyContract {
    uint256 public value;

    function add(uint256 a, uint256 b) public {
        value = Math.add(a, b);
    }
}
  1. In this example, we import the Math library and use the add function from the library to add two uint256 values and store the result in the value variable of the MyContract contract.

  2. It's important to note that libraries can only be used for internal functions, which means that they cannot be called from external accounts or contracts. Additionally, libraries cannot access contract storage directly, which means that they cannot read or write to contract state variables.