Skip to content
Back to Curriculum
ADVANCED

Libraries

Libraries are stateless contracts deployed once and reused by many. They are used to add functionality to primitive types (e.g. `using SafeMath for uint`) or to reduce bytecode size by linking.

Syntax Structure

Example.sol
Loading...

Key Components

  • Boilerplate structure required by the Solc compiler.
  • Placement of state variables versus functions.

Practical Implementation

Creating an iterable mapping using a Library for clean code.

Practical.sol
Loading...

Core Concepts

internal

Internal library functions are inlined (copied) into your contract. No external call.

external/public

External library functions are deployed separately and linked. Requires `DELEGATECALL`.

Linking

The process of injecting the library's address into the contract bytecode.

Mental Model

The Dictionary

A Library is a reference book. If it's an **Internal** library, you rip the page out and staple it into your notes (Inline). If it's an **External** library, you leave the book in the library, and whenever you need to look something up, you walk over there (DelegateCall), read it, and come back.

Under the Hood

Internal functions: Bytecode copy-paste (free execution context). External functions: `DELEGATECALL` (expensive context switch, but code resides elsewhere).

DELEGATECALL

Gas Analysis

Trade-off between deployment cost and runtime cost.

  • • Use `internal` libraries for small utilities (cheaper runtime).
  • • Use `external` libraries for massive logic blobs to keep your contract under the 24kb limit.

Security Risks

Libraries execute in YOUR context.

  • ! If you `DELEGATECALL` to a malicious library, it can destroy your contract (`SELFDESTRUCT`) or steal funds.

Common Use Cases

Math operations (SafeMath, Math.sol).
Data structure logic (EnumerableSet, Linked List).
Address utilities (isContract, sendValue).

Interactive Visualization

See exactly how the EVM handles this code in memory, storage, and the stack.

Interactive Simulation
0 / 0
Loading...
Type Solidity code (v0.8.26) and click Run. Compiler loads on first use (~2MB).

Click Run to execute the simulation

Then use the step controls to navigate