Libraries & using for
A library is a collection of reusable functions, like a contract without state. Libraries can't have state variables, can't receive ether and can't be inherited. They are used for math helpers, data-structure operations and safe wrappers around low-level calls.
library MathUtils {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
}Calling a library
Call a library function with the library's name as prefix. internal library functions are copied into the calling contract at compile time, so they cost no external call:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
library MathUtils {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function clamp(uint256 x, uint256 lo, uint256 hi) internal pure returns (uint256) {
return x < lo ? lo : (x > hi ? hi : x);
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a & b) + (a ^ b) / 2; // no overflow even near type(uint256).max
}
}
contract Main {
function main() external pure {
console.log("max(3, 9) :", MathUtils.max(3, 9));
console.log("clamp(150,0,100):", MathUtils.clamp(150, 0, 100));
console.log("average(7, 10) :", MathUtils.average(7, 10));
uint256 big = type(uint256).max;
console.log("average(max,max) == max?", MathUtils.average(big, big) == big);
}
}max(3, 9) : 9
clamp(150,0,100): 100
average(7, 10) : 8
average(max,max) == max? true
(a + b) / 2 would overflow for very large values; the bitwise trick in average cannot. Tricks like this are exactly why we collect well-tested helpers in libraries.
using for: functions as methods
using Library for Type; attaches the library's functions to a type, so the first argument becomes the receiver: x.max(y) instead of MathUtils.max(x, y).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
library Percent {
function percentOf(uint256 amount, uint256 pct) internal pure returns (uint256) {
return amount * pct / 100;
}
function addPercent(uint256 amount, uint256 pct) internal pure returns (uint256) {
return amount + percentOf(amount, pct);
}
}
contract Main {
using Percent for uint256;
function main() external pure {
uint256 price = 2500;
console.log("10% of price:", price.percentOf(10));
console.log("price + 20% :", price.addPercent(20));
console.log("chained :", price.addPercent(10).addPercent(10));
}
}10% of price: 250
price + 20% : 3000
chained : 3025
Libraries on storage data
Library functions can take storage references, which makes them perfect for reusable data structures. Here is a small address set with O(1) add, remove and membership check:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
library AddressSet {
struct Set {
address[] items;
mapping(address => uint256) position; // index + 1; 0 means absent
}
function add(Set storage s, address a) internal returns (bool) {
if (s.position[a] != 0) return false;
s.items.push(a);
s.position[a] = s.items.length;
return true;
}
function remove(Set storage s, address a) internal returns (bool) {
uint256 pos = s.position[a];
if (pos == 0) return false;
address last = s.items[s.items.length - 1];
s.items[pos - 1] = last; // swap and pop
s.position[last] = pos;
s.items.pop();
delete s.position[a];
return true;
}
function contains(Set storage s, address a) internal view returns (bool) {
return s.position[a] != 0;
}
function length(Set storage s) internal view returns (uint256) {
return s.items.length;
}
}
contract Main {
using AddressSet for AddressSet.Set;
AddressSet.Set private admins;
function main() external {
admins.add(address(0xA));
admins.add(address(0xB));
admins.add(address(0xC));
console.log("added A again?", admins.add(address(0xA)));
admins.remove(address(0xA));
console.log("size:", admins.length());
console.log("contains A?", admins.contains(address(0xA)));
console.log("contains C?", admins.contains(address(0xC)));
}
}added A again? false
size: 2
contains A? false
contains C? true
OpenZeppelin's EnumerableSet works the same way and is what you'd use in production.
using for at file level and on user types
using L for T global; at file level attaches functions everywhere the type is used. This pairs well with user-defined value types, thin wrappers that give a raw uint256 a meaning the compiler can check:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
type Cents is uint256;
library CentsMath {
function plus(Cents a, Cents b) internal pure returns (Cents) {
return Cents.wrap(Cents.unwrap(a) + Cents.unwrap(b));
}
function format(Cents c) internal pure returns (uint256 whole, uint256 frac) {
uint256 v = Cents.unwrap(c);
return (v / 100, v % 100);
}
}
using CentsMath for Cents global;
contract Main {
function main() external pure {
Cents coffee = Cents.wrap(350);
Cents cake = Cents.wrap(425);
(uint256 whole, uint256 frac) = coffee.plus(cake).format();
console.log("total:", whole, frac);
// Cents bad = coffee + 1; // compile error: Cents is not a plain uint256
}
}total: 7 75
Deployed (linked) libraries
Libraries with public or external functions are deployed separately and called with DELEGATECALL, so many contracts can share one copy of the code. That requires a "linking" step at deployment time. Most projects only use internal library functions, which are simply inlined.
Test yourself
Which statement about libraries is true?
- They can store state variables
- They can receive ether
internallibrary functions are embedded into the calling contract- They must be inherited with
is
After using Percent for uint256;, what does price.percentOf(10) call?
Percent.percentOf(10, price)Percent.percentOf(price, 10)price.Percent(10)- Nothing; it doesn't compile
Why is (a + b) / 2 risky for two uint256 values?
- It rounds up
a + bcan overflow and revert for large values- Division is not allowed
- It returns a fraction