Smart-contract development

library

A library is a reusable bundle of functions with no state of its own — shared math, helpers, or data-structure logic that many contracts can borrow rather than each re-implementing. OpenZeppelin's audited utilities and the historical SafeMath are libraries. The using-for syntax even lets you attach a library's functions to a type, so a uint256 can call x.max(y) as if max were a method.

There are two flavours under the hood. Internal library functions are inlined into the calling contract's bytecode at compile time — a plain JUMP, with no separate deployment, so they cost nothing extra to reach. Public or external library functions are deployed once as a standalone contract and invoked via DELEGATECALL: the library's code runs in the caller's storage context while the library itself holds no state. This lets many contracts share one on-chain copy of expensive code and shrink their own bytecode below the size limit.

Libraries come with firm constraints: they cannot have (non-constant) state variables, cannot hold Ether, cannot inherit or be inherited, and cannot be destroyed. A linked (public-function) library must have its deployed address patched into the consuming contract's bytecode at link time, replacing a placeholder the compiler leaves. Because they execute via delegatecall in the caller's context, a malicious or buggy library can in principle touch the caller's storage — so only link libraries you trust.

library Math {
  function max(uint256 a, uint256 b) internal pure returns (uint256) {
    return a > b ? a : b;
  }
}
using Math for uint256;
// now: x.max(y)

Stateless, reusable, attachable to types.

Internal library functions are free to deploy (inlined); public ones save bytecode by living at one address but add a DELEGATECALL per use. Choose based on whether code size or per-call gas matters more.