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
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.
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).
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
Interactive Visualization
See exactly how the EVM handles this code in memory, storage, and the stack.
Click Run to execute the simulation
Then use the step controls to navigate